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