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