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