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