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