1) Allow for the possibility for both packet summary and packet details to be
[jelmer/wireshark.git] / tshark.c
1 /* tshark.c
2  *
3  * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4  * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
5  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  */
26
27 #include "config.h"
28
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <locale.h>
34 #include <limits.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 #include <errno.h>
41
42 #ifdef HAVE_FCNTL_H
43 #include <fcntl.h>
44 #endif
45
46 #include <signal.h>
47
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
50 #endif
51
52 #ifndef HAVE_GETOPT
53 #include "wsutil/wsgetopt.h"
54 #endif
55
56 #include <glib.h>
57 #include <epan/epan.h>
58 #include <epan/filesystem.h>
59 #include <wsutil/privileges.h>
60 #include <wsutil/file_util.h>
61
62 #include "globals.h"
63 #include <epan/timestamp.h>
64 #include <epan/packet.h>
65 #include "file.h"
66 #include "disabled_protos.h"
67 #include <epan/prefs.h>
68 #include <epan/column.h>
69 #include "print.h"
70 #include <epan/addr_resolv.h>
71 #include "ui/util.h"
72 #include "clopts_common.h"
73 #include "console_io.h"
74 #include "cmdarg_err.h"
75 #include "version_info.h"
76 #include <epan/plugins.h>
77 #include "register.h"
78 #include <epan/epan_dissect.h>
79 #include <epan/tap.h>
80 #include <epan/stat_cmd_args.h>
81 #include <epan/timestamp.h>
82 #include <epan/ex-opt.h>
83
84 #ifdef HAVE_LIBPCAP
85 #include "capture_ui_utils.h"
86 #include "capture_ifinfo.h"
87 #include "capture-pcap-util.h"
88 #ifdef _WIN32
89 #include "capture-wpcap.h"
90 #include <wsutil/unicode-utils.h>
91 #endif /* _WIN32 */
92 #include "capture_sync.h"
93 #endif /* HAVE_LIBPCAP */
94 #include "log.h"
95 #include <epan/funnel.h>
96 #include "capture_opts.h"
97
98 /*
99  * This is the template for the decode as option; it is shared between the
100  * various functions that output the usage for this parameter.
101  */
102 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
103
104 static guint32 cum_bytes;
105 static nstime_t first_ts;
106 static frame_data *prev_dis;
107 static frame_data prev_dis_frame;
108 static frame_data *prev_cap;
109 static frame_data prev_cap_frame;
110
111 static const char* prev_display_dissector_name = NULL;
112
113 static gboolean perform_two_pass_analysis;
114
115 /*
116  * The way the packet decode is to be written.
117  */
118 typedef enum {
119   WRITE_TEXT,   /* summary or detail text */
120   WRITE_XML,    /* PDML or PSML */
121   WRITE_FIELDS  /* User defined list of fields */
122   /* Add CSV and the like here */
123 } output_action_e;
124
125 static output_action_e output_action;
126 static gboolean do_dissection;  /* TRUE if we have to dissect each packet */
127 static gboolean print_packet_info;/* TRUE if we're to print packet information */
128 static gint print_summary = -1; /* TRUE if we're to print packet summary information */
129 static gboolean print_details;  /* TRUE if we're to print packet details information */
130 static gboolean print_hex;      /* TRUE if we're to print hex/ascci information */
131 static gboolean line_buffered;
132
133 static print_format_e print_format = PR_FMT_TEXT;
134 static print_stream_t *print_stream;
135
136 static output_fields_t* output_fields  = NULL;
137
138 /* The line separator used between packets, changeable via the -S option */
139 static char *separator = "";
140
141 #ifdef HAVE_LIBPCAP
142 /*
143  * TRUE if we're to print packet counts to keep track of captured packets.
144  */
145 static gboolean print_packet_counts;
146
147 static capture_options global_capture_opts;
148
149 #ifdef SIGINFO
150 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
151 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
152 #endif /* SIGINFO */
153
154 static gboolean capture(void);
155 static void report_counts(void);
156 #ifdef _WIN32
157 static BOOL WINAPI capture_cleanup(DWORD);
158 #else /* _WIN32 */
159 static void capture_cleanup(int);
160 #ifdef SIGINFO
161 static void report_counts_siginfo(int);
162 #endif /* SIGINFO */
163 #endif /* _WIN32 */
164 #endif /* HAVE_LIBPCAP */
165
166 static int load_cap_file(capture_file *, char *, int, gboolean, int, gint64);
167 static gboolean process_packet(capture_file *cf, gint64 offset,
168     struct wtap_pkthdr *whdr,
169     const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
170 static void show_capture_file_io_error(const char *, int, gboolean);
171 static void show_print_file_io_error(int err);
172 static gboolean write_preamble(capture_file *cf);
173 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
174 static gboolean write_finale(void);
175 static const char *cf_open_error_message(int err, gchar *err_info,
176     gboolean for_writing, int file_type);
177
178 static void open_failure_message(const char *filename, int err,
179     gboolean for_writing);
180 static void failure_message(const char *msg_format, va_list ap);
181 static void read_failure_message(const char *filename, int err);
182 static void write_failure_message(const char *filename, int err);
183
184 capture_file cfile;
185
186 struct string_elem {
187   const char *sstr;   /* The short string */
188   const char *lstr;   /* The long string */
189 };
190
191 static gint
192 string_compare(gconstpointer a, gconstpointer b)
193 {
194   return strcmp(((const struct string_elem *)a)->sstr,
195                 ((const struct string_elem *)b)->sstr);
196 }
197
198 static void
199 string_elem_print(gpointer data, gpointer not_used _U_)
200 {
201   fprintf(stderr, "    %s - %s\n",
202           ((struct string_elem *)data)->sstr,
203           ((struct string_elem *)data)->lstr);
204 }
205
206 static void
207 list_capture_types(void) {
208   int i;
209   struct string_elem *captypes;
210   GSList *list = NULL;
211
212   captypes = g_malloc(sizeof(struct string_elem) * WTAP_NUM_FILE_TYPES);
213
214   fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
215   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
216     if (wtap_dump_can_open(i)) {
217       captypes[i].sstr = wtap_file_type_short_string(i);
218       captypes[i].lstr = wtap_file_type_string(i);
219       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
220     }
221   }
222   g_slist_foreach(list, string_elem_print, NULL);
223   g_slist_free(list);
224   g_free(captypes);
225 }
226
227 static void
228 print_usage(gboolean print_ver)
229 {
230   FILE *output;
231
232   if (print_ver) {
233     output = stdout;
234     fprintf(output,
235         "TShark " VERSION "%s\n"
236         "Dump and analyze network traffic.\n"
237         "See http://www.wireshark.org for more information.\n"
238         "\n"
239         "%s",
240          wireshark_svnversion, get_copyright_info());
241   } else {
242     output = stderr;
243   }
244   fprintf(output, "\n");
245   fprintf(output, "Usage: tshark [options] ...\n");
246   fprintf(output, "\n");
247
248 #ifdef HAVE_LIBPCAP
249   fprintf(output, "Capture interface:\n");
250   fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
251   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
252   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
253   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
254 #ifdef HAVE_PCAP_CREATE
255   fprintf(output, "  -I                       capture in monitor mode, if available\n");
256 #endif
257 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
258   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: 1MB)\n");
259 #endif
260   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
261   fprintf(output, "  -D                       print list of interfaces and exit\n");
262   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
263   fprintf(output, "\n");
264   fprintf(output, "Capture stop conditions:\n");
265   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
266   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
267   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
268   fprintf(output, "                              files:NUM - stop after NUM files\n");
269   /*fprintf(output, "\n");*/
270   fprintf(output, "Capture output:\n");
271   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
272   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
273   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
274 #endif  /* HAVE_LIBPCAP */
275 #ifdef HAVE_PCAP_REMOTE
276   fprintf(output, "RPCAP options:\n");
277   fprintf(output, "  -A <user>:<password>     use RPCAP password authentication\n");
278 #endif
279   /*fprintf(output, "\n");*/
280   fprintf(output, "Input file:\n");
281   fprintf(output, "  -r <infile>              set the filename to read from (no pipes or stdin!)\n");
282
283   fprintf(output, "\n");
284   fprintf(output, "Processing:\n");
285   fprintf(output, "  -2                       perform a two-pass analysis\n");
286   fprintf(output, "  -R <read filter>         packet filter in Wireshark display filter syntax\n");
287   fprintf(output, "  -n                       disable all name resolutions (def: all enabled)\n");
288   fprintf(output, "  -N <name resolve flags>  enable specific name resolution(s): \"mntC\"\n");
289   fprintf(output, "  -d %s ...\n", decode_as_arg_template);
290   fprintf(output, "                           \"Decode As\", see the man page for details\n");
291   fprintf(output, "                           Example: tcp.port==8888,http\n");
292   fprintf(output, "  -H <hosts file>          read a list of entries from a hosts file, which will\n");
293   fprintf(output, "                           then be written to a capture file. (Implies -W n)\n");
294
295   /*fprintf(output, "\n");*/
296   fprintf(output, "Output:\n");
297   fprintf(output, "  -w <outfile|->           write packets to a pcap-format file named \"outfile\"\n");
298   fprintf(output, "                           (or to the standard output for \"-\")\n");
299   fprintf(output, "  -C <config profile>      start with specified configuration profile\n");
300   fprintf(output, "  -F <output file type>    set the output file type, default is pcapng\n");
301   fprintf(output, "                           an empty \"-F\" option will list the file types\n");
302   fprintf(output, "  -V                       add output of packet tree        (Packet Details)\n");
303   fprintf(output, "  -O <protocols>           Only show packet details of these protocols, comma\n");
304   fprintf(output, "                           separated\n");
305   fprintf(output, "  -P                       print packet summary even when writing to a file\n");
306   fprintf(output, "  -S <separator>           the line separator to print between packets\n");
307   fprintf(output, "  -x                       add output of hex and ASCII dump (Packet Bytes)\n");
308   fprintf(output, "  -T pdml|ps|psml|text|fields\n");
309   fprintf(output, "                           format of text output (def: text)\n");
310   fprintf(output, "  -e <field>               field to print if -Tfields selected (e.g. tcp.port);\n");
311   fprintf(output, "                           this option can be repeated to print multiple fields\n");
312   fprintf(output, "  -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
313   fprintf(output, "     header=y|n            switch headers on and off\n");
314   fprintf(output, "     separator=/t|/s|<char> select tab, space, printable character as separator\n");
315   fprintf(output, "     occurrence=f|l|a      print first, last or all occurrences of each field\n");
316   fprintf(output, "     aggregator=,|/s|<char> select comma, space, printable character as\n");
317   fprintf(output, "                           aggregator\n");
318   fprintf(output, "     quote=d|s|n           select double, single, no quotes for values\n");
319   fprintf(output, "  -t ad|a|r|d|dd|e         output format of time stamps (def: r: rel. to first)\n");
320   fprintf(output, "  -u s|hms                 output format of seconds (def: s: seconds)\n");
321   fprintf(output, "  -l                       flush standard output after each packet\n");
322   fprintf(output, "  -q                       be more quiet on stdout (e.g. when using statistics)\n");
323   fprintf(output, "  -W n                     Save extra information in the file, if supported.\n");
324   fprintf(output, "                           n = write network address resolution information\n");
325   fprintf(output, "  -X <key>:<value>         eXtension options, see the man page for details\n");
326   fprintf(output, "  -z <statistics>          various statistics, see the man page for details\n");
327
328   fprintf(output, "\n");
329   fprintf(output, "Miscellaneous:\n");
330   fprintf(output, "  -h                       display this help and exit\n");
331   fprintf(output, "  -v                       display version info and exit\n");
332   fprintf(output, "  -o <name>:<value> ...    override preference setting\n");
333   fprintf(output, "  -K <keytab>              keytab file to use for kerberos decryption\n");
334   fprintf(output, "  -G [report]              dump one of several available reports and exit\n");
335   fprintf(output, "                           default report=\"fields\"\n");
336   fprintf(output, "                           use \"-G ?\" for more help\n");
337 }
338
339 static void
340 glossary_option_help(void)
341 {
342   FILE *output;
343
344   output = stdout;
345
346   fprintf(output, "TShark " VERSION "%s\n", wireshark_svnversion);
347
348   fprintf(output, "\n");
349   fprintf(output, "Usage: tshark -G [report]\n");
350   fprintf(output, "\n");
351   fprintf(output, "Glossary table reports:\n");
352   fprintf(output, "  -G [fields]              dump glossary in original format and exit\n");
353   fprintf(output, "  -G fields2               dump glossary in format 2 and exit\n");
354   fprintf(output, "  -G fields3               dump glossary in format 3 and exit\n");
355   fprintf(output, "  -G protocols             dump protocols in registration database and exit\n");
356   fprintf(output, "  -G values                dump value, range, true/false strings and exit\n");
357   fprintf(output, "  -G ftypes                dump field type basic and descriptive names\n");
358   fprintf(output, "  -G decodes               dump \"layer type\"/\"decode as\" associations and exit\n");
359   fprintf(output, "  -G heuristic-decodes     dump heuristic dissector tables\n");
360   fprintf(output, "\n");
361   fprintf(output, "Preference reports:\n");
362   fprintf(output, "  -G defaultprefs          dump default preferences and exit\n");
363   fprintf(output, "  -G currentprefs          dump current preferences and exit\n");
364   fprintf(output, "\n");
365
366 }
367
368 /*
369  * For a dissector table, print on the stream described by output,
370  * its short name (which is what's used in the "-d" option) and its
371  * descriptive name.
372  */
373 static void
374 display_dissector_table_names(const char *table_name, const char *ui_name,
375                               gpointer output)
376 {
377   if ((prev_display_dissector_name == NULL) ||
378       (strcmp(prev_display_dissector_name, table_name) != 0)) {
379      fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
380      prev_display_dissector_name = table_name;
381   }
382 }
383
384 /*
385  * For a dissector handle, print on the stream described by output,
386  * the filter name (which is what's used in the "-d" option) and the full
387  * name for the protocol that corresponds to this handle.
388  */
389 static void
390 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
391 {
392   int                proto_id;
393   const gchar*       proto_filter_name;
394   const gchar*       proto_ui_name;
395
396   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
397
398   if (proto_id != -1) {
399     proto_filter_name = proto_get_protocol_filter_name(proto_id);
400     proto_ui_name =  proto_get_protocol_name(proto_id);
401     g_assert(proto_filter_name != NULL);
402     g_assert(proto_ui_name != NULL);
403
404     if ((prev_display_dissector_name == NULL) ||
405         (strcmp(prev_display_dissector_name, proto_filter_name) != 0)) {
406       fprintf((FILE *)output, "\t%s (%s)\n",
407               proto_filter_name,
408               proto_ui_name);
409        prev_display_dissector_name = proto_filter_name;
410     }
411   }
412 }
413
414 /*
415  * The protocol_name_search structure is used by find_protocol_name_func()
416  * to pass parameters and store results
417  */
418 struct protocol_name_search{
419   gchar              *searched_name;  /* Protocol filter name we are looking for */
420   dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
421   guint               nb_match;       /* How many dissectors matched searched_name */
422 };
423 typedef struct protocol_name_search *protocol_name_search_t;
424
425 /*
426  * This function parses all dissectors associated with a table to find the
427  * one whose protocol has the specified filter name.  It is called
428  * as a reference function in a call to dissector_table_foreach_handle.
429  * The name we are looking for, as well as the results, are stored in the
430  * protocol_name_search struct pointed to by user_data.
431  * If called using dissector_table_foreach_handle, we actually parse the
432  * whole list of dissectors.
433  */
434 static void
435 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
436
437 {
438   int                         proto_id;
439   const gchar                *protocol_filter_name;
440   protocol_name_search_t      search_info;
441
442   g_assert(handle);
443
444   search_info = (protocol_name_search_t)user_data;
445
446   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
447   if (proto_id != -1) {
448     protocol_filter_name = proto_get_protocol_filter_name(proto_id);
449     g_assert(protocol_filter_name != NULL);
450     if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
451       /* Found a match */
452       if (search_info->nb_match == 0) {
453         /* Record this handle only if this is the first match */
454         search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
455       }
456       search_info->nb_match++;
457     }
458   }
459 }
460
461 /*
462  * Allow dissector key names to be sorted alphabetically
463  */
464
465 static gint
466 compare_dissector_key_name(gconstpointer dissector_a, gconstpointer dissector_b)
467 {
468   return strcmp((const char*)dissector_a, (const char*)dissector_b);
469 }
470
471 /*
472  * Print all layer type names supported.
473  * We send the output to the stream described by the handle output.
474  */
475
476 static void
477 fprint_all_layer_types(FILE *output)
478
479 {
480   prev_display_dissector_name = NULL;
481   dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output, (GCompareFunc)compare_dissector_key_name);
482 }
483
484 /*
485  * Print all protocol names supported for a specific layer type.
486  * table_name contains the layer type name in which the search is performed.
487  * We send the output to the stream described by the handle output.
488  */
489
490 static void
491 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
492
493 {
494   prev_display_dissector_name = NULL;
495   dissector_table_foreach_handle(table_name,
496                                  display_dissector_names,
497                                  (gpointer)output);
498 }
499
500 /*
501  * The function below parses the command-line parameters for the decode as
502  * feature (a string pointer by cl_param).
503  * It checks the format of the command-line, searches for a matching table
504  * and dissector.  If a table/dissector match is not found, we display a
505  * summary of the available tables/dissectors (on stderr) and return FALSE.
506  * If everything is fine, we get the "Decode as" preference activated,
507  * then we return TRUE.
508  */
509 static gboolean
510 add_decode_as(const gchar *cl_param)
511 {
512   gchar                        *table_name;
513   guint32                       selector;
514   gchar                        *decoded_param;
515   gchar                        *remaining_param;
516   gchar                        *selector_str;
517   gchar                        *dissector_str;
518   dissector_handle_t            dissector_matching;
519   dissector_table_t             table_matching;
520   ftenum_t                      dissector_table_selector_type;
521   struct protocol_name_search   user_protocol_name;
522
523   /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
524
525   g_assert(cl_param);
526   decoded_param = g_strdup(cl_param);
527   g_assert(decoded_param);
528
529
530   /* The lines below will parse this string (modifying it) to extract all
531     necessary information.  Note that decoded_param is still needed since
532     strings are not copied - we just save pointers. */
533
534   /* This section extracts a layer type (table_name) from decoded_param */
535   table_name = decoded_param; /* Layer type string starts from beginning */
536
537   remaining_param = strchr(table_name, '=');
538   if (remaining_param == NULL) {
539     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
540     /* If the argument does not follow the template, carry on anyway to check
541        if the table name is at least correct.  If remaining_param is NULL,
542        we'll exit anyway further down */
543   }
544   else {
545     *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
546   }
547
548   /* Remove leading and trailing spaces from the table name */
549   while ( table_name[0] == ' ' )
550     table_name++;
551   while ( table_name[strlen(table_name) - 1] == ' ' )
552     table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
553
554 /* The following part searches a table matching with the layer type specified */
555   table_matching = NULL;
556
557 /* Look for the requested table */
558   if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
559     cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
560   }
561   else {
562     table_matching = find_dissector_table(table_name);
563     if (!table_matching) {
564       cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
565     }
566   }
567
568   if (!table_matching) {
569     /* Display a list of supported layer types to help the user, if the
570        specified layer type was not found */
571     cmdarg_err("Valid layer types are:");
572     fprint_all_layer_types(stderr);
573   }
574   if (remaining_param == NULL || !table_matching) {
575     /* Exit if the layer type was not found, or if no '=' separator was found
576        (see above) */
577     g_free(decoded_param);
578     return FALSE;
579   }
580
581   if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
582     cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
583   }
584   else {
585     remaining_param++; /* Move to the second '=' */
586     *remaining_param = '\0'; /* Remove the second '=' */
587   }
588   remaining_param++; /* Position after the layer type string */
589
590   /* This section extracts a selector value (selector_str) from decoded_param */
591
592   selector_str = remaining_param; /* Next part starts with the selector number */
593
594   remaining_param = strchr(selector_str, ',');
595   if (remaining_param == NULL) {
596     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
597     /* If the argument does not follow the template, carry on anyway to check
598        if the selector value is at least correct.  If remaining_param is NULL,
599        we'll exit anyway further down */
600   }
601   else {
602     *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
603   }
604
605   dissector_table_selector_type = get_dissector_table_selector_type(table_name);
606
607   switch (dissector_table_selector_type) {
608
609   case FT_UINT8:
610   case FT_UINT16:
611   case FT_UINT24:
612   case FT_UINT32:
613     /* The selector for this table is an unsigned number.  Parse it as such.
614        There's no need to remove leading and trailing spaces from the
615        selector number string, because sscanf will do that for us. */
616     if ( sscanf(selector_str, "%u", &selector) != 1 ) {
617       cmdarg_err("Invalid selector number \"%s\"", selector_str);
618       g_free(decoded_param);
619       return FALSE;
620     }
621     break;
622
623   case FT_STRING:
624   case FT_STRINGZ:
625     /* The selector for this table is a string. */
626     break;
627
628   default:
629     /* There are currently no dissector tables with any types other
630        than the ones listed above. */
631     g_assert_not_reached();
632   }
633
634   if (remaining_param == NULL) {
635     /* Exit if no ',' separator was found (see above) */
636     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
637     fprint_all_protocols_for_layer_types(stderr, table_name);
638     g_free(decoded_param);
639     return FALSE;
640   }
641
642   remaining_param++; /* Position after the selector number string */
643
644   /* This section extracts a protocol filter name (dissector_str) from decoded_param */
645
646   dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
647
648   /* Remove leading and trailing spaces from the dissector name */
649   while ( dissector_str[0] == ' ' )
650     dissector_str++;
651   while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
652     dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
653
654   dissector_matching = NULL;
655
656   /* We now have a pointer to the handle for the requested table inside the variable table_matching */
657   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 */
658     cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
659   }
660   else {
661     user_protocol_name.nb_match = 0;
662     user_protocol_name.searched_name = dissector_str;
663     user_protocol_name.matched_handle = NULL;
664
665     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 */
666
667     if (user_protocol_name.nb_match != 0) {
668       dissector_matching = user_protocol_name.matched_handle;
669       if (user_protocol_name.nb_match > 1) {
670         cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
671       }
672     }
673     else {
674       /* OK, check whether the problem is that there isn't any such
675          protocol, or that there is but it's not specified as a protocol
676          that's valid for that dissector table.
677          Note, we don't exit here, but dissector_matching will remain NULL,
678          so we exit below */
679       if (proto_get_id_by_filter_name(dissector_str) == -1) {
680         /* No such protocol */
681         cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
682       } else {
683         cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
684                    dissector_str, table_name);
685       }
686     }
687   }
688
689   if (!dissector_matching) {
690     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
691     fprint_all_protocols_for_layer_types(stderr, table_name);
692     g_free(decoded_param);
693     return FALSE;
694   }
695
696 /* This is the end of the code that parses the command-line options.
697    All information is now stored in the variables:
698    table_name
699    selector
700    dissector_matching
701    The above variables that are strings are still pointing to areas within
702    decoded_parm.  decoded_parm thus still needs to be kept allocated in
703    until we stop needing these variables
704    decoded_param will be deallocated at each exit point of this function */
705
706
707   /* We now have a pointer to the handle for the requested dissector
708      (requested protocol) inside the variable dissector_matching */
709   switch (dissector_table_selector_type) {
710
711   case FT_UINT8:
712   case FT_UINT16:
713   case FT_UINT24:
714   case FT_UINT32:
715     /* The selector for this table is an unsigned number. */
716     dissector_change_uint(table_name, selector, dissector_matching);
717     break;
718
719   case FT_STRING:
720   case FT_STRINGZ:
721     /* The selector for this table is a string. */
722     dissector_change_string(table_name, selector_str, dissector_matching);
723     break;
724
725   default:
726     /* There are currently no dissector tables with any types other
727        than the ones listed above. */
728     g_assert_not_reached();
729   }
730   g_free(decoded_param); /* "Decode As" rule has been successfully added */
731   return TRUE;
732 }
733
734 static void
735 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
736     const gchar *message, gpointer user_data)
737 {
738   /* ignore log message, if log_level isn't interesting based
739      upon the console log preferences.
740      If the preferences haven't been loaded loaded yet, display the
741      message anyway.
742
743      The default console_log_level preference value is such that only
744        ERROR, CRITICAL and WARNING level messages are processed;
745        MESSAGE, INFO and DEBUG level messages are ignored.
746
747      XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
748            ERROR and CRITICAL level messages so the current code is a behavioral
749            change.  The current behavior is the same as in Wireshark.
750   */
751   if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
752      prefs.console_log_level != 0) {
753     return;
754   }
755
756   g_log_default_handler(log_domain, log_level, message, user_data);
757
758 }
759
760 static char *
761 output_file_description(const char *fname)
762 {
763   char *save_file_string;
764
765   /* Get a string that describes what we're writing to */
766   if (strcmp(fname, "-") == 0) {
767     /* We're writing to the standard output */
768     save_file_string = g_strdup("standard output");
769   } else {
770     /* We're writing to a file with the name in save_file */
771     save_file_string = g_strdup_printf("file \"%s\"", fname);
772   }
773   return save_file_string;
774 }
775
776 static void
777 print_current_user(void) {
778   gchar *cur_user, *cur_group;
779   if (started_with_special_privs()) {
780     cur_user = get_cur_username();
781     cur_group = get_cur_groupname();
782     fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
783       cur_user, cur_group);
784     g_free(cur_user);
785     g_free(cur_group);
786     if (running_with_special_privs()) {
787       fprintf(stderr, " This could be dangerous.");
788     }
789     fprintf(stderr, "\n");
790   }
791 }
792
793 static void
794 check_capture_privs(void) {
795 #ifdef _WIN32
796   load_wpcap();
797   /* Warn the user if npf.sys isn't loaded. */
798   if (!npf_sys_is_running() && get_os_major_version() >= 6) {
799     fprintf(stderr, "The NPF driver isn't running.  You may have trouble "
800       "capturing or\nlisting interfaces.\n");
801   }
802 #endif
803 }
804
805 static void
806 show_version(GString *comp_info_str, GString *runtime_info_str)
807 {
808   printf("TShark " VERSION "%s\n"
809          "\n"
810          "%s"
811          "\n"
812          "%s"
813          "\n"
814          "%s",
815          wireshark_svnversion, get_copyright_info(), comp_info_str->str,
816          runtime_info_str->str);
817 }
818
819 int
820 main(int argc, char *argv[])
821 {
822   char                *init_progfile_dir_error;
823   int                  opt;
824   gboolean             arg_error = FALSE;
825
826 #ifdef _WIN32
827   WSADATA              wsaData;
828 #endif  /* _WIN32 */
829
830   char                *gpf_path, *pf_path;
831   char                *gdp_path, *dp_path;
832   int                  gpf_open_errno, gpf_read_errno;
833   int                  pf_open_errno, pf_read_errno;
834   int                  gdp_open_errno, gdp_read_errno;
835   int                  dp_open_errno, dp_read_errno;
836   int                  err;
837   volatile int         exit_status = 0;
838 #ifdef HAVE_LIBPCAP
839   gboolean             list_link_layer_types = FALSE;
840   gboolean             start_capture = FALSE;
841   int                  status;
842   GList               *if_list;
843   gchar               *err_str;
844   guint                i;
845   interface_options    interface_opts;
846 #else
847   gboolean             capture_option_specified = FALSE;
848 #endif
849   gboolean             quiet = FALSE;
850 #ifdef PCAP_NG_DEFAULT
851   volatile int         out_file_type = WTAP_FILE_PCAPNG;
852 #else
853   volatile int         out_file_type = WTAP_FILE_PCAP;
854 #endif
855   volatile gboolean    out_file_name_res = FALSE;
856   gchar               *volatile cf_name = NULL;
857   gchar               *rfilter = NULL;
858 #ifdef HAVE_PCAP_OPEN_DEAD
859   struct bpf_program   fcode;
860 #endif
861   dfilter_t           *rfcode = NULL;
862   e_prefs             *prefs_p;
863   char                 badopt;
864   GLogLevelFlags       log_flags;
865   int                  optind_initial;
866   gchar               *output_only = NULL;
867
868 #ifdef HAVE_PCAP_REMOTE
869 #define OPTSTRING_A "A:"
870 #else
871 #define OPTSTRING_A ""
872 #endif
873 #ifdef HAVE_LIBPCAP
874 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
875 #define OPTSTRING_B "B:"
876 #else
877 #define OPTSTRING_B ""
878 #endif  /* _WIN32 or HAVE_PCAP_CREATE */
879 #else /* HAVE_LIBPCAP */
880 #define OPTSTRING_B ""
881 #endif  /* HAVE_LIBPCAP */
882
883 #ifdef HAVE_PCAP_CREATE
884 #define OPTSTRING_I "I"
885 #else
886 #define OPTSTRING_I ""
887 #endif
888
889 #define OPTSTRING "2a:" OPTSTRING_A "b:" OPTSTRING_B "c:C:d:De:E:f:F:G:hH:i:" OPTSTRING_I "K:lLnN:o:O:pPqr:R:s:S:t:T:u:vVw:W:xX:y:z:"
890
891   static const char    optstring[] = OPTSTRING;
892
893 #ifdef _WIN32
894   arg_list_utf_16to8(argc, argv);
895 #if !GLIB_CHECK_VERSION(2,31,0)
896   g_thread_init(NULL);
897 #endif
898 #endif /* _WIN32 */
899
900   /*
901    * Get credential information for later use.
902    */
903   init_process_policies();
904
905   /*
906    * Attempt to get the pathname of the executable file.
907    */
908   init_progfile_dir_error = init_progfile_dir(argv[0], main);
909   if (init_progfile_dir_error != NULL) {
910     fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
911             init_progfile_dir_error);
912   }
913
914   /*
915    * In order to have the -X opts assigned before the wslua machine starts
916    * we need to call getopts before epan_init() gets called.
917    */
918   opterr = 0;
919   optind_initial = optind;
920
921   while ((opt = getopt(argc, argv, optstring)) != -1) {
922     switch (opt) {
923     case 'C':        /* Configuration Profile */
924       if (profile_exists (optarg, FALSE)) {
925         set_profile_name (optarg);
926       } else {
927         cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
928         return 1;
929       }
930       break;
931     case 'P':        /* Print packet summary info even when writing to a file */
932       print_packet_info = TRUE;
933       print_summary = TRUE;
934       break;
935     case 'O':        /* Only output these protocols */
936       output_only = g_strdup(optarg);
937       /* FALLTHROUGH */
938     case 'V':        /* Verbose */
939       print_details = TRUE;
940       print_packet_info = TRUE;
941       break;
942     case 'x':        /* Print packet data in hex (and ASCII) */
943       print_hex = TRUE;
944       /*  The user asked for hex output, so let's ensure they get it,
945        *  even if they're writing to a file.
946        */
947       print_packet_info = TRUE;
948       break;
949     case 'X':
950       ex_opt_add(optarg);
951       break;
952     default:
953       break;
954     }
955   }
956
957   /*
958    * Print packet summary information is the default, unless either -V or -x
959    * were specified and -P was not.  Note that this is new behavior, which
960    * allows for the possibility of printing only hex/ascii output without
961    * necessarily requiring that either the summary or details be printed too.
962    */
963   if (print_summary == -1)
964     print_summary = (print_details || print_hex) ? FALSE : TRUE;
965
966   optind = optind_initial;
967   opterr = 1;
968
969
970
971 /** Send All g_log messages to our own handler **/
972
973   log_flags =
974                     G_LOG_LEVEL_ERROR|
975                     G_LOG_LEVEL_CRITICAL|
976                     G_LOG_LEVEL_WARNING|
977                     G_LOG_LEVEL_MESSAGE|
978                     G_LOG_LEVEL_INFO|
979                     G_LOG_LEVEL_DEBUG|
980                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
981
982   g_log_set_handler(NULL,
983                     log_flags,
984                     tshark_log_handler, NULL /* user_data */);
985   g_log_set_handler(LOG_DOMAIN_MAIN,
986                     log_flags,
987                     tshark_log_handler, NULL /* user_data */);
988
989 #ifdef HAVE_LIBPCAP
990   g_log_set_handler(LOG_DOMAIN_CAPTURE,
991                     log_flags,
992                     tshark_log_handler, NULL /* user_data */);
993   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
994                     log_flags,
995                     tshark_log_handler, NULL /* user_data */);
996 #endif
997
998   initialize_funnel_ops();
999
1000 #ifdef HAVE_LIBPCAP
1001   capture_opts_init(&global_capture_opts, &cfile);
1002 #endif
1003
1004   timestamp_set_type(TS_RELATIVE);
1005   timestamp_set_precision(TS_PREC_AUTO);
1006   timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1007
1008   /* Register all dissectors; we must do this before checking for the
1009      "-G" flag, as the "-G" flag dumps information registered by the
1010      dissectors, and we must do it before we read the preferences, in
1011      case any dissectors register preferences. */
1012   epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
1013             failure_message, open_failure_message, read_failure_message,
1014             write_failure_message);
1015
1016   /* Register all tap listeners; we do this before we parse the arguments,
1017      as the "-z" argument can specify a registered tap. */
1018
1019   /* we register the plugin taps before the other taps because
1020      stats_tree taps plugins will be registered as tap listeners
1021      by stats_tree_stat.c and need to registered before that */
1022 #ifdef HAVE_PLUGINS
1023   register_all_plugin_tap_listeners();
1024 #endif
1025   register_all_tap_listeners();
1026
1027   /* If invoked with the "-G" flag, we dump out information based on
1028      the argument to the "-G" flag; if no argument is specified,
1029      for backwards compatibility we dump out a glossary of display
1030      filter symbols.
1031
1032      XXX - we do this here, for now, to support "-G" with no arguments.
1033      If none of our build or other processes uses "-G" with no arguments,
1034      we can just process it with the other arguments. */
1035   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
1036     proto_initialize_all_prefixes();
1037
1038     if (argc == 2)
1039       proto_registrar_dump_fields(1);
1040     else {
1041       if (strcmp(argv[2], "fields") == 0)
1042         proto_registrar_dump_fields(1);
1043       else if (strcmp(argv[2], "fields2") == 0)
1044         proto_registrar_dump_fields(2);
1045       else if (strcmp(argv[2], "fields3") == 0)
1046         proto_registrar_dump_fields(3);
1047       else if (strcmp(argv[2], "protocols") == 0)
1048         proto_registrar_dump_protocols();
1049       else if (strcmp(argv[2], "values") == 0)
1050         proto_registrar_dump_values();
1051       else if (strcmp(argv[2], "ftypes") == 0)
1052         proto_registrar_dump_ftypes();
1053       else if (strcmp(argv[2], "decodes") == 0)
1054         dissector_dump_decodes();
1055       else if (strcmp(argv[2], "heuristic-decodes") == 0)
1056         dissector_dump_heur_decodes();
1057       else if (strcmp(argv[2], "defaultprefs") == 0)
1058         write_prefs(NULL);
1059       else if (strcmp(argv[2], "plugins") == 0)
1060         plugins_dump_all();
1061       else if (strcmp(argv[2], "?") == 0)
1062         glossary_option_help();
1063       else if (strcmp(argv[2], "-?") == 0)
1064         glossary_option_help();
1065       else if (strcmp(argv[2], "currentprefs") == 0) {
1066         read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
1067             &pf_open_errno, &pf_read_errno, &pf_path);
1068         write_prefs(NULL);
1069       } else {
1070         cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
1071         return 1;
1072       }
1073     }
1074     return 0;
1075   }
1076
1077   /* Set the C-language locale to the native environment. */
1078   setlocale(LC_ALL, "");
1079
1080   prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
1081                      &pf_open_errno, &pf_read_errno, &pf_path);
1082   if (gpf_path != NULL) {
1083     if (gpf_open_errno != 0) {
1084       cmdarg_err("Can't open global preferences file \"%s\": %s.",
1085               pf_path, g_strerror(gpf_open_errno));
1086     }
1087     if (gpf_read_errno != 0) {
1088       cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
1089               pf_path, g_strerror(gpf_read_errno));
1090     }
1091   }
1092   if (pf_path != NULL) {
1093     if (pf_open_errno != 0) {
1094       cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
1095               g_strerror(pf_open_errno));
1096     }
1097     if (pf_read_errno != 0) {
1098       cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
1099               pf_path, g_strerror(pf_read_errno));
1100     }
1101     g_free(pf_path);
1102     pf_path = NULL;
1103   }
1104
1105   /* Read the disabled protocols file. */
1106   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
1107                             &dp_path, &dp_open_errno, &dp_read_errno);
1108   if (gdp_path != NULL) {
1109     if (gdp_open_errno != 0) {
1110       cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
1111                  gdp_path, g_strerror(gdp_open_errno));
1112     }
1113     if (gdp_read_errno != 0) {
1114       cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
1115                  gdp_path, g_strerror(gdp_read_errno));
1116     }
1117     g_free(gdp_path);
1118   }
1119   if (dp_path != NULL) {
1120     if (dp_open_errno != 0) {
1121       cmdarg_err(
1122         "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
1123         g_strerror(dp_open_errno));
1124     }
1125     if (dp_read_errno != 0) {
1126       cmdarg_err(
1127         "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
1128         g_strerror(dp_read_errno));
1129     }
1130     g_free(dp_path);
1131   }
1132
1133   check_capture_privs();
1134
1135   cap_file_init(&cfile);
1136
1137   /* Print format defaults to this. */
1138   print_format = PR_FMT_TEXT;
1139
1140   output_fields = output_fields_new();
1141
1142   /* Now get our args */
1143   while ((opt = getopt(argc, argv, optstring)) != -1) {
1144     switch (opt) {
1145     case '2':        /* Perform two pass analysis */
1146       perform_two_pass_analysis = TRUE;
1147       break;
1148     case 'a':        /* autostop criteria */
1149     case 'b':        /* Ringbuffer option */
1150     case 'c':        /* Capture x packets */
1151     case 'f':        /* capture filter */
1152     case 'i':        /* Use interface x */
1153     case 'p':        /* Don't capture in promiscuous mode */
1154 #ifdef HAVE_PCAP_REMOTE
1155     case 'A':        /* Authentication */
1156 #endif
1157 #ifdef HAVE_PCAP_CREATE
1158     case 'I':        /* Capture in monitor mode, if available */
1159 #endif
1160     case 's':        /* Set the snapshot (capture) length */
1161     case 'w':        /* Write to capture file x */
1162     case 'y':        /* Set the pcap data link type */
1163 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1164     case 'B':        /* Buffer size */
1165 #endif /* _WIN32 or HAVE_PCAP_CREATE */
1166 #ifdef HAVE_LIBPCAP
1167       status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1168       if(status != 0) {
1169         return status;
1170       }
1171 #else
1172       capture_option_specified = TRUE;
1173       arg_error = TRUE;
1174 #endif
1175       break;
1176     case 'C':
1177       /* Configuration profile settings were already processed just ignore them this time*/
1178       break;
1179     case 'd':        /* Decode as rule */
1180       if (!add_decode_as(optarg))
1181         return 1;
1182       break;
1183 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1184     case 'K':        /* Kerberos keytab file */
1185       read_keytab_file(optarg);
1186       break;
1187 #endif
1188     case 'D':        /* Print a list of capture devices and exit */
1189 #ifdef HAVE_LIBPCAP
1190       if_list = capture_interface_list(&err, &err_str);
1191       if (if_list == NULL) {
1192         switch (err) {
1193         case CANT_GET_INTERFACE_LIST:
1194         case DONT_HAVE_PCAP:
1195           cmdarg_err("%s", err_str);
1196           g_free(err_str);
1197           break;
1198
1199         case NO_INTERFACES_FOUND:
1200           cmdarg_err("There are no interfaces on which a capture can be done");
1201           break;
1202         }
1203         return 2;
1204       }
1205       capture_opts_print_interfaces(if_list);
1206       free_interface_list(if_list);
1207       return 0;
1208 #else
1209       capture_option_specified = TRUE;
1210       arg_error = TRUE;
1211 #endif
1212       break;
1213     case 'e':
1214       /* Field entry */
1215       output_fields_add(output_fields, optarg);
1216       break;
1217     case 'E':
1218       /* Field option */
1219       if(!output_fields_set_option(output_fields, optarg)) {
1220         cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1221         output_fields_list_options(stderr);
1222         return 1;
1223       }
1224       break;
1225     case 'F':
1226       out_file_type = wtap_short_string_to_file_type(optarg);
1227       if (out_file_type < 0) {
1228         cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1229         list_capture_types();
1230         return 1;
1231       }
1232       break;
1233     case 'W':        /* Select extra information to save in our capture file */
1234       /* This is patterned after the -N flag which may not be the best idea. */
1235       if (strchr(optarg, 'n'))
1236         out_file_name_res = TRUE;
1237       break;
1238     case 'H':        /* Read address to name mappings from a hosts file */
1239       if (! read_hosts_file(optarg))
1240       {
1241         cmdarg_err("Can't read host entries from \"%s\"", optarg);
1242         return 1;
1243       }
1244       out_file_name_res = TRUE;
1245       break;
1246
1247     case 'h':        /* Print help and exit */
1248       print_usage(TRUE);
1249       return 0;
1250       break;
1251     case 'l':        /* "Line-buffer" standard output */
1252       /* This isn't line-buffering, strictly speaking, it's just
1253          flushing the standard output after the information for
1254          each packet is printed; however, that should be good
1255          enough for all the purposes to which "-l" is put (and
1256          is probably actually better for "-V", as it does fewer
1257          writes).
1258
1259          See the comment in "process_packet()" for an explanation of
1260          why we do that, and why we don't just use "setvbuf()" to
1261          make the standard output line-buffered (short version: in
1262          Windows, "line-buffered" is the same as "fully-buffered",
1263          and the output buffer is only flushed when it fills up). */
1264       line_buffered = TRUE;
1265       break;
1266     case 'L':        /* Print list of link-layer types and exit */
1267 #ifdef HAVE_LIBPCAP
1268       list_link_layer_types = TRUE;
1269 #else
1270       capture_option_specified = TRUE;
1271       arg_error = TRUE;
1272 #endif
1273       break;
1274     case 'n':        /* No name resolution */
1275       gbl_resolv_flags.mac_name = FALSE;
1276       gbl_resolv_flags.network_name = FALSE;
1277       gbl_resolv_flags.transport_name = FALSE;
1278       gbl_resolv_flags.concurrent_dns = FALSE;
1279       break;
1280     case 'N':        /* Select what types of addresses/port #s to resolve */
1281       badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1282       if (badopt != '\0') {
1283         cmdarg_err("-N specifies unknown resolving option '%c';",
1284                    badopt);
1285         cmdarg_err_cont( "           Valid options are 'm', 'n', 't', and 'C'");
1286         return 1;
1287       }
1288       break;
1289     case 'o':        /* Override preference from command line */
1290       switch (prefs_set_pref(optarg)) {
1291
1292       case PREFS_SET_OK:
1293         break;
1294
1295       case PREFS_SET_SYNTAX_ERR:
1296         cmdarg_err("Invalid -o flag \"%s\"", optarg);
1297         return 1;
1298         break;
1299
1300       case PREFS_SET_NO_SUCH_PREF:
1301       case PREFS_SET_OBSOLETE:
1302         cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1303         return 1;
1304         break;
1305       }
1306       break;
1307     case 'q':        /* Quiet */
1308       quiet = TRUE;
1309       break;
1310     case 'r':        /* Read capture file x */
1311       cf_name = g_strdup(optarg);
1312       break;
1313     case 'R':        /* Read file filter */
1314       rfilter = optarg;
1315       break;
1316     case 'P':
1317         /* already processed; just ignore it now */
1318         break;
1319     case 'S':        /* Set the line Separator to be printed between packets */
1320       separator = strdup(optarg);
1321       break;
1322     case 't':        /* Time stamp type */
1323       if (strcmp(optarg, "r") == 0)
1324         timestamp_set_type(TS_RELATIVE);
1325       else if (strcmp(optarg, "a") == 0)
1326         timestamp_set_type(TS_ABSOLUTE);
1327       else if (strcmp(optarg, "ad") == 0)
1328         timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1329       else if (strcmp(optarg, "d") == 0)
1330         timestamp_set_type(TS_DELTA);
1331       else if (strcmp(optarg, "dd") == 0)
1332         timestamp_set_type(TS_DELTA_DIS);
1333       else if (strcmp(optarg, "e") == 0)
1334         timestamp_set_type(TS_EPOCH);
1335       else if (strcmp(optarg, "u") == 0)
1336         timestamp_set_type(TS_UTC);
1337       else if (strcmp(optarg, "ud") == 0)
1338         timestamp_set_type(TS_UTC_WITH_DATE);
1339       else {
1340         cmdarg_err("Invalid time stamp type \"%s\"",
1341                    optarg);
1342         cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1343         cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1344         return 1;
1345       }
1346       break;
1347     case 'T':        /* printing Type */
1348       if (strcmp(optarg, "text") == 0) {
1349         output_action = WRITE_TEXT;
1350         print_format = PR_FMT_TEXT;
1351       } else if (strcmp(optarg, "ps") == 0) {
1352         output_action = WRITE_TEXT;
1353         print_format = PR_FMT_PS;
1354       } else if (strcmp(optarg, "pdml") == 0) {
1355         output_action = WRITE_XML;
1356         print_details = TRUE;   /* Need details */
1357         print_summary = FALSE;  /* Don't allow summary */
1358       } else if (strcmp(optarg, "psml") == 0) {
1359         output_action = WRITE_XML;
1360         print_details = FALSE;  /* Don't allow details */
1361         print_summary = TRUE;   /* Need summary */
1362       } else if(strcmp(optarg, "fields") == 0) {
1363         output_action = WRITE_FIELDS;
1364         print_details = TRUE;   /* Need full tree info */
1365         print_summary = FALSE;  /* Don't allow summary */
1366       } else {
1367         cmdarg_err("Invalid -T parameter.");
1368         cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1369         return 1;
1370       }
1371       break;
1372     case 'u':        /* Seconds type */
1373       if (strcmp(optarg, "s") == 0)
1374         timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1375       else if (strcmp(optarg, "hms") == 0)
1376         timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1377       else {
1378         cmdarg_err("Invalid seconds type \"%s\"", optarg);
1379         cmdarg_err_cont("It must be \"s\" for seconds or \"hms\" for hours, minutes and seconds.");
1380         return 1;
1381       }
1382       break;
1383     case 'v':         /* Show version and exit */
1384     {
1385       GString             *comp_info_str;
1386       GString             *runtime_info_str;
1387       /* Assemble the compile-time version information string */
1388       comp_info_str = g_string_new("Compiled ");
1389       get_compiled_version_info(comp_info_str, NULL, epan_get_compiled_version_info);
1390
1391       /* Assemble the run-time version information string */
1392       runtime_info_str = g_string_new("Running ");
1393       get_runtime_version_info(runtime_info_str, NULL);
1394       show_version(comp_info_str, runtime_info_str);
1395       g_string_free(comp_info_str, TRUE);
1396       g_string_free(runtime_info_str, TRUE);
1397       return 0;
1398     }
1399     case 'O':        /* Only output these protocols */
1400       /* already processed; just ignore it now */
1401       break;
1402     case 'V':        /* Verbose */
1403       /* already processed; just ignore it now */
1404       break;
1405     case 'x':        /* Print packet data in hex (and ASCII) */
1406       /* already processed; just ignore it now */
1407       break;
1408     case 'X':
1409       break;
1410     case 'z':
1411       /* We won't call the init function for the stat this soon
1412          as it would disallow MATE's fields (which are registered
1413          by the preferences set callback) from being used as
1414          part of a tap filter.  Instead, we just add the argument
1415          to a list of stat arguments. */
1416       if (!process_stat_cmd_arg(optarg)) {
1417         cmdarg_err("invalid -z argument.");
1418         cmdarg_err_cont("  -z argument must be one of :");
1419         list_stat_cmd_args();
1420         return 1;
1421       }
1422       break;
1423     default:
1424     case '?':        /* Bad flag - print usage message */
1425       switch(optopt) {
1426       case 'F':
1427         list_capture_types();
1428         break;
1429       default:
1430         print_usage(TRUE);
1431       }
1432       return 1;
1433       break;
1434     }
1435   }
1436
1437   /* If we specified output fields, but not the output field type... */
1438   if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1439         cmdarg_err("Output fields were specified with \"-e\", "
1440             "but \"-Tfields\" was not specified.");
1441         return 1;
1442   } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1443         cmdarg_err("\"-Tfields\" was specified, but no fields were "
1444                     "specified with \"-e\".");
1445
1446         return 1;
1447   }
1448
1449   /* If no capture filter or read filter has been specified, and there are
1450      still command-line arguments, treat them as the tokens of a capture
1451      filter (if no "-r" flag was specified) or a read filter (if a "-r"
1452      flag was specified. */
1453   if (optind < argc) {
1454     if (cf_name != NULL) {
1455       if (rfilter != NULL) {
1456         cmdarg_err("Read filters were specified both with \"-R\" "
1457             "and with additional command-line arguments.");
1458         return 1;
1459       }
1460       rfilter = get_args_as_string(argc, argv, optind);
1461     } else {
1462 #ifdef HAVE_LIBPCAP
1463       if (global_capture_opts.default_options.cfilter) {
1464         cmdarg_err("A default capture filter was specified both with \"-f\""
1465             " and with additional command-line arguments.");
1466         return 1;
1467       }
1468       for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1469         interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1470         if (interface_opts.cfilter == NULL) {
1471           interface_opts.cfilter = get_args_as_string(argc, argv, optind);
1472           global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
1473           g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
1474         } else {
1475           cmdarg_err("A capture filter was specified both with \"-f\""
1476               " and with additional command-line arguments.");
1477           return 1;
1478         }
1479       }
1480       global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1481 #else
1482       capture_option_specified = TRUE;
1483 #endif
1484     }
1485   }
1486
1487 #ifdef HAVE_LIBPCAP
1488   if (!global_capture_opts.saving_to_file) {
1489     /* We're not saving the capture to a file; if "-q" wasn't specified,
1490        we should print packet information */
1491     if (!quiet)
1492       print_packet_info = TRUE;
1493   } else {
1494     /* We're saving to a file; if we're writing to the standard output.
1495        and we'll also be writing dissected packets to the standard
1496        output, reject the request.  At best, we could redirect that
1497        to the standard error; we *can't* write both to the standard
1498        output and have either of them be useful. */
1499     if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1500       cmdarg_err("You can't write both raw packet data and dissected packets"
1501           " to the standard output.");
1502       return 1;
1503     }
1504   }
1505 #else
1506   /* We're not saving the capture to a file; if "-q" wasn't specified,
1507      we should print packet information */
1508   if (!quiet)
1509     print_packet_info = TRUE;
1510 #endif
1511
1512 #ifndef HAVE_LIBPCAP
1513   if (capture_option_specified)
1514     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1515 #endif
1516   if (arg_error) {
1517     print_usage(FALSE);
1518     return 1;
1519   }
1520
1521   /* We don't support capture filters when reading from a capture file
1522      (the BPF compiler doesn't support all link-layer types that we
1523      support in capture files we read). */
1524 #ifdef HAVE_LIBPCAP
1525   if (cf_name != NULL) {
1526     if (global_capture_opts.default_options.cfilter) {
1527       cmdarg_err("Only read filters, not capture filters, "
1528           "can be specified when reading a capture file.");
1529       return 1;
1530     }
1531   }
1532 #endif
1533
1534   if (print_hex) {
1535     if (output_action != WRITE_TEXT) {
1536       cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1537       return 1;
1538     }
1539   }
1540
1541   if (output_only != NULL) {
1542     char *ps;
1543
1544     if (!print_details) {
1545       cmdarg_err("-O requires -V");
1546       return 1;
1547     }
1548
1549     output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1550     for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1551       g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1552     }
1553   }
1554
1555 #ifdef HAVE_LIBPCAP
1556   if (list_link_layer_types) {
1557     /* We're supposed to list the link-layer types for an interface;
1558        did the user also specify a capture file to be read? */
1559     if (cf_name) {
1560       /* Yes - that's bogus. */
1561       cmdarg_err("You can't specify -L and a capture file to be read.");
1562       return 1;
1563     }
1564     /* No - did they specify a ring buffer option? */
1565     if (global_capture_opts.multi_files_on) {
1566       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1567       return 1;
1568     }
1569   } else {
1570     if (cf_name) {
1571       /*
1572        * "-r" was specified, so we're reading a capture file.
1573        * Capture options don't apply here.
1574        */
1575       if (global_capture_opts.multi_files_on) {
1576         cmdarg_err("Multiple capture files requested, but "
1577                    "a capture isn't being done.");
1578         return 1;
1579       }
1580       if (global_capture_opts.has_file_duration) {
1581         cmdarg_err("Switching capture files after a time interval was specified, but "
1582                    "a capture isn't being done.");
1583         return 1;
1584       }
1585       if (global_capture_opts.has_ring_num_files) {
1586         cmdarg_err("A ring buffer of capture files was specified, but "
1587           "a capture isn't being done.");
1588         return 1;
1589       }
1590       if (global_capture_opts.has_autostop_files) {
1591         cmdarg_err("A maximum number of capture files was specified, but "
1592           "a capture isn't being done.");
1593         return 1;
1594       }
1595
1596       /* Note: TShark now allows the restriction of a _read_ file by packet count
1597        * and byte count as well as a write file. Other autostop options remain valid
1598        * only for a write file.
1599        */
1600       if (global_capture_opts.has_autostop_duration) {
1601         cmdarg_err("A maximum capture time was specified, but "
1602           "a capture isn't being done.");
1603         return 1;
1604       }
1605     } else {
1606       /*
1607        * "-r" wasn't specified, so we're doing a live capture.
1608        */
1609       if (global_capture_opts.saving_to_file) {
1610         /* They specified a "-w" flag, so we'll be saving to a capture file. */
1611
1612         /* When capturing, we only support writing pcap or pcap-ng format. */
1613         if (out_file_type != WTAP_FILE_PCAP && out_file_type != WTAP_FILE_PCAPNG) {
1614           cmdarg_err("Live captures can only be saved in libpcap format.");
1615           return 1;
1616         }
1617         if (global_capture_opts.multi_files_on) {
1618           /* Multiple-file mode doesn't work under certain conditions:
1619              a) it doesn't work if you're writing to the standard output;
1620              b) it doesn't work if you're writing to a pipe;
1621           */
1622           if (strcmp(global_capture_opts.save_file, "-") == 0) {
1623             cmdarg_err("Multiple capture files requested, but "
1624               "the capture is being written to the standard output.");
1625             return 1;
1626           }
1627           if (global_capture_opts.output_to_pipe) {
1628             cmdarg_err("Multiple capture files requested, but "
1629               "the capture file is a pipe.");
1630             return 1;
1631           }
1632           if (!global_capture_opts.has_autostop_filesize &&
1633               !global_capture_opts.has_file_duration) {
1634             cmdarg_err("Multiple capture files requested, but "
1635               "no maximum capture file size or duration was specified.");
1636             return 1;
1637           }
1638         }
1639         /* Currently, we don't support read filters when capturing
1640            and saving the packets. */
1641         if (rfilter != NULL) {
1642           cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1643           return 1;
1644         }
1645       } else {
1646         /* They didn't specify a "-w" flag, so we won't be saving to a
1647            capture file.  Check for options that only make sense if
1648            we're saving to a file. */
1649         if (global_capture_opts.has_autostop_filesize) {
1650           cmdarg_err("Maximum capture file size specified, but "
1651            "capture isn't being saved to a file.");
1652           return 1;
1653         }
1654         if (global_capture_opts.multi_files_on) {
1655           cmdarg_err("Multiple capture files requested, but "
1656             "the capture isn't being saved to a file.");
1657           return 1;
1658         }
1659       }
1660     }
1661   }
1662 #endif
1663
1664 #ifdef _WIN32
1665   /* Start windows sockets */
1666   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1667 #endif /* _WIN32 */
1668
1669   /* Notify all registered modules that have had any of their preferences
1670      changed either from one of the preferences file or from the command
1671      line that their preferences have changed. */
1672   prefs_apply_all();
1673
1674   /* At this point MATE will have registered its field array so we can
1675      have a tap filter with one of MATE's late-registered fields as part
1676      of the filter.  We can now process all the "-z" arguments. */
1677   start_requested_stats();
1678
1679 #ifdef HAVE_LIBPCAP
1680   /* We currently don't support taps, or printing dissected packets,
1681      if we're writing to a pipe. */
1682   if (global_capture_opts.saving_to_file &&
1683       global_capture_opts.output_to_pipe) {
1684     if (tap_listeners_require_dissection()) {
1685       cmdarg_err("Taps aren't supported when saving to a pipe.");
1686       return 1;
1687     }
1688     if (print_packet_info) {
1689       cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1690       return 1;
1691     }
1692   }
1693 #endif
1694
1695   /* disabled protocols as per configuration file */
1696   if (gdp_path == NULL && dp_path == NULL) {
1697     set_disabled_protos_list();
1698   }
1699
1700   /* Build the column format array */
1701   build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1702
1703 #ifdef HAVE_LIBPCAP
1704   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1705   capture_opts_trim_ring_num_files(&global_capture_opts);
1706 #endif
1707
1708   if (rfilter != NULL) {
1709     if (!dfilter_compile(rfilter, &rfcode)) {
1710       cmdarg_err("%s", dfilter_error_msg);
1711       epan_cleanup();
1712 #ifdef HAVE_PCAP_OPEN_DEAD
1713       {
1714         pcap_t *pc;
1715
1716         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1717         if (pc != NULL) {
1718           if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1719             cmdarg_err_cont(
1720               "  Note: That display filter code looks like a valid capture filter;");
1721             cmdarg_err_cont(
1722               "        maybe you mixed them up?");
1723           }
1724           pcap_close(pc);
1725         }
1726       }
1727 #endif
1728       return 2;
1729     }
1730   }
1731   cfile.rfcode = rfcode;
1732
1733   if (print_packet_info) {
1734     /* If we're printing as text or PostScript, we have
1735        to create a print stream. */
1736     if (output_action == WRITE_TEXT) {
1737       switch (print_format) {
1738
1739       case PR_FMT_TEXT:
1740         print_stream = print_stream_text_stdio_new(stdout);
1741         break;
1742
1743       case PR_FMT_PS:
1744         print_stream = print_stream_ps_stdio_new(stdout);
1745         break;
1746
1747       default:
1748         g_assert_not_reached();
1749       }
1750     }
1751   }
1752
1753   /* We have to dissect each packet if:
1754
1755         we're printing information about each packet;
1756
1757         we're using a read filter on the packets;
1758
1759         we're using any taps that need dissection. */
1760   do_dissection = print_packet_info || rfcode || tap_listeners_require_dissection();
1761
1762   if (cf_name) {
1763     /*
1764      * We're reading a capture file.
1765      */
1766
1767     /*
1768      * Immediately relinquish any special privileges we have; we must not
1769      * be allowed to read any capture files the user running TShark
1770      * can't open.
1771      */
1772     relinquish_special_privs_perm();
1773     print_current_user();
1774
1775     if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1776       epan_cleanup();
1777       return 2;
1778     }
1779
1780     /* Set timestamp precision; there should arguably be a command-line
1781        option to let the user set this. */
1782     switch(wtap_file_tsprecision(cfile.wth)) {
1783     case(WTAP_FILE_TSPREC_SEC):
1784       timestamp_set_precision(TS_PREC_AUTO_SEC);
1785       break;
1786     case(WTAP_FILE_TSPREC_DSEC):
1787       timestamp_set_precision(TS_PREC_AUTO_DSEC);
1788       break;
1789     case(WTAP_FILE_TSPREC_CSEC):
1790       timestamp_set_precision(TS_PREC_AUTO_CSEC);
1791       break;
1792     case(WTAP_FILE_TSPREC_MSEC):
1793       timestamp_set_precision(TS_PREC_AUTO_MSEC);
1794       break;
1795     case(WTAP_FILE_TSPREC_USEC):
1796       timestamp_set_precision(TS_PREC_AUTO_USEC);
1797       break;
1798     case(WTAP_FILE_TSPREC_NSEC):
1799       timestamp_set_precision(TS_PREC_AUTO_NSEC);
1800       break;
1801     default:
1802       g_assert_not_reached();
1803     }
1804
1805     /* Process the packets in the file */
1806     TRY {
1807 #ifdef HAVE_LIBPCAP
1808       err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
1809           global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1810           global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1811 #else
1812       err = load_cap_file(&cfile, NULL, out_file_type, out_file_name_res, 0, 0);
1813 #endif
1814     }
1815     CATCH(OutOfMemoryError) {
1816       fprintf(stderr,
1817               "Out Of Memory!\n"
1818               "\n"
1819               "Sorry, but TShark has to terminate now!\n"
1820               "\n"
1821               "Some infos / workarounds can be found at:\n"
1822               "http://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
1823       err = ENOMEM;
1824     }
1825     ENDTRY;
1826     if (err != 0) {
1827       /* We still dump out the results of taps, etc., as we might have
1828          read some packets; however, we exit with an error status. */
1829       exit_status = 2;
1830     }
1831   } else {
1832     /* No capture file specified, so we're supposed to do a live capture
1833        (or get a list of link-layer types for a live capture device);
1834        do we have support for live captures? */
1835 #ifdef HAVE_LIBPCAP
1836     /* trim the interface name and exit if that failed */
1837     if (!capture_opts_trim_iface(&global_capture_opts,
1838         ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL)) {
1839         return 2;
1840     }
1841
1842     /* if requested, list the link layer types and exit */
1843     if (list_link_layer_types) {
1844         guint i;
1845         interface_options interface_opts;
1846
1847         /* Get the list of link-layer types for the capture devices. */
1848         for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1849             if_capabilities_t *caps;
1850
1851             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1852             caps = capture_get_if_capabilities(interface_opts.name, interface_opts.monitor_mode, &err_str);
1853             if (caps == NULL) {
1854                 cmdarg_err("%s", err_str);
1855                 g_free(err_str);
1856                 return 2;
1857             }
1858             if (caps->data_link_types == NULL) {
1859                 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
1860                 return 2;
1861             }
1862             capture_opts_print_if_capabilities(caps, interface_opts.name, interface_opts.monitor_mode);
1863             free_if_capabilities(caps);
1864         }
1865         return 0;
1866     }
1867
1868     if (print_packet_info) {
1869       if (!write_preamble(NULL)) {
1870         show_print_file_io_error(errno);
1871         return 2;
1872       }
1873     } else if (!quiet) {
1874       /*
1875        * We're not printing information for each packet, and the user
1876        * didn't ask us not to print a count of packets as they arrive,
1877        * so print that count so the user knows that packets are arriving.
1878        *
1879        * XXX - what if the user wants to do a live capture, doesn't want
1880        * to save it to a file, doesn't want information printed for each
1881        * packet, does want some "-z" statistic, and wants packet counts
1882        * so they know whether they're seeing any packets?
1883        */
1884       print_packet_counts = TRUE;
1885     }
1886
1887     /* For now, assume libpcap gives microsecond precision. */
1888     timestamp_set_precision(TS_PREC_AUTO_USEC);
1889
1890     /*
1891      * XXX - this returns FALSE if an error occurred, but it also
1892      * returns FALSE if the capture stops because a time limit
1893      * was reached (and possibly other limits), so we can't assume
1894      * it means an error.
1895      *
1896      * The capture code is a bit twisty, so it doesn't appear to
1897      * be an easy fix.  We just ignore the return value for now.
1898      * Instead, pass on the exit status from the capture child.
1899      */
1900     capture();
1901     exit_status = global_capture_opts.fork_child_status;
1902
1903     if (print_packet_info) {
1904       if (!write_finale()) {
1905         err = errno;
1906         show_print_file_io_error(err);
1907       }
1908     }
1909 #else
1910     /* No - complain. */
1911     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1912     return 2;
1913 #endif
1914   }
1915
1916   g_free(cf_name);
1917
1918   if (cfile.frames != NULL) {
1919     free_frame_data_sequence(cfile.frames);
1920     cfile.frames = NULL;
1921   }
1922
1923   draw_tap_listeners(TRUE);
1924   funnel_dump_all_text_windows();
1925   epan_cleanup();
1926
1927   output_fields_free(output_fields);
1928   output_fields = NULL;
1929
1930   return exit_status;
1931 }
1932
1933 /*#define USE_BROKEN_G_MAIN_LOOP*/
1934
1935 #ifdef USE_BROKEN_G_MAIN_LOOP
1936   GMainLoop *loop;
1937 #else
1938   gboolean loop_running = FALSE;
1939 #endif
1940   guint32 packet_count = 0;
1941
1942
1943 /* XXX - move to the right position / file */
1944 /* read from a pipe (callback) */
1945 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1946
1947 typedef struct pipe_input_tag {
1948   gint                source;
1949   gpointer            user_data;
1950   int                 *child_process;
1951   pipe_input_cb_t     input_cb;
1952   guint               pipe_input_id;
1953 #ifdef _WIN32
1954   GMutex              *callback_running;
1955 #endif
1956 } pipe_input_t;
1957
1958 static pipe_input_t pipe_input;
1959
1960 #ifdef _WIN32
1961 /* The timer has expired, see if there's stuff to read from the pipe,
1962    if so, do the callback */
1963 static gint
1964 pipe_timer_cb(gpointer data)
1965 {
1966   HANDLE handle;
1967   DWORD avail = 0;
1968   gboolean result;
1969   DWORD childstatus;
1970   pipe_input_t *pipe_input_p = data;
1971   gint iterations = 0;
1972
1973   g_mutex_lock (pipe_input_p->callback_running);
1974
1975   /* try to read data from the pipe only 5 times, to avoid blocking */
1976   while(iterations < 5) {
1977     /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1978
1979     /* Oddly enough although Named pipes don't work on win9x,
1980        PeekNamedPipe does !!! */
1981     handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
1982     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1983
1984     /* Get the child process exit status */
1985     GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
1986                        &childstatus);
1987
1988     /* If the Peek returned an error, or there are bytes to be read
1989        or the childwatcher thread has terminated then call the normal
1990        callback */
1991     if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1992
1993       /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1994
1995       /* And call the real handler */
1996       if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
1997         g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1998         /* pipe closed, return false so that the timer is stopped */
1999         g_mutex_unlock (pipe_input_p->callback_running);
2000         return FALSE;
2001       }
2002     }
2003     else {
2004       /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2005       /* No data, stop now */
2006       break;
2007     }
2008
2009     iterations++;
2010   }
2011
2012   /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2013
2014   g_mutex_unlock (pipe_input_p->callback_running);
2015
2016   /* we didn't stopped the timer, so let it run */
2017   return TRUE;
2018 }
2019 #endif
2020
2021
2022 void
2023 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
2024 {
2025
2026   pipe_input.source         = source;
2027   pipe_input.child_process  = child_process;
2028   pipe_input.user_data      = user_data;
2029   pipe_input.input_cb       = input_cb;
2030
2031 #ifdef _WIN32
2032 #if GLIB_CHECK_VERSION(2,31,0)
2033   pipe_input.callback_running = g_malloc(sizeof(GMutex));
2034   g_mutex_init(pipe_input.callback_running);
2035 #else
2036   pipe_input.callback_running = g_mutex_new();
2037 #endif
2038   /* Tricky to use pipes in win9x, as no concept of wait.  NT can
2039      do this but that doesn't cover all win32 platforms.  GTK can do
2040      this but doesn't seem to work over processes.  Attempt to do
2041      something similar here, start a timer and check for data on every
2042      timeout. */
2043   /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2044   pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2045 #endif
2046 }
2047
2048
2049 #ifdef HAVE_LIBPCAP
2050 static gboolean
2051 capture(void)
2052 {
2053   gboolean ret;
2054   guint i;
2055   GString *str = g_string_new("");
2056 #ifdef USE_TSHARK_SELECT
2057   fd_set readfds;
2058 #endif
2059 #ifndef _WIN32
2060   struct sigaction action, oldaction;
2061 #endif
2062
2063   /*
2064    * XXX - dropping privileges is still required, until code cleanup is done
2065    *
2066    * remove all dependencies to pcap specific code and using only dumpcap is almost done.
2067    * when it's done, we don't need special privileges to run tshark at all,
2068    * therefore we don't need to drop these privileges
2069    * The only thing we might want to keep is a warning if tshark is run as root,
2070    * as it's no longer necessary and potentially dangerous.
2071    *
2072    * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
2073    * We've opened the capture device, so we shouldn't need any special
2074    * privileges any more; relinquish those privileges.
2075    *
2076    * XXX - if we have saved set-user-ID support, we should give up those
2077    * privileges immediately, and then reclaim them long enough to get
2078    * a list of network interfaces and to open one, and then give them
2079    * up again, so that stuff we do while processing the argument list,
2080    * reading the user's preferences, loading and starting plugins
2081    * (especially *user* plugins), etc. is done with the user's privileges,
2082    * not special privileges.
2083    */
2084   relinquish_special_privs_perm();
2085   print_current_user();
2086
2087   /* Cleanup all data structures used for dissection. */
2088   cleanup_dissection();
2089   /* Initialize all data structures used for dissection. */
2090   init_dissection();
2091
2092 #ifdef _WIN32
2093   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2094   SetConsoleCtrlHandler(capture_cleanup, TRUE);
2095 #else /* _WIN32 */
2096   /* Catch SIGINT and SIGTERM and, if we get either of them,
2097      clean up and exit.  If SIGHUP isn't being ignored, catch
2098      it too and, if we get it, clean up and exit.
2099
2100      We restart any read that was in progress, so that it doesn't
2101      disrupt reading from the sync pipe.  The signal handler tells
2102      the capture child to finish; it will report that it finished,
2103      or will exit abnormally, so  we'll stop reading from the sync
2104      pipe, pick up the exit status, and quit. */
2105   memset(&action, 0, sizeof(action));
2106   action.sa_handler = capture_cleanup;
2107   action.sa_flags = SA_RESTART;
2108   sigemptyset(&action.sa_mask);
2109   sigaction(SIGTERM, &action, NULL);
2110   sigaction(SIGINT, &action, NULL);
2111   sigaction(SIGHUP, NULL, &oldaction);
2112   if (oldaction.sa_handler == SIG_DFL)
2113     sigaction(SIGHUP, &action, NULL);
2114
2115 #ifdef SIGINFO
2116   /* Catch SIGINFO and, if we get it and we're capturing to a file in
2117      quiet mode, report the number of packets we've captured.
2118
2119      Again, restart any read that was in progress, so that it doesn't
2120      disrupt reading from the sync pipe. */
2121   action.sa_handler = report_counts_siginfo;
2122   action.sa_flags = SA_RESTART;
2123   sigemptyset(&action.sa_mask);
2124   sigaction(SIGINFO, &action, NULL);
2125 #endif /* SIGINFO */
2126 #endif /* _WIN32 */
2127
2128   global_capture_opts.state = CAPTURE_PREPARING;
2129
2130   /* Let the user know which interfaces were chosen. */
2131   for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2132     interface_options interface_opts;
2133
2134     interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
2135     interface_opts.descr = get_interface_descriptive_name(interface_opts.name);
2136     global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
2137     g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
2138   }
2139 #ifdef _WIN32
2140   if (global_capture_opts.ifaces->len < 2) {
2141 #else
2142   if (global_capture_opts.ifaces->len < 4) {
2143 #endif
2144     for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2145       interface_options interface_opts;
2146
2147       interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
2148       if (i > 0) {
2149           if (global_capture_opts.ifaces->len > 2) {
2150               g_string_append_printf(str, ",");
2151           }
2152           g_string_append_printf(str, " ");
2153           if (i == global_capture_opts.ifaces->len - 1) {
2154               g_string_append_printf(str, "and ");
2155           }
2156       }
2157       g_string_append_printf(str, "%s", interface_opts.descr);
2158     }
2159   } else {
2160     g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
2161   }
2162   fprintf(stderr, "Capturing on %s\n", str->str);
2163   g_string_free(str, TRUE);
2164
2165   ret = sync_pipe_start(&global_capture_opts);
2166
2167   if (!ret)
2168     return FALSE;
2169
2170   /* the actual capture loop
2171    *
2172    * XXX - glib doesn't seem to provide any event based loop handling.
2173    *
2174    * XXX - for whatever reason,
2175    * calling g_main_loop_new() ends up in 100% cpu load.
2176    *
2177    * But that doesn't matter: in UNIX we can use select() to find an input
2178    * source with something to do.
2179    *
2180    * But that doesn't matter because we're in a CLI (that doesn't need to
2181    * update a GUI or something at the same time) so it's OK if we block
2182    * trying to read from the pipe.
2183    *
2184    * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2185    * wrong (but I leave it there in case I am...).
2186    */
2187
2188 #ifdef USE_TSHARK_SELECT
2189   FD_ZERO(&readfds);
2190   FD_SET(pipe_input.source, &readfds);
2191 #endif
2192
2193   loop_running = TRUE;
2194
2195   TRY
2196   {
2197     while (loop_running)
2198     {
2199 #ifdef USE_TSHARK_SELECT
2200       ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2201
2202       if (ret == -1)
2203       {
2204         perror("select()");
2205         return TRUE;
2206       } else if (ret == 1) {
2207 #endif
2208         /* Call the real handler */
2209         if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2210           g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2211           return FALSE;
2212         }
2213 #ifdef USE_TSHARK_SELECT
2214       }
2215 #endif
2216     }
2217   }
2218   CATCH(OutOfMemoryError) {
2219     fprintf(stderr,
2220             "Out Of Memory!\n"
2221             "\n"
2222             "Sorry, but TShark has to terminate now!\n"
2223             "\n"
2224             "Some infos / workarounds can be found at:\n"
2225             "http://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2226     exit(1);
2227   }
2228   ENDTRY;
2229   return TRUE;
2230 }
2231
2232
2233 /* XXX - move the call to main_window_update() out of capture_sync.c */
2234 /* dummy for capture_sync.c to make linker happy */
2235 void main_window_update(void)
2236 {
2237 }
2238
2239 /* capture child detected an error */
2240 void
2241 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
2242 {
2243   cmdarg_err("%s", error_msg);
2244   cmdarg_err_cont("%s", secondary_error_msg);
2245 }
2246
2247
2248 /* capture child detected an capture filter related error */
2249 void
2250 capture_input_cfilter_error_message(capture_options *capture_opts, guint i, char *error_message)
2251 {
2252   dfilter_t   *rfcode = NULL;
2253   interface_options interface_opts;
2254
2255   g_assert(i < capture_opts->ifaces->len);
2256   interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2257
2258   if (dfilter_compile(interface_opts.cfilter, &rfcode) && rfcode != NULL) {
2259     cmdarg_err(
2260       "Invalid capture filter \"%s\" for interface %s!\n"
2261       "\n"
2262       "That string looks like a valid display filter; however, it isn't a valid\n"
2263       "capture filter (%s).\n"
2264       "\n"
2265       "Note that display filters and capture filters don't have the same syntax,\n"
2266       "so you can't use most display filter expressions as capture filters.\n"
2267       "\n"
2268       "See the User's Guide for a description of the capture filter syntax.",
2269       interface_opts.cfilter, interface_opts.descr, error_message);
2270     dfilter_free(rfcode);
2271   } else {
2272     cmdarg_err(
2273       "Invalid capture filter \"%s\" for interface %s!\n"
2274       "\n"
2275       "That string isn't a valid capture filter (%s).\n"
2276       "See the User's Guide for a description of the capture filter syntax.",
2277       interface_opts.cfilter, interface_opts.descr, error_message);
2278   }
2279 }
2280
2281
2282 /* capture child tells us we have a new (or the first) capture file */
2283 gboolean
2284 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
2285 {
2286   gboolean is_tempfile;
2287   int  err;
2288
2289   if(capture_opts->state == CAPTURE_PREPARING) {
2290     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
2291   }
2292   g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2293
2294   g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
2295
2296   /* free the old filename */
2297   if (capture_opts->save_file != NULL) {
2298
2299     /* we start a new capture file, close the old one (if we had one before) */
2300     if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
2301       if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
2302         wtap_close(((capture_file *) capture_opts->cf)->wth);
2303       }
2304       ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
2305     }
2306
2307     g_free(capture_opts->save_file);
2308     is_tempfile = FALSE;
2309   } else {
2310     /* we didn't had a save_file before, must be a tempfile */
2311     is_tempfile = TRUE;
2312   }
2313
2314   /* save the new filename */
2315   capture_opts->save_file = g_strdup(new_file);
2316
2317   /* if we are in real-time mode, open the new file now */
2318   if(do_dissection) {
2319     /* Attempt to open the capture file and set up to read from it. */
2320     switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
2321     case CF_OK:
2322       break;
2323     case CF_ERROR:
2324       /* Don't unlink (delete) the save file - leave it around,
2325          for debugging purposes. */
2326       g_free(capture_opts->save_file);
2327       capture_opts->save_file = NULL;
2328       return FALSE;
2329     }
2330   }
2331
2332   capture_opts->state = CAPTURE_RUNNING;
2333
2334   return TRUE;
2335 }
2336
2337
2338 /* capture child tells us we have new packets to read */
2339 void
2340 capture_input_new_packets(capture_options *capture_opts, int to_read)
2341 {
2342   gboolean     ret;
2343   int          err;
2344   gchar        *err_info;
2345   gint64       data_offset;
2346   capture_file *cf = capture_opts->cf;
2347   gboolean filtering_tap_listeners;
2348   guint tap_flags;
2349
2350 #ifdef SIGINFO
2351   /*
2352    * Prevent a SIGINFO handler from writing to the standard error while
2353    * we're doing so or writing to the standard output; instead, have it
2354    * just set a flag telling us to print that information when we're done.
2355    */
2356   infodelay = TRUE;
2357 #endif /* SIGINFO */
2358
2359   /* Do we have any tap listeners with filters? */
2360   filtering_tap_listeners = have_filtering_tap_listeners();
2361
2362   /* Get the union of the flags for all tap listeners. */
2363   tap_flags = union_of_tap_listener_flags();
2364
2365   if(do_dissection) {
2366     while (to_read-- && cf->wth) {
2367       wtap_cleareof(cf->wth);
2368       ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2369       if(ret == FALSE) {
2370         /* read from file failed, tell the capture child to stop */
2371         sync_pipe_stop(capture_opts);
2372         wtap_close(cf->wth);
2373         cf->wth = NULL;
2374       } else {
2375         ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2376                              wtap_buf_ptr(cf->wth),
2377                              filtering_tap_listeners, tap_flags);
2378       }
2379       if (ret != FALSE) {
2380         /* packet successfully read and gone through the "Read Filter" */
2381         packet_count++;
2382       }
2383     }
2384   } else {
2385     /*
2386      * Dumpcap's doing all the work; we're not doing any dissection.
2387      * Count all the packets it wrote.
2388      */
2389     packet_count += to_read;
2390   }
2391
2392   if (print_packet_counts) {
2393       /* We're printing packet counts. */
2394       if (packet_count != 0) {
2395         fprintf(stderr, "\r%u ", packet_count);
2396         /* stderr could be line buffered */
2397         fflush(stderr);
2398       }
2399   }
2400
2401 #ifdef SIGINFO
2402   /*
2403    * Allow SIGINFO handlers to write.
2404    */
2405   infodelay = FALSE;
2406
2407   /*
2408    * If a SIGINFO handler asked us to write out capture counts, do so.
2409    */
2410   if (infoprint)
2411     report_counts();
2412 #endif /* SIGINFO */
2413 }
2414
2415 static void
2416 report_counts(void)
2417 {
2418   if (!print_packet_counts) {
2419     /* Report the count only if we aren't printing a packet count
2420        as packets arrive. */
2421     fprintf(stderr, "%u packet%s captured\n", packet_count,
2422             plurality(packet_count, "", "s"));
2423   }
2424 #ifdef SIGINFO
2425   infoprint = FALSE; /* we just reported it */
2426 #endif /* SIGINFO */
2427 }
2428
2429 #ifdef SIGINFO
2430 static void
2431 report_counts_siginfo(int signum _U_)
2432 {
2433   int sav_errno = errno;
2434   /* If we've been told to delay printing, just set a flag asking
2435      that we print counts (if we're supposed to), otherwise print
2436      the count of packets captured (if we're supposed to). */
2437   if (infodelay)
2438     infoprint = TRUE;
2439   else
2440     report_counts();
2441   errno = sav_errno;
2442 }
2443 #endif /* SIGINFO */
2444
2445
2446 /* capture child detected any packet drops? */
2447 void
2448 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2449 {
2450   if (print_packet_counts) {
2451     /* We're printing packet counts to stderr.
2452        Send a newline so that we move to the line after the packet count. */
2453     fprintf(stderr, "\n");
2454   }
2455
2456   if (dropped != 0) {
2457     /* We're printing packet counts to stderr.
2458        Send a newline so that we move to the line after the packet count. */
2459     fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2460   }
2461 }
2462
2463
2464 /*
2465  * Capture child closed its side of the pipe, report any error and
2466  * do the required cleanup.
2467  */
2468 void
2469 capture_input_closed(capture_options *capture_opts, gchar *msg)
2470 {
2471   capture_file *cf = (capture_file *) capture_opts->cf;
2472
2473   if (msg != NULL)
2474     fprintf(stderr, "tshark: %s\n", msg);
2475
2476   report_counts();
2477
2478   if(cf != NULL && cf->wth != NULL) {
2479     wtap_close(cf->wth);
2480     if(cf->is_tempfile) {
2481       ws_unlink(cf->filename);
2482     }
2483   }
2484 #ifdef USE_BROKEN_G_MAIN_LOOP
2485   /*g_main_loop_quit(loop);*/
2486   g_main_quit(loop);
2487 #else
2488   loop_running = FALSE;
2489 #endif
2490 }
2491
2492
2493
2494
2495 #ifdef _WIN32
2496 static BOOL WINAPI
2497 capture_cleanup(DWORD ctrltype _U_)
2498 {
2499   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2500      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2501      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2502      like SIGTERM at least when the machine's shutting down.
2503
2504      For now, we handle them all as indications that we should clean up
2505      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2506      way on UNIX.
2507
2508      We must return TRUE so that no other handler - such as one that would
2509      terminate the process - gets called.
2510
2511      XXX - for some reason, typing ^C to TShark, if you run this in
2512      a Cygwin console window in at least some versions of Cygwin,
2513      causes TShark to terminate immediately; this routine gets
2514      called, but the main loop doesn't get a chance to run and
2515      exit cleanly, at least if this is compiled with Microsoft Visual
2516      C++ (i.e., it's a property of the Cygwin console window or Bash;
2517      it happens if TShark is not built with Cygwin - for all I know,
2518      building it with Cygwin may make the problem go away). */
2519
2520   /* tell the capture child to stop */
2521   sync_pipe_stop(&global_capture_opts);
2522
2523   /* don't stop our own loop already here, otherwise status messages and
2524    * cleanup wouldn't be done properly. The child will indicate the stop of
2525    * everything by calling capture_input_closed() later */
2526
2527   return TRUE;
2528 }
2529 #else
2530 static void
2531 capture_cleanup(int signum _U_)
2532 {
2533   /* tell the capture child to stop */
2534   sync_pipe_stop(&global_capture_opts);
2535
2536   /* don't stop our own loop already here, otherwise status messages and
2537    * cleanup wouldn't be done properly. The child will indicate the stop of
2538    * everything by calling capture_input_closed() later */
2539 }
2540 #endif /* _WIN32 */
2541 #endif /* HAVE_LIBPCAP */
2542
2543 static gboolean
2544 process_packet_first_pass(capture_file *cf,
2545                gint64 offset, struct wtap_pkthdr *whdr,
2546                const guchar *pd)
2547 {
2548   frame_data fdlocal;
2549   guint32 framenum;
2550   gboolean create_proto_tree = FALSE;
2551   epan_dissect_t edt;
2552   gboolean passed;
2553
2554   /* The frame number of this packet is one more than the count of
2555      frames in this packet. */
2556   framenum = cf->count + 1;
2557
2558   /* If we're not running a display filter and we're not printing any
2559      packet information, we don't need to do a dissection. This means
2560      that all packets can be marked as 'passed'. */
2561   passed = TRUE;
2562
2563   frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
2564
2565   /* If we're going to print packet information, or we're going to
2566      run a read filter, or we're going to process taps, set up to
2567      do a dissection and do so. */
2568   if (do_dissection) {
2569     if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2570         gbl_resolv_flags.transport_name || gbl_resolv_flags.concurrent_dns)
2571       /* Grab any resolved addresses */
2572       host_name_lookup_process();
2573
2574     /* If we're going to be applying a read filter, we'll need to
2575        create a protocol tree against which to apply the filter. */
2576     if (cf->rfcode)
2577       create_proto_tree = TRUE;
2578
2579     /* We're not going to display the protocol tree on this pass,
2580        so it's not going to be "visible". */
2581     epan_dissect_init(&edt, create_proto_tree, FALSE);
2582
2583     /* If we're running a read filter, prime the epan_dissect_t with that
2584        filter. */
2585     if (cf->rfcode)
2586       epan_dissect_prime_dfilter(&edt, cf->rfcode);
2587
2588     frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2589                                   &first_ts, prev_dis, prev_cap);
2590
2591     epan_dissect_run(&edt, whdr, pd, &fdlocal, NULL);
2592
2593     /* Run the read filter if we have one. */
2594     if (cf->rfcode)
2595       passed = dfilter_apply_edt(cf->rfcode, &edt);
2596   }
2597
2598   if (passed) {
2599     frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2600     prev_dis_frame = fdlocal;
2601     prev_dis = &prev_dis_frame;
2602     frame_data_sequence_add(cf->frames, &fdlocal);
2603     cf->count++;
2604   }
2605
2606   prev_cap_frame = fdlocal;
2607   prev_cap = &prev_cap_frame;
2608
2609   if (do_dissection)
2610     epan_dissect_cleanup(&edt);
2611
2612   return passed;
2613 }
2614
2615 static gboolean
2616 process_packet_second_pass(capture_file *cf, frame_data *fdata,
2617                struct wtap_pkthdr *phdr, const guchar *pd,
2618                gboolean filtering_tap_listeners, guint tap_flags)
2619 {
2620   gboolean create_proto_tree;
2621   column_info *cinfo;
2622   epan_dissect_t edt;
2623   gboolean passed;
2624
2625   /* If we're not running a display filter and we're not printing any
2626      packet information, we don't need to do a dissection. This means
2627      that all packets can be marked as 'passed'. */
2628   passed = TRUE;
2629
2630   /* If we're going to print packet information, or we're going to
2631      run a read filter, or we're going to process taps, set up to
2632      do a dissection and do so. */
2633   if (do_dissection) {
2634     if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2635         gbl_resolv_flags.transport_name || gbl_resolv_flags.concurrent_dns)
2636       /* Grab any resolved addresses */
2637       host_name_lookup_process();
2638
2639     if (cf->rfcode || print_details || filtering_tap_listeners ||
2640         (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2641       create_proto_tree = TRUE;
2642     else
2643       create_proto_tree = FALSE;
2644
2645     /* The protocol tree will be "visible", i.e., printed, only if we're
2646        printing packet details, which is true if we're printing stuff
2647        ("print_packet_info" is true) and we're in verbose mode
2648        ("packet_details" is true). */
2649     epan_dissect_init(&edt, create_proto_tree, print_packet_info && print_details);
2650
2651     /* If we're running a read filter, prime the epan_dissect_t with that
2652        filter. */
2653     if (cf->rfcode)
2654       epan_dissect_prime_dfilter(&edt, cf->rfcode);
2655
2656     col_custom_prime_edt(&edt, &cf->cinfo);
2657
2658     /* We only need the columns if either
2659          1) some tap needs the columns
2660        or
2661          2) we're printing packet info but we're *not* verbose; in verbose
2662             mode, we print the protocol tree, not the protocol summary.
2663      */
2664     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary))
2665       cinfo = &cf->cinfo;
2666     else
2667       cinfo = NULL;
2668
2669     epan_dissect_run_with_taps(&edt, phdr, pd, fdata, cinfo);
2670
2671     /* Run the read filter if we have one. */
2672     if (cf->rfcode)
2673       passed = dfilter_apply_edt(cf->rfcode, &edt);
2674   }
2675
2676   if (passed) {
2677     /* Process this packet. */
2678     if (print_packet_info) {
2679       /* We're printing packet information; print the information for
2680          this packet. */
2681       if (do_dissection)
2682         print_packet(cf, &edt);
2683       else
2684         print_packet(cf, NULL);
2685
2686       /* The ANSI C standard does not appear to *require* that a line-buffered
2687          stream be flushed to the host environment whenever a newline is
2688          written, it just says that, on such a stream, characters "are
2689          intended to be transmitted to or from the host environment as a
2690          block when a new-line character is encountered".
2691
2692          The Visual C++ 6.0 C implementation doesn't do what is intended;
2693          even if you set a stream to be line-buffered, it still doesn't
2694          flush the buffer at the end of every line.
2695
2696          So, if the "-l" flag was specified, we flush the standard output
2697          at the end of a packet.  This will do the right thing if we're
2698          printing packet summary lines, and, as we print the entire protocol
2699          tree for a single packet without waiting for anything to happen,
2700          it should be as good as line-buffered mode if we're printing
2701          protocol trees.  (The whole reason for the "-l" flag in either
2702          tcpdump or TShark is to allow the output of a live capture to
2703          be piped to a program or script and to have that script see the
2704          information for the packet as soon as it's printed, rather than
2705          having to wait until a standard I/O buffer fills up. */
2706       if (line_buffered)
2707         fflush(stdout);
2708
2709       if (ferror(stdout)) {
2710         show_print_file_io_error(errno);
2711         exit(2);
2712       }
2713     }
2714   }
2715
2716   if (do_dissection) {
2717     epan_dissect_cleanup(&edt);
2718   }
2719   return passed;
2720 }
2721
2722 static int
2723 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2724     gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
2725 {
2726   gint         linktype;
2727   int          snapshot_length;
2728   wtap_dumper *pdh;
2729   guint32      framenum;
2730   int          err;
2731   gchar        *err_info = NULL;
2732   gint64       data_offset;
2733   char         *save_file_string = NULL;
2734   gboolean     filtering_tap_listeners;
2735   guint        tap_flags;
2736   wtapng_section_t *shb_hdr;
2737   wtapng_iface_descriptions_t *idb_inf;
2738   char         appname[100];
2739
2740   shb_hdr = wtap_file_get_shb_info(cf->wth);
2741   idb_inf = wtap_file_get_idb_info(cf->wth);
2742 #ifdef PCAP_NG_DEFAULT
2743   if (idb_inf->number_of_interfaces > 0) {
2744     linktype = WTAP_ENCAP_PER_PACKET;
2745   } else {
2746     linktype = wtap_file_encap(cf->wth);
2747   }
2748 #else
2749   linktype = wtap_file_encap(cf->wth);
2750 #endif
2751   if (save_file != NULL) {
2752     /* Get a string that describes what we're writing to */
2753     save_file_string = output_file_description(save_file);
2754
2755     /* Set up to write to the capture file. */
2756     snapshot_length = wtap_snapshot_length(cf->wth);
2757     if (snapshot_length == 0) {
2758       /* Snapshot length of input file not known. */
2759       snapshot_length = WTAP_MAX_PACKET_SIZE;
2760     }
2761     /* If we don't have an application name add Tshark */
2762     if(shb_hdr->shb_user_appl == NULL) {
2763         g_snprintf(appname, sizeof(appname), "TShark " VERSION "%s", wireshark_svnversion);
2764         shb_hdr->shb_user_appl = appname;
2765     }
2766
2767     pdh = wtap_dump_open_ng(save_file, out_file_type, linktype, snapshot_length,
2768         FALSE /* compressed */, shb_hdr, idb_inf, &err);
2769
2770     g_free(idb_inf);
2771     idb_inf = NULL;
2772
2773     if (pdh == NULL) {
2774       /* We couldn't set up to write to the capture file. */
2775       switch (err) {
2776
2777       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2778         cmdarg_err("Capture files can't be written in that format.");
2779         break;
2780
2781       case WTAP_ERR_UNSUPPORTED_ENCAP:
2782       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2783         cmdarg_err("The capture file being read can't be written as a "
2784           "\"%s\" file.", wtap_file_type_short_string(out_file_type));
2785         break;
2786
2787       case WTAP_ERR_CANT_OPEN:
2788         cmdarg_err("The %s couldn't be created for some "
2789           "unknown reason.", save_file_string);
2790         break;
2791
2792       case WTAP_ERR_SHORT_WRITE:
2793         cmdarg_err("A full header couldn't be written to the %s.",
2794                    save_file_string);
2795         break;
2796
2797       default:
2798         cmdarg_err("The %s could not be created: %s.", save_file_string,
2799                    wtap_strerror(err));
2800         break;
2801       }
2802       goto out;
2803     }
2804   } else {
2805     if (print_packet_info) {
2806       if (!write_preamble(cf)) {
2807         err = errno;
2808         show_print_file_io_error(err);
2809         goto out;
2810       }
2811     }
2812     pdh = NULL;
2813   }
2814
2815   if (pdh && out_file_name_res) {
2816     if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
2817       cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
2818                  wtap_file_type_short_string(out_file_type));
2819     }
2820   }
2821
2822   /* Do we have any tap listeners with filters? */
2823   filtering_tap_listeners = have_filtering_tap_listeners();
2824
2825   /* Get the union of the flags for all tap listeners. */
2826   tap_flags = union_of_tap_listener_flags();
2827
2828   if (perform_two_pass_analysis) {
2829     frame_data *fdata;
2830     int old_max_packet_count = max_packet_count;
2831
2832     /* Allocate a frame_data_sequence for all the frames. */
2833     cf->frames = new_frame_data_sequence();
2834
2835     while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2836       if (process_packet_first_pass(cf, data_offset, wtap_phdr(cf->wth),
2837                          wtap_buf_ptr(cf->wth))) {
2838         /* Stop reading if we have the maximum number of packets;
2839          * When the -c option has not been used, max_packet_count
2840          * starts at 0, which practically means, never stop reading.
2841          * (unless we roll over max_packet_count ?)
2842          */
2843         if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2844           err = 0; /* This is not an error */
2845           break;
2846         }
2847       }
2848     }
2849
2850     /* Close the sequential I/O side, to free up memory it requires. */
2851     wtap_sequential_close(cf->wth);
2852
2853     /* Allow the protocol dissectors to free up memory that they
2854      * don't need after the sequential run-through of the packets. */
2855     postseq_cleanup_all_protocols();
2856
2857     max_packet_count = old_max_packet_count;
2858
2859     for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
2860       fdata = frame_data_sequence_find(cf->frames, framenum);
2861       if (wtap_seek_read(cf->wth, fdata->file_off, &cf->phdr,
2862           cf->pd, fdata->cap_len, &err, &err_info)) {
2863         if (process_packet_second_pass(cf, fdata,
2864                            &cf->phdr, cf->pd,
2865                            filtering_tap_listeners, tap_flags)) {
2866           /* Either there's no read filtering or this packet passed the
2867              filter, so, if we're writing to a capture file, write
2868              this packet out. */
2869           if (pdh != NULL) {
2870             if (!wtap_dump(pdh, wtap_phdr(cf->wth), wtap_buf_ptr(cf->wth), &err)) {
2871               /* Error writing to a capture file */
2872               switch (err) {
2873
2874               case WTAP_ERR_UNSUPPORTED_ENCAP:
2875                 /*
2876                  * This is a problem with the particular frame we're writing;
2877                  * note that, and give the frame number.
2878                  *
2879                  * XXX - framenum is not necessarily the frame number in
2880                  * the input file if there was a read filter.
2881                  */
2882                 fprintf(stderr,
2883                         "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
2884                         framenum, cf->filename,
2885                         wtap_file_type_short_string(out_file_type));
2886                 break;
2887
2888               default:
2889                 show_capture_file_io_error(save_file, err, FALSE);
2890                 break;
2891               }
2892               wtap_dump_close(pdh, &err);
2893               g_free(shb_hdr);
2894               exit(2);
2895             }
2896           }
2897           /* Stop reading if we have the maximum number of packets;
2898            * When the -c option has not been used, max_packet_count
2899            * starts at 0, which practically means, never stop reading.
2900            * (unless we roll over max_packet_count ?)
2901            */
2902           if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2903             err = 0; /* This is not an error */
2904             break;
2905           }
2906         }
2907       }
2908     }
2909   }
2910   else {
2911     framenum = 0;
2912     while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2913       framenum++;
2914
2915       if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2916                          wtap_buf_ptr(cf->wth),
2917                          filtering_tap_listeners, tap_flags)) {
2918         /* Either there's no read filtering or this packet passed the
2919            filter, so, if we're writing to a capture file, write
2920            this packet out. */
2921         if (pdh != NULL) {
2922           if (!wtap_dump(pdh, wtap_phdr(cf->wth), wtap_buf_ptr(cf->wth), &err)) {
2923             /* Error writing to a capture file */
2924             switch (err) {
2925
2926             case WTAP_ERR_UNSUPPORTED_ENCAP:
2927               /*
2928                * This is a problem with the particular frame we're writing;
2929                * note that, and give the frame number.
2930                */
2931               fprintf(stderr,
2932                       "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
2933                       framenum, cf->filename,
2934                       wtap_file_type_short_string(out_file_type));
2935               break;
2936
2937             default:
2938               show_capture_file_io_error(save_file, err, FALSE);
2939               break;
2940             }
2941             wtap_dump_close(pdh, &err);
2942             g_free(shb_hdr);
2943             exit(2);
2944           }
2945         }
2946         /* Stop reading if we have the maximum number of packets;
2947          * When the -c option has not been used, max_packet_count
2948          * starts at 0, which practically means, never stop reading.
2949          * (unless we roll over max_packet_count ?)
2950          */
2951         if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2952           err = 0; /* This is not an error */
2953           break;
2954         }
2955       }
2956     }
2957   }
2958
2959   if (err != 0) {
2960     /*
2961      * Print a message noting that the read failed somewhere along the line.
2962      *
2963      * If we're printing packet data, and the standard output and error are
2964      * going to the same place, flush the standard output, so everything
2965      * buffered up is written, and then print a newline to the standard error
2966      * before printing the error message, to separate it from the packet
2967      * data.  (Alas, that only works on UN*X; st_dev is meaningless, and
2968      * the _fstat() documentation at Microsoft doesn't indicate whether
2969      * st_ino is even supported.)
2970      */
2971 #ifndef _WIN32
2972     if (print_packet_info) {
2973       struct stat stat_stdout, stat_stderr;
2974
2975       if (fstat(1, &stat_stdout) == 0 && fstat(2, &stat_stderr) == 0) {
2976         if (stat_stdout.st_dev == stat_stderr.st_dev &&
2977             stat_stdout.st_ino == stat_stderr.st_ino) {
2978           fflush(stdout);
2979           fprintf(stderr, "\n");
2980         }
2981       }
2982     }
2983 #endif
2984     switch (err) {
2985
2986     case WTAP_ERR_UNSUPPORTED:
2987       cmdarg_err("The file \"%s\" contains record data that TShark doesn't support.\n(%s)",
2988                  cf->filename, err_info);
2989       g_free(err_info);
2990       break;
2991
2992     case WTAP_ERR_UNSUPPORTED_ENCAP:
2993       cmdarg_err("The file \"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2994                  cf->filename, err_info);
2995       g_free(err_info);
2996       break;
2997
2998     case WTAP_ERR_CANT_READ:
2999       cmdarg_err("An attempt to read from the file \"%s\" failed for some unknown reason.",
3000                  cf->filename);
3001       break;
3002
3003     case WTAP_ERR_SHORT_READ:
3004       cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
3005                  cf->filename);
3006       break;
3007
3008     case WTAP_ERR_BAD_FILE:
3009       cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
3010                  cf->filename, err_info);
3011       g_free(err_info);
3012       break;
3013
3014     case WTAP_ERR_DECOMPRESS:
3015       cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
3016                  "(%s)", cf->filename, err_info);
3017       break;
3018
3019     default:
3020       cmdarg_err("An error occurred while reading the file \"%s\": %s.",
3021                  cf->filename, wtap_strerror(err));
3022       break;
3023     }
3024     if (save_file != NULL) {
3025       /* Now close the capture file. */
3026       if (!wtap_dump_close(pdh, &err))
3027         show_capture_file_io_error(save_file, err, TRUE);
3028     }
3029   } else {
3030     if (save_file != NULL) {
3031       /* Now close the capture file. */
3032       if (!wtap_dump_close(pdh, &err))
3033         show_capture_file_io_error(save_file, err, TRUE);
3034     } else {
3035       if (print_packet_info) {
3036         if (!write_finale()) {
3037           err = errno;
3038           show_print_file_io_error(err);
3039         }
3040       }
3041     }
3042   }
3043
3044 out:
3045   wtap_close(cf->wth);
3046   cf->wth = NULL;
3047
3048   g_free(save_file_string);
3049   g_free(shb_hdr);
3050
3051   return err;
3052 }
3053
3054 static gboolean
3055 process_packet(capture_file *cf, gint64 offset, struct wtap_pkthdr *whdr,
3056                const guchar *pd,
3057                gboolean filtering_tap_listeners, guint tap_flags)
3058 {
3059   frame_data fdata;
3060   gboolean create_proto_tree;
3061   column_info *cinfo;
3062   epan_dissect_t edt;
3063   gboolean passed;
3064
3065   /* Count this packet. */
3066   cf->count++;
3067
3068   /* If we're not running a display filter and we're not printing any
3069      packet information, we don't need to do a dissection. This means
3070      that all packets can be marked as 'passed'. */
3071   passed = TRUE;
3072
3073   frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
3074
3075   /* If we're going to print packet information, or we're going to
3076      run a read filter, or we're going to process taps, set up to
3077      do a dissection and do so. */
3078   if (do_dissection) {
3079     if (print_packet_info && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
3080         gbl_resolv_flags.transport_name || gbl_resolv_flags.concurrent_dns))
3081       /* Grab any resolved addresses */
3082       host_name_lookup_process();
3083
3084     if (cf->rfcode || print_details || filtering_tap_listeners ||
3085         (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3086       create_proto_tree = TRUE;
3087     else
3088       create_proto_tree = FALSE;
3089
3090     /* The protocol tree will be "visible", i.e., printed, only if we're
3091        printing packet details, which is true if we're printing stuff
3092        ("print_packet_info" is true) and we're in verbose mode
3093        ("packet_details" is true). */
3094     epan_dissect_init(&edt, create_proto_tree, print_packet_info && print_details);
3095
3096     /* If we're running a read filter, prime the epan_dissect_t with that
3097        filter. */
3098     if (cf->rfcode)
3099       epan_dissect_prime_dfilter(&edt, cf->rfcode);
3100
3101     col_custom_prime_edt(&edt, &cf->cinfo);
3102
3103     /* We only need the columns if either
3104          1) some tap needs the columns
3105        or
3106          2) we're printing packet info but we're *not* verbose; in verbose
3107             mode, we print the protocol tree, not the protocol summary. */
3108     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary))
3109       cinfo = &cf->cinfo;
3110     else
3111       cinfo = NULL;
3112
3113     frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3114                                   &first_ts, prev_dis, prev_cap);
3115
3116     epan_dissect_run_with_taps(&edt, whdr, pd, &fdata, cinfo);
3117
3118     /* Run the read filter if we have one. */
3119     if (cf->rfcode)
3120       passed = dfilter_apply_edt(cf->rfcode, &edt);
3121   }
3122
3123   if (passed) {
3124     frame_data_set_after_dissect(&fdata, &cum_bytes);
3125     prev_dis_frame = fdata;
3126     prev_dis = &prev_dis_frame;
3127
3128     /* Process this packet. */
3129     if (print_packet_info) {
3130       /* We're printing packet information; print the information for
3131          this packet. */
3132       if (do_dissection)
3133         print_packet(cf, &edt);
3134       else
3135         print_packet(cf, NULL);
3136
3137       /* The ANSI C standard does not appear to *require* that a line-buffered
3138          stream be flushed to the host environment whenever a newline is
3139          written, it just says that, on such a stream, characters "are
3140          intended to be transmitted to or from the host environment as a
3141          block when a new-line character is encountered".
3142
3143          The Visual C++ 6.0 C implementation doesn't do what is intended;
3144          even if you set a stream to be line-buffered, it still doesn't
3145          flush the buffer at the end of every line.
3146
3147          So, if the "-l" flag was specified, we flush the standard output
3148          at the end of a packet.  This will do the right thing if we're
3149          printing packet summary lines, and, as we print the entire protocol
3150          tree for a single packet without waiting for anything to happen,
3151          it should be as good as line-buffered mode if we're printing
3152          protocol trees.  (The whole reason for the "-l" flag in either
3153          tcpdump or TShark is to allow the output of a live capture to
3154          be piped to a program or script and to have that script see the
3155          information for the packet as soon as it's printed, rather than
3156          having to wait until a standard I/O buffer fills up. */
3157       if (line_buffered)
3158         fflush(stdout);
3159
3160       if (ferror(stdout)) {
3161         show_print_file_io_error(errno);
3162         exit(2);
3163       }
3164     }
3165   }
3166
3167   prev_cap_frame = fdata;
3168   prev_cap = &prev_cap_frame;
3169
3170   if (do_dissection) {
3171     epan_dissect_cleanup(&edt);
3172     frame_data_cleanup(&fdata);
3173   }
3174   return passed;
3175 }
3176
3177 static gboolean
3178 write_preamble(capture_file *cf)
3179 {
3180   switch (output_action) {
3181
3182   case WRITE_TEXT:
3183     return print_preamble(print_stream, cf ? cf->filename : NULL);
3184
3185   case WRITE_XML:
3186     if (print_details)
3187       write_pdml_preamble(stdout, cf ? cf->filename : NULL);
3188     else
3189       write_psml_preamble(stdout);
3190     return !ferror(stdout);
3191
3192   case WRITE_FIELDS:
3193     write_fields_preamble(output_fields, stdout);
3194     return !ferror(stdout);
3195
3196   default:
3197     g_assert_not_reached();
3198     return FALSE;
3199   }
3200 }
3201
3202 static char *
3203 get_line_buf(size_t len)
3204 {
3205   static char *line_bufp = NULL;
3206   static size_t line_buf_len = 256;
3207   size_t new_line_buf_len;
3208
3209   for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3210        new_line_buf_len *= 2)
3211     ;
3212   if (line_bufp == NULL) {
3213     line_buf_len = new_line_buf_len;
3214     line_bufp = g_malloc(line_buf_len + 1);
3215   } else {
3216     if (new_line_buf_len > line_buf_len) {
3217       line_buf_len = new_line_buf_len;
3218       line_bufp = g_realloc(line_bufp, line_buf_len + 1);
3219     }
3220   }
3221   return line_bufp;
3222 }
3223
3224 static gboolean
3225 print_columns(capture_file *cf)
3226 {
3227   char *line_bufp;
3228   int i;
3229   size_t buf_offset;
3230   size_t column_len;
3231
3232   line_bufp = get_line_buf(256);
3233   buf_offset = 0;
3234   *line_bufp = '\0';
3235   for (i = 0; i < cf->cinfo.num_cols; i++) {
3236     /* Skip columns not marked as visible. */
3237     if (!get_column_visible(i))
3238       continue;
3239     switch (cf->cinfo.col_fmt[i]) {
3240     case COL_NUMBER:
3241 #ifdef HAVE_LIBPCAP
3242       /*
3243        * Don't print this if we're doing a live capture from a network
3244        * interface - if we're doing a live capture, you won't be
3245        * able to look at the capture in the future (it's not being
3246        * saved anywhere), so the frame numbers are unlikely to be
3247        * useful.
3248        *
3249        * (XXX - it might be nice to be able to save and print at
3250        * the same time, sort of like an "Update list of packets
3251        * in real time" capture in Wireshark.)
3252        */
3253       if (global_capture_opts.ifaces->len > 0)
3254         continue;
3255 #endif
3256       column_len = strlen(cf->cinfo.col_data[i]);
3257       if (column_len < 3)
3258         column_len = 3;
3259       line_bufp = get_line_buf(buf_offset + column_len);
3260       g_snprintf(line_bufp + buf_offset, (int)column_len + 1, "%3s", cf->cinfo.col_data[i]);
3261       break;
3262
3263     case COL_CLS_TIME:
3264     case COL_REL_TIME:
3265     case COL_ABS_TIME:
3266     case COL_ABS_DATE_TIME:
3267     case COL_UTC_TIME:
3268     case COL_UTC_DATE_TIME: /* XXX - wider */
3269       column_len = strlen(cf->cinfo.col_data[i]);
3270       if (column_len < 10)
3271         column_len = 10;
3272       line_bufp = get_line_buf(buf_offset + column_len);
3273       g_snprintf(line_bufp + buf_offset, (int)column_len + 1, "%10s", cf->cinfo.col_data[i]);
3274       break;
3275
3276     case COL_DEF_SRC:
3277     case COL_RES_SRC:
3278     case COL_UNRES_SRC:
3279     case COL_DEF_DL_SRC:
3280     case COL_RES_DL_SRC:
3281     case COL_UNRES_DL_SRC:
3282     case COL_DEF_NET_SRC:
3283     case COL_RES_NET_SRC:
3284     case COL_UNRES_NET_SRC:
3285       column_len = strlen(cf->cinfo.col_data[i]);
3286       if (column_len < 12)
3287         column_len = 12;
3288       line_bufp = get_line_buf(buf_offset + column_len);
3289       g_snprintf(line_bufp + buf_offset, (int)column_len + 1, "%12s", cf->cinfo.col_data[i]);
3290       break;
3291
3292     case COL_DEF_DST:
3293     case COL_RES_DST:
3294     case COL_UNRES_DST:
3295     case COL_DEF_DL_DST:
3296     case COL_RES_DL_DST:
3297     case COL_UNRES_DL_DST:
3298     case COL_DEF_NET_DST:
3299     case COL_RES_NET_DST:
3300     case COL_UNRES_NET_DST:
3301       column_len = strlen(cf->cinfo.col_data[i]);
3302       if (column_len < 12)
3303         column_len = 12;
3304       line_bufp = get_line_buf(buf_offset + column_len);
3305       g_snprintf(line_bufp + buf_offset, (int)column_len + 1, "%-12s", cf->cinfo.col_data[i]);
3306       break;
3307
3308     default:
3309       column_len = strlen(cf->cinfo.col_data[i]);
3310       line_bufp = get_line_buf(buf_offset + column_len);
3311       g_strlcat(line_bufp + buf_offset, cf->cinfo.col_data[i], column_len + 1);
3312       break;
3313     }
3314     buf_offset += column_len;
3315     if (i != cf->cinfo.num_cols - 1) {
3316       /*
3317        * This isn't the last column, so we need to print a
3318        * separator between this column and the next.
3319        *
3320        * If we printed a network source and are printing a
3321        * network destination of the same type next, separate
3322        * them with " -> "; if we printed a network destination
3323        * and are printing a network source of the same type
3324        * next, separate them with " <- "; otherwise separate them
3325        * with a space.
3326        *
3327        * We add enough space to the buffer for " <- " or " -> ",
3328        * even if we're only adding " ".
3329        */
3330       line_bufp = get_line_buf(buf_offset + 4);
3331       switch (cf->cinfo.col_fmt[i]) {
3332
3333       case COL_DEF_SRC:
3334       case COL_RES_SRC:
3335       case COL_UNRES_SRC:
3336         switch (cf->cinfo.col_fmt[i + 1]) {
3337
3338         case COL_DEF_DST:
3339         case COL_RES_DST:
3340         case COL_UNRES_DST:
3341           g_strlcat(line_bufp + buf_offset, " -> ", 5);
3342           buf_offset += 4;
3343           break;
3344
3345         default:
3346           g_strlcat(line_bufp + buf_offset, " ", 5);
3347           buf_offset += 1;
3348           break;
3349         }
3350         break;
3351
3352       case COL_DEF_DL_SRC:
3353       case COL_RES_DL_SRC:
3354       case COL_UNRES_DL_SRC:
3355         switch (cf->cinfo.col_fmt[i + 1]) {
3356
3357         case COL_DEF_DL_DST:
3358         case COL_RES_DL_DST:
3359         case COL_UNRES_DL_DST:
3360           g_strlcat(line_bufp + buf_offset, " -> ", 5);
3361           buf_offset += 4;
3362           break;
3363
3364         default:
3365           g_strlcat(line_bufp + buf_offset, " ", 5);
3366           buf_offset += 1;
3367           break;
3368         }
3369         break;
3370
3371       case COL_DEF_NET_SRC:
3372       case COL_RES_NET_SRC:
3373       case COL_UNRES_NET_SRC:
3374         switch (cf->cinfo.col_fmt[i + 1]) {
3375
3376         case COL_DEF_NET_DST:
3377         case COL_RES_NET_DST:
3378         case COL_UNRES_NET_DST:
3379           g_strlcat(line_bufp + buf_offset, " -> ", 5);
3380           buf_offset += 4;
3381           break;
3382
3383         default:
3384           g_strlcat(line_bufp + buf_offset, " ", 5);
3385           buf_offset += 1;
3386           break;
3387         }
3388         break;
3389
3390       case COL_DEF_DST:
3391       case COL_RES_DST:
3392       case COL_UNRES_DST:
3393         switch (cf->cinfo.col_fmt[i + 1]) {
3394
3395         case COL_DEF_SRC:
3396         case COL_RES_SRC:
3397         case COL_UNRES_SRC:
3398           g_strlcat(line_bufp + buf_offset, " <- ", 5);
3399           buf_offset += 4;
3400           break;
3401
3402         default:
3403           g_strlcat(line_bufp + buf_offset, " ", 5);
3404           buf_offset += 1;
3405           break;
3406         }
3407         break;
3408
3409       case COL_DEF_DL_DST:
3410       case COL_RES_DL_DST:
3411       case COL_UNRES_DL_DST:
3412         switch (cf->cinfo.col_fmt[i + 1]) {
3413
3414         case COL_DEF_DL_SRC:
3415         case COL_RES_DL_SRC:
3416         case COL_UNRES_DL_SRC:
3417           g_strlcat(line_bufp + buf_offset, " <- ", 5);
3418           buf_offset += 4;
3419           break;
3420
3421         default:
3422           g_strlcat(line_bufp + buf_offset, " ", 5);
3423           buf_offset += 1;
3424           break;
3425         }
3426         break;
3427
3428       case COL_DEF_NET_DST:
3429       case COL_RES_NET_DST:
3430       case COL_UNRES_NET_DST:
3431         switch (cf->cinfo.col_fmt[i + 1]) {
3432
3433         case COL_DEF_NET_SRC:
3434         case COL_RES_NET_SRC:
3435         case COL_UNRES_NET_SRC:
3436           g_strlcat(line_bufp + buf_offset, " <- ", 5);
3437           buf_offset += 4;
3438           break;
3439
3440         default:
3441           g_strlcat(line_bufp + buf_offset, " ", 5);
3442           buf_offset += 1;
3443           break;
3444         }
3445         break;
3446
3447       default:
3448         g_strlcat(line_bufp + buf_offset, " ", 5);
3449         buf_offset += 1;
3450         break;
3451       }
3452     }
3453   }
3454   return print_line(print_stream, 0, line_bufp);
3455 }
3456
3457 static gboolean
3458 print_packet(capture_file *cf, epan_dissect_t *edt)
3459 {
3460   print_args_t  print_args;
3461
3462   if (print_summary) {
3463     /* Just fill in the columns. */
3464     epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3465
3466     /* Now print them. */
3467     switch (output_action) {
3468
3469     case WRITE_TEXT:
3470         if (!print_columns(cf))
3471           return FALSE;
3472         break;
3473
3474     case WRITE_XML:
3475         proto_tree_write_psml(edt, stdout);
3476         return !ferror(stdout);
3477     case WRITE_FIELDS: /*No non-verbose "fields" format */
3478         g_assert_not_reached();
3479         break;
3480     }
3481   }
3482   if (print_details) {
3483     /* Print the information in the protocol tree. */
3484     switch (output_action) {
3485
3486     case WRITE_TEXT:
3487       /* Only initialize the fields that are actually used in proto_tree_print.
3488        * This is particularly important for .range, as that's heap memory which
3489        * we would otherwise have to g_free().
3490       print_args.to_file = TRUE;
3491       print_args.format = print_format;
3492       print_args.print_summary = print_summary;
3493       print_args.print_formfeed = FALSE;
3494       packet_range_init(&print_args.range, &cfile);
3495       */
3496       print_args.print_hex = print_hex;
3497       print_args.print_dissections = print_details ? print_dissections_expanded : print_dissections_none;
3498
3499       if (!proto_tree_print(&print_args, edt, print_stream))
3500         return FALSE;
3501       if (!print_hex) {
3502         /* "print_hex_data()" will put out a leading blank line, as well
3503          as a trailing one; print one here, to separate the packets,
3504          only if "print_hex_data()" won't be called. */
3505         if (!print_line(print_stream, 0, separator))
3506           return FALSE;
3507       }
3508       break;
3509
3510     case WRITE_XML:
3511       proto_tree_write_pdml(edt, stdout);
3512       printf("\n");
3513       return !ferror(stdout);
3514     case WRITE_FIELDS:
3515       proto_tree_write_fields(output_fields, edt, stdout);
3516       printf("\n");
3517       return !ferror(stdout);
3518     }
3519   }
3520   if (print_hex) {
3521     if (print_summary || print_details) {
3522       if (!print_line(print_stream, 0, ""))
3523         return FALSE;
3524     }
3525     if (!print_hex_data(print_stream, edt))
3526       return FALSE;
3527     if (!print_line(print_stream, 0, separator))
3528       return FALSE;
3529   }
3530   return TRUE;
3531 }
3532
3533 static gboolean
3534 write_finale(void)
3535 {
3536   switch (output_action) {
3537
3538   case WRITE_TEXT:
3539     return print_finale(print_stream);
3540
3541   case WRITE_XML:
3542     if (print_details)
3543       write_pdml_finale(stdout);
3544     else
3545       write_psml_finale(stdout);
3546     return !ferror(stdout);
3547
3548   case WRITE_FIELDS:
3549     write_fields_finale(output_fields, stdout);
3550     return !ferror(stdout);
3551
3552   default:
3553     g_assert_not_reached();
3554     return FALSE;
3555   }
3556 }
3557
3558 cf_status_t
3559 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3560 {
3561   wtap       *wth;
3562   gchar       *err_info;
3563   char        err_msg[2048+1];
3564
3565   wth = wtap_open_offline(fname, err, &err_info, perform_two_pass_analysis);
3566   if (wth == NULL)
3567     goto fail;
3568
3569   /* The open succeeded.  Fill in the information for this file. */
3570
3571   /* Cleanup all data structures used for dissection. */
3572   cleanup_dissection();
3573   /* Initialize all data structures used for dissection. */
3574   init_dissection();
3575
3576   cf->wth = wth;
3577   cf->f_datalen = 0; /* not used, but set it anyway */
3578
3579   /* Set the file name because we need it to set the follow stream filter.
3580      XXX - is that still true?  We need it for other reasons, though,
3581      in any case. */
3582   cf->filename = g_strdup(fname);
3583
3584   /* Indicate whether it's a permanent or temporary file. */
3585   cf->is_tempfile = is_tempfile;
3586
3587   /* No user changes yet. */
3588   cf->unsaved_changes = FALSE;
3589
3590   cf->cd_t      = wtap_file_type(cf->wth);
3591   cf->count     = 0;
3592   cf->drops_known = FALSE;
3593   cf->drops     = 0;
3594   cf->snap      = wtap_snapshot_length(cf->wth);
3595   if (cf->snap == 0) {
3596     /* Snapshot length not known. */
3597     cf->has_snap = FALSE;
3598     cf->snap = WTAP_MAX_PACKET_SIZE;
3599   } else
3600     cf->has_snap = TRUE;
3601   nstime_set_zero(&cf->elapsed_time);
3602   nstime_set_unset(&first_ts);
3603   prev_dis = NULL;
3604   prev_cap = NULL;
3605
3606   cf->state = FILE_READ_IN_PROGRESS;
3607
3608   wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
3609   wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
3610
3611   return CF_OK;
3612
3613 fail:
3614   g_snprintf(err_msg, sizeof err_msg,
3615              cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3616   cmdarg_err("%s", err_msg);
3617   return CF_ERROR;
3618 }
3619
3620 static void
3621 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3622 {
3623   char *save_file_string;
3624
3625   save_file_string = output_file_description(fname);
3626
3627   switch (err) {
3628
3629   case ENOSPC:
3630     cmdarg_err("Not all the packets could be written to the %s because there is "
3631                "no space left on the file system.",
3632                save_file_string);
3633     break;
3634
3635 #ifdef EDQUOT
3636   case EDQUOT:
3637     cmdarg_err("Not all the packets could be written to the %s because you are "
3638                "too close to, or over your disk quota.",
3639                save_file_string);
3640   break;
3641 #endif
3642
3643   case WTAP_ERR_CANT_CLOSE:
3644     cmdarg_err("The %s couldn't be closed for some unknown reason.",
3645                save_file_string);
3646     break;
3647
3648   case WTAP_ERR_SHORT_WRITE:
3649     cmdarg_err("Not all the packets could be written to the %s.",
3650                save_file_string);
3651     break;
3652
3653   default:
3654     if (is_close) {
3655       cmdarg_err("The %s could not be closed: %s.", save_file_string,
3656                  wtap_strerror(err));
3657     } else {
3658       cmdarg_err("An error occurred while writing to the %s: %s.",
3659                  save_file_string, wtap_strerror(err));
3660     }
3661     break;
3662   }
3663   g_free(save_file_string);
3664 }
3665
3666 static void
3667 show_print_file_io_error(int err)
3668 {
3669   switch (err) {
3670
3671   case ENOSPC:
3672     cmdarg_err("Not all the packets could be printed because there is "
3673 "no space left on the file system.");
3674     break;
3675
3676 #ifdef EDQUOT
3677   case EDQUOT:
3678     cmdarg_err("Not all the packets could be printed because you are "
3679 "too close to, or over your disk quota.");
3680   break;
3681 #endif
3682
3683   default:
3684     cmdarg_err("An error occurred while printing packets: %s.",
3685       g_strerror(err));
3686     break;
3687   }
3688 }
3689
3690 static const char *
3691 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3692                       int file_type)
3693 {
3694   const char *errmsg;
3695   static char errmsg_errno[1024+1];
3696
3697   if (err < 0) {
3698     /* Wiretap error. */
3699     switch (err) {
3700
3701     case WTAP_ERR_NOT_REGULAR_FILE:
3702       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3703       break;
3704
3705     case WTAP_ERR_RANDOM_OPEN_PIPE:
3706       /* Seen only when opening a capture file for reading. */
3707       errmsg = "The file \"%s\" is a pipe or FIFO; TShark can't read pipe or FIFO files in two-pass mode.";
3708       break;
3709
3710     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3711       /* Seen only when opening a capture file for reading. */
3712       errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3713       break;
3714
3715     case WTAP_ERR_UNSUPPORTED:
3716       /* Seen only when opening a capture file for reading. */
3717       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3718                "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3719                "(%s)", err_info);
3720       g_free(err_info);
3721       errmsg = errmsg_errno;
3722       break;
3723
3724     case WTAP_ERR_CANT_WRITE_TO_PIPE:
3725       /* Seen only when opening a capture file for writing. */
3726       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3727                  "The file \"%%s\" is a pipe, and \"%s\" capture files can't be "
3728                  "written to a pipe.", wtap_file_type_short_string(file_type));
3729       errmsg = errmsg_errno;
3730       break;
3731
3732     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3733       /* Seen only when opening a capture file for writing. */
3734       errmsg = "TShark doesn't support writing capture files in that format.";
3735       break;
3736
3737     case WTAP_ERR_UNSUPPORTED_ENCAP:
3738       if (for_writing) {
3739         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3740                    "TShark can't save this capture as a \"%s\" file.",
3741                    wtap_file_type_short_string(file_type));
3742       } else {
3743         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3744                  "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3745                  "(%s)", err_info);
3746         g_free(err_info);
3747       }
3748       errmsg = errmsg_errno;
3749       break;
3750
3751     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3752       if (for_writing) {
3753         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3754                    "TShark can't save this capture as a \"%s\" file.",
3755                    wtap_file_type_short_string(file_type));
3756         errmsg = errmsg_errno;
3757       } else
3758         errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3759       break;
3760
3761     case WTAP_ERR_BAD_FILE:
3762       /* Seen only when opening a capture file for reading. */
3763       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3764                "The file \"%%s\" appears to be damaged or corrupt.\n"
3765                "(%s)", err_info);
3766       g_free(err_info);
3767       errmsg = errmsg_errno;
3768       break;
3769
3770     case WTAP_ERR_CANT_OPEN:
3771       if (for_writing)
3772         errmsg = "The file \"%s\" could not be created for some unknown reason.";
3773       else
3774         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3775       break;
3776
3777     case WTAP_ERR_SHORT_READ:
3778       errmsg = "The file \"%s\" appears to have been cut short"
3779                " in the middle of a packet or other data.";
3780       break;
3781
3782     case WTAP_ERR_SHORT_WRITE:
3783       errmsg = "A full header couldn't be written to the file \"%s\".";
3784       break;
3785
3786     case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
3787       errmsg = "This file type cannot be written as a compressed file.";
3788       break;
3789
3790     case WTAP_ERR_DECOMPRESS:
3791       /* Seen only when opening a capture file for reading. */
3792       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3793                  "The compressed file \"%%s\" appears to be damaged or corrupt.\n"
3794                  "(%s)", err_info);
3795       g_free(err_info);
3796       errmsg = errmsg_errno;
3797       break;
3798
3799     default:
3800       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3801                  "The file \"%%s\" could not be %s: %s.",
3802                  for_writing ? "created" : "opened",
3803                  wtap_strerror(err));
3804       errmsg = errmsg_errno;
3805       break;
3806     }
3807   } else
3808     errmsg = file_open_error_message(err, for_writing);
3809   return errmsg;
3810 }
3811
3812 /*
3813  * Open/create errors are reported with an console message in TShark.
3814  */
3815 static void
3816 open_failure_message(const char *filename, int err, gboolean for_writing)
3817 {
3818   fprintf(stderr, "tshark: ");
3819   fprintf(stderr, file_open_error_message(err, for_writing), filename);
3820   fprintf(stderr, "\n");
3821 }
3822
3823
3824 /*
3825  * General errors are reported with an console message in TShark.
3826  */
3827 static void
3828 failure_message(const char *msg_format, va_list ap)
3829 {
3830   fprintf(stderr, "tshark: ");
3831   vfprintf(stderr, msg_format, ap);
3832   fprintf(stderr, "\n");
3833 }
3834
3835 /*
3836  * Read errors are reported with an console message in TShark.
3837  */
3838 static void
3839 read_failure_message(const char *filename, int err)
3840 {
3841   cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3842           filename, g_strerror(err));
3843 }
3844
3845 /*
3846  * Write errors are reported with an console message in TShark.
3847  */
3848 static void
3849 write_failure_message(const char *filename, int err)
3850 {
3851   cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3852           filename, g_strerror(err));
3853 }
3854
3855 /*
3856  * Print to the standard error.  This is a command-line tool, so there's
3857  * no need to pop up a console.
3858  */
3859 void
3860 vfprintf_stderr(const char *fmt, va_list ap)
3861 {
3862   vfprintf(stderr, fmt, ap);
3863 }
3864
3865 void
3866 fprintf_stderr(const char *fmt, ...)
3867 {
3868   va_list ap;
3869
3870   va_start(ap, fmt);
3871   vfprintf_stderr(fmt, ap);
3872   va_end(ap);
3873 }
3874
3875 /*
3876  * Report an error in command-line arguments.
3877  */
3878 void
3879 cmdarg_err(const char *fmt, ...)
3880 {
3881   va_list ap;
3882
3883   va_start(ap, fmt);
3884   failure_message(fmt, ap);
3885   va_end(ap);
3886 }
3887
3888 /*
3889  * Report additional information for an error in command-line arguments.
3890  */
3891 void
3892 cmdarg_err_cont(const char *fmt, ...)
3893 {
3894   va_list ap;
3895
3896   va_start(ap, fmt);
3897   vfprintf(stderr, fmt, ap);
3898   fprintf(stderr, "\n");
3899   va_end(ap);
3900 }