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