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