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