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