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