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