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