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