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