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