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