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