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