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