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