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