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