HUGE STEP (hopefully toward the right direction):
[obnox/wireshark/wip.git] / tethereal.c
1 /* tethereal.c
2  *
3  * $Id$
4  *
5  * Ethereal - Network traffic analyzer
6  * By Gerald Combs <gerald@ethereal.com>
7  * Copyright 1998 Gerald Combs
8  *
9  * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10  * and Guy Harris <guy@alum.mit.edu>.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <locale.h>
36 #include <limits.h>
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #include <errno.h>
43
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47
48 #include <signal.h>
49
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
52 #endif
53
54 #ifdef NEED_STRERROR_H
55 #include "strerror.h"
56 #endif
57
58 #ifdef NEED_GETOPT_H
59 #include "getopt.h"
60 #endif
61
62 #include <glib.h>
63 #include <epan/epan.h>
64 #include <epan/filesystem.h>
65 #include <wiretap/file_util.h>
66
67 #include "globals.h"
68 #include <epan/timestamp.h>
69 #include <epan/packet.h>
70 #include "file.h"
71 #include "disabled_protos.h"
72 #include <epan/prefs.h>
73 #include <epan/column.h>
74 #include "print.h"
75 #include <epan/addr_resolv.h>
76 #include "util.h"
77 #include "clopts_common.h"
78 #include "cmdarg_err.h"
79 #include "version_info.h"
80 #include <epan/conversation.h>
81 #include <epan/plugins.h>
82 #include "register.h"
83 #include "conditions.h"
84 #include "capture_stop_conditions.h"
85 #include "ringbuffer.h"
86 #include "capture_ui_utils.h"
87 #include <epan/epan_dissect.h>
88 #include <epan/tap.h>
89 #include <epan/stat_cmd_args.h>
90 #include <epan/timestamp.h>
91
92 #ifdef HAVE_LIBPCAP
93 #include <pcap.h>
94 #include <setjmp.h>
95 #include "capture-pcap-util.h"
96 #include <wiretap/wtap-capture.h>
97 #include <wiretap/libpcap.h>
98 #ifdef _WIN32
99 #include "capture-wpcap.h"
100 #include "capture_errs.h"
101 #endif /* _WIN32 */
102 #include "capture.h"
103 #include "capture_loop.h"
104 #endif /* HAVE_LIBPCAP */
105 #include "epan/emem.h"
106
107 /*
108  * This is the template for the decode as option; it is shared between the
109  * various functions that output the usage for this parameter.
110  */
111 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
112
113 static nstime_t first_ts;
114 static nstime_t prev_ts;
115 static GString *comp_info_str, *runtime_info_str;
116
117 static gboolean print_packet_info;      /* TRUE if we're to print packet information */
118 /*
119  * The way the packet decode is to be written.
120  */
121 typedef enum {
122         WRITE_TEXT,     /* summary or detail text */
123         WRITE_XML       /* PDML or PSML */
124         /* Add CSV and the like here */
125 } output_action_e;
126 static output_action_e output_action;
127 static gboolean do_dissection;  /* TRUE if we have to dissect each packet */
128 static gboolean verbose;
129 static gboolean print_hex;
130 static gboolean line_buffered;
131 static guint32 cum_bytes = 0;
132 static print_format_e print_format = PR_FMT_TEXT;
133 static print_stream_t *print_stream;
134
135 #ifdef HAVE_LIBPCAP
136 /*
137  * TRUE if we're to print packet counts to keep track of captured packets.
138  */
139 static gboolean print_packet_counts;
140
141
142 static loop_data ld;
143
144 #ifdef HAVE_LIBPCAP
145 static capture_options capture_opts;
146
147
148 #ifdef SIGINFO
149 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
150 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
151 #endif /* SIGINFO */
152 #endif /* HAVE_LIBPCAP */
153
154
155 static int capture(char *, int);
156 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
157   const u_char *);
158 static void report_counts(void);
159 #ifdef _WIN32
160 static BOOL WINAPI capture_cleanup(DWORD);
161 #else /* _WIN32 */
162 static void capture_cleanup(int);
163 #ifdef SIGINFO
164 static void report_counts_siginfo(int);
165 #endif /* SIGINFO */
166 #endif /* _WIN32 */
167 #endif /* HAVE_LIBPCAP */
168
169 static int load_cap_file(capture_file *, char *, int);
170 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
171     const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
172     const guchar *pd, int *err);
173 static void show_capture_file_io_error(const char *, int, gboolean);
174 static void show_print_file_io_error(int err);
175 static gboolean write_preamble(capture_file *cf);
176 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
177 static gboolean write_finale(void);
178 static const char *cf_open_error_message(int err, gchar *err_info,
179     gboolean for_writing, int file_type);
180
181 static void open_failure_message(const char *filename, int err,
182     gboolean for_writing);
183 static void failure_message(const char *msg_format, va_list ap);
184 static void read_failure_message(const char *filename, int err);
185
186 capture_file cfile;
187
188
189 static void
190 print_usage(gboolean print_ver)
191 {
192   int i;
193   FILE *output;
194
195   if (print_ver) {
196     output = stdout;
197     fprintf(output, "This is t" PACKAGE " " VERSION "%s"
198         "\n (C) 1998-2005 Gerald Combs <gerald@ethereal.com>"
199         "\n%s\n%s\n",
200
201         svnversion, comp_info_str->str, runtime_info_str->str);
202   } else {
203     output = stderr;
204   }
205 #ifdef HAVE_LIBPCAP
206   fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
207           PACKAGE);
208   fprintf(output, "\t[ -b <capture ring buffer option> ] ...\n");
209 #ifdef _WIN32
210   fprintf(output, "\t[ -B <capture buffer size> ]\n");
211 #endif
212   fprintf(output, "\t[ -c <capture packet count> ]\n");
213   fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
214   fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
215   fprintf(output, "\t[ -i <capture interface> ] [ -N <name resolving flags> ]\n");
216   fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
217   fprintf(output, "\t[ -R <read (display) filter> ] [ -s <capture snaplen> ]\n");
218   fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ]\n");
219   fprintf(output, "\t[ -w <savefile> ] [ -y <capture link type> ] [ -z <statistics> ]\n");
220 #else
221   fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
222   fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
223   fprintf(output, "\t[ -F <output file type> ] [ -N <name resolving flags> ]\n");
224   fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
225   fprintf(output, "\t[ -R <read (display) filter> ] \t[ -t <time stamp format> ]\n");
226   fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -z <statistics ]\n");
227 #endif
228   fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
229   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
230     if (wtap_dump_can_open(i))
231       fprintf(output, "\t%s - %s\n",
232         wtap_file_type_short_string(i), wtap_file_type_string(i));
233   }
234   fprintf(output, "\tdefault is libpcap\n");
235 }
236
237 /*
238  * For a dissector table, print on the stream described by output,
239  * its short name (which is what's used in the "-d" option) and its
240  * descriptive name.
241  */
242 static void
243 display_dissector_table_names(char *table_name, const char *ui_name,
244                               gpointer output)
245 {
246   fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
247 }
248
249 /*
250  * For a dissector handle, print on the stream described by output,
251  * the filter name (which is what's used in the "-d" option) and the full
252  * name for the protocol that corresponds to this handle.
253  */
254 static void
255 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
256 {
257   int                proto_id;
258   const gchar*       proto_filter_name;
259   const gchar*       proto_ui_name;
260
261   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
262
263   if (proto_id != -1) {
264     proto_filter_name = proto_get_protocol_filter_name(proto_id);
265     proto_ui_name =  proto_get_protocol_name(proto_id);
266     g_assert(proto_filter_name != NULL);
267     g_assert(proto_ui_name != NULL);
268
269     fprintf((FILE *)output, "\t%s (%s)\n",
270             proto_filter_name,
271             proto_ui_name);
272   }
273 }
274
275 /*
276  * The protocol_name_search structure is used by find_protocol_name_func()
277  * to pass parameters and store results
278  */
279 struct protocol_name_search{
280   gchar              *searched_name;  /* Protocol filter name we are looking for */
281   dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
282   guint               nb_match;       /* How many dissectors matched searched_name */
283 };
284 typedef struct protocol_name_search *protocol_name_search_t;
285
286 /*
287  * This function parses all dissectors associated with a table to find the
288  * one whose protocol has the specified filter name.  It is called
289  * as a reference function in a call to dissector_table_foreach_handle.
290  * The name we are looking for, as well as the results, are stored in the
291  * protocol_name_search struct pointed to by user_data.
292  * If called using dissector_table_foreach_handle, we actually parse the
293  * whole list of dissectors.
294  */
295 static void
296 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
297
298 {
299   int                         proto_id;
300   const gchar                *protocol_filter_name;
301   protocol_name_search_t      search_info;
302
303   g_assert(handle);
304
305   search_info = (protocol_name_search_t)user_data;
306
307   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
308   if (proto_id != -1) {
309     protocol_filter_name = proto_get_protocol_filter_name(proto_id);
310     g_assert(protocol_filter_name != NULL);
311     if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
312       /* Found a match */
313       if (search_info->nb_match == 0) {
314         /* Record this handle only if this is the first match */
315         search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
316       }
317       search_info->nb_match++;
318     }
319   }
320 }
321
322 /*
323  * Print all layer type names supported.
324  * We send the output to the stream described by the handle output.
325  */
326
327 static void
328 fprint_all_layer_types(FILE *output)
329
330 {
331   dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
332 }
333
334 /*
335  * Print all protocol names supported for a specific layer type.
336  * table_name contains the layer type name in which the search is performed.
337  * We send the output to the stream described by the handle output.
338  */
339
340 static void
341 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
342
343 {
344   dissector_table_foreach_handle(table_name,
345                                  display_dissector_names,
346                                  (gpointer)output);
347 }
348
349 /*
350  * The function below parses the command-line parameters for the decode as
351  * feature (a string pointer by cl_param).
352  * It checks the format of the command-line, searches for a matching table
353  * and dissector.  If a table/dissector match is not found, we display a
354  * summary of the available tables/dissectors (on stderr) and return FALSE.
355  * If everything is fine, we get the "Decode as" preference activated,
356  * then we return TRUE.
357  */
358 static gboolean
359 add_decode_as(const gchar *cl_param)
360 {
361   gchar                        *table_name;
362   guint32                       selector;
363   gchar                        *decoded_param;
364   gchar                        *remaining_param;
365   gchar                        *selector_str;
366   gchar                        *dissector_str;
367   dissector_handle_t            dissector_matching;
368   dissector_table_t             table_matching;
369   ftenum_t                      dissector_table_selector_type;
370   struct protocol_name_search   user_protocol_name;
371
372 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
373
374   g_assert(cl_param);
375   decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
376   g_assert(decoded_param);
377   strcpy(decoded_param, cl_param);
378
379
380   /* The lines below will parse this string (modifying it) to extract all
381     necessary information.  Note that decoded_param is still needed since
382     strings are not copied - we just save pointers. */
383
384   /* This section extracts a layer type (table_name) from decoded_param */
385   table_name = decoded_param; /* Layer type string starts from beginning */
386
387   remaining_param = strchr(table_name, '=');
388   if (remaining_param == NULL) {
389     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
390     /* If the argument does not follow the template, carry on anyway to check
391        if the table name is at least correct.  If remaining_param is NULL,
392        we'll exit anyway further down */
393   }
394   else {
395     *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
396   }
397
398   /* Remove leading and trailing spaces from the table name */
399   while ( table_name[0] == ' ' )
400     table_name++; 
401   while ( table_name[strlen(table_name) - 1] == ' ' )
402     table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
403
404 /* The following part searches a table matching with the layer type specified */
405   table_matching = NULL;
406
407 /* Look for the requested table */
408   if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
409     cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
410   }
411   else {
412     table_matching = find_dissector_table(table_name);
413     if (!table_matching) {
414       cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
415     }
416   }
417
418   if (!table_matching) {
419     /* Display a list of supported layer types to help the user, if the 
420        specified layer type was not found */
421     cmdarg_err("Valid layer types are:");
422     fprint_all_layer_types(stderr);
423   }
424   if (remaining_param == NULL || !table_matching) {
425     /* Exit if the layer type was not found, or if no '=' separator was found
426        (see above) */
427     g_free(decoded_param); 
428     return FALSE;
429   }
430   
431   if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
432     cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
433   }
434   else {
435     remaining_param++; /* Move to the second '=' */
436     *remaining_param = '\0'; /* Remove the second '=' */
437   }
438   remaining_param++; /* Position after the layer type string */
439
440   /* This section extracts a selector value (selector_str) from decoded_param */
441
442   selector_str = remaining_param; /* Next part starts with the selector number */
443
444   remaining_param = strchr(selector_str, ',');
445   if (remaining_param == NULL) {
446     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
447     /* If the argument does not follow the template, carry on anyway to check
448        if the selector value is at least correct.  If remaining_param is NULL,
449        we'll exit anyway further down */
450   }
451   else {
452     *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
453   }
454
455   dissector_table_selector_type = get_dissector_table_selector_type(table_name);
456
457   switch (dissector_table_selector_type) {
458
459   case FT_UINT8:
460   case FT_UINT16:
461   case FT_UINT24:
462   case FT_UINT32:
463     /* The selector for this table is an unsigned number.  Parse it as such.
464        There's no need to remove leading and trailing spaces from the
465        selector number string, because sscanf will do that for us. */
466     if ( sscanf(selector_str, "%u", &selector) != 1 ) {
467       cmdarg_err("Invalid selector number \"%s\"", selector_str);
468       g_free(decoded_param);
469       return FALSE;
470     }
471     break;
472
473   case FT_STRING:
474   case FT_STRINGZ:
475     /* The selector for this table is a string. */
476     break;
477
478   default:
479     /* There are currently no dissector tables with any types other
480        than the ones listed above. */
481     g_assert_not_reached();
482   }
483
484   if (remaining_param == NULL) {
485     /* Exit if no ',' separator was found (see above) */
486     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
487     fprint_all_protocols_for_layer_types(stderr, table_name);
488     g_free(decoded_param); 
489     return FALSE;
490   }
491
492   remaining_param++; /* Position after the selector number string */
493
494   /* This section extracts a protocol filter name (dissector_str) from decoded_param */
495
496   dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
497   
498   /* Remove leading and trailing spaces from the dissector name */
499   while ( dissector_str[0] == ' ' )
500     dissector_str++; 
501   while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
502     dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
503
504   dissector_matching = NULL;
505   
506   /* We now have a pointer to the handle for the requested table inside the variable table_matching */
507   if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
508     cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
509   }
510   else {
511     user_protocol_name.nb_match = 0;
512     user_protocol_name.searched_name = dissector_str;
513     user_protocol_name.matched_handle = NULL;
514     
515     dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
516     
517     if (user_protocol_name.nb_match != 0) {
518       dissector_matching = user_protocol_name.matched_handle;
519       if (user_protocol_name.nb_match > 1) {
520         cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
521       }
522     }
523     else {
524       /* OK, check whether the problem is that there isn't any such
525          protocol, or that there is but it's not specified as a protocol
526          that's valid for that dissector table.
527          Note, we don't exit here, but dissector_matching will remain NULL,
528          so we exit below */
529       if (proto_get_id_by_filter_name(dissector_str) == -1) {
530         /* No such protocol */
531         cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
532       } else {
533         cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
534                 dissector_str, table_name);
535       }
536     }
537   }
538
539   if (!dissector_matching) {
540     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
541     fprint_all_protocols_for_layer_types(stderr, table_name);
542     g_free(decoded_param); 
543     return FALSE;
544   }
545
546 /* This is the end of the code that parses the command-line options.
547    All information is now stored in the variables:
548    table_name
549    selector
550    dissector_matching
551    The above variables that are strings are still pointing to areas within
552    decoded_parm.  decoded_parm thus still needs to be kept allocated in 
553    until we stop needing these variables
554    decoded_param will be deallocated at each exit point of this function */
555
556
557   /* We now have a pointer to the handle for the requested dissector
558      (requested protocol) inside the variable dissector_matching */
559   switch (dissector_table_selector_type) {
560
561   case FT_UINT8:
562   case FT_UINT16:
563   case FT_UINT24:
564   case FT_UINT32:
565     /* The selector for this table is an unsigned number. */
566     dissector_change(table_name, selector, dissector_matching);
567     break;
568
569   case FT_STRING:
570   case FT_STRINGZ:
571     /* The selector for this table is a string. */
572     dissector_change_string(table_name, selector_str, dissector_matching);
573     break;
574
575   default:
576     /* There are currently no dissector tables with any types other
577        than the ones listed above. */
578     g_assert_not_reached();
579   }
580   g_free(decoded_param); /* "Decode As" rule has been succesfully added */
581   return TRUE;
582 }
583
584 void log_func_ignore (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)
585 {
586 }
587
588 int
589 main(int argc, char *argv[])
590 {
591   int                  opt, i;
592   extern char         *optarg;
593   gboolean             arg_error = FALSE;
594
595 #ifdef _WIN32
596   WSADATA               wsaData;
597 #endif  /* _WIN32 */
598
599   char                *gpf_path, *pf_path;
600   char                *gdp_path, *dp_path;
601   int                  gpf_open_errno, gpf_read_errno;
602   int                  pf_open_errno, pf_read_errno;
603   int                  gdp_open_errno, gdp_read_errno;
604   int                  dp_open_errno, dp_read_errno;
605   int                  err;
606 #ifdef HAVE_LIBPCAP
607   gboolean             capture_filter_specified = FALSE;
608   gboolean             list_link_layer_types = FALSE;
609   gboolean             start_capture = FALSE;
610 #else
611   gboolean             capture_option_specified = FALSE;
612 #endif
613   gboolean             quiet = FALSE;
614   gchar               *save_file = NULL;
615   int                  out_file_type = WTAP_FILE_PCAP;
616   gchar               *cf_name = NULL, *rfilter = NULL;
617 #ifdef HAVE_PCAP_OPEN_DEAD
618   struct bpf_program   fcode;
619 #endif
620   dfilter_t           *rfcode = NULL;
621   e_prefs             *prefs;
622   char                 badopt;
623   GLogLevelFlags       log_flags;
624
625 #define OPTSTRING_INIT "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vVw:xy:z:"
626 #ifdef HAVE_LIBPCAP
627 #ifdef _WIN32
628 #define OPTSTRING_WIN32 "B:"
629 #else
630 #define OPTSTRING_WIN32 ""
631 #endif  /* _WIN32 */
632 #else
633 #define OPTSTRING_WIN32 ""
634 #endif  /* HAVE_LIBPCAP */
635
636   static const char    optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
637
638   /* nothing more than the standard GLib handler, but without a warning */
639   log_flags = 
640                     G_LOG_LEVEL_ERROR|
641                     G_LOG_LEVEL_CRITICAL|
642                     G_LOG_LEVEL_WARNING|
643                     G_LOG_LEVEL_MESSAGE|
644                     G_LOG_LEVEL_INFO|
645                     G_LOG_LEVEL_DEBUG|
646                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
647
648   g_log_set_handler(NULL,
649                     log_flags,
650                     log_func_ignore, NULL /* user_data */);
651
652   /* initialize memory allocation subsystem */
653   ep_init_chunk();
654   se_init_chunk();
655   
656 #ifdef HAVE_LIBPCAP
657   capture_opts_init(&capture_opts, NULL /* cfile */);
658 #endif
659
660   timestamp_set_type(TS_RELATIVE);
661   timestamp_set_precision(TS_PREC_AUTO);
662
663   /* Register all dissectors; we must do this before checking for the
664      "-G" flag, as the "-G" flag dumps information registered by the
665      dissectors, and we must do it before we read the preferences, in
666      case any dissectors register preferences. */
667   epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
668             failure_message,open_failure_message,read_failure_message);
669
670   /* Register all tap listeners; we do this before we parse the arguments,
671      as the "-z" argument can specify a registered tap. */
672   
673   /* we register the plugin taps before the other taps because
674           stats_tree taps plugins will be registered as tap listeners
675           by stats_tree_stat.c and need to registered before that */
676 #ifdef HAVE_PLUGINS
677   register_all_plugin_tap_listeners();
678 #endif
679   register_all_tap_listeners();
680
681   /* Now register the preferences for any non-dissector modules.
682      We must do that before we read the preferences as well. */
683   prefs_register_modules();
684
685   /* If invoked with the "-G" flag, we dump out information based on
686      the argument to the "-G" flag; if no argument is specified,
687      for backwards compatibility we dump out a glossary of display
688      filter symbols.
689
690      XXX - we do this here, for now, to support "-G" with no arguments.
691      If none of our build or other processes uses "-G" with no arguments,
692      we can just process it with the other arguments. */
693   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
694     if (argc == 2)
695       proto_registrar_dump_fields(1);
696     else {
697       if (strcmp(argv[2], "fields") == 0)
698         proto_registrar_dump_fields(1);
699       else if (strcmp(argv[2], "fields2") == 0)
700         proto_registrar_dump_fields(2);
701       else if (strcmp(argv[2], "fields3") == 0)
702         proto_registrar_dump_fields(3);
703       else if (strcmp(argv[2], "protocols") == 0)
704         proto_registrar_dump_protocols();
705       else if (strcmp(argv[2], "values") == 0)
706         proto_registrar_dump_values();
707       else if (strcmp(argv[2], "decodes") == 0)
708         dissector_dump_decodes();
709       else if (strcmp(argv[2], "defaultprefs") == 0)
710         write_prefs(NULL);
711       else if (strcmp(argv[2], "currentprefs") == 0) {
712         read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
713             &pf_open_errno, &pf_read_errno, &pf_path);
714         write_prefs(NULL);
715       } else {
716         cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
717         exit(1);
718       }
719     }
720     exit(0);
721   }
722
723   /* Set the C-language locale to the native environment. */
724   setlocale(LC_ALL, "");
725
726   prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
727                      &pf_open_errno, &pf_read_errno, &pf_path);
728   if (gpf_path != NULL) {
729     if (gpf_open_errno != 0) {
730       cmdarg_err("Can't open global preferences file \"%s\": %s.",
731               pf_path, strerror(gpf_open_errno));
732     }
733     if (gpf_read_errno != 0) {
734       cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
735               pf_path, strerror(gpf_read_errno));
736     }
737   }
738   if (pf_path != NULL) {
739     if (pf_open_errno != 0) {
740       cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
741               strerror(pf_open_errno));
742     }
743     if (pf_read_errno != 0) {
744       cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
745               pf_path, strerror(pf_read_errno));
746     }
747     g_free(pf_path);
748     pf_path = NULL;
749   }
750
751   /* Set the name resolution code's flags from the preferences. */
752   g_resolv_flags = prefs->name_resolve;
753
754   /* Read the disabled protocols file. */
755   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
756                             &dp_path, &dp_open_errno, &dp_read_errno);
757   if (gdp_path != NULL) {
758     if (gdp_open_errno != 0) {
759       cmdarg_err(
760         "Could not open global disabled protocols file\n\"%s\": %s.",
761         gdp_path, strerror(gdp_open_errno));
762     }
763     if (gdp_read_errno != 0) {
764       cmdarg_err(
765         "I/O error reading global disabled protocols file\n\"%s\": %s.",
766         gdp_path, strerror(gdp_read_errno));
767     }
768     g_free(gdp_path);
769   }
770   if (dp_path != NULL) {
771     if (dp_open_errno != 0) {
772       cmdarg_err(
773         "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
774         strerror(dp_open_errno));
775     }
776     if (dp_read_errno != 0) {
777       cmdarg_err(
778         "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
779         strerror(dp_read_errno));
780     }
781     g_free(dp_path);
782   }
783
784 #ifdef _WIN32
785   /* Load Wpcap, if possible */
786   load_wpcap();
787 #endif
788
789   init_cap_file(&cfile);
790
791   /* Assemble the compile-time version information string */
792   comp_info_str = g_string_new("Compiled ");
793   get_compiled_version_info(comp_info_str);
794
795   /* Assemble the run-time version information string */
796   runtime_info_str = g_string_new("Running ");
797   get_runtime_version_info(runtime_info_str);
798
799   /* Print format defaults to this. */
800   print_format = PR_FMT_TEXT;
801
802   /* Now get our args */
803   while ((opt = getopt(argc, argv, optstring)) != -1) {
804     switch (opt) {
805       case 'a':        /* autostop criteria */
806       case 'b':        /* Ringbuffer option */
807       case 'c':        /* Capture xxx packets */
808       case 'f':        /* capture filter */
809       case 'i':        /* Use interface xxx */
810       case 'p':        /* Don't capture in promiscuous mode */
811       case 's':        /* Set the snapshot (capture) length */
812       case 'y':        /* Set the pcap data link type */
813 #ifdef _WIN32
814       case 'B':        /* Buffer size */
815 #endif /* _WIN32 */
816 #ifdef HAVE_LIBPCAP
817         capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
818 #else
819         capture_option_specified = TRUE;
820         arg_error = TRUE;
821 #endif
822         break;
823       case 'd':        /* Decode as rule */
824         if (!add_decode_as(optarg))
825           exit(1);
826         break;
827       case 'D':        /* Print a list of capture devices and exit */
828 #ifdef HAVE_LIBPCAP
829         capture_opts_list_interfaces();
830         exit(0);
831 #else
832         capture_option_specified = TRUE;
833         arg_error = TRUE;
834 #endif
835         break;
836       case 'F':
837         out_file_type = wtap_short_string_to_file_type(optarg);
838         if (out_file_type < 0) {
839           cmdarg_err("\"%s\" isn't a valid capture file type",
840                         optarg);
841           exit(1);
842         }
843         break;
844       case 'h':        /* Print help and exit */
845         print_usage(TRUE);
846         exit(0);
847         break;
848       case 'l':        /* "Line-buffer" standard output */
849         /* This isn't line-buffering, strictly speaking, it's just
850            flushing the standard output after the information for
851            each packet is printed; however, that should be good
852            enough for all the purposes to which "-l" is put (and
853            is probably actually better for "-V", as it does fewer
854            writes).
855
856            See the comment in "process_packet()" for an explanation of
857            why we do that, and why we don't just use "setvbuf()" to
858            make the standard output line-buffered (short version: in
859            Windows, "line-buffered" is the same as "fully-buffered",
860            and the output buffer is only flushed when it fills up). */
861         line_buffered = TRUE;
862         break;
863       case 'L':        /* Print list of link-layer types and exit */
864 #ifdef HAVE_LIBPCAP
865         list_link_layer_types = TRUE;
866         break;
867 #else
868         capture_option_specified = TRUE;
869         arg_error = TRUE;
870 #endif
871         break;
872       case 'n':        /* No name resolution */
873         g_resolv_flags = RESOLV_NONE;
874         break;
875       case 'N':        /* Select what types of addresses/port #s to resolve */
876         if (g_resolv_flags == RESOLV_ALL)
877           g_resolv_flags = RESOLV_NONE;
878         badopt = string_to_name_resolve(optarg, &g_resolv_flags);
879         if (badopt != '\0') {
880           cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
881                         badopt);
882           exit(1);
883         }
884         break;
885       case 'o':        /* Override preference from command line */
886         switch (prefs_set_pref(optarg)) {
887
888         case PREFS_SET_SYNTAX_ERR:
889           cmdarg_err("Invalid -o flag \"%s\"", optarg);
890           exit(1);
891           break;
892
893         case PREFS_SET_NO_SUCH_PREF:
894         case PREFS_SET_OBSOLETE:
895           cmdarg_err("-o flag \"%s\" specifies unknown preference",
896                         optarg);
897           exit(1);
898           break;
899         }
900         break;
901       case 'q':        /* Quiet */
902         quiet = TRUE;
903         break;
904       case 'r':        /* Read capture file xxx */
905         cf_name = g_strdup(optarg);
906         break;
907       case 'R':        /* Read file filter */
908         rfilter = optarg;
909         break;
910       case 'S':        /* show packets in real time */
911         print_packet_info = TRUE;
912         break;
913       case 't':        /* Time stamp type */
914         if (strcmp(optarg, "r") == 0)
915           timestamp_set_type(TS_RELATIVE);
916         else if (strcmp(optarg, "a") == 0)
917           timestamp_set_type(TS_ABSOLUTE);
918         else if (strcmp(optarg, "ad") == 0)
919           timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
920         else if (strcmp(optarg, "d") == 0)
921           timestamp_set_type(TS_DELTA);
922         else {
923           cmdarg_err("Invalid time stamp type \"%s\"",
924             optarg);
925           cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
926           cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
927           exit(1);
928         }
929         break;
930       case 'T':        /* printing Type */
931         if (strcmp(optarg, "text") == 0) {
932           output_action = WRITE_TEXT;
933           print_format = PR_FMT_TEXT;
934         } else if (strcmp(optarg, "ps") == 0) {
935           output_action = WRITE_TEXT;
936           print_format = PR_FMT_PS;
937         } else if (strcmp(optarg, "pdml") == 0) {
938           output_action = WRITE_XML;
939           verbose = TRUE;
940         } else if (strcmp(optarg, "psml") == 0) {
941           output_action = WRITE_XML;
942           verbose = FALSE;
943         } else {
944           cmdarg_err("Invalid -T parameter.");
945           cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
946           exit(1);
947         }
948         break;
949       case 'v':        /* Show version and exit */
950         printf("t" PACKAGE " " VERSION "%s\n%s\n%s\n",
951             svnversion, comp_info_str->str, runtime_info_str->str);
952         exit(0);
953         break;
954       case 'w':        /* Write to capture file xxx */
955         save_file = g_strdup(optarg);
956         break;
957       case 'V':        /* Verbose */
958         verbose = TRUE;
959         break;
960       case 'x':        /* Print packet data in hex (and ASCII) */
961         print_hex = TRUE;
962         break;
963       case 'z':
964         /* We won't call the init function for the stat this soon
965            as it would disallow MATE's fields (which are registered
966            by the preferences set callback) from being used as
967            part of a tap filter.  Instead, we just add the argument
968            to a list of stat arguments. */
969         if (!process_stat_cmd_arg(optarg)) {
970           cmdarg_err("invalid -z argument.");
971           cmdarg_err_cont("  -z argument must be one of :");
972           list_stat_cmd_args();
973           exit(1);
974         }
975         break;
976       default:
977       case '?':        /* Bad flag - print usage message */
978         arg_error = TRUE;
979         break;
980     }
981   }
982
983   /* If no capture filter or read filter has been specified, and there are
984      still command-line arguments, treat them as the tokens of a capture
985      filter (if no "-r" flag was specified) or a read filter (if a "-r"
986      flag was specified. */
987   if (optind < argc) {
988     if (cf_name != NULL) {
989       if (rfilter != NULL) {
990         cmdarg_err("Read filters were specified both with \"-R\" "
991             "and with additional command-line arguments");
992         exit(2);
993       }
994       rfilter = get_args_as_string(argc, argv, optind);
995     } else {
996 #ifdef HAVE_LIBPCAP
997       if (capture_filter_specified) {
998         cmdarg_err("Capture filters were specified both with \"-f\""
999             " and with additional command-line arguments");
1000         exit(2);
1001       }
1002       capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1003 #else
1004       capture_option_specified = TRUE;
1005 #endif
1006     }
1007   }
1008
1009   /* See if we're writing a capture file and the file is a pipe */
1010 #ifdef HAVE_LIBPCAP
1011   ld.output_to_pipe = FALSE;
1012 #endif
1013   if (save_file != NULL) {
1014     /* We're writing to a capture file. */
1015     if (strcmp(save_file, "-") == 0) {
1016       /* Write to the standard output. */
1017       g_free(save_file);
1018       save_file = g_strdup("");
1019 #ifdef HAVE_LIBPCAP
1020       /* XXX - should we check whether it's a pipe?  It's arguably
1021          silly to do "-w - >output_file" rather than "-w output_file",
1022          but by not checking we might be violating the Principle Of
1023          Least Astonishment. */
1024       ld.output_to_pipe = TRUE;
1025 #endif
1026     }
1027 #ifdef HAVE_LIBPCAP
1028     else {
1029       err = test_for_fifo(save_file);
1030       switch (err) {
1031
1032       case ENOENT:      /* it doesn't exist, so we'll be creating it,
1033                            and it won't be a FIFO */
1034       case 0:           /* found it, but it's not a FIFO */
1035         break;
1036
1037       case ESPIPE:      /* it is a FIFO */
1038         ld.output_to_pipe = TRUE;
1039         break;
1040
1041       default:          /* couldn't stat it */
1042         cmdarg_err("Error testing whether capture file is a pipe: %s",
1043                 strerror(errno));
1044         exit(2);
1045       }
1046     }
1047 #endif
1048   } else {
1049     /* We're not writing to a file, so we should print packet information
1050        unless "-q" was specified. */
1051     if (!quiet)
1052       print_packet_info = TRUE;
1053   }
1054
1055 #ifndef HAVE_LIBPCAP
1056   if (capture_option_specified)
1057     cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1058 #endif
1059   if (arg_error) {
1060     print_usage(FALSE);
1061     exit(1);
1062   }
1063
1064   /* We don't support capture filters when reading from a capture file
1065      (the BPF compiler doesn't support all link-layer types that we
1066      support in capture files we read). */
1067 #ifdef HAVE_LIBPCAP
1068   if (cf_name != NULL) {
1069     if (capture_filter_specified) {
1070       cmdarg_err("Only read filters, not capture filters, "
1071           "can be specified when reading a capture file.");
1072       exit(2);
1073     }
1074   }
1075 #endif
1076
1077   if (print_hex) {
1078     if (output_action != WRITE_TEXT) {
1079       cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1080       exit(1);
1081     }
1082   }
1083
1084 #ifdef HAVE_LIBPCAP
1085   if (list_link_layer_types) {
1086     /* We're supposed to list the link-layer types for an interface;
1087        did the user also specify a capture file to be read? */
1088     if (cf_name) {
1089       /* Yes - that's bogus. */
1090       cmdarg_err("You can't specify -L and a capture file to be read.");
1091       exit(1);
1092     }
1093     /* No - did they specify a ring buffer option? */
1094     if (capture_opts.multi_files_on) {
1095       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1096       exit(1);
1097     }
1098   } else {
1099     /* If they didn't specify a "-w" flag, but specified a maximum capture
1100        file size, tell them that this doesn't work, and exit. */
1101     if (capture_opts.has_autostop_filesize && save_file == NULL) {
1102       cmdarg_err("Maximum capture file size specified, but "
1103         "capture isn't being saved to a file.");
1104       exit(1);
1105     }
1106
1107     if (capture_opts.multi_files_on) {
1108       /* Ring buffer works only under certain conditions:
1109          a) ring buffer does not work if you're not saving the capture to
1110             a file;
1111          b) ring buffer only works if you're saving in libpcap format;
1112          c) it makes no sense to enable the ring buffer if the maximum
1113             file size is set to "infinite";
1114          d) file must not be a pipe. */
1115       if (save_file == NULL) {
1116         cmdarg_err("Ring buffer requested, but capture isn't being saved to a file.");
1117         exit(1);
1118       }
1119       if (out_file_type != WTAP_FILE_PCAP) {
1120         cmdarg_err("Ring buffer requested, but "
1121           "capture isn't being saved in libpcap format.");
1122         exit(2);
1123       }
1124       if (!capture_opts.has_autostop_filesize) {
1125         cmdarg_err("Ring buffer requested, but "
1126           "no maximum capture file size was specified.");
1127         exit(2);
1128       }
1129       if (ld.output_to_pipe) {
1130         cmdarg_err("Ring buffer requested, but capture file is a pipe.");
1131         exit(2);
1132       }
1133     }
1134   }
1135 #endif
1136
1137 #ifdef _WIN32
1138   /* Start windows sockets */
1139   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1140 #endif  /* _WIN32 */
1141
1142   /* Notify all registered modules that have had any of their preferences
1143      changed either from one of the preferences file or from the command
1144      line that their preferences have changed. */
1145   prefs_apply_all();
1146
1147   /* At this point MATE will have registered its field array so we can
1148      have a tap filter with one of MATE's late-registered fields as part
1149      of the filter.  We can now process all the "-z" arguments. */
1150   start_requested_stats();
1151   
1152   /* disabled protocols as per configuration file */
1153   if (gdp_path == NULL && dp_path == NULL) {
1154     set_disabled_protos_list();
1155   }
1156
1157   /* Build the column format array */
1158   col_setup(&cfile.cinfo, prefs->num_cols);
1159   for (i = 0; i < cfile.cinfo.num_cols; i++) {
1160     cfile.cinfo.col_fmt[i] = get_column_format(i);
1161     cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1162     cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1163       NUM_COL_FMTS);
1164     get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1165     cfile.cinfo.col_data[i] = NULL;
1166     if (cfile.cinfo.col_fmt[i] == COL_INFO)
1167       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1168     else
1169       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1170     cfile.cinfo.col_fence[i] = 0;
1171     cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1172     cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1173   }
1174
1175   for (i = 0; i < cfile.cinfo.num_cols; i++) {
1176       int j;
1177
1178       for (j = 0; j < NUM_COL_FMTS; j++) {
1179          if (!cfile.cinfo.fmt_matx[i][j])
1180              continue;
1181          
1182          if (cfile.cinfo.col_first[j] == -1)
1183              cfile.cinfo.col_first[j] = i;
1184          cfile.cinfo.col_last[j] = i;
1185       }
1186   }
1187
1188 #ifdef HAVE_LIBPCAP
1189   capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1190   capture_opts_trim_ring_num_files(&capture_opts);
1191 #endif
1192
1193   if (rfilter != NULL) {
1194     if (!dfilter_compile(rfilter, &rfcode)) {
1195       cmdarg_err("%s", dfilter_error_msg);
1196       epan_cleanup();
1197 #ifdef HAVE_PCAP_OPEN_DEAD
1198       {
1199         pcap_t *pc;
1200
1201         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1202         if (pc != NULL) {
1203           if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1204             cmdarg_err_cont(
1205               "  Note: That display filter code looks like a valid capture filter;");
1206             cmdarg_err_cont(
1207               "        maybe you mixed them up?");
1208           }
1209           pcap_close(pc);
1210         }
1211       }
1212 #endif
1213       exit(2);
1214     }
1215   }
1216   cfile.rfcode = rfcode;
1217
1218   if (print_packet_info) {
1219     /* If we're printing as text or PostScript, we have
1220        to create a print stream. */
1221     if (output_action == WRITE_TEXT) {
1222       switch (print_format) {
1223
1224       case PR_FMT_TEXT:
1225         print_stream = print_stream_text_stdio_new(stdout);
1226         break;
1227
1228       case PR_FMT_PS:
1229         print_stream = print_stream_ps_stdio_new(stdout);
1230         break;
1231
1232       default:
1233         g_assert_not_reached();
1234       }
1235     }
1236   }
1237
1238   /* We have to dissect each packet if:
1239
1240         we're printing information about each packet;
1241
1242         we're using a read filter on the packets;
1243
1244         we're using any taps. */
1245   do_dissection = print_packet_info || rfcode || have_tap_listeners();
1246
1247   if (cf_name) {
1248     /*
1249      * We're reading a capture file.
1250      */
1251
1252 #ifndef _WIN32
1253     /*
1254      * Immediately relinquish any set-UID or set-GID privileges we have;
1255      * we must not be allowed to read any capture files the user running
1256      * Tethereal can't open.
1257      */
1258     setuid(getuid());
1259     setgid(getgid());
1260 #endif
1261
1262     if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1263       epan_cleanup();
1264       exit(2);
1265     }
1266
1267     /* Set timestamp precision; there should arguably be a command-line
1268        option to let the user set this. */
1269     switch(wtap_file_tsprecision(cfile.wth)) {
1270     case(WTAP_FILE_TSPREC_SEC):
1271       timestamp_set_precision(TS_PREC_AUTO_SEC);
1272       break;
1273     case(WTAP_FILE_TSPREC_DSEC):
1274       timestamp_set_precision(TS_PREC_AUTO_DSEC);
1275       break;
1276     case(WTAP_FILE_TSPREC_CSEC):
1277       timestamp_set_precision(TS_PREC_AUTO_CSEC);
1278       break;
1279     case(WTAP_FILE_TSPREC_MSEC):
1280       timestamp_set_precision(TS_PREC_AUTO_MSEC);
1281       break;
1282     case(WTAP_FILE_TSPREC_USEC):
1283       timestamp_set_precision(TS_PREC_AUTO_USEC);
1284       break;
1285     case(WTAP_FILE_TSPREC_NSEC):
1286       timestamp_set_precision(TS_PREC_AUTO_NSEC);
1287       break;
1288     default:
1289       g_assert_not_reached();
1290     }
1291
1292     /* Process the packets in the file */
1293     err = load_cap_file(&cfile, save_file, out_file_type);
1294     if (err != 0) {
1295       epan_cleanup();
1296       exit(2);
1297     }
1298     cf_name[0] = '\0';
1299   } else {
1300     /* No capture file specified, so we're supposed to do a live capture
1301        (or get a list of link-layer types for a live capture device);
1302        do we have support for live captures? */
1303 #ifdef HAVE_LIBPCAP
1304
1305 #ifdef _WIN32
1306     if (!has_wpcap) {
1307       char *detailed_err;
1308
1309       cmdarg_err("WinPcap couldn't be found.");
1310       detailed_err = cant_load_winpcap_err("Tethereal");
1311       cmdarg_err_cont("%s", detailed_err);
1312       g_free(detailed_err);
1313       exit(2);
1314     }
1315 #endif
1316
1317     /* trim the interface name and exit if that failed */
1318     if (!capture_opts_trim_iface(&capture_opts, 
1319         (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1320         exit(2);
1321     }
1322
1323     /* if requested, list the link layer types and exit */
1324     if (list_link_layer_types) {
1325         capture_opts_list_link_layer_types(&capture_opts);
1326         exit(0);
1327     }
1328
1329     if (!quiet) {
1330       /*
1331        * The user didn't ask us not to print a count of packets as
1332        * they arrive, so do so.
1333        */
1334       print_packet_counts = TRUE;
1335     }
1336
1337     /* For now, assume libpcap gives microsecond precision. */
1338     timestamp_set_precision(TS_PREC_AUTO_USEC);
1339
1340     capture(save_file, out_file_type);
1341
1342     if (capture_opts.multi_files_on) {
1343       ringbuf_free();
1344     }
1345 #else
1346     /* No - complain. */
1347     cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1348     exit(2);
1349 #endif
1350   }
1351
1352   draw_tap_listeners(TRUE);
1353   epan_cleanup();
1354
1355   return 0;
1356 }
1357
1358 #ifdef HAVE_LIBPCAP
1359 /* Do the low-level work of a capture.
1360    Returns TRUE if it succeeds, FALSE otherwise. */
1361
1362 static condition  *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1363
1364 static int
1365 capture(char *save_file, int out_file_type)
1366 {
1367   int         err = 0;
1368   int         volatile volatile_err = 0;
1369   int         volatile inpkts = 0;
1370   int         pcap_cnt;
1371   char        errmsg[1024+1];
1372   condition  *volatile cnd_autostop_size = NULL;
1373   condition  *volatile cnd_autostop_duration = NULL;
1374   char       *descr;
1375 #ifndef _WIN32
1376   void        (*oldhandler)(int);
1377   guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1378 #endif
1379   struct pcap_stat stats;
1380   gboolean    write_ok;
1381   gboolean    close_ok;
1382   dfilter_t   *rfcode = NULL;
1383   int         save_file_fd;
1384
1385   /* Initialize all data structures used for dissection. */
1386   init_dissection();
1387
1388   ld.wtap_linktype  = WTAP_ENCAP_UNKNOWN;
1389   ld.wtap_pdh       = NULL;
1390   ld.packet_cb      = capture_pcap_cb;
1391
1392
1393   /* open the "input file" from network interface or capture pipe */
1394   if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg)))
1395   {
1396     goto error;
1397   }
1398
1399 #ifndef _WIN32
1400   /*
1401    * We've opened the capture device, so, if we're set-UID or set-GID,
1402    * relinquish those privileges.
1403    *
1404    * XXX - if we have saved set-user-ID support, we should give up those
1405    * privileges immediately, and then reclaim them long enough to get
1406    * a list of network interfaces and to open one, and then give them
1407    * up again, so that stuff we do while processing the argument list,
1408    * reading the user's preferences, etc. is done as the real user and
1409    * group, not the effective user and group.
1410    */
1411   setuid(getuid());
1412   setgid(getgid());
1413 #endif
1414
1415   capture_opts.save_file = save_file;
1416
1417   /* open the output file (temporary/specified name/ringbuffer) */
1418   if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1419     goto error;    
1420   }
1421
1422   /* init the input filter from the network interface (capture pipe will do nothing) */
1423   if(!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, 
1424       capture_opts.iface, capture_opts.cfilter, errmsg, sizeof errmsg)) 
1425   {
1426       goto error;
1427   }
1428
1429   /* open the wiretap part of the output file (the output file is already open) */
1430   if(!capture_loop_init_wiretap_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg))
1431   {
1432       goto error;
1433   }
1434
1435
1436 #ifdef _WIN32
1437   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1438   SetConsoleCtrlHandler(capture_cleanup, TRUE);
1439 #else /* _WIN32 */
1440   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1441      and exit.
1442      XXX - deal with signal semantics on various UNIX platforms.  Or just
1443      use "sigaction()" and be done with it? */
1444   signal(SIGTERM, capture_cleanup);
1445   signal(SIGINT, capture_cleanup);
1446   if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1447     signal(SIGHUP, oldhandler);
1448
1449 #ifdef SIGINFO
1450   /* Catch SIGINFO and, if we get it and we're capturing to a file in
1451      quiet mode, report the number of packets we've captured. */
1452   signal(SIGINFO, report_counts_siginfo);
1453 #endif /* SIGINFO */
1454 #endif /* _WIN32 */
1455
1456   /* Let the user know what interface was chosen. */
1457   descr = get_interface_descriptive_name(capture_opts.iface);
1458   fprintf(stderr, "Capturing on %s\n", descr);
1459   g_free(descr);
1460
1461   /* initialize capture stop conditions */
1462   init_capture_stop_conditions();
1463   /* create stop conditions */
1464   if (capture_opts.has_autostop_filesize)
1465     cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1466                                    (long)capture_opts.autostop_filesize * 1024);
1467   if (capture_opts.has_autostop_duration)
1468     cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1469                                (gint32)capture_opts.autostop_duration);
1470
1471   if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1472     cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT, 
1473                                capture_opts.file_duration);
1474
1475   if (!setjmp(ld.stopenv)) {
1476     ld.go = TRUE;
1477     ld.packet_count = 0;
1478   } else
1479     ld.go = FALSE;
1480
1481   while (ld.go) {
1482     /* We need to be careful with automatic variables defined in the
1483        outer scope which are changed inside the loop.  Most compilers
1484        don't try to roll them back to their original values after the
1485        longjmp which causes the loop to finish, but all that the
1486        standards say is that their values are indeterminate.  If we
1487        don't want them to be rolled back, we should define them with the
1488        volatile attribute (paraphrasing W. Richard Stevens, Advanced
1489        Programming in the UNIX Environment, p. 178).
1490
1491        The "err" variable causes a particular problem.  If we give it
1492        the volatile attribute, then when we pass a reference to it (as
1493        in "&err") to a function, GCC warns: "passing arg <n> of
1494        <function> discards qualifiers from pointer target type".
1495        Therefore within the loop and just beyond we don't use "err".
1496        Within the loop we define "loop_err", and assign its value to
1497        "volatile_err", which is in the outer scope and is checked when
1498        the loop finishes.
1499
1500        We also define "packet_count_prev" here to keep things tidy,
1501        since it's used only inside the loop.  If it were defined in the
1502        outer scope, GCC would give a warning (unnecessary in this case)
1503        that it might be clobbered, and we'd need to give it the volatile
1504        attribute to suppress the warning. */
1505
1506     int loop_err = 0;
1507     int packet_count_prev = 0;
1508
1509     if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1510       /* We're not stopping at a particular capture file size, and we're
1511          not stopping after some particular amount of time has expired,
1512          so either we have no stop condition or the only stop condition
1513          is a maximum packet count.
1514
1515          If there's no maximum packet count, pass it -1, meaning "until
1516          you run out of packets in the bufferful you read".  Otherwise,
1517          pass it the number of packets we have left to capture.
1518
1519          We don't call "pcap_loop()" as, if we're saving to a file that's
1520          a FIFO, we want to flush the FIFO after we're done processing
1521          this libpcap bufferful of packets, so that the program
1522          reading the FIFO sees the packets immediately and doesn't get
1523          any partial packet, forcing it to block in the middle of reading
1524          that packet. */
1525       if (capture_opts.autostop_packets == 0)
1526         pcap_cnt = -1;
1527       else {
1528         if (ld.packet_count >= capture_opts.autostop_packets) {
1529           /* XXX do we need this test here? */
1530           /* It appears there's nothing more to capture. */
1531           break;
1532         }
1533         pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1534       }
1535     } else {
1536       /* We need to check the capture file size or the timeout after
1537          each packet. */
1538       pcap_cnt = 1;
1539     }
1540 #ifndef _WIN32
1541     if (ld.from_cap_pipe) {
1542       inpkts = cap_pipe_dispatch(ld.cap_pipe_fd, &ld, &ld.cap_pipe_hdr, &ld.cap_pipe_rechdr, pcap_data,
1543         errmsg, sizeof errmsg);
1544     } else
1545 #endif
1546       inpkts = pcap_dispatch(ld.pcap_h, pcap_cnt, capture_pcap_cb, (u_char *) &ld);
1547     if (inpkts < 0) {
1548       /* Error from "pcap_dispatch()", or error or "no more packets" from
1549          "cap_pipe_dispatch(). */
1550       ld.go = FALSE;
1551     } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1552       /* The specified capture time has elapsed; stop the capture. */
1553       ld.go = FALSE;
1554     } else if (inpkts > 0) {
1555       if (capture_opts.autostop_packets != 0 &&
1556                  ld.packet_count >= capture_opts.autostop_packets) {
1557         /* The specified number of packets have been captured and have
1558            passed both any capture filter in effect and any read filter
1559            in effect. */
1560         ld.go = FALSE;
1561       } else if (cnd_autostop_size != NULL &&
1562                     cnd_eval(cnd_autostop_size,
1563                               (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))) {
1564         /* We're saving the capture to a file, and the capture file reached
1565            its maximum size. */
1566         if (capture_opts.multi_files_on) {
1567           /* Switch to the next ringbuffer file */
1568           if (ringbuf_switch_file(&ld.wtap_pdh, &save_file, &save_file_fd, &loop_err)) {
1569             /* File switch succeeded: reset the condition */
1570             cnd_reset(cnd_autostop_size);
1571             if (cnd_file_duration) {
1572               cnd_reset(cnd_file_duration);
1573             }
1574           } else {
1575             /* File switch failed: stop here */
1576             volatile_err = loop_err;
1577             ld.go = FALSE;
1578           }
1579         } else {
1580           /* No ringbuffer - just stop. */
1581           ld.go = FALSE;
1582         }
1583       }
1584       if (ld.output_to_pipe) {
1585         if (ld.packet_count > packet_count_prev) {
1586           wtap_dump_flush(ld.wtap_pdh);
1587           packet_count_prev = ld.packet_count;
1588         }
1589       }
1590     } /* inpkts > 0 */
1591   } /* while (ld.go) */
1592
1593   /* delete stop conditions */
1594   if (cnd_autostop_size != NULL)
1595     cnd_delete(cnd_autostop_size);
1596   if (cnd_autostop_duration != NULL)
1597     cnd_delete(cnd_autostop_duration);
1598   if (cnd_file_duration != NULL)
1599     cnd_delete(cnd_file_duration);
1600
1601   if (print_packet_counts) {
1602     /* We're printing packet counts to stderr.
1603        Send a newline so that we move to the line after the packet count. */
1604     fprintf(stderr, "\n");
1605   }
1606
1607   /* If we got an error while capturing, report it. */
1608   if (inpkts < 0) {
1609 #ifndef _WIN32
1610     if (ld.from_cap_pipe) {
1611       if (ld.cap_pipe_err == PIPERR) {
1612         cmdarg_err("Error while capturing packets: %s",
1613           errmsg);
1614       }
1615     } else
1616 #endif
1617     {
1618       cmdarg_err("Error while capturing packets: %s",
1619           pcap_geterr(ld.pcap_h));
1620     }
1621   }
1622
1623   if (volatile_err == 0)
1624     write_ok = TRUE;
1625   else {
1626     show_capture_file_io_error(save_file, volatile_err, FALSE);
1627     write_ok = FALSE;
1628   }
1629
1630   if (save_file != NULL) {
1631     /* We're saving to a file or files; close all files. */
1632     close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1633
1634     /* If we've displayed a message about a write error, there's no point
1635        in displaying another message about an error on close. */
1636     if (!close_ok && write_ok)
1637       show_capture_file_io_error(save_file, err, TRUE);
1638   }
1639
1640 #ifndef _WIN32
1641   if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1642     eth_close(ld.cap_pipe_fd);
1643   else
1644 #endif
1645   {
1646     /* Get the capture statistics, and, if any packets were dropped, report
1647        that. */
1648     if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1649       if (stats.ps_drop != 0) {
1650         fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1651       }
1652     } else {
1653       cmdarg_err("Can't get packet-drop statistics: %s",
1654           pcap_geterr(ld.pcap_h));
1655     }
1656     pcap_close(ld.pcap_h);
1657   }
1658
1659   /* Report the number of captured packets if not reported during capture
1660      and we are saving to a file. */
1661   report_counts();
1662
1663   return TRUE;
1664
1665 error:
1666   if (capture_opts.multi_files_on) {
1667     ringbuf_error_cleanup();
1668   }
1669   g_free(save_file);
1670   save_file = NULL;
1671   cmdarg_err("%s", errmsg);
1672 #ifndef _WIN32
1673   if (ld.from_cap_pipe) {
1674     if (ld.cap_pipe_fd >= 0)
1675       eth_close(ld.cap_pipe_fd);
1676   } else
1677 #endif
1678   {
1679   if (ld.pcap_h != NULL)
1680     pcap_close(ld.pcap_h);
1681   }
1682
1683   return FALSE;
1684 }
1685
1686 static void
1687 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1688   const u_char *pd)
1689 {
1690   struct wtap_pkthdr whdr;
1691   union wtap_pseudo_header pseudo_header;
1692   loop_data *ld = (loop_data *) user;
1693   int loop_err;
1694   int err;
1695   int save_file_fd;
1696
1697   /* Convert from libpcap to Wiretap format.
1698      If that fails, ignore the packet (wtap_process_pcap_packet has
1699      written an error message). */
1700   pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1701                                 &whdr, &err);
1702   if (pd == NULL)
1703     return;
1704
1705 #ifdef SIGINFO
1706   /*
1707    * Prevent a SIGINFO handler from writing to stdout while we're
1708    * doing so; instead, have it just set a flag telling us to print
1709    * that information when we're done.
1710    */
1711   infodelay = TRUE;
1712 #endif /* SIGINFO */
1713
1714   /* The current packet may have arrived after a very long silence,
1715    * way past the time to switch files.  In order not to have
1716    * the first packet of a new series of events as the last
1717    * [or only] packet in the file, switch before writing!
1718    */
1719   if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1720     /* time elapsed for this ring file, switch to the next */
1721     if (ringbuf_switch_file(&ld->wtap_pdh, &ld->save_file, &save_file_fd, &loop_err)) {
1722       /* File switch succeeded: reset the condition */
1723       cnd_reset(cnd_file_duration);
1724     } else {
1725       /* File switch failed: stop here */
1726       /* XXX - we should do something with "loop_err" */
1727       ld->go = FALSE;
1728     }
1729   }
1730
1731   if (!process_packet(&cfile, ld->wtap_pdh, 0, &whdr, &pseudo_header, pd, &err)) {
1732     /* Error writing to a capture file */
1733     if (print_packet_counts) {
1734       /* We're printing counts of packets captured; move to the line after
1735          the count. */
1736       fprintf(stderr, "\n");
1737     }
1738     show_capture_file_io_error(ld->save_file, err, FALSE);
1739     pcap_close(ld->pcap_h);
1740     wtap_dump_close(ld->wtap_pdh, &err);
1741     exit(2);
1742   }
1743
1744 #ifdef SIGINFO
1745   /*
1746    * Allow SIGINFO handlers to write.
1747    */
1748   infodelay = FALSE;
1749
1750   /*
1751    * If a SIGINFO handler asked us to write out capture counts, do so.
1752    */
1753   if (infoprint)
1754     report_counts();
1755 #endif /* SIGINFO */
1756 }
1757
1758 #ifdef _WIN32
1759 static BOOL WINAPI
1760 capture_cleanup(DWORD ctrltype _U_)
1761 {
1762   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1763      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1764      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1765      like SIGTERM at least when the machine's shutting down.
1766
1767      For now, we handle them all as indications that we should clean up
1768      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1769      way on UNIX.
1770
1771      However, as handlers run in a new thread, we can't just longjmp
1772      out; we have to set "ld.go" to FALSE, and must return TRUE so that
1773      no other handler - such as one that would terminate the process -
1774      gets called.
1775
1776      XXX - for some reason, typing ^C to Tethereal, if you run this in
1777      a Cygwin console window in at least some versions of Cygwin,
1778      causes Tethereal to terminate immediately; this routine gets
1779      called, but the main loop doesn't get a chance to run and
1780      exit cleanly, at least if this is compiled with Microsoft Visual
1781      C++ (i.e., it's a property of the Cygwin console window or Bash;
1782      it happens if Tethereal is not built with Cygwin - for all I know,
1783      building it with Cygwin may make the problem go away). */
1784   ld.go = FALSE;
1785   return TRUE;
1786 }
1787 #else
1788 static void
1789 capture_cleanup(int signum _U_)
1790 {
1791   /* Longjmp back to the starting point; "pcap_dispatch()", on many
1792      UNIX platforms, just keeps looping if it gets EINTR, so if we set
1793      "ld.go" to FALSE and return, we won't break out of it and quit
1794      capturing. */
1795   longjmp(ld.stopenv, 1);
1796 }
1797 #endif /* _WIN32 */
1798
1799 static void
1800 report_counts(void)
1801 {
1802 #ifdef SIGINFO
1803   /* XXX - if we use sigaction, this doesn't have to be done.
1804      (Yes, this isn't necessary on BSD, but just in case a system
1805      where "signal()" has AT&T semantics adopts SIGINFO....) */
1806   signal(SIGINFO, report_counts_siginfo);
1807 #endif /* SIGINFO */
1808
1809   if (!print_packet_counts) {
1810     /* Report the count only if we aren't printing a packet count
1811        as packets arrive. */
1812     fprintf(stderr, "%u packets captured\n", ld.packet_count);
1813   }
1814 #ifdef SIGINFO
1815   infoprint = FALSE;    /* we just reported it */
1816 #endif /* SIGINFO */
1817 }
1818
1819 #ifdef SIGINFO
1820 static void
1821 report_counts_siginfo(int signum _U_)
1822 {
1823   int sav_errno = errno;
1824   /* If we've been told to delay printing, just set a flag asking
1825      that we print counts (if we're supposed to), otherwise print
1826      the count of packets captured (if we're supposed to). */
1827   if (infodelay)
1828     infoprint = TRUE;
1829   else
1830     report_counts();
1831   errno = sav_errno;
1832 }
1833 #endif /* SIGINFO */
1834 #endif /* HAVE_LIBPCAP */
1835
1836 static int
1837 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
1838 {
1839   gint         linktype;
1840   int          snapshot_length;
1841   wtap_dumper *pdh;
1842   int          err;
1843   gchar        *err_info;
1844   long         data_offset;
1845
1846   linktype = wtap_file_encap(cf->wth);
1847   if (save_file != NULL) {
1848     /* Set up to write to the capture file. */
1849     snapshot_length = wtap_snapshot_length(cf->wth);
1850     if (snapshot_length == 0) {
1851       /* Snapshot length of input file not known. */
1852       snapshot_length = WTAP_MAX_PACKET_SIZE;
1853     }
1854     pdh = wtap_dump_open(save_file, out_file_type,
1855                 linktype, snapshot_length, FALSE /* compressed */, &err);
1856
1857     if (pdh == NULL) {
1858       /* We couldn't set up to write to the capture file. */
1859       switch (err) {
1860
1861       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1862         cmdarg_err("Capture files can't be written in that format.");
1863         break;
1864
1865       case WTAP_ERR_UNSUPPORTED_ENCAP:
1866       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1867         cmdarg_err("The capture file being read can't be written in "
1868           "that format.");
1869         break;
1870
1871       case WTAP_ERR_CANT_OPEN:
1872         cmdarg_err("The file \"%s\" couldn't be created for some "
1873           "unknown reason.",
1874             *save_file == '\0' ? "stdout" : save_file);
1875         break;
1876
1877       case WTAP_ERR_SHORT_WRITE:
1878         cmdarg_err("A full header couldn't be written to the file \"%s\".",
1879                 *save_file == '\0' ? "stdout" : save_file);
1880         break;
1881
1882       default:
1883         cmdarg_err("The file \"%s\" could not be created: %s.",
1884                 *save_file == '\0' ? "stdout" : save_file,
1885                 wtap_strerror(err));
1886         break;
1887       }
1888       goto out;
1889     }
1890   } else {
1891     if (print_packet_info) {
1892       if (!write_preamble(cf)) {
1893         err = errno;
1894         show_print_file_io_error(err);
1895         goto out;
1896       }
1897     }
1898     pdh = NULL;
1899   }
1900   while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
1901     if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
1902                         wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
1903                         &err)) {
1904       /* Error writing to a capture file */
1905       show_capture_file_io_error(save_file, err, FALSE);
1906       wtap_dump_close(pdh, &err);
1907       exit(2);
1908     }
1909   }
1910   if (err != 0) {
1911     /* Print a message noting that the read failed somewhere along the line. */
1912     switch (err) {
1913
1914     case WTAP_ERR_UNSUPPORTED_ENCAP:
1915       cmdarg_err("\"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)",
1916         cf->filename, err_info);
1917       break;
1918
1919     case WTAP_ERR_CANT_READ:
1920       cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
1921         cf->filename);
1922       break;
1923
1924     case WTAP_ERR_SHORT_READ:
1925       cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
1926         cf->filename);
1927       break;
1928
1929     case WTAP_ERR_BAD_RECORD:
1930       cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
1931         cf->filename, err_info);
1932       break;
1933
1934     default:
1935       cmdarg_err("An error occurred while reading \"%s\": %s.",
1936         cf->filename, wtap_strerror(err));
1937       break;
1938     }
1939     if (save_file != NULL) {
1940       /* Now close the capture file. */
1941       if (!wtap_dump_close(pdh, &err))
1942         show_capture_file_io_error(save_file, err, TRUE);
1943     }
1944   } else {
1945     if (save_file != NULL) {
1946       /* Now close the capture file. */
1947       if (!wtap_dump_close(pdh, &err))
1948         show_capture_file_io_error(save_file, err, TRUE);
1949     } else {
1950       if (print_packet_info) {
1951         if (!write_finale()) {
1952           err = errno;
1953           show_print_file_io_error(err);
1954         }
1955       }
1956     }
1957   }
1958
1959 out:
1960   wtap_close(cf->wth);
1961   cf->wth = NULL;
1962
1963   return err;
1964 }
1965
1966 static void
1967 fill_in_fdata(frame_data *fdata, capture_file *cf,
1968         const struct wtap_pkthdr *phdr, long offset)
1969 {
1970   fdata->next = NULL;
1971   fdata->prev = NULL;
1972   fdata->pfd = NULL;
1973   fdata->num = cf->count;
1974   fdata->pkt_len = phdr->len;
1975   cum_bytes += phdr->len;
1976   fdata->cum_bytes  = cum_bytes;
1977   fdata->cap_len = phdr->caplen;
1978   fdata->file_off = offset;
1979   fdata->lnk_t = phdr->pkt_encap;
1980   fdata->abs_ts = *((nstime_t *) &phdr->ts);
1981   fdata->flags.passed_dfilter = 0;
1982   fdata->flags.encoding = CHAR_ASCII;
1983   fdata->flags.visited = 0;
1984   fdata->flags.marked = 0;
1985   fdata->flags.ref_time = 0;
1986
1987   /* If we don't have the time stamp of the first packet in the
1988      capture, it's because this is the first packet.  Save the time
1989      stamp of this packet as the time stamp of the first packet. */
1990   if (nstime_is_zero(&first_ts)) {
1991     first_ts = fdata->abs_ts;
1992   }
1993
1994   /* If we don't have the time stamp of the previous displayed packet,
1995      it's because this is the first displayed packet.  Save the time
1996      stamp of this packet as the time stamp of the previous displayed
1997      packet. */
1998   if (nstime_is_zero(&prev_ts)) {
1999     prev_ts = fdata->abs_ts;
2000   }
2001
2002   /* Get the time elapsed between the first packet and this packet. */
2003   nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2004
2005   /* If it's greater than the current elapsed time, set the elapsed time
2006      to it (we check for "greater than" so as not to be confused by
2007      time moving backwards). */
2008   if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2009         || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2010     cf->elapsed_time = fdata->rel_ts;
2011   }
2012
2013   /* Get the time elapsed between the previous displayed packet and
2014      this packet. */
2015   nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2016   prev_ts = fdata->abs_ts;
2017 }
2018
2019 /* Free up all data attached to a "frame_data" structure. */
2020 static void
2021 clear_fdata(frame_data *fdata)
2022 {
2023   if (fdata->pfd)
2024     g_slist_free(fdata->pfd);
2025 }
2026
2027 static gboolean
2028 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2029                const struct wtap_pkthdr *whdr,
2030                union wtap_pseudo_header *pseudo_header, const guchar *pd,
2031                int *err)
2032 {
2033   frame_data fdata;
2034   gboolean create_proto_tree;
2035   epan_dissect_t *edt;
2036   gboolean passed;
2037
2038   /* Count this packet. */
2039   cf->count++;
2040
2041   /* If we're going to print packet information, or we're going to
2042      run a read filter, or we're going to process taps, set up to
2043      do a dissection and do so. */
2044   if (do_dissection) {
2045     fill_in_fdata(&fdata, cf, whdr, offset);
2046
2047     if (print_packet_info) {
2048       /* Grab any resolved addresses */
2049     
2050       if (g_resolv_flags) {
2051         host_name_lookup_process(NULL);
2052       }
2053     }
2054
2055     passed = TRUE;
2056     if (cf->rfcode || verbose || num_tap_filters!=0)
2057       create_proto_tree = TRUE;
2058     else
2059       create_proto_tree = FALSE;
2060     /* The protocol tree will be "visible", i.e., printed, only if we're
2061        printing packet details, which is true if we're printing stuff
2062        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2063        is true). */
2064     edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2065
2066     /* If we're running a read filter, prime the epan_dissect_t with that
2067        filter. */
2068     if (cf->rfcode)
2069       epan_dissect_prime_dfilter(edt, cf->rfcode);
2070
2071     tap_queue_init(edt);
2072
2073     /* We only need the columns if we're printing packet info but we're
2074        *not* verbose; in verbose mode, we print the protocol tree, not
2075        the protocol summary. */
2076     epan_dissect_run(edt, pseudo_header, pd, &fdata,
2077                      (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2078
2079     tap_push_tapped_queue(edt);
2080
2081     /* Run the read filter if we have one. */
2082     if (cf->rfcode)
2083       passed = dfilter_apply_edt(cf->rfcode, edt);
2084     else
2085       passed = TRUE;
2086   } else {
2087     /* We're not running a display filter and we're not printing any
2088        packet information, so we don't need to do a dissection, and all
2089        packets are processed. */
2090     edt = NULL;
2091     passed = TRUE;
2092   }
2093
2094   if (passed) {
2095     /* Count this packet. */
2096 #ifdef HAVE_LIBPCAP
2097     ld.packet_count++;
2098 #endif
2099
2100     /* Process this packet. */
2101     if (pdh != NULL) {
2102       /* We're writing to a capture file; write this packet. */
2103       if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2104         return FALSE;
2105 #ifdef HAVE_LIBPCAP
2106       if (print_packet_counts) {
2107         /* We're printing packet counts. */
2108         if (ld.packet_count != 0) {
2109           fprintf(stderr, "\r%u ", ld.packet_count);
2110           /* stderr could be line buffered */
2111           fflush(stderr);
2112         }
2113       }
2114 #endif
2115     }
2116     if (print_packet_info) {
2117       /* We're printing packet information; print the information for
2118          this packet. */
2119       print_packet(cf, edt);
2120
2121       /* The ANSI C standard does not appear to *require* that a line-buffered
2122          stream be flushed to the host environment whenever a newline is
2123          written, it just says that, on such a stream, characters "are
2124          intended to be transmitted to or from the host environment as a
2125          block when a new-line character is encountered".
2126
2127          The Visual C++ 6.0 C implementation doesn't do what is intended;
2128          even if you set a stream to be line-buffered, it still doesn't
2129          flush the buffer at the end of every line.
2130
2131          So, if the "-l" flag was specified, we flush the standard output
2132          at the end of a packet.  This will do the right thing if we're
2133          printing packet summary lines, and, as we print the entire protocol
2134          tree for a single packet without waiting for anything to happen,
2135          it should be as good as line-buffered mode if we're printing
2136          protocol trees.  (The whole reason for the "-l" flag in either
2137          tcpdump or Tethereal is to allow the output of a live capture to
2138          be piped to a program or script and to have that script see the
2139          information for the packet as soon as it's printed, rather than
2140          having to wait until a standard I/O buffer fills up. */
2141       if (line_buffered)
2142         fflush(stdout);
2143
2144       if (ferror(stdout)) {
2145         show_print_file_io_error(errno);
2146         exit(2);
2147       }
2148     }
2149   }
2150
2151   if (do_dissection) {
2152     epan_dissect_free(edt);
2153     clear_fdata(&fdata);
2154   }
2155   return TRUE;
2156 }
2157
2158 static void
2159 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2160 {
2161   if (*fname == '\0')
2162     fname = "stdout";
2163
2164   switch (err) {
2165
2166   case ENOSPC:
2167     cmdarg_err("Not all the packets could be written to \"%s\" because there is "
2168 "no space left on the file system.",
2169         fname);
2170     break;
2171
2172 #ifdef EDQUOT
2173   case EDQUOT:
2174     cmdarg_err("Not all the packets could be written to \"%s\" because you are "
2175 "too close to, or over your disk quota.",
2176         fname);
2177   break;
2178 #endif
2179
2180   case WTAP_ERR_CANT_CLOSE:
2181     cmdarg_err("\"%s\" couldn't be closed for some unknown reason.",
2182         fname);
2183     break;
2184
2185   case WTAP_ERR_SHORT_WRITE:
2186     cmdarg_err("Not all the packets could be written to \"%s\".",
2187         fname);
2188     break;
2189
2190   default:
2191     if (is_close) {
2192       cmdarg_err("\"%s\" could not be closed: %s.",
2193         fname, wtap_strerror(err));
2194     } else {
2195       cmdarg_err("An error occurred while writing to \"%s\": %s.",
2196         fname, wtap_strerror(err));
2197     }
2198     break;
2199   }
2200 }
2201
2202 static gboolean
2203 write_preamble(capture_file *cf)
2204 {
2205   switch (output_action) {
2206
2207   case WRITE_TEXT:
2208     return print_preamble(print_stream, cf->filename);
2209     break;
2210
2211   case WRITE_XML:
2212     if (verbose)
2213       write_pdml_preamble(stdout);
2214     else
2215       write_psml_preamble(stdout);
2216     return !ferror(stdout);
2217
2218   default:
2219     g_assert_not_reached();
2220     return FALSE;
2221   }
2222 }
2223
2224 static char *
2225 get_line_buf(size_t len)
2226 {
2227   static char *line_bufp = NULL;
2228   static size_t line_buf_len = 256;
2229   size_t new_line_buf_len;
2230
2231   for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2232        new_line_buf_len *= 2)
2233     ;
2234   if (line_bufp == NULL) {
2235     line_buf_len = new_line_buf_len;
2236     line_bufp = g_malloc(line_buf_len + 1);
2237   } else {
2238     if (new_line_buf_len > line_buf_len) {
2239       line_buf_len = new_line_buf_len;
2240       line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2241     }
2242   }
2243   return line_bufp;
2244 }
2245
2246 static gboolean
2247 print_columns(capture_file *cf)
2248 {
2249   char *line_bufp;
2250   int i;
2251   size_t buf_offset;
2252   size_t column_len;
2253
2254   line_bufp = get_line_buf(256);
2255   buf_offset = 0;
2256   *line_bufp = '\0';
2257   for (i = 0; i < cf->cinfo.num_cols; i++) {
2258     switch (cf->cinfo.col_fmt[i]) {
2259     case COL_NUMBER:
2260 #ifdef HAVE_LIBPCAP
2261       /*
2262        * Don't print this if we're doing a live capture from a network
2263        * interface - if we're doing a live capture, you won't be
2264        * able to look at the capture in the future (it's not being
2265        * saved anywhere), so the frame numbers are unlikely to be
2266        * useful.
2267        *
2268        * (XXX - it might be nice to be able to save and print at
2269        * the same time, sort of like an "Update list of packets
2270        * in real time" capture in Ethereal.)
2271        */
2272       if (capture_opts.iface != NULL)
2273         continue;
2274 #endif
2275       column_len = strlen(cf->cinfo.col_data[i]);
2276       if (column_len < 3)
2277         column_len = 3;
2278       line_bufp = get_line_buf(buf_offset + column_len);
2279       sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2280       break;
2281
2282     case COL_CLS_TIME:
2283     case COL_REL_TIME:
2284     case COL_ABS_TIME:
2285     case COL_ABS_DATE_TIME:     /* XXX - wider */
2286       column_len = strlen(cf->cinfo.col_data[i]);
2287       if (column_len < 10)
2288         column_len = 10;
2289       line_bufp = get_line_buf(buf_offset + column_len);
2290       sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2291       break;
2292
2293     case COL_DEF_SRC:
2294     case COL_RES_SRC:
2295     case COL_UNRES_SRC:
2296     case COL_DEF_DL_SRC:
2297     case COL_RES_DL_SRC:
2298     case COL_UNRES_DL_SRC:
2299     case COL_DEF_NET_SRC:
2300     case COL_RES_NET_SRC:
2301     case COL_UNRES_NET_SRC:
2302       column_len = strlen(cf->cinfo.col_data[i]);
2303       if (column_len < 12)
2304         column_len = 12;
2305       line_bufp = get_line_buf(buf_offset + column_len);
2306       sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2307       break;
2308
2309     case COL_DEF_DST:
2310     case COL_RES_DST:
2311     case COL_UNRES_DST:
2312     case COL_DEF_DL_DST:
2313     case COL_RES_DL_DST:
2314     case COL_UNRES_DL_DST:
2315     case COL_DEF_NET_DST:
2316     case COL_RES_NET_DST:
2317     case COL_UNRES_NET_DST:
2318       column_len = strlen(cf->cinfo.col_data[i]);
2319       if (column_len < 12)
2320         column_len = 12;
2321       line_bufp = get_line_buf(buf_offset + column_len);
2322       sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2323       break;
2324
2325     default:
2326       column_len = strlen(cf->cinfo.col_data[i]);
2327       line_bufp = get_line_buf(buf_offset + column_len);
2328       strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2329       break;
2330     }
2331     buf_offset += column_len;
2332     if (i != cf->cinfo.num_cols - 1) {
2333       /*
2334        * This isn't the last column, so we need to print a
2335        * separator between this column and the next.
2336        *
2337        * If we printed a network source and are printing a
2338        * network destination of the same type next, separate
2339        * them with "->"; if we printed a network destination
2340        * and are printing a network source of the same type
2341        * next, separate them with "<-"; otherwise separate them
2342        * with a space.
2343        *
2344        * We add enough space to the buffer for " <- " or " -> ",
2345        * even if we're only adding " ".
2346        */
2347       line_bufp = get_line_buf(buf_offset + 4);
2348       switch (cf->cinfo.col_fmt[i]) {
2349
2350       case COL_DEF_SRC:
2351       case COL_RES_SRC:
2352       case COL_UNRES_SRC:
2353         switch (cf->cinfo.col_fmt[i + 1]) {
2354
2355         case COL_DEF_DST:
2356         case COL_RES_DST:
2357         case COL_UNRES_DST:
2358           strcat(line_bufp + buf_offset, " -> ");
2359           buf_offset += 4;
2360           break;
2361
2362         default:
2363           strcat(line_bufp + buf_offset, " ");
2364           buf_offset += 1;
2365           break;
2366         }
2367         break;
2368
2369       case COL_DEF_DL_SRC:
2370       case COL_RES_DL_SRC:
2371       case COL_UNRES_DL_SRC:
2372         switch (cf->cinfo.col_fmt[i + 1]) {
2373
2374         case COL_DEF_DL_DST:
2375         case COL_RES_DL_DST:
2376         case COL_UNRES_DL_DST:
2377           strcat(line_bufp + buf_offset, " -> ");
2378           buf_offset += 4;
2379           break;
2380
2381         default:
2382           strcat(line_bufp + buf_offset, " ");
2383           buf_offset += 1;
2384           break;
2385         }
2386         break;
2387
2388       case COL_DEF_NET_SRC:
2389       case COL_RES_NET_SRC:
2390       case COL_UNRES_NET_SRC:
2391         switch (cf->cinfo.col_fmt[i + 1]) {
2392
2393         case COL_DEF_NET_DST:
2394         case COL_RES_NET_DST:
2395         case COL_UNRES_NET_DST:
2396           strcat(line_bufp + buf_offset, " -> ");
2397           buf_offset += 4;
2398           break;
2399
2400         default:
2401           strcat(line_bufp + buf_offset, " ");
2402           buf_offset += 1;
2403           break;
2404         }
2405         break;
2406
2407       case COL_DEF_DST:
2408       case COL_RES_DST:
2409       case COL_UNRES_DST:
2410         switch (cf->cinfo.col_fmt[i + 1]) {
2411
2412         case COL_DEF_SRC:
2413         case COL_RES_SRC:
2414         case COL_UNRES_SRC:
2415           strcat(line_bufp + buf_offset, " <- ");
2416           buf_offset += 4;
2417           break;
2418
2419         default:
2420           strcat(line_bufp + buf_offset, " ");
2421           buf_offset += 1;
2422           break;
2423         }
2424         break;
2425
2426       case COL_DEF_DL_DST:
2427       case COL_RES_DL_DST:
2428       case COL_UNRES_DL_DST:
2429         switch (cf->cinfo.col_fmt[i + 1]) {
2430
2431         case COL_DEF_DL_SRC:
2432         case COL_RES_DL_SRC:
2433         case COL_UNRES_DL_SRC:
2434           strcat(line_bufp + buf_offset, " <- ");
2435           buf_offset += 4;
2436           break;
2437
2438         default:
2439           strcat(line_bufp + buf_offset, " ");
2440           buf_offset += 1;
2441           break;
2442         }
2443         break;
2444
2445       case COL_DEF_NET_DST:
2446       case COL_RES_NET_DST:
2447       case COL_UNRES_NET_DST:
2448         switch (cf->cinfo.col_fmt[i + 1]) {
2449
2450         case COL_DEF_NET_SRC:
2451         case COL_RES_NET_SRC:
2452         case COL_UNRES_NET_SRC:
2453           strcat(line_bufp + buf_offset, " <- ");
2454           buf_offset += 4;
2455           break;
2456
2457         default:
2458           strcat(line_bufp + buf_offset, " ");
2459           buf_offset += 1;
2460           break;
2461         }
2462         break;
2463
2464       default:
2465         strcat(line_bufp + buf_offset, " ");
2466         buf_offset += 1;
2467         break;
2468       }
2469     }
2470   }
2471   return print_line(print_stream, 0, line_bufp);
2472 }
2473
2474 static gboolean
2475 print_packet(capture_file *cf, epan_dissect_t *edt)
2476 {
2477   print_args_t  print_args;
2478
2479   if (verbose) {
2480     /* Print the information in the protocol tree. */
2481     switch (output_action) {
2482
2483     case WRITE_TEXT:
2484       print_args.to_file = TRUE;
2485       print_args.format = print_format;
2486       print_args.print_summary = !verbose;
2487       print_args.print_hex = verbose && print_hex;
2488       print_args.print_formfeed = FALSE;
2489       print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2490
2491       /* init the packet range */
2492       packet_range_init(&print_args.range);
2493
2494       if (!proto_tree_print(&print_args, edt, print_stream))
2495         return FALSE;
2496       if (!print_hex) {
2497         /* "print_hex_data()" will put out a leading blank line, as well
2498          as a trailing one; print one here, to separate the packets,
2499          only if "print_hex_data()" won't be called. */
2500         if (!print_line(print_stream, 0, ""))
2501           return FALSE;
2502       }
2503       break;
2504
2505     case WRITE_XML:
2506       proto_tree_write_pdml(edt, stdout);
2507       printf("\n");
2508       return !ferror(stdout);
2509     }
2510   } else {
2511     /* Just fill in the columns. */
2512     epan_dissect_fill_in_columns(edt);
2513
2514     /* Now print them. */
2515     switch (output_action) {
2516
2517     case WRITE_TEXT:
2518         if (!print_columns(cf))
2519           return FALSE;
2520         break;
2521
2522     case WRITE_XML:
2523         proto_tree_write_psml(edt, stdout);
2524         return !ferror(stdout);
2525     }
2526   }
2527   if (print_hex) {
2528     if (!print_hex_data(print_stream, edt))
2529       return FALSE;
2530     if (!print_line(print_stream, 0, ""))
2531       return FALSE;
2532   }
2533   return TRUE;
2534 }
2535
2536 static gboolean
2537 write_finale(void)
2538 {
2539   switch (output_action) {
2540
2541   case WRITE_TEXT:
2542     return print_finale(print_stream);
2543     break;
2544
2545   case WRITE_XML:
2546     if (verbose)
2547       write_pdml_finale(stdout);
2548     else
2549       write_psml_finale(stdout);
2550     return !ferror(stdout);
2551
2552   default:
2553     g_assert_not_reached();
2554     return FALSE;
2555   }
2556 }
2557
2558 static void
2559 show_print_file_io_error(int err)
2560 {
2561   switch (err) {
2562
2563   case ENOSPC:
2564     cmdarg_err("Not all the packets could be printed because there is "
2565 "no space left on the file system.");
2566     break;
2567
2568 #ifdef EDQUOT
2569   case EDQUOT:
2570     cmdarg_err("Not all the packets could be printed because you are "
2571 "too close to, or over your disk quota.");
2572   break;
2573 #endif
2574
2575   default:
2576     cmdarg_err("An error occurred while printing packets: %s.",
2577       strerror(err));
2578     break;
2579   }
2580 }
2581
2582 static const char *
2583 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2584                       int file_type)
2585 {
2586   const char *errmsg;
2587   static char errmsg_errno[1024+1];
2588
2589   if (err < 0) {
2590     /* Wiretap error. */
2591     switch (err) {
2592
2593     case WTAP_ERR_NOT_REGULAR_FILE:
2594       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2595       break;
2596
2597     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2598       /* Seen only when opening a capture file for reading. */
2599       errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2600       break;
2601
2602     case WTAP_ERR_UNSUPPORTED:
2603       /* Seen only when opening a capture file for reading. */
2604       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2605                "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2606                "(%s)", err_info);
2607       g_free(err_info);
2608       errmsg = errmsg_errno;
2609       break;
2610
2611     case WTAP_ERR_CANT_WRITE_TO_PIPE:
2612       /* Seen only when opening a capture file for writing. */
2613       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2614                "The file \"%%s\" is a pipe, and %s capture files can't be "
2615                "written to a pipe.", wtap_file_type_string(file_type));
2616       errmsg = errmsg_errno;
2617       break;
2618
2619     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2620       /* Seen only when opening a capture file for writing. */
2621       errmsg = "Tethereal doesn't support writing capture files in that format.";
2622       break;
2623
2624     case WTAP_ERR_UNSUPPORTED_ENCAP:
2625       if (for_writing)
2626         errmsg = "Tethereal can't save this capture in that format.";
2627       else {
2628         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2629                  "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2630                  "(%s)", err_info);
2631         g_free(err_info);
2632         errmsg = errmsg_errno;
2633       }
2634       break;
2635
2636     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2637       if (for_writing)
2638         errmsg = "Tethereal can't save this capture in that format.";
2639       else
2640         errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2641       break;
2642
2643     case WTAP_ERR_BAD_RECORD:
2644       /* Seen only when opening a capture file for reading. */
2645       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2646                "The file \"%%s\" appears to be damaged or corrupt.\n"
2647                "(%s)", err_info);
2648       g_free(err_info);
2649       errmsg = errmsg_errno;
2650       break;
2651
2652     case WTAP_ERR_CANT_OPEN:
2653       if (for_writing)
2654         errmsg = "The file \"%s\" could not be created for some unknown reason.";
2655       else
2656         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2657       break;
2658
2659     case WTAP_ERR_SHORT_READ:
2660       errmsg = "The file \"%s\" appears to have been cut short"
2661                " in the middle of a packet or other data.";
2662       break;
2663
2664     case WTAP_ERR_SHORT_WRITE:
2665       errmsg = "A full header couldn't be written to the file \"%s\".";
2666       break;
2667
2668     default:
2669       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2670                "The file \"%%s\" could not be %s: %s.",
2671                for_writing ? "created" : "opened",
2672                wtap_strerror(err));
2673       errmsg = errmsg_errno;
2674       break;
2675     }
2676   } else
2677     errmsg = file_open_error_message(err, for_writing);
2678   return errmsg;
2679 }
2680
2681 /*
2682  * Open/create errors are reported with an console message in Tethereal.
2683  */
2684 static void
2685 open_failure_message(const char *filename, int err, gboolean for_writing)
2686 {
2687   fprintf(stderr, "tethereal: ");
2688   fprintf(stderr, file_open_error_message(err, for_writing), filename);
2689   fprintf(stderr, "\n");
2690 }
2691
2692 cf_status_t
2693 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2694 {
2695   wtap       *wth;
2696   gchar       *err_info;
2697   char        err_msg[2048+1];
2698
2699   wth = wtap_open_offline(fname, err, &err_info, FALSE);
2700   if (wth == NULL)
2701     goto fail;
2702
2703   /* The open succeeded.  Fill in the information for this file. */
2704
2705   /* Initialize all data structures used for dissection. */
2706   init_dissection();
2707
2708   cf->wth = wth;
2709   cf->f_datalen = 0;    /* not used, but set it anyway */
2710
2711   /* Set the file name because we need it to set the follow stream filter.
2712      XXX - is that still true?  We need it for other reasons, though,
2713      in any case. */
2714   cf->filename = g_strdup(fname);
2715
2716   /* Indicate whether it's a permanent or temporary file. */
2717   cf->is_tempfile = is_tempfile;
2718
2719   /* If it's a temporary capture buffer file, mark it as not saved. */
2720   cf->user_saved = !is_tempfile;
2721
2722   cf->cd_t      = wtap_file_type(cf->wth);
2723   cf->count     = 0;
2724   cf->drops_known = FALSE;
2725   cf->drops     = 0;
2726   cf->snap      = wtap_snapshot_length(cf->wth);
2727   if (cf->snap == 0) {
2728     /* Snapshot length not known. */
2729     cf->has_snap = FALSE;
2730     cf->snap = WTAP_MAX_PACKET_SIZE;
2731   } else
2732     cf->has_snap = TRUE;
2733   nstime_set_zero(&cf->elapsed_time);
2734   nstime_set_zero(&first_ts);
2735   nstime_set_zero(&prev_ts);
2736
2737   return CF_OK;
2738
2739 fail:
2740   g_snprintf(err_msg, sizeof err_msg,
2741            cf_open_error_message(*err, err_info, FALSE, 0), fname);
2742   cmdarg_err("%s", err_msg);
2743   return CF_ERROR;
2744 }
2745
2746
2747 /*
2748  * General errors are reported with an console message in Tethereal.
2749  */
2750 static void
2751 failure_message(const char *msg_format, va_list ap)
2752 {
2753   fprintf(stderr, "tethereal: ");
2754   vfprintf(stderr, msg_format, ap);
2755   fprintf(stderr, "\n");
2756 }
2757
2758 /*
2759  * Read errors are reported with an console message in Tethereal.
2760  */
2761 static void
2762 read_failure_message(const char *filename, int err)
2763 {
2764   cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2765           filename, strerror(err));
2766 }
2767
2768 /*
2769  * Report an error in command-line arguments.
2770  */
2771 void
2772 cmdarg_err(const char *fmt, ...)
2773 {
2774   va_list ap;
2775
2776   va_start(ap, fmt);
2777   fprintf(stderr, "tethereal: ");
2778   vfprintf(stderr, fmt, ap);
2779   fprintf(stderr, "\n");
2780   va_end(ap);
2781 }
2782
2783 /*
2784  * Report additional information for an error in command-line arguments.
2785  */
2786 void
2787 cmdarg_err_cont(const char *fmt, ...)
2788 {
2789   va_list ap;
2790
2791   va_start(ap, fmt);
2792   vfprintf(stderr, fmt, ap);
2793   fprintf(stderr, "\n");
2794   va_end(ap);
2795 }
2796
2797
2798 /****************************************************************************************************************/
2799 /* sync pipe "dummies", needed for capture_loop.c */
2800
2801 #ifdef HAVE_LIBPCAP
2802
2803 /** the child has opened a new capture file, notify the parent */
2804 void
2805 sync_pipe_filename_to_parent(const char *filename)
2806 {
2807     /* shouldn't happen */
2808     g_assert(0);
2809 }
2810
2811 /** the child captured some new packets, notify the parent */
2812 void
2813 sync_pipe_packet_count_to_parent(int packet_count)
2814 {
2815     /* shouldn't happen */
2816     g_assert(0);
2817 }
2818
2819 /** the child stopped capturing, notify the parent */
2820 void
2821 sync_pipe_drops_to_parent(int drops)
2822 {
2823     /* shouldn't happen */
2824     g_assert(0);
2825 }
2826
2827 /** the child encountered an error, notify the parent */
2828 void 
2829 sync_pipe_errmsg_to_parent(const char *errmsg)
2830 {
2831     cmdarg_err(errmsg);
2832 }
2833
2834 #endif /* HAVE_LIBPCAP */
2835
2836
2837 /****************************************************************************************************************/
2838 /* simple_dialog "dummies", needed for capture_loop.c */
2839
2840
2841 #ifdef HAVE_LIBPCAP
2842
2843 char *simple_dialog_primary_start(void)
2844 {
2845     return "";
2846 }
2847
2848 char *simple_dialog_primary_end(void)
2849 {
2850     return "";
2851 }
2852
2853
2854 /* XXX - do we need to convert the string for the console? */
2855 char *
2856 simple_dialog_format_message(const char *msg)
2857 {
2858     char *str;
2859
2860
2861     if (msg) {
2862 #if GTK_MAJOR_VERSION < 2
2863         str = g_strdup(msg);
2864 #else
2865         str = xml_escape(msg);
2866 #endif
2867     } else {
2868         str = NULL;
2869     }
2870     return str;
2871 }
2872
2873 #endif /* HAVE_LIBPCAP */
2874
2875