wsutil/wsgcrypt.c decrypt_des_ecb
[wireshark-sm.git] / tshark.c
blob92bf3f46c97ac573c5f5b6e28b68d95420e7c999
1 /* tshark.c
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>.
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * SPDX-License-Identifier: GPL-2.0-or-later
13 #include <config.h>
15 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <locale.h>
21 #include <limits.h>
23 #include <wsutil/ws_getopt.h>
25 #include <errno.h>
27 #ifdef _WIN32
28 # include <winsock2.h>
29 #endif
31 #ifndef _WIN32
32 #include <signal.h>
33 #endif
35 #include <glib.h>
37 #include <epan/exceptions.h>
38 #include <epan/epan.h>
40 #include <ws_exit_codes.h>
41 #include <wsutil/clopts_common.h>
42 #include <wsutil/cmdarg_err.h>
43 #include <ui/urls.h>
44 #include <wsutil/filesystem.h>
45 #include <wsutil/file_util.h>
46 #include <wsutil/time_util.h>
47 #include <wsutil/socket.h>
48 #include <wsutil/privileges.h>
49 #include <wsutil/please_report_bug.h>
50 #include <wsutil/wslog.h>
51 #include <wsutil/ws_assert.h>
52 #include <wsutil/strtoi.h>
53 #include <cli_main.h>
54 #include <wsutil/version_info.h>
55 #include <wiretap/wtap_opttypes.h>
57 #include "globals.h"
58 #include <epan/timestamp.h>
59 #include <epan/packet.h>
60 #ifdef HAVE_LUA
61 #include <epan/wslua/init_wslua.h>
62 #endif
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 #include <epan/enterprises.h>
70 #include <epan/manuf.h>
71 #include <epan/services.h>
72 #ifdef HAVE_LIBPCAP
73 #include "ui/capture_ui_utils.h"
74 #endif
75 #include "ui/taps.h"
76 #include "ui/util.h"
77 #include "ui/ws_ui_util.h"
78 #include "ui/decode_as_utils.h"
79 #include "wsutil/filter_files.h"
80 #include "ui/cli/tshark-tap.h"
81 #include "ui/cli/tap-exportobject.h"
82 #include "ui/tap_export_pdu.h"
83 #include "ui/dissect_opts.h"
84 #include "ui/ssl_key_export.h"
85 #include "ui/failure_message.h"
86 #include "ui/capture_opts.h"
87 #if defined(HAVE_LIBSMI)
88 #include "epan/oids.h"
89 #endif
90 #include "epan/maxmind_db.h"
91 #include <epan/epan_dissect.h>
92 #include <epan/tap.h>
93 #include <epan/stat_tap_ui.h>
94 #include <epan/conversation_table.h>
95 #include <epan/srt_table.h>
96 #include <epan/rtd_table.h>
97 #include <epan/ex-opt.h>
98 #include <epan/exported_pdu.h>
99 #include <epan/secrets.h>
101 #include "capture/capture-pcap-util.h"
103 #ifdef HAVE_LIBPCAP
104 #include "capture/capture_ifinfo.h"
105 #ifdef _WIN32
106 #include "capture/capture-wpcap.h"
107 #endif /* _WIN32 */
108 #include <capture/capture_session.h>
109 #include <capture/capture_sync.h>
110 #include <ui/capture_info.h>
111 #endif /* HAVE_LIBPCAP */
112 #include <epan/funnel.h>
114 #include <wsutil/str_util.h>
115 #include <wsutil/utf8_entities.h>
116 #include <wsutil/json_dumper.h>
117 #include <wsutil/wslog.h>
118 #ifdef _WIN32
119 #include <wsutil/win32-utils.h>
120 #endif
122 #include "extcap.h"
124 #ifdef HAVE_PLUGINS
125 #include <wsutil/codecs.h>
126 #include <wsutil/plugins.h>
127 #endif
129 /* Additional exit codes */
130 #define INVALID_EXPORT 2
131 #define INVALID_TAP 2
132 #define INVALID_CAPTURE 2
134 #define LONGOPT_EXPORT_OBJECTS LONGOPT_BASE_APPLICATION+1
135 #define LONGOPT_COLOR LONGOPT_BASE_APPLICATION+2
136 #define LONGOPT_NO_DUPLICATE_KEYS LONGOPT_BASE_APPLICATION+3
137 #define LONGOPT_ELASTIC_MAPPING_FILTER LONGOPT_BASE_APPLICATION+4
138 #define LONGOPT_EXPORT_TLS_SESSION_KEYS LONGOPT_BASE_APPLICATION+5
139 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
140 #define LONGOPT_HEXDUMP LONGOPT_BASE_APPLICATION+7
141 #define LONGOPT_SELECTED_FRAME LONGOPT_BASE_APPLICATION+8
142 #define LONGOPT_PRINT_TIMERS LONGOPT_BASE_APPLICATION+9
143 #define LONGOPT_GLOBAL_PROFILE LONGOPT_BASE_APPLICATION+10
144 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+11
146 capture_file cfile;
148 static uint32_t cum_bytes;
149 static frame_data ref_frame;
150 static frame_data prev_dis_frame;
151 static frame_data prev_cap_frame;
153 static bool perform_two_pass_analysis;
154 static uint32_t epan_auto_reset_count;
155 static bool epan_auto_reset;
157 static uint32_t selected_frame_number;
160 * The way the packet decode is to be written.
162 typedef enum {
163 WRITE_NONE, /* dummy initial state */
164 WRITE_TEXT, /* summary or detail text */
165 WRITE_XML, /* PDML or PSML */
166 WRITE_FIELDS, /* User defined list of fields */
167 WRITE_JSON, /* JSON */
168 WRITE_JSON_RAW, /* JSON only raw hex */
169 WRITE_EK /* JSON bulk insert to Elasticsearch */
170 /* Add CSV and the like here */
171 } output_action_e;
173 static output_action_e output_action;
174 static bool do_dissection; /* true if we have to dissect each packet */
175 static bool print_packet_info; /* true if we're to print packet information */
176 static bool print_summary; /* true if we're to print packet summary information */
177 static bool print_details; /* true if we're to print packet details information */
178 static bool print_hex; /* true if we're to print hex/ascii information */
179 static bool line_buffered;
180 static bool quiet;
181 static bool really_quiet;
182 static char* delimiter_char = " ";
183 static bool dissect_color;
184 static unsigned hexdump_source_option = HEXDUMP_SOURCE_MULTI; /* Default - Enable legacy multi-source mode */
185 static unsigned hexdump_ascii_option = HEXDUMP_ASCII_INCLUDE; /* Default - Enable legacy undelimited ASCII dump */
186 static unsigned hexdump_timestamp_option = HEXDUMP_TIMESTAMP_NONE; /* Default - no timestamp preamble */
188 static print_format_e print_format = PR_FMT_TEXT;
189 static print_stream_t *print_stream;
191 static char *output_file_name;
193 static output_fields_t* output_fields;
195 static bool no_duplicate_keys;
196 static proto_node_children_grouper_func node_children_grouper = proto_node_group_children_by_unique;
198 static json_dumper jdumper;
200 /* The line separator used between packets, changeable via the -S option */
201 static const char *separator = "";
203 /* Per-file comments to be added to the output file. */
204 static GPtrArray *capture_comments;
206 static bool prefs_loaded;
208 #ifdef HAVE_LIBPCAP
210 * true if we're to print packet counts to keep track of captured packets.
212 static bool print_packet_counts;
214 static capture_options global_capture_opts;
215 static capture_session global_capture_session;
216 static info_data_t global_info_data;
218 #ifdef SIGINFO
219 static bool infodelay; /* if true, don't print capture info in SIGINFO handler */
220 static bool infoprint; /* if true, print capture info after clearing infodelay */
221 #endif /* SIGINFO */
223 static bool capture(void);
224 static bool capture_input_new_file(capture_session *cap_session,
225 char *new_file);
226 static void capture_input_new_packets(capture_session *cap_session,
227 int to_read);
228 static void capture_input_drops(capture_session *cap_session, uint32_t dropped,
229 const char* interface_name);
230 static void capture_input_error(capture_session *cap_session,
231 char *error_msg, char *secondary_error_msg);
232 static void capture_input_cfilter_error(capture_session *cap_session,
233 unsigned i, const char *error_message);
234 static void capture_input_closed(capture_session *cap_session, char *msg);
236 static void report_counts(void);
237 #ifdef _WIN32
238 static BOOL WINAPI capture_cleanup(DWORD);
239 #else /* _WIN32 */
240 static void capture_cleanup(int);
241 #ifdef SIGINFO
242 static void report_counts_siginfo(int);
243 #endif /* SIGINFO */
244 #endif /* _WIN32 */
245 #endif /* HAVE_LIBPCAP */
247 static void reset_epan_mem(capture_file *cf, epan_dissect_t *edt, bool tree, bool visual);
249 typedef enum {
250 PROCESS_FILE_SUCCEEDED,
251 PROCESS_FILE_NO_FILE_PROCESSED,
252 PROCESS_FILE_ERROR,
253 PROCESS_FILE_INTERRUPTED
254 } process_file_status_t;
255 static process_file_status_t process_cap_file(capture_file *, char *, int, bool, int, int64_t, int, wtap_compression_type);
257 static bool process_packet_single_pass(capture_file *cf,
258 epan_dissect_t *edt, int64_t offset, wtap_rec *rec, unsigned tap_flags);
259 static void show_print_file_io_error(void);
260 static bool write_preamble(capture_file *cf);
261 static bool print_packet(capture_file *cf, epan_dissect_t *edt);
262 static bool write_finale(void);
264 static GHashTable *output_only_tables;
266 static bool opt_print_timers;
267 struct elapsed_pass_s {
268 int64_t dissect;
269 int64_t dfilter_read;
270 int64_t dfilter_filter;
272 static struct {
273 int64_t dfilter_expand;
274 int64_t dfilter_compile;
275 struct elapsed_pass_s first_pass;
276 int64_t elapsed_first_pass;
277 struct elapsed_pass_s second_pass;
278 int64_t elapsed_second_pass;
280 tshark_elapsed;
282 static void
283 print_elapsed_json(const char *cf_name, const char *dfilter)
285 json_dumper dumper = {
286 .output_file = stderr,
287 .flags = JSON_DUMPER_FLAGS_PRETTY_PRINT,
290 if (tshark_elapsed.elapsed_first_pass == 0) {
291 // Should not happen
292 ws_warning("Print timers requested but no timing info provided");
293 return;
296 #define DUMP(name, val) \
297 json_dumper_set_member_name(&dumper, name); \
298 json_dumper_value_anyf(&dumper, "%"PRId64, val)
300 json_dumper_begin_object(&dumper);
301 json_dumper_set_member_name(&dumper, "version");
302 json_dumper_value_string(&dumper, get_ws_vcs_version_info_short());
303 if (cf_name) {
304 json_dumper_set_member_name(&dumper, "path");
305 json_dumper_value_string(&dumper, cf_name);
307 if (dfilter) {
308 json_dumper_set_member_name(&dumper, "filter");
309 json_dumper_value_string(&dumper, dfilter);
311 json_dumper_set_member_name(&dumper, "time_unit");
312 json_dumper_value_string(&dumper, "microseconds");
313 DUMP("elapsed", tshark_elapsed.elapsed_first_pass +
314 tshark_elapsed.elapsed_second_pass);
315 DUMP("dfilter_expand", tshark_elapsed.dfilter_expand);
316 DUMP("dfilter_compile", tshark_elapsed.dfilter_compile);
317 json_dumper_begin_array(&dumper);
318 json_dumper_begin_object(&dumper);
319 DUMP("elapsed", tshark_elapsed.elapsed_first_pass);
320 DUMP("dissect", tshark_elapsed.first_pass.dissect);
321 DUMP("display_filter", tshark_elapsed.first_pass.dfilter_filter);
322 DUMP("read_filter", tshark_elapsed.first_pass.dfilter_read);
323 json_dumper_end_object(&dumper);
324 if (tshark_elapsed.elapsed_second_pass) {
325 json_dumper_begin_object(&dumper);
326 DUMP("elapsed", tshark_elapsed.elapsed_second_pass);
327 DUMP("dissect", tshark_elapsed.second_pass.dissect);
328 DUMP("display_filter", tshark_elapsed.second_pass.dfilter_filter);
329 DUMP("read_filter", tshark_elapsed.second_pass.dfilter_read);
330 json_dumper_end_object(&dumper);
332 json_dumper_end_array(&dumper);
333 json_dumper_end_object(&dumper);
334 json_dumper_finish(&dumper);
337 static void
338 list_capture_types(void)
340 GArray *writable_type_subtypes;
342 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
343 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
344 for (unsigned i = 0; i < writable_type_subtypes->len; i++) {
345 int ft = g_array_index(writable_type_subtypes, int, i);
346 fprintf(stderr, " %s - %s\n", wtap_file_type_subtype_name(ft),
347 wtap_file_type_subtype_description(ft));
349 g_array_free(writable_type_subtypes, TRUE);
352 static void
353 list_output_compression_types(void) {
354 GSList *output_compression_types;
356 cmdarg_err("The available output compression type(s) are:");
357 output_compression_types = wtap_get_all_output_compression_type_names_list();
358 for (GSList *compression_type = output_compression_types;
359 compression_type != NULL;
360 compression_type = g_slist_next(compression_type)) {
361 cmdarg_err_cont(" %s", (const char *)compression_type->data);
364 g_slist_free(output_compression_types);
367 struct string_elem {
368 const char *sstr; /* The short string */
369 const char *lstr; /* The long string */
372 static int
373 string_compare(const void *a, const void *b)
375 return strcmp(((const struct string_elem *)a)->sstr,
376 ((const struct string_elem *)b)->sstr);
379 static void
380 string_elem_print(void *data)
382 fprintf(stderr, " %s - %s\n",
383 ((struct string_elem *)data)->sstr,
384 ((struct string_elem *)data)->lstr);
387 static void
388 list_read_capture_types(void)
390 unsigned i;
391 size_t num_file_types;
392 struct string_elem *captypes;
393 GSList *list = NULL;
394 const char *magic = "Magic-value-based";
395 const char *heuristic = "Heuristics-based";
397 /* How many readable file types are there? */
398 num_file_types = 0;
399 for (i = 0; open_routines[i].name != NULL; i++)
400 num_file_types++;
401 captypes = g_new(struct string_elem, num_file_types);
403 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
404 for (i = 0; i < num_file_types && open_routines[i].name != NULL; i++) {
405 captypes[i].sstr = open_routines[i].name;
406 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
407 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
409 g_slist_free_full(list, string_elem_print);
410 g_free(captypes);
413 static void
414 list_export_pdu_taps(void)
416 fprintf(stderr, "tshark: The available export tap names and the encapsulation types they produce for the \"-U tap_name\" option are:\n");
417 for (GSList *export_pdu_tap_name_list = get_export_pdu_tap_list();
418 export_pdu_tap_name_list != NULL;
419 export_pdu_tap_name_list = g_slist_next(export_pdu_tap_name_list)) {
420 fprintf(stderr, " %s - %s\n", (const char*)(export_pdu_tap_name_list->data), wtap_encap_description(export_pdu_tap_get_encap((const char*)export_pdu_tap_name_list->data)));
424 static void
425 print_usage(FILE *output)
427 fprintf(output, "\n");
428 fprintf(output, "Usage: tshark [options] ...\n");
429 fprintf(output, "\n");
431 #ifdef HAVE_LIBPCAP
432 fprintf(output, "Capture interface:\n");
433 fprintf(output, " -i <interface>, --interface <interface>\n");
434 fprintf(output, " name or idx of interface (def: first non-loopback)\n");
435 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
436 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
437 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
438 fprintf(output, " -p, --no-promiscuous-mode\n");
439 fprintf(output, " don't capture in promiscuous mode\n");
440 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
441 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
442 fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
443 fprintf(output, " -y <link type>, --linktype <link type>\n");
444 fprintf(output, " link layer type (def: first appropriate)\n");
445 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
446 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
447 fprintf(output, " -L, --list-data-link-types\n");
448 fprintf(output, " print list of link-layer types of iface and exit\n");
449 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
450 fprintf(output, "\n");
451 fprintf(output, "Capture display:\n");
452 fprintf(output, " --update-interval interval between updates with new packets, in milliseconds (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
453 fprintf(output, "Capture stop conditions:\n");
454 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
455 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
456 fprintf(output, " duration:NUM - stop after NUM seconds\n");
457 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
458 fprintf(output, " files:NUM - stop after NUM files\n");
459 fprintf(output, " packets:NUM - stop after NUM packets\n");
460 /*fprintf(output, "\n");*/
461 fprintf(output, "Capture output:\n");
462 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
463 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
464 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
465 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
466 fprintf(output, " packets:NUM - switch to next file after NUM packets\n");
467 fprintf(output, " interval:NUM - switch to next file when the time is\n");
468 fprintf(output, " an exact multiple of NUM secs\n");
469 fprintf(output, " printname:FILE - print filename to FILE when written\n");
470 fprintf(output, " (can use 'stdout' or 'stderr')\n");
471 #endif /* HAVE_LIBPCAP */
472 #ifdef HAVE_PCAP_REMOTE
473 fprintf(output, "RPCAP options:\n");
474 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
475 #endif
476 /*fprintf(output, "\n");*/
477 fprintf(output, "Input file:\n");
478 fprintf(output, " -r <infile>, --read-file <infile>\n");
479 fprintf(output, " set the filename to read from (or '-' for stdin)\n");
481 fprintf(output, "\n");
482 fprintf(output, "Processing:\n");
483 fprintf(output, " -2 perform a two-pass analysis\n");
484 fprintf(output, " -M <packet count> perform session auto reset\n");
485 fprintf(output, " -R <read filter>, --read-filter <read filter>\n");
486 fprintf(output, " packet Read filter in Wireshark display filter syntax\n");
487 fprintf(output, " (requires -2)\n");
488 fprintf(output, " -Y <display filter>, --display-filter <display filter>\n");
489 fprintf(output, " packet displaY filter in Wireshark display filter\n");
490 fprintf(output, " syntax\n");
491 fprintf(output, " -n disable all name resolutions (def: \"mNd\" enabled, or\n");
492 fprintf(output, " as set in preferences)\n");
493 // Note: the order of the flags here matches the options in the settings dialog e.g. "dsN" only have an effect if "n" is set
494 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mtndsNvg\"\n");
495 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
496 fprintf(output, " \"Decode As\", see the man page for details\n");
497 fprintf(output, " Example: tcp.port==8888,http\n");
498 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
499 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
500 fprintf(output, " --enable-protocol <proto_name>\n");
501 fprintf(output, " enable dissection of proto_name\n");
502 fprintf(output, " --disable-protocol <proto_name>\n");
503 fprintf(output, " disable dissection of proto_name\n");
504 fprintf(output, " --only-protocols <protocols>\n");
505 fprintf(output, " Only enable dissection of these protocols, comma\n");
506 fprintf(output, " separated. Disable everything else\n");
507 fprintf(output, " --disable-all-protocols\n");
508 fprintf(output, " Disable dissection of all protocols\n");
509 fprintf(output, " --enable-heuristic <short_name>\n");
510 fprintf(output, " enable dissection of heuristic protocol\n");
511 fprintf(output, " --disable-heuristic <short_name>\n");
512 fprintf(output, " disable dissection of heuristic protocol\n");
514 /*fprintf(output, "\n");*/
515 fprintf(output, "Output:\n");
516 fprintf(output, " -w <outfile|-> write packets to a pcapng-format file named \"outfile\"\n");
517 fprintf(output, " (or '-' for stdout). If the output filename has the\n");
518 fprintf(output, " .gz extension, it will be compressed to a gzip archive\n");
519 fprintf(output, " --capture-comment <comment>\n");
520 fprintf(output, " add a capture file comment, if supported\n");
521 fprintf(output, " -C <config profile> start with specified configuration profile\n");
522 fprintf(output, " --global-profile use the global profile instead of personal profile\n");
523 fprintf(output, " -F <output file type> set the output file type; default is pcapng.\n");
524 fprintf(output, " an empty \"-F\" option will list the file types\n");
525 fprintf(output, " -V add output of packet tree (Packet Details)\n");
526 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
527 fprintf(output, " separated\n");
528 fprintf(output, " -P, --print print packet summary even when writing to a file\n");
529 fprintf(output, " -S <separator> the line separator to print between packets\n");
530 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
531 fprintf(output, " --hexdump <hexoption> add hexdump, set options for data source and ASCII dump\n");
532 fprintf(output, " all dump all data sources (-x default)\n");
533 fprintf(output, " frames dump only frame data source\n");
534 fprintf(output, " ascii include ASCII dump text (-x default)\n");
535 fprintf(output, " delimit delimit ASCII dump text with '|' characters\n");
536 fprintf(output, " noascii exclude ASCII dump text\n");
537 fprintf(output, " time include frame timestamp preamble\n");
538 fprintf(output, " notime do not include frame timestamp preamble (-x default)\n");
539 fprintf(output, " help display help for --hexdump and exit\n");
540 fprintf(output, " -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?\n");
541 fprintf(output, " format of text output (def: text)\n");
542 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected\n");
543 fprintf(output, " (e.g. \"ip ip.flags text\", filter does not expand child\n");
544 fprintf(output, " nodes, unless child is specified also in the filter)\n");
545 fprintf(output, " -J <protocolfilter> top level protocol filter if -T ek|pdml|json selected\n");
546 fprintf(output, " (e.g. \"http tcp\", filter which expands all child nodes)\n");
547 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
548 fprintf(output, " _ws.col.info)\n");
549 fprintf(output, " this option can be repeated to print multiple fields\n");
550 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
551 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
552 fprintf(output, " header=y|n switch headers on and off\n");
553 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
554 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
555 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
556 fprintf(output, " aggregator\n");
557 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
558 fprintf(output, " -t (a|ad|adoy|d|dd|e|r|u|ud|udoy)[.[N]]|.[N]\n");
559 fprintf(output, " output format of time stamps (def: r: rel. to first)\n");
560 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
561 fprintf(output, " -l flush standard output after each packet\n");
562 fprintf(output, " (implies --update-interval 0)\n");
563 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
564 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
565 fprintf(output, " -g enable group read access on the output file(s)\n");
566 fprintf(output, " -W n Save extra information in the file, if supported.\n");
567 fprintf(output, " n = write network address resolution information\n");
568 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
569 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
570 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
571 fprintf(output, " --export-objects <protocol>,<destdir>\n");
572 fprintf(output, " save exported objects for a protocol to a directory\n");
573 fprintf(output, " named \"destdir\"\n");
574 fprintf(output, " --export-tls-session-keys <keyfile>\n");
575 fprintf(output, " export TLS Session Keys to a file named \"keyfile\"\n");
576 fprintf(output, " --color color output text similarly to the Wireshark GUI,\n");
577 fprintf(output, " requires a terminal with 24-bit color support\n");
578 fprintf(output, " Also supplies color attributes to pdml and psml formats\n");
579 fprintf(output, " (Note that attributes are nonstandard)\n");
580 fprintf(output, " --no-duplicate-keys If -T json is specified, merge duplicate keys in an object\n");
581 fprintf(output, " into a single key with as value a json array containing all\n");
582 fprintf(output, " values\n");
583 fprintf(output, " --elastic-mapping-filter <protocols> If -G elastic-mapping is specified, put only the\n");
584 fprintf(output, " specified protocols within the mapping file\n");
585 fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
586 fprintf(output, " (default: %s)\n", g_get_tmp_dir());
587 fprintf(output, " --compress <type> compress the output file using the type compression format\n");
588 fprintf(output, "\n");
590 ws_log_print_usage(output);
591 fprintf(output, "\n");
593 fprintf(output, "Miscellaneous:\n");
594 fprintf(output, " -h, --help display this help and exit\n");
595 fprintf(output, " -v, --version display version info and exit\n");
596 fprintf(output, " -o <name>:<value> ... override preference setting\n");
597 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
598 fprintf(output, " -G [report] dump one of several available reports and exit\n");
599 fprintf(output, " default report=\"fields\"\n");
600 fprintf(output, " use \"-G help\" for more help\n");
601 #ifdef __linux__
602 fprintf(output, "\n");
603 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
604 fprintf(output, "You might want to enable it by executing:\n");
605 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
606 fprintf(output, "Note that this can make your system less secure!\n");
607 #endif
611 static void
612 glossary_option_help(void)
614 FILE *output;
616 output = stdout;
618 fprintf(output, "%s\n", get_appname_and_version());
620 fprintf(output, "\n");
621 fprintf(output, "Usage: tshark -G [report]\n");
622 fprintf(output, "\n");
623 fprintf(output, "Glossary table reports:\n");
624 fprintf(output, " -G column-formats dump column format codes and exit\n");
625 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
626 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
627 fprintf(output, " -G dissectors dump registered dissector names\n");
628 fprintf(output, " -G elastic-mapping dump ElasticSearch mapping file\n");
629 fprintf(output, " -G enterprises dump IANA Private Enterprise Number (PEN) table\n");
630 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
631 fprintf(output, " -G fields,[prefix] dump fields glossary and exit\n");
632 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
633 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
634 fprintf(output, " -G manuf dump ethernet manufacturer tables\n");
635 fprintf(output, " -G plugins dump installed plugins and exit\n");
636 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
637 fprintf(output, " -G services dump transport service (port) names\n");
638 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
639 fprintf(output, "\n");
640 fprintf(output, "Preference reports:\n");
641 fprintf(output, " -G currentprefs dump current preferences and exit\n");
642 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
643 fprintf(output, " -G folders dump about:folders\n");
644 fprintf(output, "\n");
647 static void
648 hexdump_option_help(FILE *output)
650 fprintf(output, "%s\n", get_appname_and_version());
651 fprintf(output, "\n");
652 fprintf(output, "tshark: Valid --hexdump <hexoption> values include:\n");
653 fprintf(output, "\n");
654 fprintf(output, "Data source options:\n");
655 fprintf(output, " all add hexdump, dump all data sources (-x default)\n");
656 fprintf(output, " frames add hexdump, dump only frame data source\n");
657 fprintf(output, "\n");
658 fprintf(output, "ASCII options:\n");
659 fprintf(output, " ascii add hexdump, include ASCII dump text (-x default)\n");
660 fprintf(output, " delimit add hexdump, delimit ASCII dump text with '|' characters\n");
661 fprintf(output, " noascii add hexdump, exclude ASCII dump text\n");
662 fprintf(output, "\n");
663 fprintf(output, "Timestamp options:\n");
664 fprintf(output, " time add hexdump, include frame timestamp preamble (uses the format from -t)\n");
665 fprintf(output, " notime add hexdump, do not include frame timestamp preamble (-x default)\n");
666 fprintf(output, "Miscellaneous:\n");
667 fprintf(output, " help display this help and exit\n");
668 fprintf(output, "\n");
669 fprintf(output, "Example:\n");
670 fprintf(output, "\n");
671 fprintf(output, " $ tshark ... --hexdump frames --hexdump delimit ...\n");
672 fprintf(output, "\n");
675 static void
676 print_current_user(void)
678 char *cur_user, *cur_group;
680 if (started_with_special_privs()) {
681 cur_user = get_cur_username();
682 cur_group = get_cur_groupname();
683 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
684 cur_user, cur_group);
685 g_free(cur_user);
686 g_free(cur_group);
687 if (running_with_special_privs()) {
688 fprintf(stderr, " This could be dangerous.");
690 fprintf(stderr, "\n");
694 static void
695 gather_tshark_compile_info(feature_list l)
697 /* Capture libraries */
698 gather_caplibs_compile_info(l);
699 epan_gather_compile_info(l);
702 static void
703 gather_tshark_runtime_info(feature_list l)
705 #ifdef HAVE_LIBPCAP
706 gather_caplibs_runtime_info(l);
707 #endif
709 /* stuff used by libwireshark */
710 epan_gather_runtime_info(l);
713 static bool
714 _compile_dfilter(const char *text, dfilter_t **dfp, const char *caller)
716 bool ok;
717 df_error_t *df_err;
718 char *err_off;
719 char *expanded;
720 int64_t elapsed_start;
722 elapsed_start = g_get_monotonic_time();
723 expanded = dfilter_expand(text, &df_err);
724 if (expanded == NULL) {
725 cmdarg_err("%s", df_err->msg);
726 df_error_free(&df_err);
727 return false;
729 tshark_elapsed.dfilter_expand = g_get_monotonic_time() - elapsed_start;
731 elapsed_start = g_get_monotonic_time();
732 ok = dfilter_compile_full(expanded, dfp, &df_err, DF_OPTIMIZE, caller);
733 if (!ok ) {
734 cmdarg_err("%s", df_err->msg);
736 if (df_err->loc.col_start >= 0) {
737 err_off = ws_strdup_underline(NULL, df_err->loc.col_start, df_err->loc.col_len);
738 cmdarg_err_cont(" %s", expanded);
739 cmdarg_err_cont(" %s", err_off);
740 g_free(err_off);
742 df_error_free(&df_err);
744 tshark_elapsed.dfilter_compile = g_get_monotonic_time() - elapsed_start;
746 g_free(expanded);
747 return ok;
750 #define compile_dfilter(text, dfp) _compile_dfilter(text, dfp, __func__)
752 static bool
753 protocolfilter_add_opt(const char* arg, pf_flags filter_flags)
755 char **newfilter = NULL;
756 for (newfilter = wmem_strsplit(wmem_epan_scope(), arg, " ", -1); *newfilter; newfilter++) {
757 if (strcmp(*newfilter, "") == 0) {
758 /* Don't treat the empty string as an intended field abbreviation
759 * to output, consecutive spaces on the command line probably
760 * aren't intentional.
762 continue;
764 if (!output_fields_add_protocolfilter(output_fields, *newfilter, filter_flags)) {
765 cmdarg_err("%s was already specified with different filter flags. Overwriting previous protocol filter.", *newfilter);
768 return true;
771 static void
772 about_folders(void)
774 const char *constpath;
775 char *path;
776 int i;
777 char **resultArray;
779 /* "file open" */
782 * Fetching the "File" dialogs folder not implemented.
783 * This is arguably just a pwd for a ui/cli .
786 /* temp */
787 constpath = g_get_tmp_dir();
788 #ifdef HAVE_LIBPCAP
789 /* global_capture_opts only exists in this case */
790 if (global_capture_opts.temp_dir)
791 constpath = global_capture_opts.temp_dir;
792 #endif
793 printf("%-21s\t%s\n", "Temp:", constpath);
795 /* pers conf */
796 path = get_persconffile_path("", false);
797 printf("%-21s\t%s\n", "Personal configuration:", path);
798 g_free(path);
800 /* global conf */
801 constpath = get_datafile_dir();
802 if (constpath != NULL) {
803 printf("%-21s\t%s\n", "Global configuration:", constpath);
806 /* system */
807 constpath = get_systemfile_dir();
808 printf("%-21s\t%s\n", "System:", constpath);
810 /* program */
811 constpath = get_progfile_dir();
812 printf("%-21s\t%s\n", "Program:", constpath);
814 #ifdef HAVE_PLUGINS
815 /* pers plugins */
816 printf("%-21s\t%s\n", "Personal Plugins:", get_plugins_pers_dir_with_version());
818 /* global plugins */
819 printf("%-21s\t%s\n", "Global Plugins:", get_plugins_dir_with_version());
820 #endif
822 #ifdef HAVE_LUA
823 /* pers lua plugins */
824 printf("%-21s\t%s\n", "Personal Lua Plugins:", get_plugins_pers_dir());
826 /* global lua plugins */
827 printf("%-21s\t%s\n", "Global Lua Plugins:", get_plugins_dir());
828 #endif
830 /* Personal Extcap */
831 constpath = get_extcap_pers_dir();
833 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
834 for(i = 0; resultArray[i]; i++)
835 printf("%-21s\t%s\n", "Personal Extcap path:", g_strstrip(resultArray[i]));
837 g_strfreev(resultArray);
839 /* Global Extcap */
840 constpath = get_extcap_dir();
842 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
843 for(i = 0; resultArray[i]; i++)
844 printf("%-21s\t%s\n", "Global Extcap path:", g_strstrip(resultArray[i]));
846 g_strfreev(resultArray);
848 /* MaxMindDB */
849 path = maxmind_db_get_paths();
851 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
853 for(i = 0; resultArray[i]; i++)
854 printf("%-21s\t%s\n", "MaxMind database path:", g_strstrip(resultArray[i]));
856 g_strfreev(resultArray);
857 g_free(path);
859 #ifdef HAVE_LIBSMI
860 /* SMI MIBs/PIBs */
861 path = oid_get_default_mib_path();
863 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 20);
865 for(i = 0; resultArray[i]; i++)
866 printf("%-21s\t%s\n", "MIB/PIB path:", g_strstrip(resultArray[i]));
868 g_strfreev(resultArray);
869 g_free(path);
870 #endif
874 static int
875 dump_glossary(const char* glossary, const char* elastic_mapping_filter)
877 int exit_status = EXIT_SUCCESS;
878 /* If invoked with the "-G" flag, we dump out information based on
879 the argument to the "-G" flag.
882 /* This is now called after the preferences are loaded and all
883 * the command line options are handled, including -o, -d,
884 * --[enable|disable]-[protocol|heuristic].
885 * Some UATs can register new fields (e.g. HTTP/2), so for most
886 * cases load everything.
888 * prefs_reset() is used for defaultprefs to get the default values.
889 * Note that makes it difficult to use defaultprefs in concert with
890 * any other glossary (we could do it last.)
892 proto_initialize_all_prefixes();
894 if (strcmp(glossary, "column-formats") == 0)
895 column_dump_column_formats();
896 else if (strcmp(glossary, "currentprefs") == 0) {
897 write_prefs(NULL);
899 else if (strcmp(glossary, "decodes") == 0) {
900 dissector_dump_decodes();
901 } else if (strcmp(glossary, "defaultprefs") == 0) {
902 prefs_reset();
903 write_prefs(NULL);
904 } else if (strcmp(glossary, "dissector-tables") == 0)
905 dissector_dump_dissector_tables();
906 else if (strcmp(glossary, "dissectors") == 0)
907 dissector_dump_dissectors();
908 else if (strcmp(glossary, "elastic-mapping") == 0)
909 proto_registrar_dump_elastic(elastic_mapping_filter);
910 else if (strncmp(glossary, "elastic-mapping,", strlen("elastic-mapping,")) == 0) {
911 elastic_mapping_filter = glossary + strlen("elastic-mapping,");
912 proto_registrar_dump_elastic(elastic_mapping_filter);
914 else if (strcmp(glossary, "fieldcount") == 0) {
915 /* return value for the test suite */
916 exit_status = proto_registrar_dump_fieldcount();
918 else if (strcmp(glossary, "fields") == 0) {
919 proto_registrar_dump_fields();
921 else if (strncmp(glossary, "fields,", strlen("fields,")) == 0) {
922 const char* prefix = glossary + strlen("fields,");
923 bool matched = proto_registrar_dump_field_completions(prefix);
924 if (!matched) {
925 cmdarg_err("No field or protocol begins with \"%s\"", prefix);
926 exit_status = EXIT_FAILURE;
929 else if (strcmp(glossary, "folders") == 0) {
930 about_folders();
931 } else if (strcmp(glossary, "ftypes") == 0)
932 proto_registrar_dump_ftypes();
933 else if (strcmp(glossary, "heuristic-decodes") == 0) {
934 dissector_dump_heur_decodes();
935 } else if (strcmp(glossary, "manuf") == 0)
936 ws_manuf_dump(stdout);
937 else if (strcmp(glossary, "enterprises") == 0)
938 global_enterprises_dump(stdout);
939 else if (strcmp(glossary, "services") == 0)
940 global_services_dump(stdout);
941 else if (strcmp(glossary, "plugins") == 0) {
942 #ifdef HAVE_PLUGINS
943 codecs_init();
944 plugins_dump_all();
945 #endif
946 #ifdef HAVE_LUA
947 wslua_plugins_dump_all();
948 #endif
949 extcap_dump_all();
951 else if (strcmp(glossary, "protocols") == 0) {
952 proto_registrar_dump_protocols();
953 } else if (strcmp(glossary, "values") == 0)
954 proto_registrar_dump_values();
955 else if (strcmp(glossary, "help") == 0)
956 glossary_option_help();
957 /* These are supported only for backwards compatibility and may or may not work
958 * for a given user in a given directory on a given operating system with a given
959 * command-line interpreter.
961 else if (strcmp(glossary, "?") == 0)
962 glossary_option_help();
963 else if (strcmp(glossary, "-?") == 0)
964 glossary_option_help();
965 else {
966 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G help for more help.", glossary);
967 exit_status = WS_EXIT_INVALID_OPTION;
970 return exit_status;
973 static bool
974 must_do_dissection(dfilter_t *rfcode, dfilter_t *dfcode,
975 char *volatile pdu_export_arg)
977 /* We have to dissect each packet if:
979 we're printing information about each packet;
981 we're using a read filter on the packets;
983 we're using a display filter on the packets;
985 we're exporting PDUs;
987 we're using any taps that need dissection. */
988 return print_packet_info || rfcode || dfcode || pdu_export_arg ||
989 tap_listeners_require_dissection();
992 #ifdef HAVE_LIBPCAP
994 * Check whether a purported *shark packet-matching expression (display
995 * or read filter) looks like a capture filter and, if so, print a
996 * warning.
998 * Used, for example, if the string in question isn't a valid packet-
999 * matching expression.
1001 static void
1002 warn_about_capture_filter(const char *rfilter)
1004 struct bpf_program fcode;
1005 pcap_t *pc;
1007 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1008 if (pc != NULL) {
1009 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1010 pcap_freecode(&fcode);
1011 cmdarg_err_cont(
1012 " Note: That read filter code looks like a valid capture filter;\n"
1013 " maybe you mixed them up?");
1015 pcap_close(pc);
1018 #endif
1020 #ifdef HAVE_LIBPCAP
1021 static GList *cached_if_list;
1023 static GList *
1024 capture_opts_get_interface_list(int *err, char **err_str)
1026 if (cached_if_list == NULL) {
1028 * This isn't a GUI tool, so no need for a callback.
1030 cached_if_list = capture_interface_list(err, err_str, NULL);
1033 * Routines expect to free the returned interface list, so return
1034 * a deep copy.
1036 return interface_list_copy(cached_if_list);
1038 #endif
1041 main(int argc, char *argv[])
1043 char *err_msg;
1044 int opt;
1045 static const struct ws_option long_options[] = {
1046 {"help", ws_no_argument, NULL, 'h'},
1047 {"version", ws_no_argument, NULL, 'v'},
1048 LONGOPT_CAPTURE_COMMON
1049 LONGOPT_DISSECT_COMMON
1050 LONGOPT_READ_CAPTURE_COMMON
1051 {"print", ws_no_argument, NULL, 'P'},
1052 {"export-objects", ws_required_argument, NULL, LONGOPT_EXPORT_OBJECTS},
1053 {"export-tls-session-keys", ws_required_argument, NULL, LONGOPT_EXPORT_TLS_SESSION_KEYS},
1054 {"color", ws_no_argument, NULL, LONGOPT_COLOR},
1055 {"no-duplicate-keys", ws_no_argument, NULL, LONGOPT_NO_DUPLICATE_KEYS},
1056 {"elastic-mapping-filter", ws_required_argument, NULL, LONGOPT_ELASTIC_MAPPING_FILTER},
1057 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
1058 {"hexdump", ws_required_argument, NULL, LONGOPT_HEXDUMP},
1059 {"selected-frame", ws_required_argument, NULL, LONGOPT_SELECTED_FRAME},
1060 {"print-timers", ws_no_argument, NULL, LONGOPT_PRINT_TIMERS},
1061 {"global-profile", ws_no_argument, NULL, LONGOPT_GLOBAL_PROFILE},
1062 {"compress", ws_required_argument, NULL, LONGOPT_COMPRESS},
1063 {0, 0, 0, 0}
1065 bool arg_error = false;
1066 bool has_extcap_options = false;
1067 volatile bool is_capturing = true;
1069 int err;
1070 char *err_info;
1071 bool exp_pdu_status;
1072 volatile process_file_status_t status;
1073 volatile bool draw_taps = false;
1074 volatile int exit_status = EXIT_SUCCESS;
1075 #ifdef HAVE_LIBPCAP
1076 int caps_queries = 0;
1077 GList *if_list;
1078 char *err_str, *err_str_secondary;
1079 #else
1080 bool capture_option_specified = false;
1081 volatile int max_packet_count = 0;
1082 #endif
1083 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_UNKNOWN;
1084 volatile bool out_file_name_res = false;
1085 volatile int in_file_type = WTAP_TYPE_AUTO;
1086 char *volatile cf_name = NULL;
1087 char *rfilter = NULL;
1088 char *volatile dfilter = NULL;
1089 dfilter_t *rfcode = NULL;
1090 dfilter_t *dfcode = NULL;
1091 e_prefs *prefs_p;
1092 char *output_only = NULL;
1093 char *volatile pdu_export_arg = NULL;
1094 char *volatile exp_pdu_filename = NULL;
1095 const char *volatile tls_session_keys_file = NULL;
1096 exp_pdu_t exp_pdu_tap_data;
1097 const char* glossary = NULL;
1098 const char* elastic_mapping_filter = NULL;
1099 wtap_compression_type volatile compression_type = WTAP_UNKNOWN_COMPRESSION;
1102 * The leading + ensures that getopt_long() does not permute the argv[]
1103 * entries.
1105 * We have to make sure that the first getopt_long() preserves the content
1106 * of argv[] for the subsequent getopt_long() call.
1108 * We use getopt_long() in both cases to ensure that we're using a routine
1109 * whose permutation behavior we can control in the same fashion on all
1110 * platforms, and so that, if we ever need to process a long argument before
1111 * doing further initialization, we can do so.
1113 * Glibc and Solaris libc document that a leading + disables permutation
1114 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
1115 * and macOS don't document it, but do so anyway.
1117 * We do *not* use a leading - because the behavior of a leading - is
1118 * platform-dependent.
1120 #define OPTSTRING "+2" OPTSTRING_CAPTURE_COMMON OPTSTRING_DISSECT_COMMON OPTSTRING_READ_CAPTURE_COMMON "M:C:e:E:F:gG:hH:j:J:lo:O:PqQS:T:U:vVw:W:xX:z:"
1122 static const char optstring[] = OPTSTRING;
1124 /* Set the program name. */
1125 g_set_prgname("tshark");
1128 * Set the C-language locale to the native environment and set the
1129 * code page to UTF-8 on Windows.
1131 #ifdef _WIN32
1132 setlocale(LC_ALL, ".UTF-8");
1133 #else
1134 setlocale(LC_ALL, "");
1135 #endif
1137 ws_tzset();
1139 cmdarg_err_init(stderr_cmdarg_err, stderr_cmdarg_err_cont);
1141 /* Initialize log handler early so we can have proper logging during startup. */
1142 ws_log_init(vcmdarg_err);
1144 /* Early logging command-line initialization. */
1145 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1147 ws_noisy("Finished log init and parsing command line log arguments");
1148 ws_debug("tshark started with %d args", argc);
1150 #ifdef _WIN32
1151 create_app_running_mutex();
1152 #endif /* _WIN32 */
1155 * Get credential information for later use, and drop privileges
1156 * before doing anything else.
1157 * Let the user know if anything happened.
1159 init_process_policies();
1160 relinquish_special_privs_perm();
1161 print_current_user();
1164 * Attempt to get the pathname of the directory containing the
1165 * executable file.
1167 err_msg = configuration_init(argv[0]);
1168 if (err_msg != NULL) {
1169 fprintf(stderr,
1170 "tshark: Can't get pathname of directory containing the tshark program: %s.\n"
1171 "It won't be possible to capture traffic.\n"
1172 "Report this to the Wireshark developers.",
1173 err_msg);
1174 g_free(err_msg);
1177 initialize_funnel_ops();
1179 #ifdef _WIN32
1180 ws_init_dll_search_path();
1181 #ifdef HAVE_LIBPCAP
1182 /* Load wpcap if possible. Do this before collecting the run-time version information */
1183 load_wpcap();
1184 #endif /* HAVE_LIBPCAP */
1185 #endif /* _WIN32 */
1187 /* Initialize the version information. */
1188 ws_init_version_info("TShark",
1189 gather_tshark_compile_info, gather_tshark_runtime_info);
1191 /* Fail sometimes. Useful for testing fuzz scripts. */
1192 /* if (g_random_int_range(0, 100) < 5) abort(); */
1195 * In order to have the -X opts assigned before the wslua machine starts
1196 * we need to call getopt_long before epan_init() gets called.
1198 * In order to handle, for example, -o options, we also need to call it
1199 * *after* epan_init() gets called, so that the dissectors have had a
1200 * chance to register their preferences.
1202 * Spawning a bunch of extcap processes can delay program startup,
1203 * particularly on Windows. Check to see if we have any options that
1204 * might require extcap and set has_extcap_options = true if that's
1205 * the case.
1207 * XXX - can we do this all with one getopt_long() call, saving the
1208 * arguments we can't handle until after initializing libwireshark,
1209 * and then process them after initializing libwireshark?
1211 * We set ws_opterr to 0 so that ws_getopt_long doesn't print error
1212 * messages for bad long options. We'll do that once, in the final
1213 * call where all the error handling happens.
1215 ws_opterr = 0;
1217 /* We should check at first if we should use a global profile before
1218 parsing the profile name
1219 XXX - We could check this in the next ws_getopt_long, and save the
1220 profile name and only apply it after finishing the loop. */
1221 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1222 switch (opt) {
1223 case LONGOPT_GLOBAL_PROFILE:
1224 set_persconffile_dir(get_datafile_dir());
1225 break;
1226 default:
1227 break;
1232 * Reset the options parser, set ws_optreset to 1 and set ws_optind to 1.
1233 * We still don't want to print error messages, though.
1235 ws_optreset = 1;
1236 ws_optind = 1;
1238 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1239 switch (opt) {
1240 case 'C': /* Configuration Profile */
1241 if (profile_exists (ws_optarg, false)) {
1242 set_profile_name (ws_optarg);
1243 } else if (profile_exists (ws_optarg, true)) {
1244 char *pf_dir_path, *pf_dir_path2, *pf_filename;
1245 /* Copy from global profile */
1246 if (create_persconffile_profile(ws_optarg, &pf_dir_path) == -1) {
1247 cmdarg_err("Can't create directory\n\"%s\":\n%s.",
1248 pf_dir_path, g_strerror(errno));
1250 g_free(pf_dir_path);
1251 exit_status = WS_EXIT_INVALID_FILE;
1252 goto clean_exit;
1254 if (copy_persconffile_profile(ws_optarg, ws_optarg, true, &pf_filename,
1255 &pf_dir_path, &pf_dir_path2) == -1) {
1256 cmdarg_err("Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
1257 pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno));
1259 g_free(pf_filename);
1260 g_free(pf_dir_path);
1261 g_free(pf_dir_path2);
1262 exit_status = WS_EXIT_INVALID_FILE;
1263 goto clean_exit;
1265 set_profile_name (ws_optarg);
1266 } else {
1267 cmdarg_err("Configuration Profile \"%s\" does not exist", ws_optarg);
1268 exit_status = WS_EXIT_INVALID_OPTION;
1269 goto clean_exit;
1271 break;
1272 case 'G':
1273 if (glossary != NULL) {
1274 /* Multiple glossaries are difficult especially due to defaultprefs */
1275 cmdarg_err("Multiple glossary reports (-G) are unsupported");
1276 exit_status = WS_EXIT_INVALID_OPTION;
1277 goto clean_exit;
1278 } else {
1279 glossary = ws_optarg;
1281 if (g_str_has_suffix(ws_optarg, "prefs")) {
1282 has_extcap_options = true;
1284 is_capturing = false;
1285 break;
1286 case 'i':
1287 has_extcap_options = true;
1288 break;
1289 case 'o':
1290 if (g_str_has_prefix(ws_optarg, "extcap.")) {
1291 has_extcap_options = true;
1293 break;
1294 case 'P': /* Print packet summary info even when writing to a file */
1295 print_packet_info = true;
1296 print_summary = true;
1297 break;
1298 case 'r': /* Read capture file x */
1299 cf_name = g_strdup(ws_optarg);
1300 is_capturing = false;
1301 break;
1302 case 'O': /* Only output these protocols */
1303 output_only = g_strdup(ws_optarg);
1304 /* FALLTHROUGH */
1305 case 'V': /* Verbose */
1306 print_details = true;
1307 print_packet_info = true;
1308 break;
1309 case 'x': /* Print packet data in hex (and ASCII) */
1310 print_hex = true;
1311 /* The user asked for hex output, so let's ensure they get it,
1312 * even if they're writing to a file.
1314 print_packet_info = true;
1315 break;
1316 case 'X':
1317 ex_opt_add(ws_optarg);
1318 break;
1319 case 'h':
1320 case 'v':
1321 is_capturing = false;
1322 break;
1323 default:
1324 break;
1328 #ifndef HAVE_LUA
1329 if (ex_opt_count("lua_script") > 0) {
1330 cmdarg_err("This version of TShark was not built with support for Lua scripting.");
1331 exit_status = WS_EXIT_INIT_FAILED;
1332 goto clean_exit;
1334 #endif /* HAVE_LUA */
1336 init_report_failure_message("TShark");
1338 #ifdef HAVE_LIBPCAP
1339 capture_opts_init(&global_capture_opts, capture_opts_get_interface_list);
1340 capture_session_init(&global_capture_session, &cfile,
1341 capture_input_new_file, capture_input_new_packets,
1342 capture_input_drops, capture_input_error,
1343 capture_input_cfilter_error, capture_input_closed);
1344 #endif
1346 timestamp_set_type(TS_RELATIVE);
1347 timestamp_set_precision(TS_PREC_AUTO);
1348 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1351 * Libwiretap must be initialized before libwireshark is, so that
1352 * dissection-time handlers for file-type-dependent blocks can
1353 * register using the file type/subtype value for the file type.
1355 wtap_init(true);
1357 /* Register all dissectors; we must do this before checking for the
1358 "-G" flag, as the "-G" flag dumps information registered by the
1359 dissectors, and we must do it before we read the preferences, in
1360 case any dissectors register preferences. */
1361 if (!epan_init(NULL, NULL, true)) {
1362 exit_status = WS_EXIT_INIT_FAILED;
1363 goto clean_exit;
1366 /* Register all tap listeners; we do this before we parse the arguments,
1367 as the "-z" argument can specify a registered tap. */
1369 register_all_tap_listeners(tap_reg_listener);
1371 /* Register extcap preferences only when needed. */
1372 if (has_extcap_options || is_capturing) {
1374 * XXX - We don't properly handle the capture_no_extcap preference.
1375 * To make it work, before registering the extcap preferences we'd
1376 * have to read at least that preference for the chosen profile, and
1377 * also check to make sure an "-o" option didn't override it.
1378 * Then, after registering the extcap preferences, we'd have to
1379 * set the extcap preferences from the preferences file and "-o"
1380 * options on the command line.
1382 extcap_register_preferences();
1385 conversation_table_set_gui_info(init_iousers);
1386 endpoint_table_set_gui_info(init_endpoints);
1387 srt_table_iterate_tables(register_srt_tables, NULL);
1388 rtd_table_iterate_tables(register_rtd_tables, NULL);
1389 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
1391 ws_debug("tshark reading settings");
1393 /* Load libwireshark settings from the current profile. */
1394 prefs_p = epan_load_settings();
1395 prefs_loaded = true;
1397 cap_file_init(&cfile);
1399 /* Print format defaults to this. */
1400 print_format = PR_FMT_TEXT;
1401 delimiter_char = " ";
1403 output_fields = output_fields_new();
1406 * To reset the options parser, set ws_optreset to 1 and set ws_optind to 1.
1408 * Also reset ws_opterr to 1, so that error messages are printed by
1409 * getopt_long().
1411 ws_optreset = 1;
1412 ws_optind = 1;
1413 ws_opterr = 1;
1415 /* Now get our args */
1416 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1417 switch (opt) {
1418 case '2': /* Perform two-pass analysis */
1419 if(epan_auto_reset){
1420 cmdarg_err("-2 does not support auto session reset.");
1421 arg_error=true;
1423 perform_two_pass_analysis = true;
1424 break;
1425 case 'M':
1426 if(perform_two_pass_analysis){
1427 cmdarg_err("-M does not support two-pass analysis.");
1428 arg_error=true;
1430 epan_auto_reset_count = get_positive_int(ws_optarg, "epan reset count");
1431 epan_auto_reset = true;
1432 break;
1433 case 'a': /* autostop criteria */
1434 case 'b': /* Ringbuffer option */
1435 case 'f': /* capture filter */
1436 case 'g': /* enable group read access on file(s) */
1437 case 'i': /* Use interface x */
1438 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
1439 case 'p': /* Don't capture in promiscuous mode */
1440 #ifdef HAVE_PCAP_REMOTE
1441 case 'A': /* Authentication */
1442 #endif
1443 case 'I': /* Capture in monitor mode, if available */
1444 case 's': /* Set the snapshot (capture) length */
1445 case 'y': /* Set the pcap data link type */
1446 case 'B': /* Buffer size */
1447 case LONGOPT_COMPRESS_TYPE: /* compress type */
1448 case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
1449 case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
1450 /* These are options only for packet capture. */
1451 #ifdef HAVE_LIBPCAP
1452 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1453 if (exit_status != 0) {
1454 goto clean_exit;
1456 #else
1457 capture_option_specified = true;
1458 arg_error = true;
1459 #endif
1460 break;
1461 case 'c': /* Stop after x packets */
1462 #ifdef HAVE_LIBPCAP
1463 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1464 if (exit_status != 0) {
1465 goto clean_exit;
1467 #else
1468 max_packet_count = get_positive_int(ws_optarg, "packet count");
1469 #endif
1470 break;
1471 case 'w': /* Write to file x */
1472 output_file_name = g_strdup(ws_optarg);
1473 #ifdef HAVE_LIBPCAP
1474 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1475 if (exit_status != 0) {
1476 goto clean_exit;
1478 #endif
1479 break;
1480 case 'C':
1481 /* already processed; just ignore it now */
1482 break;
1483 case 'D': /* Print a list of capture devices and exit */
1484 #ifdef HAVE_LIBPCAP
1485 exit_status = EXIT_SUCCESS;
1486 if_list = capture_interface_list(&err, &err_str,NULL);
1487 if (err != 0) {
1489 * An error occurred when fetching the local
1490 * interfaces. Report it.
1492 cmdarg_err("%s", err_str);
1493 g_free(err_str);
1494 exit_status = WS_EXIT_PCAP_ERROR;
1496 if (if_list == NULL) {
1498 * No interfaces were found. If that's not the
1499 * result of an error when fetching the local
1500 * interfaces, let the user know.
1502 if (err == 0) {
1503 cmdarg_err("There are no interfaces on which a capture can be done");
1504 exit_status = WS_EXIT_NO_INTERFACES;
1506 goto clean_exit;
1508 capture_opts_print_interfaces(if_list);
1509 free_interface_list(if_list);
1510 goto clean_exit;
1511 #else
1512 capture_option_specified = true;
1513 arg_error = true;
1514 #endif
1515 break;
1516 case 'e':
1517 /* Field entry */
1519 const char* col_field = try_convert_to_column_field(ws_optarg);
1520 if (col_field) {
1521 output_fields_add(output_fields, col_field);
1522 } else {
1523 header_field_info *hfi = proto_registrar_get_byalias(ws_optarg);
1524 if (hfi)
1525 output_fields_add(output_fields, hfi->abbrev);
1526 else
1527 output_fields_add(output_fields, ws_optarg);
1530 break;
1531 case 'E':
1532 /* Field option */
1533 if (!output_fields_set_option(output_fields, ws_optarg)) {
1534 cmdarg_err("\"%s\" is not a valid field output option=value pair.", ws_optarg);
1535 output_fields_list_options(stderr);
1536 exit_status = WS_EXIT_INVALID_OPTION;
1537 goto clean_exit;
1539 break;
1540 case 'F':
1541 out_file_type = wtap_name_to_file_type_subtype(ws_optarg);
1542 if (out_file_type < 0) {
1543 cmdarg_err("\"%s\" isn't a valid capture file type", ws_optarg);
1544 list_capture_types();
1545 exit_status = WS_EXIT_INVALID_OPTION;
1546 goto clean_exit;
1548 break;
1549 case 'G':
1550 /* already processed; just ignore it now */
1551 break;
1552 case 'j':
1553 if (!protocolfilter_add_opt(ws_optarg, PF_NONE)) {
1554 exit_status = WS_EXIT_INVALID_OPTION;
1555 goto clean_exit;
1557 break;
1558 case 'J':
1559 if (!protocolfilter_add_opt(ws_optarg, PF_INCLUDE_CHILDREN)) {
1560 exit_status = WS_EXIT_INVALID_OPTION;
1561 goto clean_exit;
1563 break;
1564 case 'W': /* Select extra information to save in our capture file */
1565 /* This is patterned after the -N flag which may not be the best idea. */
1566 if (strchr(ws_optarg, 'n')) {
1567 out_file_name_res = true;
1568 } else {
1569 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", ws_optarg);
1570 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1571 exit_status = WS_EXIT_INVALID_OPTION;
1572 goto clean_exit;
1574 break;
1575 case 'H': /* Read address to name mappings from a hosts file */
1576 if (! add_hosts_file(ws_optarg))
1578 cmdarg_err("Can't read host entries from \"%s\"", ws_optarg);
1579 exit_status = WS_EXIT_INVALID_OPTION;
1580 goto clean_exit;
1582 out_file_name_res = true;
1583 break;
1585 case 'h': /* Print help and exit */
1586 show_help_header("Dump and analyze network traffic.");
1587 print_usage(stdout);
1588 exit_status = EXIT_SUCCESS;
1589 goto clean_exit;
1590 break;
1591 case 'l': /* "Line-buffer" standard output */
1592 /* The ANSI C standard does not appear to *require* that a line-buffered
1593 stream be flushed to the host environment whenever a newline is
1594 written, it just says that, on such a stream, characters "are
1595 intended to be transmitted to or from the host environment as a
1596 block when a new-line character is encountered".
1598 The Visual C++ 6.0 C implementation doesn't do what is intended;
1599 even if you set a stream to be line-buffered, it still doesn't
1600 flush the buffer at the end of every line.
1602 The whole reason for the "-l" flag in either tcpdump or TShark
1603 is to allow the output of a live capture to be piped to a program
1604 or script and to have that script see the information for the
1605 packet as soon as it's printed, rather than having to wait until
1606 a standard I/O buffer fills up.
1608 So, if the "-l" flag is specified, we flush the standard output
1609 at the end of a packet. This will do the right thing if we're
1610 printing packet summary lines, and, as we print the entire protocol
1611 tree for a single packet without waiting for anything to happen,
1612 it should be as good as line-buffered mode if we're printing
1613 protocol trees - arguably even better, as it may do fewer
1614 writes. */
1615 line_buffered = true;
1616 #ifdef HAVE_LIBPCAP
1617 /* Set the update-interval to 0 so that dumpcap reports packets
1618 * as soon as available instead of buffering them.
1620 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1621 if (exit_status != 0) {
1622 goto clean_exit;
1624 #endif
1625 break;
1626 case 'L': /* Print list of link-layer types and exit */
1627 #ifdef HAVE_LIBPCAP
1628 caps_queries |= CAPS_QUERY_LINK_TYPES;
1629 #else
1630 capture_option_specified = true;
1631 arg_error = true;
1632 #endif
1633 break;
1634 case LONGOPT_LIST_TSTAMP_TYPES: /* List possible timestamp types */
1635 #ifdef HAVE_LIBPCAP
1636 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
1637 #else
1638 capture_option_specified = true;
1639 arg_error = true;
1640 #endif
1641 break;
1642 case 'o': /* Override preference from command line */
1644 char *errmsg = NULL;
1646 switch (prefs_set_pref(ws_optarg, &errmsg)) {
1648 case PREFS_SET_OK:
1649 break;
1651 case PREFS_SET_SYNTAX_ERR:
1652 cmdarg_err("Invalid -o flag \"%s\"%s%s", ws_optarg,
1653 errmsg ? ": " : "", errmsg ? errmsg : "");
1654 g_free(errmsg);
1655 exit_status = WS_EXIT_INVALID_OPTION;
1656 goto clean_exit;
1657 break;
1659 case PREFS_SET_NO_SUCH_PREF:
1660 cmdarg_err("-o flag \"%s\" specifies unknown preference", ws_optarg);
1661 exit_status = WS_EXIT_INVALID_OPTION;
1662 goto clean_exit;
1663 break;
1665 case PREFS_SET_OBSOLETE:
1666 cmdarg_err("-o flag \"%s\" specifies obsolete preference", ws_optarg);
1667 exit_status = WS_EXIT_INVALID_OPTION;
1668 goto clean_exit;
1669 break;
1671 break;
1673 case 'q': /* Quiet */
1674 quiet = true;
1675 break;
1676 case 'Q': /* Really quiet */
1677 quiet = true;
1678 really_quiet = true;
1679 break;
1680 case 'r':
1681 /* already processed; just ignore it now */
1682 break;
1683 case 'R': /* Read file filter */
1684 rfilter = ws_optarg;
1685 break;
1686 case 'P':
1687 /* already processed; just ignore it now */
1688 break;
1689 case 'S': /* Set the line Separator to be printed between packets */
1690 separator = ws_optarg;
1691 break;
1692 case 'T': /* printing Type */
1693 /* output_action has been already set. It means multiple -T. */
1694 if (output_action > WRITE_NONE) {
1695 cmdarg_err("Multiple -T parameters are unsupported");
1696 exit_status = WS_EXIT_INVALID_OPTION;
1697 goto clean_exit;
1699 print_packet_info = true;
1700 if (strcmp(ws_optarg, "text") == 0) {
1701 output_action = WRITE_TEXT;
1702 print_format = PR_FMT_TEXT;
1703 } else if (strcmp(ws_optarg, "tabs") == 0) {
1704 output_action = WRITE_TEXT;
1705 print_format = PR_FMT_TEXT;
1706 delimiter_char = "\t";
1707 } else if (strcmp(ws_optarg, "ps") == 0) {
1708 output_action = WRITE_TEXT;
1709 print_format = PR_FMT_PS;
1710 } else if (strcmp(ws_optarg, "pdml") == 0) {
1711 output_action = WRITE_XML;
1712 print_details = true; /* Need details */
1713 print_summary = false; /* Don't allow summary */
1714 } else if (strcmp(ws_optarg, "psml") == 0) {
1715 output_action = WRITE_XML;
1716 print_details = false; /* Don't allow details */
1717 print_summary = true; /* Need summary */
1718 } else if (strcmp(ws_optarg, "fields") == 0) {
1719 output_action = WRITE_FIELDS;
1720 print_details = true; /* Need full tree info */
1721 print_summary = false; /* Don't allow summary */
1722 } else if (strcmp(ws_optarg, "json") == 0) {
1723 output_action = WRITE_JSON;
1724 print_details = true; /* Need details */
1725 print_summary = false; /* Don't allow summary */
1726 } else if (strcmp(ws_optarg, "ek") == 0) {
1727 output_action = WRITE_EK;
1728 if (!print_summary)
1729 print_details = true;
1730 } else if (strcmp(ws_optarg, "jsonraw") == 0) {
1731 output_action = WRITE_JSON_RAW;
1732 print_details = true; /* Need details */
1733 print_summary = false; /* Don't allow summary */
1735 else {
1736 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", ws_optarg); /* x */
1737 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1738 "\t specified by the -E option.\n"
1739 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1740 "\t details of a decoded packet. This information is equivalent to\n"
1741 "\t the packet details printed with the -V flag.\n"
1742 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1743 "\t the packets, or a multi-line view of the details of each of\n"
1744 "\t the packets, depending on whether the -V flag was specified.\n"
1745 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1746 "\t summary information of a decoded packet. This information is\n"
1747 "\t equivalent to the information shown in the one-line summary\n"
1748 "\t printed by default.\n"
1749 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1750 "\t summary information of a decoded packet. This information is \n"
1751 "\t equivalent to the packet details printed with the -V flag.\n"
1752 "\t\"jsonraw\" Packet Details, a JSON-based format for machine parsing\n"
1753 "\t including only raw hex decoded fields (same as -T json -x but\n"
1754 "\t without text decoding, only raw fields included). \n"
1755 "\t\"ek\" Packet Details, an EK JSON-based format for the bulk insert \n"
1756 "\t into elastic search cluster. This information is \n"
1757 "\t equivalent to the packet details printed with the -V flag.\n"
1758 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1759 "\t packets, or a multi-line view of the details of each of the\n"
1760 "\t packets, depending on whether the -V flag was specified.\n"
1761 "\t This is the default.\n"
1762 "\t\"tabs\" Similar to the text report except that each column of the\n"
1763 "\t human-readable one-line summary is delimited with an ASCII\n"
1764 "\t horizontal tab character.");
1765 exit_status = WS_EXIT_INVALID_OPTION;
1766 goto clean_exit;
1768 break;
1769 case 'U': /* Export PDUs to file */
1770 if (strcmp(ws_optarg, "") == 0 || strcmp(ws_optarg, "?") == 0) {
1771 list_export_pdu_taps();
1772 exit_status = WS_EXIT_INVALID_OPTION;
1773 goto clean_exit;
1775 pdu_export_arg = g_strdup(ws_optarg);
1776 break;
1777 case 'v': /* Show version and exit */
1778 #ifdef ENABLE_CHECK_FILTER
1779 /* If we're testing start-up of the epan library, go ahead and
1780 * load all the delayed initialization prefixes (e.g. Diameter)
1781 * so that they are reported on.
1783 proto_initialize_all_prefixes();
1784 #endif
1785 show_version();
1786 /* We don't really have to cleanup here, but it's a convenient way to test
1787 * start-up and shut-down of the epan library without any UI-specific
1788 * cruft getting in the way. Makes the results of running
1789 * $ ./tools/valgrind-wireshark -n
1790 * much more useful. */
1791 epan_cleanup();
1792 extcap_cleanup();
1793 exit_status = EXIT_SUCCESS;
1794 goto clean_exit;
1795 case 'O': /* Only output these protocols */
1796 /* already processed; just ignore it now */
1797 break;
1798 case 'V': /* Verbose */
1799 /* already processed; just ignore it now */
1800 break;
1801 case 'x': /* Print packet data in hex (and ASCII) */
1802 /* already processed; just ignore it now */
1803 break;
1804 case 'X':
1805 /* already processed; just ignore it now */
1806 break;
1807 case 'Y':
1808 dfilter = g_strdup(ws_optarg);
1809 break;
1810 case 'z':
1811 /* We won't call the init function for the stat this soon
1812 as it would disallow MATE's fields (which are registered
1813 by the preferences set callback) from being used as
1814 part of a tap filter. Instead, we just add the argument
1815 to a list of stat arguments. */
1816 if (strcmp("help", ws_optarg) == 0) {
1817 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1818 list_stat_cmd_args();
1819 exit_status = EXIT_SUCCESS;
1820 goto clean_exit;
1822 if (!process_stat_cmd_arg(ws_optarg)) {
1823 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", ws_optarg);
1824 list_stat_cmd_args();
1825 exit_status = WS_EXIT_INVALID_OPTION;
1826 goto clean_exit;
1828 break;
1829 case 'd': /* Decode as rule */
1830 case 'K': /* Kerberos keytab file */
1831 case 'n': /* No name resolution */
1832 case 'N': /* Select what types of addresses/port #s to resolve */
1833 case 't': /* Time stamp type */
1834 case 'u': /* Seconds type */
1835 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1836 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1837 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1838 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
1839 case LONGOPT_ONLY_PROTOCOLS: /* enable dissection of only this comma separated list of protocols */
1840 case LONGOPT_DISABLE_ALL_PROTOCOLS: /* enable dissection of protocol (that is disabled by default) */
1841 if (!dissect_opts_handle_opt(opt, ws_optarg)) {
1842 exit_status = WS_EXIT_INVALID_OPTION;
1843 goto clean_exit;
1845 break;
1846 case LONGOPT_EXPORT_OBJECTS: /* --export-objects */
1847 if (strcmp("help", ws_optarg) == 0) {
1848 fprintf(stderr, "tshark: The available export object types for the \"--export-objects\" option are:\n");
1849 eo_list_object_types();
1850 exit_status = EXIT_SUCCESS;
1851 goto clean_exit;
1853 if (!eo_tap_opt_add(ws_optarg)) {
1854 exit_status = WS_EXIT_INVALID_OPTION;
1855 goto clean_exit;
1857 break;
1858 case LONGOPT_EXPORT_TLS_SESSION_KEYS: /* --export-tls-session-keys */
1859 tls_session_keys_file = ws_optarg;
1860 break;
1861 case LONGOPT_COLOR: /* print in color where appropriate */
1862 dissect_color = true;
1863 /* This has no effect if we don't print packet info or filter
1864 (we can filter on the coloring rules). Should we warn or
1865 error later if so, instead of silently ignoring it? */
1866 break;
1867 case LONGOPT_NO_DUPLICATE_KEYS:
1868 no_duplicate_keys = true;
1869 node_children_grouper = proto_node_group_children_by_json_key;
1870 break;
1871 case LONGOPT_ELASTIC_MAPPING_FILTER:
1873 * XXX - A long option that exists to alter one other option
1874 * (-G elastic-mapping) and for no other reason seems verbose.
1875 * Deprecate in favor of -G elastic-mapping,<filter> ?
1877 elastic_mapping_filter = ws_optarg;
1878 break;
1879 case LONGOPT_CAPTURE_COMMENT: /* capture comment */
1880 if (capture_comments == NULL) {
1881 capture_comments = g_ptr_array_new_with_free_func(g_free);
1883 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
1884 break;
1885 case LONGOPT_HEXDUMP:
1886 print_hex = true;
1887 print_packet_info = true;
1888 if (strcmp(ws_optarg, "all") == 0)
1889 hexdump_source_option = HEXDUMP_SOURCE_MULTI;
1890 else if (strcmp(ws_optarg, "frames") == 0)
1891 hexdump_source_option = HEXDUMP_SOURCE_PRIMARY;
1892 else if (strcmp(ws_optarg, "ascii") == 0)
1893 hexdump_ascii_option = HEXDUMP_ASCII_INCLUDE;
1894 else if (strcmp(ws_optarg, "delimit") == 0)
1895 hexdump_ascii_option = HEXDUMP_ASCII_DELIMIT;
1896 else if (strcmp(ws_optarg, "noascii") == 0)
1897 hexdump_ascii_option = HEXDUMP_ASCII_EXCLUDE;
1898 else if (strcmp(ws_optarg, "time") == 0)
1899 hexdump_timestamp_option = HEXDUMP_TIMESTAMP;
1900 else if (strcmp(ws_optarg, "notime") == 0)
1901 hexdump_timestamp_option = HEXDUMP_TIMESTAMP_NONE;
1902 else if (strcmp("help", ws_optarg) == 0) {
1903 hexdump_option_help(stdout);
1904 exit_status = EXIT_SUCCESS;
1905 goto clean_exit;
1906 } else {
1907 fprintf(stderr, "tshark: \"%s\" is an invalid value for --hexdump <hexoption>\n", ws_optarg);
1908 fprintf(stderr, "For valid <hexoption> values enter: tshark --hexdump help\n");
1909 exit_status = WS_EXIT_INVALID_OPTION;
1910 goto clean_exit;
1912 break;
1913 case LONGOPT_SELECTED_FRAME:
1914 /* Hidden option to mark a frame as "selected". Used for testing and debugging.
1915 * Only active in two-pass mode. */
1916 if (!ws_strtou32(ws_optarg, NULL, &selected_frame_number)) {
1917 fprintf(stderr, "tshark: \"%s\" is not a valid frame number\n", ws_optarg);
1918 exit_status = WS_EXIT_INVALID_OPTION;
1919 goto clean_exit;
1921 break;
1922 case LONGOPT_PRINT_TIMERS:
1923 opt_print_timers = true;
1924 break;
1925 case LONGOPT_GLOBAL_PROFILE:
1926 /* already processed; just ignore it now */
1927 break;
1928 case LONGOPT_COMPRESS: /* compress type */
1929 compression_type = wtap_name_to_compression_type(ws_optarg);
1930 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1931 cmdarg_err("\"%s\" isn't a valid output compression mode",
1932 ws_optarg);
1933 list_output_compression_types();
1934 goto clean_exit;
1936 break;
1937 default:
1938 case '?': /* Bad flag - print usage message */
1939 switch(ws_optopt) {
1940 case 'F':
1941 list_capture_types();
1942 break;
1943 case LONGOPT_COMPRESS:
1944 case LONGOPT_COMPRESS_TYPE:
1945 list_output_compression_types();
1946 break;
1947 default:
1948 print_usage(stderr);
1950 exit_status = WS_EXIT_INVALID_OPTION;
1951 goto clean_exit;
1952 break;
1956 /* set the default output action to TEXT */
1957 if (output_action == WRITE_NONE)
1958 output_action = WRITE_TEXT;
1960 /* set the default file type to pcapng */
1961 if (out_file_type == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN)
1962 out_file_type = wtap_pcapng_file_type_subtype();
1965 * Print packet summary information is the default if neither -V or -x
1966 * were specified. Note that this is new behavior, which allows for the
1967 * possibility of printing only hex/ascii output without necessarily
1968 * requiring that either the summary or details be printed too.
1970 if (!print_summary && !print_details && !print_hex)
1971 print_summary = true;
1973 if (no_duplicate_keys && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW) {
1974 cmdarg_err("--no-duplicate-keys can only be used with \"-T json\" and \"-T jsonraw\"");
1975 exit_status = WS_EXIT_INVALID_OPTION;
1976 goto clean_exit;
1979 /* If we specified output fields, but not the output field type... */
1980 /* XXX: If we specfied both output fields with -e *and* protocol filters
1981 * with -j/-J, only the former are used. Should we warn or abort?
1982 * This also doesn't distinguish PDML from PSML, but shouldn't allow the
1983 * latter.
1985 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1986 cmdarg_err("Output fields were specified with \"-e\", "
1987 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1988 exit_status = WS_EXIT_INVALID_OPTION;
1989 goto clean_exit;
1990 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1991 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1992 "specified with \"-e\".");
1994 exit_status = WS_EXIT_INVALID_OPTION;
1995 goto clean_exit;
1998 if (dissect_color) {
1999 if (!color_filters_init(&err_msg, NULL)) {
2000 fprintf(stderr, "%s\n", err_msg);
2001 g_free(err_msg);
2005 /* If no capture filter or display filter has been specified, and there are
2006 still command-line arguments, treat them as the tokens of a capture
2007 filter (if no "-r" flag was specified) or a display filter (if a "-r"
2008 flag was specified. */
2009 if (ws_optind < argc) {
2010 if (cf_name != NULL) {
2011 if (dfilter != NULL) {
2012 cmdarg_err("Display filters were specified both with \"-Y\" "
2013 "and with additional command-line arguments.");
2014 exit_status = WS_EXIT_INVALID_OPTION;
2015 goto clean_exit;
2017 dfilter = get_args_as_string(argc, argv, ws_optind);
2018 } else {
2019 #ifdef HAVE_LIBPCAP
2020 unsigned i;
2022 if (global_capture_opts.default_options.cfilter) {
2023 cmdarg_err("A default capture filter was specified both with \"-f\""
2024 " and with additional command-line arguments.");
2025 exit_status = WS_EXIT_INVALID_OPTION;
2026 goto clean_exit;
2028 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2029 interface_options *interface_opts;
2030 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2031 if (interface_opts->cfilter == NULL) {
2032 interface_opts->cfilter = get_args_as_string(argc, argv, ws_optind);
2033 } else {
2034 cmdarg_err("A capture filter was specified both with \"-f\""
2035 " and with additional command-line arguments.");
2036 exit_status = WS_EXIT_INVALID_OPTION;
2037 goto clean_exit;
2040 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, ws_optind);
2041 #else
2042 capture_option_specified = true;
2043 #endif
2047 if (!output_file_name) {
2048 /* We're not saving the capture to a file; if "-q" wasn't specified,
2049 we should print packet information */
2050 if (!quiet)
2051 print_packet_info = true;
2052 } else {
2053 const char *save_file = output_file_name;
2054 /* We're saving to a file; if we're writing to the standard output.
2055 and we'll also be writing dissected packets to the standard
2056 output, reject the request. At best, we could redirect that
2057 to the standard error; we *can't* write both to the standard
2058 output and have either of them be useful. */
2059 if (strcmp(save_file, "-") == 0 && print_packet_info) {
2060 cmdarg_err("You can't write both raw packet data and dissected packets"
2061 " to the standard output.");
2062 exit_status = WS_EXIT_INVALID_OPTION;
2063 goto clean_exit;
2065 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
2066 /* An explicitly specified compression type overrides filename
2067 * magic. (Should we allow a way to specify "no" compression
2068 * with, e.g. a ".gz" extension?) */
2069 const char *sfx = strrchr(save_file, '.');
2070 if (sfx) {
2071 compression_type = wtap_extension_to_compression_type(sfx + 1);
2076 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
2077 compression_type = WTAP_UNCOMPRESSED;
2080 if (!wtap_can_write_compression_type(compression_type)) {
2081 cmdarg_err("Output files can't be written as %s",
2082 wtap_compression_type_description(compression_type));
2083 exit_status = WS_EXIT_INVALID_OPTION;
2084 goto clean_exit;
2087 if (compression_type != WTAP_UNCOMPRESSED && !wtap_dump_can_compress(out_file_type)) {
2088 cmdarg_err("The file format %s can't be written to output compressed format",
2089 wtap_file_type_subtype_name(out_file_type));
2090 exit_status = WS_EXIT_INVALID_OPTION;
2091 goto clean_exit;
2094 /* XXX - We have two different long options for compression type;
2095 * one (undocumented) for live capturing and one for not. That is confusing.
2096 * LONGOPT_COMPRESS doesn't set "capture_option_specified" because it can be
2097 * used when capturing or when not capturing.
2099 if (compression_type != WTAP_UNCOMPRESSED && is_capturing) {
2100 #ifdef HAVE_LIBPCAP
2101 exit_status = capture_opts_add_opt(&global_capture_opts, LONGOPT_COMPRESS_TYPE, wtap_compression_type_name(compression_type));
2102 if (exit_status != 0) {
2103 goto clean_exit;
2105 #else
2106 capture_option_specified = true;
2107 arg_error = true;
2108 #endif
2111 #ifndef HAVE_LIBPCAP
2112 if (capture_option_specified)
2113 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2114 #endif
2115 if (arg_error) {
2116 print_usage(stderr);
2117 exit_status = WS_EXIT_INVALID_OPTION;
2118 goto clean_exit;
2121 if (print_hex) {
2122 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW && output_action != WRITE_EK) {
2123 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON, JSONRAW or EK JSON");
2124 exit_status = WS_EXIT_INVALID_OPTION;
2125 goto clean_exit;
2129 if (output_only != NULL) {
2130 char *ps;
2132 if (!print_details) {
2133 cmdarg_err("-O requires -V");
2134 exit_status = WS_EXIT_INVALID_OPTION;
2135 goto clean_exit;
2138 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
2139 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
2140 const char *name = ps;
2141 header_field_info *hfi = proto_registrar_get_byalias(name);
2142 if (hfi) {
2143 name = hfi->abbrev;
2145 g_hash_table_insert(output_only_tables, (void *)name, (void *)name);
2149 if (rfilter != NULL && !perform_two_pass_analysis) {
2150 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
2151 exit_status = WS_EXIT_INVALID_OPTION;
2152 goto clean_exit;
2155 #ifdef HAVE_LIBPCAP
2156 if (caps_queries) {
2157 /* We're supposed to list the link-layer/timestamp types for an interface;
2158 did the user also specify a capture file to be read? */
2159 if (cf_name) {
2160 /* Yes - that's bogus. */
2161 cmdarg_err("You can't specify %s and a capture file to be read.",
2162 caps_queries & CAPS_QUERY_LINK_TYPES ? "-L" : "--list-time-stamp-types");
2163 exit_status = WS_EXIT_INVALID_OPTION;
2164 goto clean_exit;
2166 /* No - did they specify a ring buffer option? */
2167 if (global_capture_opts.multi_files_on) {
2168 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2169 exit_status = WS_EXIT_INVALID_OPTION;
2170 goto clean_exit;
2172 } else {
2173 if (cf_name) {
2175 * "-r" was specified, so we're reading a capture file.
2176 * Capture options don't apply here.
2179 /* We don't support capture filters when reading from a capture file
2180 (the BPF compiler doesn't support all link-layer types that we
2181 support in capture files we read). */
2182 if (global_capture_opts.default_options.cfilter) {
2183 cmdarg_err("Only read filters, not capture filters, "
2184 "can be specified when reading a capture file.");
2185 exit_status = WS_EXIT_INVALID_OPTION;
2186 goto clean_exit;
2188 if (global_capture_opts.multi_files_on) {
2189 cmdarg_err("Multiple capture files requested, but "
2190 "a capture isn't being done.");
2191 exit_status = WS_EXIT_INVALID_OPTION;
2192 goto clean_exit;
2194 if (global_capture_opts.has_file_duration) {
2195 cmdarg_err("Switching capture files after a time period was specified, but "
2196 "a capture isn't being done.");
2197 exit_status = WS_EXIT_INVALID_OPTION;
2198 goto clean_exit;
2200 if (global_capture_opts.has_file_interval) {
2201 cmdarg_err("Switching capture files after a time interval was specified, but "
2202 "a capture isn't being done.");
2203 exit_status = WS_EXIT_INVALID_OPTION;
2204 goto clean_exit;
2206 if (global_capture_opts.has_ring_num_files) {
2207 cmdarg_err("A ring buffer of capture files was specified, but "
2208 "a capture isn't being done.");
2209 exit_status = WS_EXIT_INVALID_OPTION;
2210 goto clean_exit;
2212 if (global_capture_opts.has_autostop_files) {
2213 cmdarg_err("A maximum number of capture files was specified, but "
2214 "a capture isn't being done.");
2215 exit_status = WS_EXIT_INVALID_OPTION;
2216 goto clean_exit;
2219 /* Note: TShark now allows the restriction of a _read_ file by packet count
2220 * and byte count as well as a write file. Other autostop options remain valid
2221 * only for a write file.
2223 if (global_capture_opts.has_autostop_duration) {
2224 cmdarg_err("A maximum capture time was specified, but "
2225 "a capture isn't being done.");
2226 exit_status = WS_EXIT_INVALID_OPTION;
2227 goto clean_exit;
2229 } else {
2231 * "-r" wasn't specified, so we're doing a live capture.
2233 bool use_pcapng = true;
2235 if (perform_two_pass_analysis) {
2236 /* Two-pass analysis doesn't work with live capture since it requires us
2237 * to buffer packets until we've read all of them, but a live capture
2238 * has no useful/meaningful definition of "all" */
2239 cmdarg_err("Live captures do not support two-pass analysis.");
2240 exit_status = WS_EXIT_INVALID_OPTION;
2241 goto clean_exit;
2244 if (global_capture_opts.saving_to_file) {
2245 /* They specified a "-w" flag, so we'll be saving to a capture file. */
2247 /* When capturing, we only support writing pcap or pcapng format. */
2248 if (out_file_type == wtap_pcapng_file_type_subtype()) {
2249 use_pcapng = true;
2250 } else if (out_file_type == wtap_pcap_file_type_subtype()) {
2251 use_pcapng = false;
2252 } else if (out_file_type == wtap_pcap_nsec_file_type_subtype()) {
2253 /* XXX - We request nanosecond time resolution regardless.
2254 * In the future wiretap might treat the two pcap subtypes
2255 * the same.
2257 use_pcapng = false;
2258 } else {
2259 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
2260 capture_opts_list_file_types();
2261 exit_status = WS_EXIT_INVALID_OPTION;
2262 goto clean_exit;
2264 if (capture_comments != NULL && !use_pcapng) {
2265 cmdarg_err("Capture comments can only be written to a pcapng file.");
2266 exit_status = WS_EXIT_INVALID_OPTION;
2267 goto clean_exit;
2269 if (global_capture_opts.multi_files_on) {
2270 /* Multiple-file mode doesn't work under certain conditions:
2271 a) it doesn't work if you're writing to the standard output;
2272 b) it doesn't work if you're writing to a pipe;
2274 if (strcmp(global_capture_opts.save_file, "-") == 0) {
2275 cmdarg_err("Multiple capture files requested, but "
2276 "the capture is being written to the standard output.");
2277 exit_status = WS_EXIT_INVALID_OPTION;
2278 goto clean_exit;
2280 if (global_capture_opts.output_to_pipe) {
2281 cmdarg_err("Multiple capture files requested, but "
2282 "the capture file is a pipe.");
2283 exit_status = WS_EXIT_INVALID_OPTION;
2284 goto clean_exit;
2286 if (!global_capture_opts.has_autostop_filesize &&
2287 !global_capture_opts.has_file_duration &&
2288 !global_capture_opts.has_file_interval &&
2289 !global_capture_opts.has_file_packets) {
2290 cmdarg_err("Multiple capture files requested, but "
2291 "no maximum capture file size, duration, interval or packets were specified.");
2292 exit_status = WS_EXIT_INVALID_OPTION;
2293 goto clean_exit;
2296 /* Currently, we don't support read or display filters when capturing
2297 and saving the packets. */
2298 if (rfilter != NULL) {
2299 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
2300 exit_status = WS_EXIT_INVALID_OPTION;
2301 goto clean_exit;
2303 if (dfilter != NULL) {
2304 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
2305 exit_status = WS_EXIT_INVALID_OPTION;
2306 goto clean_exit;
2308 global_capture_opts.use_pcapng = use_pcapng;
2309 } else {
2310 /* They didn't specify a "-w" flag, so we won't be saving to a
2311 capture file. Check for options that only make sense if
2312 we're saving to a file. */
2313 if (global_capture_opts.has_autostop_filesize) {
2314 cmdarg_err("Maximum capture file size specified, but "
2315 "capture isn't being saved to a file.");
2316 exit_status = WS_EXIT_INVALID_OPTION;
2317 goto clean_exit;
2319 if (global_capture_opts.multi_files_on) {
2320 cmdarg_err("Multiple capture files requested, but "
2321 "the capture isn't being saved to a file.");
2322 exit_status = WS_EXIT_INVALID_OPTION;
2323 goto clean_exit;
2325 if (capture_comments != NULL) {
2326 cmdarg_err("Capture comments were specified, but "
2327 "the capture isn't being saved to a file.");
2328 exit_status = WS_EXIT_INVALID_OPTION;
2329 goto clean_exit;
2334 #endif
2337 * If capture comments were specified, -w also has to have been specified.
2339 if (capture_comments != NULL) {
2340 if (output_file_name) {
2341 /* They specified a "-w" flag, so we'll be saving to a capture file.
2342 * This is fine if they're writing in a format that supports
2343 * section block comments.
2345 if (wtap_file_type_subtype_supports_option(out_file_type,
2346 WTAP_BLOCK_SECTION,
2347 OPT_COMMENT) == OPTION_NOT_SUPPORTED) {
2348 GArray *writable_type_subtypes;
2350 cmdarg_err("Capture comments can only be written to files of the following types:");
2351 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
2352 for (unsigned i = 0; i < writable_type_subtypes->len; i++) {
2353 int ft = g_array_index(writable_type_subtypes, int, i);
2355 if (wtap_file_type_subtype_supports_option(ft, WTAP_BLOCK_SECTION,
2356 OPT_COMMENT) != OPTION_NOT_SUPPORTED)
2357 cmdarg_err_cont(" %s - %s", wtap_file_type_subtype_name(ft),
2358 wtap_file_type_subtype_description(ft));
2360 exit_status = WS_EXIT_INVALID_OPTION;
2361 goto clean_exit;
2364 else {
2365 cmdarg_err("Capture comments were specified, but you aren't writing a capture file.");
2366 exit_status = WS_EXIT_INVALID_OPTION;
2367 goto clean_exit;
2371 err_msg = ws_init_sockets();
2372 if (err_msg != NULL)
2374 cmdarg_err("%s", err_msg);
2375 g_free(err_msg);
2376 cmdarg_err_cont("%s", please_report_bug());
2377 exit_status = WS_EXIT_INIT_FAILED;
2378 goto clean_exit;
2381 /* Notify all registered modules that have had any of their preferences
2382 changed either from one of the preferences file or from the command
2383 line that their preferences have changed. */
2384 prefs_apply_all();
2386 /* We can also enable specified taps for export object */
2387 start_exportobjects();
2389 /* At this point MATE will have registered its field array so we can
2390 check if the fields specified by the user are all good.
2393 GSList* it = NULL;
2394 GSList *invalid_fields = output_fields_valid(output_fields);
2395 if (invalid_fields != NULL) {
2397 cmdarg_err("Some fields aren't valid:");
2398 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
2399 cmdarg_err_cont("\t%s", (char *)it->data);
2401 g_slist_free(invalid_fields);
2402 exit_status = WS_EXIT_INVALID_OPTION;
2403 goto clean_exit;
2407 if (ex_opt_count("read_format") > 0) {
2408 const char* name = ex_opt_get_next("read_format");
2409 in_file_type = open_info_name_to_type(name);
2410 if (in_file_type == WTAP_TYPE_AUTO) {
2411 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
2412 list_read_capture_types();
2413 exit_status = WS_EXIT_INVALID_OPTION;
2414 goto clean_exit;
2418 if (global_dissect_options.time_format != TS_NOT_SET)
2419 timestamp_set_type(global_dissect_options.time_format);
2420 if (global_dissect_options.time_precision != TS_PREC_NOT_SET)
2421 timestamp_set_precision(global_dissect_options.time_precision);
2424 * Enabled and disabled protocols and heuristic dissectors as per
2425 * command-line options.
2427 if (!setup_enabled_and_disabled_protocols()) {
2428 exit_status = WS_EXIT_INVALID_OPTION;
2429 goto clean_exit;
2432 /* Build the column format array */
2433 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, true);
2435 /* Everything is setup, dump glossaries now if that's what we're doing.
2436 * We want to do this after protocols and heuristic dissectors are
2437 * enabled and disabled. Doing it after building the column format
2438 * array might make it easier to add a report that describes the
2439 * current list of columns and how to add a new one (#17332).
2441 if (glossary != NULL) {
2442 exit_status = dump_glossary(glossary, elastic_mapping_filter);
2443 goto clean_exit;
2446 #ifdef HAVE_LIBPCAP
2447 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2448 capture_opts_trim_ring_num_files(&global_capture_opts);
2449 #endif
2451 if (rfilter != NULL) {
2452 ws_debug("Compiling read filter: '%s'", rfilter);
2453 if (!compile_dfilter(rfilter, &rfcode)) {
2454 epan_cleanup();
2455 extcap_cleanup();
2457 #ifdef HAVE_LIBPCAP
2458 warn_about_capture_filter(rfilter);
2459 #endif
2461 exit_status = WS_EXIT_INVALID_INTERFACE;
2462 goto clean_exit;
2465 cfile.rfcode = rfcode;
2467 if (dfilter != NULL) {
2468 ws_debug("Compiling display filter: '%s'", dfilter);
2469 if (!compile_dfilter(dfilter, &dfcode)) {
2470 epan_cleanup();
2471 extcap_cleanup();
2473 #ifdef HAVE_LIBPCAP
2474 warn_about_capture_filter(dfilter);
2475 #endif
2477 exit_status = WS_EXIT_INVALID_FILTER;
2478 goto clean_exit;
2481 cfile.dfcode = dfcode;
2483 if (print_packet_info) {
2484 /* If we're printing as text or PostScript, we have
2485 to create a print stream. */
2486 if (output_action == WRITE_TEXT) {
2487 switch (print_format) {
2489 case PR_FMT_TEXT:
2490 print_stream = print_stream_text_stdio_new(stdout);
2491 break;
2493 case PR_FMT_PS:
2494 print_stream = print_stream_ps_stdio_new(stdout);
2495 break;
2497 default:
2498 ws_assert_not_reached();
2503 /* PDU export requested. Take the ownership of the '-w' file, apply tap
2504 * filters and start tapping. */
2505 if (pdu_export_arg) {
2506 const char *exp_pdu_tap_name = pdu_export_arg;
2507 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
2508 char *exp_pdu_error;
2509 int exp_fd;
2510 char *comment;
2512 if (!cf_name) {
2513 cmdarg_err("PDUs export requires a capture file (specify with -r).");
2514 exit_status = WS_EXIT_INVALID_OPTION;
2515 goto clean_exit;
2517 /* Take ownership of the '-w' output file. */
2518 exp_pdu_filename = output_file_name;
2519 output_file_name = NULL;
2520 #ifdef HAVE_LIBPCAP
2521 global_capture_opts.save_file = NULL;
2522 #endif
2523 if (exp_pdu_filename == NULL) {
2524 cmdarg_err("PDUs export requires an output file (-w).");
2525 exit_status = WS_EXIT_INVALID_OPTION;
2526 goto clean_exit;
2529 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
2530 &exp_pdu_tap_data);
2531 if (exp_pdu_error) {
2532 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
2533 g_free(exp_pdu_error);
2534 list_export_pdu_taps();
2535 exit_status = INVALID_TAP;
2536 goto clean_exit;
2539 if (strcmp(exp_pdu_filename, "-") == 0) {
2540 /* Write to the standard output. */
2541 exp_fd = 1;
2542 } else {
2543 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2544 if (exp_fd == -1) {
2545 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, true));
2546 exit_status = WS_EXIT_INVALID_FILE;
2547 goto clean_exit;
2551 /* Activate the export PDU tap */
2552 /* Write to our output file with this comment (if the type supports it,
2553 * otherwise exp_pdu_open() will ignore the comment) */
2554 comment = ws_strdup_printf("Dump of PDUs from %s", cf_name);
2555 exp_pdu_status = exp_pdu_open(&exp_pdu_tap_data, exp_pdu_filename,
2556 out_file_type, exp_fd, comment,
2557 &err, &err_info);
2558 g_free(comment);
2559 if (!exp_pdu_status) {
2560 cfile_dump_open_failure_message(exp_pdu_filename, err, err_info,
2561 out_file_type);
2562 exit_status = INVALID_EXPORT;
2563 goto clean_exit;
2567 if (cf_name) {
2568 ws_debug("tshark: Opening capture file: %s", cf_name);
2570 * We're reading a capture file.
2572 if (cf_open(&cfile, cf_name, in_file_type, false, &err) != CF_OK) {
2573 epan_cleanup();
2574 extcap_cleanup();
2575 exit_status = WS_EXIT_INVALID_FILE;
2576 goto clean_exit;
2579 /* Start statistics taps; we do so after successfully opening the
2580 capture file, so we know we have something to compute stats
2581 on, and after registering all dissectors, so that MATE will
2582 have registered its field array so we can have a tap filter
2583 with one of MATE's late-registered fields as part of the
2584 filter. */
2585 start_requested_stats();
2587 /* Do we need to do dissection of packets? That depends on, among
2588 other things, what taps are listening, so determine that after
2589 starting the statistics taps. */
2590 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2591 ws_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2593 /* Process the packets in the file */
2594 ws_debug("tshark: invoking process_cap_file() to process the packets");
2595 TRY {
2596 status = process_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res,
2597 #ifdef HAVE_LIBPCAP
2598 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
2599 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0,
2600 global_capture_opts.has_autostop_written_packets ? global_capture_opts.autostop_written_packets : 0,
2601 compression_type);
2602 #else
2603 max_packet_count,
2606 WTAP_UNCOMPRESSED);
2607 #endif
2609 CATCH(OutOfMemoryError) {
2610 fprintf(stderr,
2611 "Out Of Memory.\n"
2612 "\n"
2613 "Sorry, but TShark has to terminate now.\n"
2614 "\n"
2615 "More information and workarounds can be found at\n"
2616 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
2617 status = PROCESS_FILE_ERROR;
2619 ENDTRY;
2621 switch (status) {
2623 case PROCESS_FILE_SUCCEEDED:
2624 /* Everything worked OK; draw the taps. */
2625 draw_taps = true;
2626 break;
2628 case PROCESS_FILE_NO_FILE_PROCESSED:
2629 /* We never got to try to read the file, so there are no tap
2630 results to dump. Exit with an error status. */
2631 exit_status = 2;
2632 break;
2634 case PROCESS_FILE_ERROR:
2635 /* We still dump out the results of taps, etc., as we might have
2636 read some packets; however, we exit with an error status. */
2637 draw_taps = true;
2638 exit_status = 2;
2639 break;
2641 case PROCESS_FILE_INTERRUPTED:
2642 /* The user interrupted the read process; Don't dump out the
2643 result of taps, etc., and exit with an error status. */
2644 exit_status = 2;
2645 break;
2648 if (pdu_export_arg) {
2649 if (!exp_pdu_close(&exp_pdu_tap_data, &err, &err_info)) {
2650 cfile_close_failure_message(exp_pdu_filename, err, err_info);
2651 exit_status = 2;
2653 g_free(pdu_export_arg);
2654 g_free(exp_pdu_filename);
2656 } else {
2657 ws_debug("tshark: no capture file specified");
2658 /* No capture file specified, so we're supposed to do a live capture
2659 or get a list of link-layer types for a live capture device;
2660 do we have support for live captures? */
2661 #ifdef HAVE_LIBPCAP
2662 #ifdef _WIN32
2663 /* Warn the user if npf.sys isn't loaded. */
2664 if (!npf_sys_is_running()) {
2665 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
2666 "capturing or\nlisting interfaces.\n");
2668 #endif /* _WIN32 */
2670 /* if no interface was specified, pick a default */
2671 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
2672 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
2673 if (exit_status != 0) {
2674 goto clean_exit;
2678 * If requested, list the link layer types and/or time stamp types
2679 * and exit.
2681 if (caps_queries) {
2682 unsigned i;
2684 /* Get the list of link-layer types for the capture devices. */
2685 exit_status = EXIT_SUCCESS;
2686 GList *if_cap_queries = NULL;
2687 if_cap_query_t *if_cap_query;
2688 GHashTable *capability_hash;
2689 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2690 interface_options *interface_opts;
2691 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2692 if_cap_query = g_new(if_cap_query_t, 1);
2693 if_cap_query->name = interface_opts->name;
2694 if_cap_query->monitor_mode = interface_opts->monitor_mode;
2695 if_cap_query->auth_username = NULL;
2696 if_cap_query->auth_password = NULL;
2697 #ifdef HAVE_PCAP_REMOTE
2698 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
2699 if_cap_query->auth_username = interface_opts->auth_username;
2700 if_cap_query->auth_password = interface_opts->auth_password;
2702 #endif
2703 if_cap_queries = g_list_prepend(if_cap_queries, if_cap_query);
2705 if_cap_queries = g_list_reverse(if_cap_queries);
2706 capability_hash = capture_get_if_list_capabilities(if_cap_queries, &err_str, &err_str_secondary, NULL);
2707 g_list_free_full(if_cap_queries, g_free);
2708 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2709 interface_options *interface_opts;
2710 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2711 if_capabilities_t *caps;
2712 caps = g_hash_table_lookup(capability_hash, interface_opts->name);
2713 if (caps == NULL) {
2714 cmdarg_err("%s%s%s", err_str, err_str_secondary ? "\n" : "", err_str_secondary ? err_str_secondary : "");
2715 g_free(err_str);
2716 g_free(err_str_secondary);
2717 exit_status = WS_EXIT_INVALID_CAPABILITY;
2718 break;
2720 exit_status = capture_opts_print_if_capabilities(caps, interface_opts,
2721 caps_queries);
2722 if (exit_status != EXIT_SUCCESS) {
2723 break;
2726 g_hash_table_destroy(capability_hash);
2727 goto clean_exit;
2731 * If the standard error isn't a terminal, don't print packet counts,
2732 * as they won't show up on the user's terminal and they'll get in
2733 * the way of error messages in the file (to which we assume the
2734 * standard error was redirected; if it's redirected to the null
2735 * device, there's no point in printing packet counts anyway).
2737 * Otherwise, if we're printing packet information and the standard
2738 * output is a terminal (which we assume means the standard output and
2739 * error are going to the same terminal), don't print packet counts,
2740 * as they'll get in the way of the packet information.
2742 * Otherwise, if the user specified -q, don't print packet counts.
2744 * Otherwise, print packet counts.
2746 * XXX - what if the user wants to do a live capture, doesn't want
2747 * to save it to a file, doesn't want information printed for each
2748 * packet, does want some "-z" statistic, and wants packet counts
2749 * so they know whether they're seeing any packets? -q will
2750 * suppress the information printed for each packet, but it'll
2751 * also suppress the packet counts.
2753 if (!ws_isatty(ws_fileno(stderr)))
2754 print_packet_counts = false;
2755 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
2756 print_packet_counts = false;
2757 else if (quiet)
2758 print_packet_counts = false;
2759 else
2760 print_packet_counts = true;
2762 ws_debug("tshark: performing live capture");
2764 /* Start statistics taps; we should only do so after the capture
2765 started successfully, so we know we have something to compute
2766 stats, but we currently don't check for that - see below.
2768 We do so after registering all dissectors, so that MATE will
2769 have registered its field array so we can have a tap filter
2770 with one of MATE's late-registered fields as part of the
2771 filter. */
2772 start_requested_stats();
2774 /* Do we need to do dissection of packets? That depends on, among
2775 other things, what taps are listening, so determine that after
2776 starting the statistics taps. */
2777 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2778 ws_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2780 /* We're doing live capture; if the capture child is writing to a pipe,
2781 we can't do dissection, because that would mean two readers for
2782 the pipe, tshark and whatever else. */
2783 if (do_dissection && global_capture_opts.output_to_pipe) {
2784 if (tap_listeners_require_dissection()) {
2785 cmdarg_err("Taps aren't supported when capturing and saving to a pipe.");
2786 exit_status = WS_EXIT_INVALID_OPTION;
2787 goto clean_exit;
2789 if (print_packet_info) {
2790 cmdarg_err("Printing dissected packets isn't supported when capturing and saving to a pipe.");
2791 exit_status = WS_EXIT_INVALID_OPTION;
2792 goto clean_exit;
2794 /* We already checked the next three reasons for supersets of
2795 capturing and saving to a pipe, but this doesn't hurt. */
2796 if (pdu_export_arg) {
2797 cmdarg_err("PDUs export isn't supported when capturing and saving to a pipe.");
2798 exit_status = WS_EXIT_INVALID_OPTION;
2799 goto clean_exit;
2801 if (rfcode != NULL) {
2802 cmdarg_err("Read filters aren't supported when capturing and saving to a pipe.");
2803 exit_status = WS_EXIT_INVALID_OPTION;
2804 goto clean_exit;
2806 if (dfcode != NULL) {
2807 cmdarg_err("Display filters aren't supported when capturing and saving to a pipe.");
2808 exit_status = WS_EXIT_INVALID_OPTION;
2809 goto clean_exit;
2811 /* There's some other reason we're dissecting. */
2812 cmdarg_err("Dissection isn't supported when capturing and saving to a pipe.");
2813 exit_status = WS_EXIT_INVALID_OPTION;
2814 goto clean_exit;
2817 /* Write a preamble if we're printing one. Do this after all checking
2818 * for invalid options, so we don't print just a preamble and quit. */
2819 if (print_packet_info) {
2820 if (!write_preamble(&cfile)) {
2821 show_print_file_io_error();
2822 exit_status = WS_EXIT_INVALID_FILE;
2823 goto clean_exit;
2828 * XXX - this returns false if an error occurred, but it also
2829 * returns false if the capture stops because a time limit
2830 * was reached (and possibly other limits), so we can't assume
2831 * it means an error.
2833 * The capture code is a bit twisty, so it doesn't appear to
2834 * be an easy fix. We just ignore the return value for now.
2835 * Instead, pass on the exit status from the capture child.
2837 capture();
2838 exit_status = global_capture_session.fork_child_status;
2840 if (print_packet_info) {
2841 if (!write_finale()) {
2842 show_print_file_io_error();
2847 * If we never got a capture file, don't draw the taps; we not only
2848 * didn't capture any packets, we never even did any capturing.
2850 if (cfile.filename != NULL)
2851 draw_taps = true;
2852 #else
2853 /* No - complain. */
2854 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2855 exit_status = INVALID_CAPTURE;
2856 goto clean_exit;
2857 #endif
2860 if (cfile.provider.frames != NULL) {
2861 free_frame_data_sequence(cfile.provider.frames);
2862 cfile.provider.frames = NULL;
2865 if (draw_taps)
2866 draw_tap_listeners(true);
2868 if (tls_session_keys_file) {
2869 size_t keylist_length;
2870 char *keylist = ssl_export_sessions(&keylist_length);
2871 write_file_binary_mode(tls_session_keys_file, keylist, keylist_length);
2872 g_free(keylist);
2875 if (opt_print_timers) {
2876 if (cf_name == NULL) {
2877 /* We're doind a live capture. That isn't currently supported
2878 * with timers. */
2879 ws_message("Ignoring option --print-timers because we are doing a live capture");
2881 else {
2882 print_elapsed_json(cf_name, dfilter);
2886 /* Memory cleanup */
2887 reset_tap_listeners();
2888 funnel_dump_all_text_windows();
2889 epan_free(cfile.epan);
2890 epan_cleanup();
2891 extcap_cleanup();
2893 output_fields_free(output_fields);
2894 output_fields = NULL;
2896 clean_exit:
2897 cf_close(&cfile);
2898 g_free(cf_name);
2899 destroy_print_stream(print_stream);
2900 g_free(output_file_name);
2901 #ifdef HAVE_LIBPCAP
2902 capture_opts_cleanup(&global_capture_opts);
2903 if (cached_if_list) {
2904 free_interface_list(cached_if_list);
2906 #endif
2907 col_cleanup(&cfile.cinfo);
2908 wtap_cleanup();
2909 free_progdirs();
2910 dfilter_free(dfcode);
2911 g_free(dfilter);
2912 return exit_status;
2915 bool loop_running;
2916 uint32_t packet_count;
2918 static epan_t *
2919 tshark_epan_new(capture_file *cf)
2921 static const struct packet_provider_funcs funcs = {
2922 cap_file_provider_get_frame_ts,
2923 cap_file_provider_get_interface_name,
2924 cap_file_provider_get_interface_description,
2925 NULL,
2928 return epan_new(&cf->provider, &funcs);
2931 #ifdef HAVE_LIBPCAP
2932 static bool
2933 capture(void)
2935 volatile bool ret = true;
2936 GString *str;
2937 GMainContext *ctx;
2938 #ifndef _WIN32
2939 struct sigaction action, oldaction;
2940 #endif
2942 /* Create new dissection section. */
2943 epan_free(cfile.epan);
2944 cfile.epan = tshark_epan_new(&cfile);
2946 #ifdef _WIN32
2947 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2948 SetConsoleCtrlHandler(capture_cleanup, true);
2949 #else /* _WIN32 */
2950 /* Catch SIGINT and SIGTERM and, if we get either of them,
2951 clean up and exit. If SIGHUP isn't being ignored, catch
2952 it too and, if we get it, clean up and exit.
2954 We restart any read that was in progress, so that it doesn't
2955 disrupt reading from the sync pipe. The signal handler tells
2956 the capture child to finish; it will report that it finished,
2957 or will exit abnormally, so we'll stop reading from the sync
2958 pipe, pick up the exit status, and quit. */
2959 memset(&action, 0, sizeof(action));
2960 action.sa_handler = capture_cleanup;
2961 action.sa_flags = SA_RESTART;
2962 sigemptyset(&action.sa_mask);
2963 sigaction(SIGTERM, &action, NULL);
2964 sigaction(SIGINT, &action, NULL);
2965 sigaction(SIGHUP, NULL, &oldaction);
2966 if (oldaction.sa_handler == SIG_DFL)
2967 sigaction(SIGHUP, &action, NULL);
2969 #ifdef SIGINFO
2970 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2971 quiet mode, report the number of packets we've captured.
2973 Again, restart any read that was in progress, so that it doesn't
2974 disrupt reading from the sync pipe. */
2975 action.sa_handler = report_counts_siginfo;
2976 action.sa_flags = SA_RESTART;
2977 sigemptyset(&action.sa_mask);
2978 sigaction(SIGINFO, &action, NULL);
2979 #endif /* SIGINFO */
2980 #endif /* _WIN32 */
2982 global_capture_session.state = CAPTURE_PREPARING;
2984 /* Let the user know which interfaces were chosen. */
2985 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2986 if (really_quiet == false)
2987 fprintf(stderr, "Capturing on %s\n", str->str);
2988 fflush(stderr);
2989 g_string_free(str, TRUE);
2991 ret = sync_pipe_start(&global_capture_opts, capture_comments,
2992 &global_capture_session, &global_info_data, NULL);
2994 if (!ret)
2995 return false;
2998 * Force synchronous resolution of IP addresses; we're doing only
2999 * one pass, so we can't do it in the background and fix up past
3000 * dissections.
3002 set_resolution_synchrony(true);
3004 /* the actual capture loop */
3005 ctx = g_main_context_default();
3006 loop_running = true;
3010 while (loop_running)
3012 g_main_context_iteration(ctx, true);
3015 CATCH(OutOfMemoryError) {
3016 fprintf(stderr,
3017 "Out Of Memory.\n"
3018 "\n"
3019 "Sorry, but TShark has to terminate now.\n"
3020 "\n"
3021 "More information and workarounds can be found at\n"
3022 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
3023 abort();
3025 ENDTRY;
3026 return ret;
3029 /* capture child detected an error */
3030 static void
3031 capture_input_error(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
3033 /* The primary message might be an empty string, e.g. when the error was
3034 * from extcap. (The extcap stderr is gathered when the session closes
3035 * and printed in capture_input_closed below.) */
3036 if (*error_msg != '\0') {
3037 cmdarg_err("%s", error_msg);
3038 if (secondary_error_msg != NULL && *secondary_error_msg != '\0') {
3039 /* We have both primary and secondary messages. */
3040 cmdarg_err_cont("%s", secondary_error_msg);
3046 /* capture child detected an capture filter related error */
3047 static void
3048 capture_input_cfilter_error(capture_session *cap_session, unsigned i, const char *error_message)
3050 capture_options *capture_opts = cap_session->capture_opts;
3051 dfilter_t *rfcode = NULL;
3052 interface_options *interface_opts;
3054 ws_assert(i < capture_opts->ifaces->len);
3055 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3057 if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
3058 cmdarg_err(
3059 "Invalid capture filter \"%s\" for interface '%s'.\n"
3060 "\n"
3061 "That string looks like a valid display filter; however, it isn't a valid\n"
3062 "capture filter (%s).\n"
3063 "\n"
3064 "Note that display filters and capture filters don't have the same syntax,\n"
3065 "so you can't use most display filter expressions as capture filters.\n"
3066 "\n"
3067 "See the User's Guide for a description of the capture filter syntax.",
3068 interface_opts->cfilter, interface_opts->descr, error_message);
3069 dfilter_free(rfcode);
3070 } else {
3071 cmdarg_err(
3072 "Invalid capture filter \"%s\" for interface '%s'.\n"
3073 "\n"
3074 "That string isn't a valid capture filter (%s).\n"
3075 "See the User's Guide for a description of the capture filter syntax.",
3076 interface_opts->cfilter, interface_opts->descr, error_message);
3081 /* capture child tells us we have a new (or the first) capture file */
3082 static bool
3083 capture_input_new_file(capture_session *cap_session, char *new_file)
3085 capture_options *capture_opts = cap_session->capture_opts;
3086 capture_file *cf = cap_session->cf;
3087 bool is_tempfile;
3088 int err;
3090 if (really_quiet == false) {
3091 if (cap_session->state == CAPTURE_PREPARING) {
3092 ws_info("Capture started.");
3094 ws_info("File: \"%s\"", new_file);
3097 ws_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
3099 /* free the old filename */
3100 if (capture_opts->save_file != NULL) {
3102 /* we start a new capture file, close the old one (if we had one before) */
3103 if (cf->state != FILE_CLOSED) {
3104 cf_close(cf);
3107 g_free(capture_opts->save_file);
3108 is_tempfile = false;
3110 epan_free(cf->epan);
3111 cf->epan = tshark_epan_new(cf);
3112 } else {
3113 /* we didn't had a save_file before, must be a tempfile */
3114 is_tempfile = true;
3117 /* save the new filename */
3118 capture_opts->save_file = g_strdup(new_file);
3120 /* if we are in real-time mode, open the new file now */
3121 if (do_dissection) {
3122 /* this is probably unnecessary, but better safe than sorry */
3123 cap_session->cf->open_type = WTAP_TYPE_AUTO;
3124 /* Attempt to open the capture file and set up to read from it. */
3125 switch(cf_open(cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
3126 case CF_OK:
3127 break;
3128 case CF_ERROR:
3129 /* Don't unlink (delete) the save file - leave it around,
3130 for debugging purposes. */
3131 g_free(capture_opts->save_file);
3132 capture_opts->save_file = NULL;
3133 return false;
3135 } else if (quiet && is_tempfile) {
3136 cf->state = FILE_READ_ABORTED;
3137 cf->filename = g_strdup(new_file);
3138 cf->is_tempfile = is_tempfile;
3141 cap_session->state = CAPTURE_RUNNING;
3143 return true;
3147 /* capture child tells us we have new packets to read */
3148 static void
3149 capture_input_new_packets(capture_session *cap_session, int to_read)
3151 bool ret;
3152 int err;
3153 char *err_info;
3154 int64_t data_offset;
3155 capture_file *cf = cap_session->cf;
3156 bool filtering_tap_listeners;
3157 unsigned tap_flags;
3159 #ifdef SIGINFO
3161 * Prevent a SIGINFO handler from writing to the standard error while
3162 * we're doing so or writing to the standard output; instead, have it
3163 * just set a flag telling us to print that information when we're done.
3165 infodelay = true;
3166 #endif /* SIGINFO */
3168 /* Do we have any tap listeners with filters? */
3169 filtering_tap_listeners = have_filtering_tap_listeners();
3171 /* Get the union of the flags for all tap listeners. */
3172 tap_flags = union_of_tap_listener_flags();
3174 if (do_dissection) {
3175 bool create_proto_tree;
3176 epan_dissect_t *edt;
3177 wtap_rec rec;
3180 * Determine whether we need to create a protocol tree.
3181 * We do if:
3183 * we're going to apply a read filter;
3185 * we're going to apply a display filter;
3187 * we're going to print the protocol tree;
3189 * one of the tap listeners is going to apply a filter;
3191 * one of the tap listeners requires a protocol tree;
3193 * a postdissector wants field values or protocols
3194 * on the first pass;
3196 * we have custom columns (which require field values, which
3197 * currently requires that we build a protocol tree).
3199 create_proto_tree =
3200 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3201 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3202 have_custom_cols(&cf->cinfo) || dissect_color);
3204 /* The protocol tree will be "visible", i.e., nothing faked, only if
3205 we're printing packet details, which is true if we're printing stuff
3206 ("print_packet_info" is true) and we're in verbose mode
3207 ("packet_details" is true). But if we specified certain fields with
3208 "-e", we'll prime those directly later. */
3209 bool visible = print_packet_info && print_details && output_fields_num_fields(output_fields) == 0;
3210 edt = epan_dissect_new(cf->epan, create_proto_tree, visible);
3212 wtap_rec_init(&rec, 1514);
3214 while (to_read-- && cf->provider.wth) {
3215 wtap_cleareof(cf->provider.wth);
3216 ret = wtap_read(cf->provider.wth, &rec, &err, &err_info, &data_offset);
3217 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3218 if (ret == false) {
3219 /* read from file failed, tell the capture child to stop */
3220 sync_pipe_stop(cap_session);
3221 wtap_close(cf->provider.wth);
3222 cf->provider.wth = NULL;
3223 } else {
3224 ret = process_packet_single_pass(cf, edt, data_offset, &rec,
3225 tap_flags);
3227 if (ret != false) {
3228 /* packet successfully read and gone through the "Read Filter" */
3229 packet_count++;
3231 wtap_rec_reset(&rec);
3234 epan_dissect_free(edt);
3236 wtap_rec_cleanup(&rec);
3238 } else {
3240 * Dumpcap's doing all the work; we're not doing any dissection.
3241 * Count all the packets it wrote.
3243 packet_count += to_read;
3246 if (print_packet_counts) {
3247 /* We're printing packet counts. */
3248 if (packet_count != 0) {
3249 fprintf(stderr, "\r%u ", packet_count);
3250 /* stderr could be line buffered */
3251 fflush(stderr);
3255 #ifdef SIGINFO
3257 * Allow SIGINFO handlers to write.
3259 infodelay = false;
3262 * If a SIGINFO handler asked us to write out capture counts, do so.
3264 if (infoprint)
3265 report_counts();
3266 #endif /* SIGINFO */
3269 static void
3270 report_counts(void)
3272 if ((print_packet_counts == false) && (really_quiet == false)) {
3273 /* Report the count only if we aren't printing a packet count
3274 as packets arrive. */
3275 fprintf(stderr, "%u packet%s captured\n", packet_count,
3276 plurality(packet_count, "", "s"));
3278 #ifdef SIGINFO
3279 infoprint = false; /* we just reported it */
3280 #endif /* SIGINFO */
3283 #ifdef SIGINFO
3284 static void
3285 report_counts_siginfo(int signum _U_)
3287 int sav_errno = errno;
3288 /* If we've been told to delay printing, just set a flag asking
3289 that we print counts (if we're supposed to), otherwise print
3290 the count of packets captured (if we're supposed to). */
3291 if (infodelay)
3292 infoprint = true;
3293 else
3294 report_counts();
3295 errno = sav_errno;
3297 #endif /* SIGINFO */
3300 /* capture child detected any packet drops? */
3301 static void
3302 capture_input_drops(capture_session *cap_session _U_, uint32_t dropped, const char* interface_name)
3304 if (print_packet_counts) {
3305 /* We're printing packet counts to stderr.
3306 Send a newline so that we move to the line after the packet count. */
3307 fprintf(stderr, "\n");
3310 if (dropped != 0) {
3311 /* We're printing packet counts to stderr.
3312 Send a newline so that we move to the line after the packet count. */
3313 if (interface_name != NULL) {
3314 fprintf(stderr, "%u packet%s dropped from %s\n", dropped, plurality(dropped, "", "s"), interface_name);
3315 } else {
3316 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
3323 * Capture child closed its side of the pipe, report any error and
3324 * do the required cleanup.
3326 static void
3327 capture_input_closed(capture_session *cap_session _U_, char *msg)
3329 if (msg != NULL && *msg != '\0')
3330 fprintf(stderr, "tshark: %s\n", msg);
3332 report_counts();
3334 loop_running = false;
3337 #ifdef _WIN32
3338 static BOOL WINAPI
3339 capture_cleanup(DWORD ctrltype _U_)
3341 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
3342 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
3343 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
3344 like SIGTERM at least when the machine's shutting down.
3346 For now, we handle them all as indications that we should clean up
3347 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
3348 way on UNIX.
3350 We must return true so that no other handler - such as one that would
3351 terminate the process - gets called.
3353 XXX - for some reason, typing ^C to TShark, if you run this in
3354 a Cygwin console window in at least some versions of Cygwin,
3355 causes TShark to terminate immediately; this routine gets
3356 called, but the main loop doesn't get a chance to run and
3357 exit cleanly, at least if this is compiled with Microsoft Visual
3358 C++ (i.e., it's a property of the Cygwin console window or Bash;
3359 it happens if TShark is not built with Cygwin - for all I know,
3360 building it with Cygwin may make the problem go away). */
3362 /* tell the capture child to stop */
3363 sync_pipe_stop(&global_capture_session);
3365 /* don't stop our own loop already here, otherwise status messages and
3366 * cleanup wouldn't be done properly. The child will indicate the stop of
3367 * everything by calling capture_input_closed() later */
3369 return true;
3371 #else
3372 static void
3373 capture_cleanup(int signum _U_)
3375 /* tell the capture child to stop */
3376 sync_pipe_stop(&global_capture_session);
3378 /* don't stop our own loop already here, otherwise status messages and
3379 * cleanup wouldn't be done properly. The child will indicate the stop of
3380 * everything by calling capture_input_closed() later */
3382 #endif /* _WIN32 */
3383 #endif /* HAVE_LIBPCAP */
3385 static bool
3386 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
3387 int64_t offset, wtap_rec *rec)
3389 frame_data fdlocal;
3390 uint32_t framenum;
3391 bool passed;
3392 int64_t elapsed_start;
3394 /* The frame number of this packet is one more than the count of
3395 frames in this packet. */
3396 framenum = cf->count + 1;
3398 /* If we're not running a display filter and we're not printing any
3399 packet information, we don't need to do a dissection. This means
3400 that all packets can be marked as 'passed'. */
3401 passed = true;
3403 frame_data_init(&fdlocal, framenum, rec, offset, cum_bytes);
3405 /* If we're going to run a read filter or a display filter, set up to
3406 do a dissection and do so. (This is the first pass of two passes
3407 over the packets, so we will not be printing any information
3408 from the dissection or running taps on the packet; if we're doing
3409 any of that, we'll do it in the second pass.) */
3410 if (edt) {
3411 if (gbl_resolv_flags.network_name || gbl_resolv_flags.maxmind_geoip) {
3412 /* If we're doing async lookups, send any that are queued and
3413 * retrieve results.
3415 * Ideally we'd force any lookups that need to happen on the second pass
3416 * to be sent asynchronously on this pass so the results would be ready.
3417 * That will happen if they're involved in a filter (because we prime the
3418 * tree below), but not currently for taps, if we're printing packet
3419 * summaries or details, etc.
3421 * XXX - If we're running a read filter that depends on a resolved
3422 * name, we should be doing synchronous lookups in that case. Also
3423 * marking the dependent frames below might not work with a display
3424 * filter that depends on a resolved name.
3426 host_name_lookup_process();
3429 column_info *cinfo = NULL;
3431 /* If we're running a read filter, prime the epan_dissect_t with that
3432 filter. */
3433 if (cf->rfcode)
3434 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
3436 if (cf->dfcode)
3437 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3439 /* This is the first pass, so prime the epan_dissect_t with the
3440 hfids postdissectors want on the first pass. */
3441 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
3443 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
3444 &cf->provider.ref, cf->provider.prev_dis);
3445 if (cf->provider.ref == &fdlocal) {
3446 ref_frame = fdlocal;
3447 cf->provider.ref = &ref_frame;
3450 /* If we're applying a filter that needs the columns, construct them. */
3451 if (dfilter_requires_columns(cf->rfcode) || dfilter_requires_columns(cf->dfcode)) {
3452 cinfo = &cf->cinfo;
3455 elapsed_start = g_get_monotonic_time();
3456 epan_dissect_run(edt, cf->cd_t, rec, &fdlocal, cinfo);
3457 tshark_elapsed.first_pass.dissect += g_get_monotonic_time() - elapsed_start;
3459 /* Run the read filter if we have one. */
3460 if (cf->rfcode) {
3461 elapsed_start = g_get_monotonic_time();
3462 passed = dfilter_apply_edt(cf->rfcode, edt);
3463 tshark_elapsed.first_pass.dfilter_read += g_get_monotonic_time() - elapsed_start;
3467 if (passed) {
3468 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
3469 cf->provider.prev_cap = cf->provider.prev_dis = frame_data_sequence_add(cf->provider.frames, &fdlocal);
3471 /* If we're not doing dissection then there won't be any dependent frames.
3472 * More importantly, edt.pi.fd.dependent_frames won't be initialized because
3473 * epan hasn't been initialized.
3474 * if we *are* doing dissection, then mark the dependent frames, but only
3475 * if a display filter was given and it matches this packet.
3477 if (edt && cf->dfcode) {
3478 elapsed_start = g_get_monotonic_time();
3479 if (dfilter_apply_edt(cf->dfcode, edt) && edt->pi.fd->dependent_frames) {
3480 g_hash_table_foreach(edt->pi.fd->dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
3483 if (selected_frame_number != 0 && selected_frame_number == cf->count + 1) {
3484 /* If we are doing dissection and we have a "selected frame"
3485 * then load that frame's references (if any) onto the compiled
3486 * display filter. Selected frame number is ordinal, count is cardinal. */
3487 dfilter_load_field_references(cf->dfcode, edt->tree);
3489 tshark_elapsed.first_pass.dfilter_filter += g_get_monotonic_time() - elapsed_start;
3492 cf->count++;
3493 } else {
3494 /* if we don't add it to the frame_data_sequence, clean it up right now
3495 * to avoid leaks */
3496 frame_data_destroy(&fdlocal);
3499 if (edt)
3500 epan_dissect_reset(edt);
3502 return passed;
3506 * Set if reading a file was interrupted by a CTRL_ event on Windows or
3507 * a signal on UN*X.
3509 static bool read_interrupted;
3511 #ifdef _WIN32
3512 static BOOL WINAPI
3513 read_cleanup(DWORD ctrltype _U_)
3515 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
3516 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
3517 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
3518 like SIGTERM at least when the machine's shutting down.
3520 For now, we handle them all as indications that we should clean up
3521 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
3522 way on UNIX.
3524 We must return true so that no other handler - such as one that would
3525 terminate the process - gets called.
3527 XXX - for some reason, typing ^C to TShark, if you run this in
3528 a Cygwin console window in at least some versions of Cygwin,
3529 causes TShark to terminate immediately; this routine gets
3530 called, but the main loop doesn't get a chance to run and
3531 exit cleanly, at least if this is compiled with Microsoft Visual
3532 C++ (i.e., it's a property of the Cygwin console window or Bash;
3533 it happens if TShark is not built with Cygwin - for all I know,
3534 building it with Cygwin may make the problem go away). */
3536 /* tell the read to stop */
3537 read_interrupted = true;
3539 return true;
3541 #else
3542 static void
3543 read_cleanup(int signum _U_)
3545 /* tell the read to stop */
3546 read_interrupted = true;
3548 #endif /* _WIN32 */
3550 typedef enum {
3551 PASS_SUCCEEDED,
3552 PASS_READ_ERROR,
3553 PASS_WRITE_ERROR,
3554 PASS_INTERRUPTED
3555 } pass_status_t;
3557 static pass_status_t
3558 process_cap_file_first_pass(capture_file *cf, int max_packet_count,
3559 int64_t max_byte_count, int *err, char **err_info)
3561 wtap_rec rec;
3562 epan_dissect_t *edt = NULL;
3563 int64_t data_offset;
3564 pass_status_t status = PASS_SUCCEEDED;
3565 int framenum = 0;
3567 wtap_rec_init(&rec, 1514);
3569 /* Allocate a frame_data_sequence for all the frames. */
3570 cf->provider.frames = new_frame_data_sequence();
3572 if (do_dissection) {
3573 bool create_proto_tree;
3576 * Determine whether we need to create a protocol tree.
3577 * We do if:
3579 * we're going to apply a read filter;
3581 * we're going to apply a display filter;
3583 * a postdissector wants field values or protocols
3584 * on the first pass.
3586 create_proto_tree =
3587 (cf->rfcode != NULL || cf->dfcode != NULL || postdissectors_want_hfids() || dissect_color);
3589 ws_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3591 /* We're not going to display the protocol tree on this pass,
3592 so it's not going to be "visible". */
3593 edt = epan_dissect_new(cf->epan, create_proto_tree, false);
3596 ws_debug("tshark: reading records for first pass");
3597 *err = 0;
3598 while (wtap_read(cf->provider.wth, &rec, err, err_info, &data_offset)) {
3599 if (read_interrupted) {
3600 status = PASS_INTERRUPTED;
3601 break;
3603 framenum++;
3605 if (process_packet_first_pass(cf, edt, data_offset, &rec)) {
3606 /* Stop reading if we hit a stop condition */
3607 if (max_packet_count > 0 && framenum >= max_packet_count) {
3608 ws_debug("tshark: max_packet_count (%d) reached", max_packet_count);
3609 *err = 0; /* This is not an error */
3610 break;
3612 if (max_byte_count != 0 && data_offset >= max_byte_count) {
3613 ws_debug("tshark: max_byte_count (%" PRId64 "/%" PRId64 ") reached",
3614 data_offset, max_byte_count);
3615 *err = 0; /* This is not an error */
3616 break;
3619 wtap_rec_reset(&rec);
3621 if (*err != 0)
3622 status = PASS_READ_ERROR;
3624 if (edt)
3625 epan_dissect_free(edt);
3627 /* Close the sequential I/O side, to free up memory it requires. */
3628 wtap_sequential_close(cf->provider.wth);
3630 /* Allow the protocol dissectors to free up memory that they
3631 * don't need after the sequential run-through of the packets. */
3632 postseq_cleanup_all_protocols();
3634 cf->provider.prev_dis = NULL;
3635 cf->provider.prev_cap = NULL;
3637 return status;
3640 static bool
3641 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
3642 frame_data *fdata, wtap_rec *rec, unsigned tap_flags _U_)
3644 column_info *cinfo;
3645 bool passed;
3646 wtap_block_t block = NULL;
3647 int64_t elapsed_start;
3649 /* If we're not running a display filter and we're not printing any
3650 packet information, we don't need to do a dissection. This means
3651 that all packets can be marked as 'passed'. */
3652 passed = true;
3654 /* If we're going to print packet information, or we're going to
3655 run a read filter, or we're going to process taps, set up to
3656 do a dissection and do so. (This is the second pass of two
3657 passes over the packets; that's the pass where we print
3658 packet information or run taps.) */
3659 if (edt) {
3660 /* If we're running a display filter, prime the epan_dissect_t with that
3661 filter. */
3662 if (cf->dfcode)
3663 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3665 col_custom_prime_edt(edt, &cf->cinfo);
3667 output_fields_prime_edt(edt, output_fields);
3668 /* The PDML spec requires a 'geninfo' pseudo-protocol that needs
3669 * information from our 'frame' protocol.
3671 if (output_fields_num_fields(output_fields) != 0 &&
3672 output_action == WRITE_XML) {
3673 epan_dissect_prime_with_hfid(edt, proto_registrar_get_id_byname("frame"));
3676 /* We only need the columns if either
3677 1) some tap or filter needs the columns
3679 2) we're printing packet info but we're *not* verbose; in verbose
3680 mode, we print the protocol tree, not the protocol summary.
3682 3) there is a column mapped to an individual field
3684 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields) || dfilter_requires_columns(cf->dfcode))
3685 cinfo = &cf->cinfo;
3686 else
3687 cinfo = NULL;
3689 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
3690 &cf->provider.ref, cf->provider.prev_dis);
3691 if (cf->provider.ref == fdata) {
3692 ref_frame = *fdata;
3693 cf->provider.ref = &ref_frame;
3696 if (dissect_color) {
3697 color_filters_prime_edt(edt);
3698 fdata->need_colorize = 1;
3701 /* epan_dissect_run (and epan_dissect_reset) unref the block.
3702 * We need it later, e.g. in order to copy the options. */
3703 block = wtap_block_ref(rec->block);
3704 elapsed_start = g_get_monotonic_time();
3705 epan_dissect_run_with_taps(edt, cf->cd_t, rec, fdata, cinfo);
3706 tshark_elapsed.second_pass.dissect += g_get_monotonic_time() - elapsed_start;
3708 /* Run the display filter if we have one. */
3709 if (cf->dfcode) {
3710 elapsed_start = g_get_monotonic_time();
3711 passed = dfilter_apply_edt(cf->dfcode, edt);
3712 tshark_elapsed.second_pass.dfilter_filter += g_get_monotonic_time() - elapsed_start;
3716 if (passed) {
3717 frame_data_set_after_dissect(fdata, &cum_bytes);
3718 /* Process this packet. */
3719 if (print_packet_info) {
3720 /* We're printing packet information; print the information for
3721 this packet. */
3722 print_packet(cf, edt);
3724 /* If we're doing "line-buffering", flush the standard output
3725 after every packet. See the comment above, for the "-l"
3726 option, for an explanation of why we do that. */
3727 if (line_buffered)
3728 fflush(stdout);
3730 if (ferror(stdout)) {
3731 show_print_file_io_error();
3732 exit(2);
3735 cf->provider.prev_dis = fdata;
3737 cf->provider.prev_cap = fdata;
3739 if (edt) {
3740 epan_dissect_reset(edt);
3741 rec->block = block;
3743 return passed || fdata->dependent_of_displayed;
3746 static bool
3747 process_new_idbs(wtap *wth, wtap_dumper *pdh, int *err, char **err_info)
3749 wtap_block_t if_data;
3751 while ((if_data = wtap_get_next_interface_description(wth)) != NULL) {
3753 * Only add interface blocks if the output file supports (meaning
3754 * *requires*) them.
3756 * That mean that the abstract interface provided by libwiretap
3757 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
3759 if (pdh != NULL) {
3760 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh), WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
3761 if (!wtap_dump_add_idb(pdh, if_data, err, err_info))
3762 return false;
3766 return true;
3769 static pass_status_t
3770 process_cap_file_second_pass(capture_file *cf, wtap_dumper *pdh,
3771 int *err, char **err_info,
3772 volatile uint32_t *err_framenum,
3773 int max_write_packet_count)
3775 wtap_rec rec;
3776 int framenum = 0;
3777 int write_framenum = 0;
3778 frame_data *fdata;
3779 bool filtering_tap_listeners;
3780 unsigned tap_flags;
3781 epan_dissect_t *edt = NULL;
3782 pass_status_t status = PASS_SUCCEEDED;
3785 * Process whatever IDBs we haven't seen yet. This will be all
3786 * the IDBs in the file, as we've finished reading it; they'll
3787 * all be at the beginning of the output file.
3789 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3790 *err_framenum = 0;
3791 return PASS_WRITE_ERROR;
3794 wtap_rec_init(&rec, 1514);
3796 /* Do we have any tap listeners with filters? */
3797 filtering_tap_listeners = have_filtering_tap_listeners();
3799 /* Get the union of the flags for all tap listeners. */
3800 tap_flags = union_of_tap_listener_flags();
3802 if (do_dissection) {
3803 bool create_proto_tree;
3806 * Determine whether we need to create a protocol tree.
3807 * We do if:
3809 * we're going to apply a display filter;
3811 * we're going to print the protocol tree;
3813 * one of the tap listeners requires a protocol tree;
3815 * we have custom columns (which require field values, which
3816 * currently requires that we build a protocol tree).
3818 create_proto_tree =
3819 (cf->dfcode || print_details || filtering_tap_listeners ||
3820 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo) || dissect_color);
3822 ws_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3824 /* The protocol tree will be "visible", i.e., nothing faked, only if
3825 we're printing packet details, which is true if we're printing stuff
3826 ("print_packet_info" is true) and we're in verbose mode
3827 ("packet_details" is true). But if we specified certain fields with
3828 "-e", we'll prime those directly later. */
3829 bool visible = print_packet_info && print_details && output_fields_num_fields(output_fields) == 0;
3830 edt = epan_dissect_new(cf->epan, create_proto_tree, visible);
3834 * Force synchronous resolution of IP addresses; in this pass, we
3835 * can't do it in the background and fix up past dissections.
3837 set_resolution_synchrony(true);
3839 for (framenum = 1; framenum <= (int)cf->count; framenum++) {
3840 if (read_interrupted) {
3841 status = PASS_INTERRUPTED;
3842 break;
3844 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3845 if (!wtap_seek_read(cf->provider.wth, fdata->file_off, &rec, err,
3846 err_info)) {
3847 /* Error reading from the input file. */
3848 status = PASS_READ_ERROR;
3849 break;
3851 ws_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3852 if (process_packet_second_pass(cf, edt, fdata, &rec, tap_flags)) {
3853 /* Either there's no read filtering or this packet passed the
3854 filter, so, if we're writing to a capture file, write
3855 this packet out. */
3856 write_framenum++;
3857 if (pdh != NULL) {
3858 ws_debug("tshark: writing packet #%d to outfile packet #%d", framenum, write_framenum);
3859 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&rec.data), err, err_info)) {
3860 /* Error writing to the output file. */
3861 ws_debug("tshark: error writing to a capture file (%d)", *err);
3862 *err_framenum = framenum;
3863 status = PASS_WRITE_ERROR;
3864 break;
3866 /* Stop reading if we hit a stop condition */
3867 if (max_write_packet_count > 0 && write_framenum >= max_write_packet_count) {
3868 ws_debug("tshark: max_write_packet_count (%d) reached", max_write_packet_count);
3869 *err = 0; /* This is not an error */
3870 break;
3874 wtap_rec_reset(&rec);
3877 if (edt)
3878 epan_dissect_free(edt);
3880 wtap_rec_cleanup(&rec);
3882 return status;
3885 static pass_status_t
3886 process_cap_file_single_pass(capture_file *cf, wtap_dumper *pdh,
3887 int max_packet_count, int64_t max_byte_count,
3888 int max_write_packet_count,
3889 int *err, char **err_info,
3890 volatile uint32_t *err_framenum)
3892 wtap_rec rec;
3893 bool create_proto_tree = false;
3894 bool filtering_tap_listeners;
3895 unsigned tap_flags;
3896 int framenum = 0;
3897 int write_framenum = 0;
3898 epan_dissect_t *edt = NULL;
3899 int64_t data_offset;
3900 pass_status_t status = PASS_SUCCEEDED;
3902 wtap_rec_init(&rec, 1514);
3904 /* Do we have any tap listeners with filters? */
3905 filtering_tap_listeners = have_filtering_tap_listeners();
3907 /* Get the union of the flags for all tap listeners. */
3908 tap_flags = union_of_tap_listener_flags();
3910 if (do_dissection) {
3912 * Determine whether we need to create a protocol tree.
3913 * We do if:
3915 * we're going to apply a read filter;
3917 * we're going to apply a display filter;
3919 * we're going to print the protocol tree;
3921 * one of the tap listeners is going to apply a filter;
3923 * one of the tap listeners requires a protocol tree;
3925 * a postdissector wants field values or protocols
3926 * on the first pass;
3928 * we have custom columns (which require field values, which
3929 * currently requires that we build a protocol tree).
3931 create_proto_tree =
3932 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3933 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3934 have_custom_cols(&cf->cinfo) || dissect_color);
3936 ws_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3938 /* The protocol tree will be "visible", i.e., nothing faked, only if
3939 we're printing packet details, which is true if we're printing stuff
3940 ("print_packet_info" is true) and we're in verbose mode
3941 ("packet_details" is true). But if we specified certain fields with
3942 "-e", we'll prime those directly later. */
3943 bool visible = print_packet_info && print_details && output_fields_num_fields(output_fields) == 0;
3944 edt = epan_dissect_new(cf->epan, create_proto_tree, visible);
3948 * Force synchronous resolution of IP addresses; we're doing only
3949 * one pass, so we can't do it in the background and fix up past
3950 * dissections.
3952 set_resolution_synchrony(true);
3954 *err = 0;
3955 while (wtap_read(cf->provider.wth, &rec, err, err_info, &data_offset)) {
3956 if (read_interrupted) {
3957 status = PASS_INTERRUPTED;
3958 break;
3960 framenum++;
3963 * Process whatever IDBs we haven't seen yet.
3965 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3966 *err_framenum = framenum;
3967 status = PASS_WRITE_ERROR;
3968 break;
3971 ws_debug("tshark: processing packet #%d", framenum);
3973 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3975 if (process_packet_single_pass(cf, edt, data_offset, &rec, tap_flags)) {
3976 /* Either there's no read filtering or this packet passed the
3977 filter, so, if we're writing to a capture file, write
3978 this packet out. */
3979 write_framenum++;
3980 if (pdh != NULL) {
3981 ws_debug("tshark: writing packet #%d to outfile as #%d",
3982 framenum, write_framenum);
3983 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&rec.data), err, err_info)) {
3984 /* Error writing to the output file. */
3985 ws_debug("tshark: error writing to a capture file (%d)", *err);
3986 *err_framenum = framenum;
3987 status = PASS_WRITE_ERROR;
3988 break;
3992 /* Stop reading if we hit a stop condition */
3993 if (max_packet_count > 0 && framenum >= max_packet_count) {
3994 ws_debug("tshark: max_packet_count (%d) reached", max_packet_count);
3995 *err = 0; /* This is not an error */
3996 break;
3998 if (max_write_packet_count > 0 && write_framenum >= max_write_packet_count) {
3999 ws_debug("tshark: max_write_packet_count (%d) reached", max_write_packet_count);
4000 *err = 0; /* This is not an error */
4001 break;
4003 if (max_byte_count != 0 && data_offset >= max_byte_count) {
4004 ws_debug("tshark: max_byte_count (%" PRId64 "/%" PRId64 ") reached",
4005 data_offset, max_byte_count);
4006 *err = 0; /* This is not an error */
4007 break;
4009 wtap_rec_reset(&rec);
4011 if (status == PASS_SUCCEEDED) {
4012 if (*err != 0) {
4013 /* Error reading from the input file. */
4014 status = PASS_READ_ERROR;
4015 } else {
4017 * Process whatever IDBs we haven't seen yet.
4019 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
4020 *err_framenum = framenum;
4021 status = PASS_WRITE_ERROR;
4026 if (edt)
4027 epan_dissect_free(edt);
4029 wtap_rec_cleanup(&rec);
4031 return status;
4034 static process_file_status_t
4035 process_cap_file(capture_file *cf, char *save_file, int out_file_type,
4036 bool out_file_name_res, int max_packet_count, int64_t max_byte_count,
4037 int max_write_packet_count, wtap_compression_type compression_type)
4039 process_file_status_t status = PROCESS_FILE_SUCCEEDED;
4040 wtap_dumper *pdh;
4041 #ifndef _WIN32
4042 struct sigaction action, oldaction;
4043 #endif
4044 int err = 0, err_pass1 = 0;
4045 char *err_info = NULL, *err_info_pass1 = NULL;
4046 volatile uint32_t err_framenum;
4047 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
4048 char *shb_user_appl;
4049 pass_status_t first_pass_status, second_pass_status;
4050 int64_t elapsed_start;
4052 if (save_file != NULL) {
4053 /* Set up to write to the capture file. */
4054 wtap_dump_params_init_no_idbs(&params, cf->provider.wth);
4056 /* If we don't have an application name add TShark */
4057 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) {
4058 /* this is free'd by wtap_block_unref() later */
4059 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
4061 if (capture_comments != NULL) {
4062 for (unsigned i = 0; i < capture_comments->len; i++) {
4063 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0),
4064 OPT_COMMENT, "%s",
4065 (char *)g_ptr_array_index(capture_comments, i));
4069 ws_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
4070 if (strcmp(save_file, "-") == 0) {
4071 /* Write to the standard output. */
4072 pdh = wtap_dump_open_stdout(out_file_type, compression_type, &params,
4073 &err, &err_info);
4074 } else {
4075 pdh = wtap_dump_open(save_file, out_file_type, compression_type, &params,
4076 &err, &err_info);
4079 g_free(params.idb_inf);
4080 params.idb_inf = NULL;
4082 if (pdh == NULL) {
4083 /* We couldn't set up to write to the capture file. */
4084 cfile_dump_open_failure_message(save_file, err, err_info,
4085 out_file_type);
4086 status = PROCESS_FILE_NO_FILE_PROCESSED;
4087 goto out;
4089 } else {
4090 /* Set up to print packet information. */
4091 if (print_packet_info) {
4092 if (!write_preamble(cf)) {
4093 show_print_file_io_error();
4094 status = PROCESS_FILE_NO_FILE_PROCESSED;
4095 goto out;
4098 pdh = NULL;
4101 #ifdef _WIN32
4102 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
4103 SetConsoleCtrlHandler(read_cleanup, true);
4104 #else /* _WIN32 */
4105 /* Catch SIGINT and SIGTERM and, if we get either of them,
4106 clean up and exit. If SIGHUP isn't being ignored, catch
4107 it too and, if we get it, clean up and exit.
4109 We restart any read that was in progress, so that it doesn't
4110 disrupt reading from the sync pipe. The signal handler tells
4111 the capture child to finish; it will report that it finished,
4112 or will exit abnormally, so we'll stop reading from the sync
4113 pipe, pick up the exit status, and quit. */
4114 memset(&action, 0, sizeof(action));
4115 action.sa_handler = read_cleanup;
4116 action.sa_flags = SA_RESTART;
4117 sigemptyset(&action.sa_mask);
4118 sigaction(SIGTERM, &action, NULL);
4119 sigaction(SIGINT, &action, NULL);
4120 sigaction(SIGHUP, NULL, &oldaction);
4121 if (oldaction.sa_handler == SIG_DFL)
4122 sigaction(SIGHUP, &action, NULL);
4123 #endif /* _WIN32 */
4125 if (perform_two_pass_analysis) {
4126 ws_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
4128 elapsed_start = g_get_monotonic_time();
4129 first_pass_status = process_cap_file_first_pass(cf, max_packet_count,
4130 max_byte_count,
4131 &err_pass1,
4132 &err_info_pass1);
4133 tshark_elapsed.elapsed_first_pass = g_get_monotonic_time() - elapsed_start;
4135 ws_debug("tshark: done with first pass");
4137 if (first_pass_status == PASS_INTERRUPTED) {
4138 /* The first pass was interrupted; skip the second pass.
4139 It won't be run, so it won't get an error. */
4140 second_pass_status = PASS_SUCCEEDED;
4141 } else {
4143 * If we got a read error on the first pass, we still do the second
4144 * pass, so we can at least process the packets we read, and then
4145 * report the first-pass error after the second pass (and before
4146 * we report any second-pass errors), so all the errors show up
4147 * at the end.
4149 elapsed_start = g_get_monotonic_time();
4150 second_pass_status = process_cap_file_second_pass(cf, pdh, &err, &err_info,
4151 &err_framenum,
4152 max_write_packet_count);
4153 tshark_elapsed.elapsed_second_pass = g_get_monotonic_time() - elapsed_start;
4155 ws_debug("tshark: done with second pass");
4158 else {
4159 /* !perform_two_pass_analysis */
4160 ws_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
4162 first_pass_status = PASS_SUCCEEDED; /* There is no first pass */
4164 elapsed_start = g_get_monotonic_time();
4165 second_pass_status = process_cap_file_single_pass(cf, pdh,
4166 max_packet_count,
4167 max_byte_count,
4168 max_write_packet_count,
4169 &err, &err_info,
4170 &err_framenum);
4171 tshark_elapsed.elapsed_first_pass = g_get_monotonic_time() - elapsed_start;
4173 ws_debug("tshark: done with single pass");
4176 if (first_pass_status != PASS_SUCCEEDED ||
4177 second_pass_status != PASS_SUCCEEDED) {
4179 * At least one of the passes didn't succeed; either it got a failure
4180 * or it was interrupted.
4182 if (first_pass_status != PASS_INTERRUPTED ||
4183 second_pass_status != PASS_INTERRUPTED) {
4184 /* At least one of the passes got an error. */
4185 ws_debug("tshark: something failed along the line (%d)", err);
4187 * If we're printing packet data, and the standard output and error
4188 * are going to the same place, flush the standard output, so everything
4189 * buffered up is written, and then print a newline to the standard
4190 * error before printing the error message, to separate it from the
4191 * packet data. (Alas, that only works on UN*X; st_dev is meaningless,
4192 * and the _fstat() documentation at Microsoft doesn't indicate whether
4193 * st_ino is even supported.)
4195 #ifndef _WIN32
4196 if (print_packet_info) {
4197 ws_statb64 stat_stdout, stat_stderr;
4199 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
4200 if (stat_stdout.st_dev == stat_stderr.st_dev &&
4201 stat_stdout.st_ino == stat_stderr.st_ino) {
4202 fflush(stdout);
4203 fprintf(stderr, "\n");
4207 #endif
4209 /* Report status of pass 1 of two-pass processing. */
4210 switch (first_pass_status) {
4212 case PASS_SUCCEEDED:
4213 /* No problem. */
4214 break;
4216 case PASS_READ_ERROR:
4217 /* Read error. */
4218 cfile_read_failure_message(cf->filename, err_pass1, err_info_pass1);
4219 status = PROCESS_FILE_ERROR;
4220 break;
4222 case PASS_WRITE_ERROR:
4223 /* Won't happen on the first pass. */
4224 break;
4226 case PASS_INTERRUPTED:
4227 /* Not an error, so nothing to report. */
4228 status = PROCESS_FILE_INTERRUPTED;
4229 break;
4232 /* Report status of pass 2 of two-pass processing or the only pass
4233 of one-pass processing. */
4234 switch (second_pass_status) {
4236 case PASS_SUCCEEDED:
4237 /* No problem. */
4238 break;
4240 case PASS_READ_ERROR:
4241 /* Read error. */
4242 cfile_read_failure_message(cf->filename, err, err_info);
4243 status = PROCESS_FILE_ERROR;
4244 break;
4246 case PASS_WRITE_ERROR:
4247 /* Write error.
4248 XXX - framenum is not necessarily the frame number in
4249 the input file if there was a read filter. */
4250 cfile_write_failure_message(cf->filename, save_file, err, err_info,
4251 err_framenum, out_file_type);
4252 status = PROCESS_FILE_ERROR;
4253 break;
4255 case PASS_INTERRUPTED:
4256 /* Not an error, so nothing to report. */
4257 status = PROCESS_FILE_INTERRUPTED;
4258 break;
4261 if (save_file != NULL) {
4262 if (second_pass_status != PASS_WRITE_ERROR) {
4263 if (pdh && out_file_name_res) {
4264 /* XXX: This doesn't work as expected. First, it should be
4265 * moved to between the first and second passes (if doing
4266 * two-pass mode), so that the new NRB appears before packets,
4267 * which is better for subsequent one-pass mode. It never works
4268 * well in one-pass mode.
4270 * Second, it only writes hosts that we've done lookups for,
4271 * which means unless packet details are printed (or there's
4272 * a display filter that matches something that will do a host
4273 * lookup, e.g. -Y "ip") it doesn't actually have anything
4274 * in the list to save. Notably, that includes the case of
4275 * "tshark [-2] -H hosts.txt -r <infile> -w <outfile>",
4276 * which a user would certainly expect to dissect packets,
4277 * lookup hostnames, and add them to an NRB for later use.
4278 * A workaround is if "-V > /dev/null" is added, but who
4279 * expects that?
4281 * A third issue is that name resolution blocks aren't
4282 * written for live captures.
4284 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
4285 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
4286 wtap_file_type_subtype_name(out_file_type));
4289 /* Now close the capture file. */
4290 if (!wtap_dump_close(pdh, NULL, &err, &err_info)) {
4291 cfile_close_failure_message(save_file, err, err_info);
4292 status = PROCESS_FILE_ERROR;
4294 } else {
4295 /* We got a write error; it was reported, so just close the dump file
4296 without bothering to check for further errors. */
4297 wtap_dump_close(pdh, NULL, &err, &err_info);
4298 g_free(err_info);
4299 status = PROCESS_FILE_ERROR;
4301 } else {
4302 if (print_packet_info) {
4303 if (!write_finale()) {
4304 show_print_file_io_error();
4305 status = PROCESS_FILE_ERROR;
4310 out:
4311 wtap_close(cf->provider.wth);
4312 cf->provider.wth = NULL;
4314 wtap_dump_params_cleanup(&params);
4316 return status;
4319 static bool
4320 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, int64_t offset,
4321 wtap_rec *rec, unsigned tap_flags _U_)
4323 frame_data fdata;
4324 column_info *cinfo;
4325 bool passed;
4326 wtap_block_t block = NULL;
4327 int64_t elapsed_start;
4329 /* Count this packet. */
4330 cf->count++;
4332 /* If we're not running a display filter and we're not printing any
4333 packet information, we don't need to do a dissection. This means
4334 that all packets can be marked as 'passed'. */
4335 passed = true;
4337 frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
4339 /* If we're going to print packet information, or we're going to
4340 run a read filter, or we're going to process taps, set up to
4341 do a dissection and do so. (This is the one and only pass
4342 over the packets, so, if we'll be printing packet information
4343 or running taps, we'll be doing it here.) */
4344 if (edt) {
4345 /* If we're running a filter, prime the epan_dissect_t with that
4346 filter. */
4347 if (cf->dfcode)
4348 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
4350 /* This is the first and only pass, so prime the epan_dissect_t
4351 with the hfids postdissectors want on the first pass. */
4352 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
4354 col_custom_prime_edt(edt, &cf->cinfo);
4356 output_fields_prime_edt(edt, output_fields);
4357 /* The PDML spec requires a 'geninfo' pseudo-protocol that needs
4358 * information from our 'frame' protocol.
4360 if (output_fields_num_fields(output_fields) != 0 &&
4361 output_action == WRITE_XML) {
4362 epan_dissect_prime_with_hfid(edt, proto_registrar_get_id_byname("frame"));
4365 /* We only need the columns if either
4366 1) some tap or filter needs the columns
4368 2) we're printing packet info but we're *not* verbose; in verbose
4369 mode, we print the protocol tree, not the protocol summary.
4371 3) there is a column mapped as an individual field */
4372 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields) || dfilter_requires_columns(cf->dfcode))
4373 cinfo = &cf->cinfo;
4374 else
4375 cinfo = NULL;
4377 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
4378 &cf->provider.ref, cf->provider.prev_dis);
4379 if (cf->provider.ref == &fdata) {
4380 ref_frame = fdata;
4381 cf->provider.ref = &ref_frame;
4384 if (dissect_color) {
4385 color_filters_prime_edt(edt);
4386 fdata.need_colorize = 1;
4389 /* epan_dissect_run (and epan_dissect_reset) unref the block.
4390 * We need it later, e.g. in order to copy the options. */
4391 block = wtap_block_ref(rec->block);
4392 elapsed_start = g_get_monotonic_time();
4393 epan_dissect_run_with_taps(edt, cf->cd_t, rec, &fdata, cinfo);
4394 tshark_elapsed.first_pass.dissect += g_get_monotonic_time() - elapsed_start;
4396 /* Run the filter if we have it. */
4397 if (cf->dfcode) {
4398 elapsed_start = g_get_monotonic_time();
4399 passed = dfilter_apply_edt(cf->dfcode, edt);
4400 tshark_elapsed.first_pass.dfilter_filter += g_get_monotonic_time() - elapsed_start;
4404 if (passed) {
4405 frame_data_set_after_dissect(&fdata, &cum_bytes);
4407 /* Process this packet. */
4408 if (print_packet_info) {
4409 /* We're printing packet information; print the information for
4410 this packet. */
4411 ws_assert(edt);
4412 print_packet(cf, edt);
4414 /* If we're doing "line-buffering", flush the standard output
4415 after every packet. See the comment above, for the "-l"
4416 option, for an explanation of why we do that. */
4417 if (line_buffered)
4418 fflush(stdout);
4420 if (ferror(stdout)) {
4421 show_print_file_io_error();
4422 exit(2);
4426 /* this must be set after print_packet() [bug #8160] */
4427 prev_dis_frame = fdata;
4428 cf->provider.prev_dis = &prev_dis_frame;
4431 prev_cap_frame = fdata;
4432 cf->provider.prev_cap = &prev_cap_frame;
4434 if (edt) {
4435 epan_dissect_reset(edt);
4436 frame_data_destroy(&fdata);
4437 rec->block = block;
4439 return passed;
4442 static bool
4443 write_preamble(capture_file *cf)
4445 switch (output_action) {
4447 case WRITE_TEXT:
4448 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
4450 case WRITE_XML:
4451 if (print_details)
4452 write_pdml_preamble(stdout, cf->filename);
4453 else
4454 write_psml_preamble(&cf->cinfo, stdout);
4455 return !ferror(stdout);
4457 case WRITE_FIELDS:
4458 write_fields_preamble(output_fields, stdout);
4459 return !ferror(stdout);
4461 case WRITE_JSON:
4462 case WRITE_JSON_RAW:
4463 jdumper = write_json_preamble(stdout);
4464 return !ferror(stdout);
4466 case WRITE_EK:
4467 return true;
4469 default:
4470 ws_assert_not_reached();
4471 return false;
4475 static char *
4476 get_line_buf(size_t len)
4478 static char *line_bufp = NULL;
4479 static size_t line_buf_len = 256;
4480 size_t new_line_buf_len;
4482 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
4483 new_line_buf_len *= 2)
4485 if (line_bufp == NULL) {
4486 line_buf_len = new_line_buf_len;
4487 line_bufp = (char *)g_malloc(line_buf_len + 1);
4488 } else {
4489 if (new_line_buf_len > line_buf_len) {
4490 line_buf_len = new_line_buf_len;
4491 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
4494 return line_bufp;
4497 static inline void
4498 put_string(char *dest, const char *str, size_t str_len)
4500 memcpy(dest, str, str_len);
4501 dest[str_len] = '\0';
4504 static inline void
4505 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
4507 size_t i;
4509 for (i = str_len; i < str_with_spaces; i++)
4510 *dest++ = ' ';
4512 put_string(dest, str, str_len);
4515 static inline void
4516 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
4518 size_t i;
4520 memcpy(dest, str, str_len);
4521 for (i = str_len; i < str_with_spaces; i++)
4522 dest[i] = ' ';
4524 dest[str_with_spaces] = '\0';
4527 static bool
4528 print_columns(capture_file *cf, const epan_dissect_t *edt)
4530 char *line_bufp;
4531 int i;
4532 size_t buf_offset;
4533 size_t column_len;
4534 size_t col_len;
4535 col_item_t* col_item;
4536 char str_format[11];
4537 const color_filter_t *color_filter = NULL;
4539 line_bufp = get_line_buf(256);
4540 buf_offset = 0;
4541 *line_bufp = '\0';
4543 if (dissect_color)
4544 color_filter = edt->pi.fd->color_filter;
4546 for (i = 0; i < cf->cinfo.num_cols; i++) {
4547 col_item = &cf->cinfo.columns[i];
4548 /* Skip columns not marked as visible. */
4549 if (!get_column_visible(i))
4550 continue;
4551 const char* col_text = get_column_text(&cf->cinfo, i);
4552 switch (col_item->col_fmt) {
4553 case COL_NUMBER:
4554 case COL_NUMBER_DIS:
4555 column_len = col_len = strlen(col_text);
4556 if (column_len < 5)
4557 column_len = 5;
4558 line_bufp = get_line_buf(buf_offset + column_len);
4559 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
4560 break;
4562 case COL_CLS_TIME:
4563 case COL_REL_TIME:
4564 case COL_ABS_TIME:
4565 case COL_ABS_YMD_TIME: /* XXX - wider */
4566 case COL_ABS_YDOY_TIME: /* XXX - wider */
4567 case COL_UTC_TIME:
4568 case COL_UTC_YMD_TIME: /* XXX - wider */
4569 case COL_UTC_YDOY_TIME: /* XXX - wider */
4570 column_len = col_len = strlen(col_text);
4571 if (column_len < 10)
4572 column_len = 10;
4573 line_bufp = get_line_buf(buf_offset + column_len);
4574 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
4575 break;
4577 case COL_DEF_SRC:
4578 case COL_RES_SRC:
4579 case COL_UNRES_SRC:
4580 case COL_DEF_DL_SRC:
4581 case COL_RES_DL_SRC:
4582 case COL_UNRES_DL_SRC:
4583 case COL_DEF_NET_SRC:
4584 case COL_RES_NET_SRC:
4585 case COL_UNRES_NET_SRC:
4586 column_len = col_len = strlen(col_text);
4587 if (column_len < 12)
4588 column_len = 12;
4589 line_bufp = get_line_buf(buf_offset + column_len);
4590 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
4591 break;
4593 case COL_DEF_DST:
4594 case COL_RES_DST:
4595 case COL_UNRES_DST:
4596 case COL_DEF_DL_DST:
4597 case COL_RES_DL_DST:
4598 case COL_UNRES_DL_DST:
4599 case COL_DEF_NET_DST:
4600 case COL_RES_NET_DST:
4601 case COL_UNRES_NET_DST:
4602 column_len = col_len = strlen(col_text);
4603 if (column_len < 12)
4604 column_len = 12;
4605 line_bufp = get_line_buf(buf_offset + column_len);
4606 put_string_spaces(line_bufp + buf_offset, col_text, col_len, column_len);
4607 break;
4609 default:
4610 column_len = strlen(col_text);
4611 line_bufp = get_line_buf(buf_offset + column_len);
4612 put_string(line_bufp + buf_offset, col_text, column_len);
4613 break;
4615 buf_offset += column_len;
4616 if (i != cf->cinfo.num_cols - 1) {
4618 * This isn't the last column, so we need to print a
4619 * separator between this column and the next.
4621 * If we printed a network source and are printing a
4622 * network destination of the same type next, separate
4623 * them with a UTF-8 right arrow; if we printed a network
4624 * destination and are printing a network source of the same
4625 * type next, separate them with a UTF-8 left arrow;
4626 * otherwise separate them with a space.
4628 * We add enough space to the buffer for " \xe2\x86\x90 "
4629 * or " \xe2\x86\x92 ", even if we're only adding " ".
4631 line_bufp = get_line_buf(buf_offset + 5);
4632 switch (col_item->col_fmt) {
4634 case COL_DEF_SRC:
4635 case COL_RES_SRC:
4636 case COL_UNRES_SRC:
4637 switch (cf->cinfo.columns[i+1].col_fmt) {
4639 case COL_DEF_DST:
4640 case COL_RES_DST:
4641 case COL_UNRES_DST:
4642 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4643 put_string(line_bufp + buf_offset, str_format, 5);
4644 buf_offset += 5;
4645 break;
4647 default:
4648 put_string(line_bufp + buf_offset, delimiter_char, 1);
4649 buf_offset += 1;
4650 break;
4652 break;
4654 case COL_DEF_DL_SRC:
4655 case COL_RES_DL_SRC:
4656 case COL_UNRES_DL_SRC:
4657 switch (cf->cinfo.columns[i+1].col_fmt) {
4659 case COL_DEF_DL_DST:
4660 case COL_RES_DL_DST:
4661 case COL_UNRES_DL_DST:
4662 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4663 put_string(line_bufp + buf_offset, str_format, 5);
4664 buf_offset += 5;
4665 break;
4667 default:
4668 put_string(line_bufp + buf_offset, delimiter_char, 1);
4669 buf_offset += 1;
4670 break;
4672 break;
4674 case COL_DEF_NET_SRC:
4675 case COL_RES_NET_SRC:
4676 case COL_UNRES_NET_SRC:
4677 switch (cf->cinfo.columns[i+1].col_fmt) {
4679 case COL_DEF_NET_DST:
4680 case COL_RES_NET_DST:
4681 case COL_UNRES_NET_DST:
4682 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4683 put_string(line_bufp + buf_offset, str_format, 5);
4684 buf_offset += 5;
4685 break;
4687 default:
4688 put_string(line_bufp + buf_offset, delimiter_char, 1);
4689 buf_offset += 1;
4690 break;
4692 break;
4694 case COL_DEF_DST:
4695 case COL_RES_DST:
4696 case COL_UNRES_DST:
4697 switch (cf->cinfo.columns[i+1].col_fmt) {
4699 case COL_DEF_SRC:
4700 case COL_RES_SRC:
4701 case COL_UNRES_SRC:
4702 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4703 put_string(line_bufp + buf_offset, str_format, 5);
4704 buf_offset += 5;
4705 break;
4707 default:
4708 put_string(line_bufp + buf_offset, delimiter_char, 1);
4709 buf_offset += 1;
4710 break;
4712 break;
4714 case COL_DEF_DL_DST:
4715 case COL_RES_DL_DST:
4716 case COL_UNRES_DL_DST:
4717 switch (cf->cinfo.columns[i+1].col_fmt) {
4719 case COL_DEF_DL_SRC:
4720 case COL_RES_DL_SRC:
4721 case COL_UNRES_DL_SRC:
4722 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4723 put_string(line_bufp + buf_offset, str_format, 5);
4724 buf_offset += 5;
4725 break;
4727 default:
4728 put_string(line_bufp + buf_offset, delimiter_char, 1);
4729 buf_offset += 1;
4730 break;
4732 break;
4734 case COL_DEF_NET_DST:
4735 case COL_RES_NET_DST:
4736 case COL_UNRES_NET_DST:
4737 switch (cf->cinfo.columns[i+1].col_fmt) {
4739 case COL_DEF_NET_SRC:
4740 case COL_RES_NET_SRC:
4741 case COL_UNRES_NET_SRC:
4742 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4743 put_string(line_bufp + buf_offset, str_format, 5);
4744 buf_offset += 5;
4745 break;
4747 default:
4748 put_string(line_bufp + buf_offset, delimiter_char, 1);
4749 buf_offset += 1;
4750 break;
4752 break;
4754 default:
4755 put_string(line_bufp + buf_offset, delimiter_char, 1);
4756 buf_offset += 1;
4757 break;
4762 if (dissect_color && color_filter != NULL)
4763 return print_line_color(print_stream, 0, line_bufp, &color_filter->fg_color, &color_filter->bg_color);
4764 else
4765 return print_line(print_stream, 0, line_bufp);
4768 static bool
4769 print_packet(capture_file *cf, epan_dissect_t *edt)
4771 if (print_summary || output_fields_has_cols(output_fields))
4772 /* Just fill in the columns. */
4773 epan_dissect_fill_in_columns(edt, false, true);
4775 /* Print summary columns and/or protocol tree */
4776 switch (output_action) {
4778 case WRITE_TEXT:
4779 if (print_summary && !print_columns(cf, edt))
4780 return false;
4781 if (print_details) {
4782 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
4783 print_hex, edt, output_only_tables, print_stream))
4784 return false;
4785 if (!print_hex) {
4786 if (!print_line(print_stream, 0, separator))
4787 return false;
4790 break;
4792 case WRITE_XML:
4793 if (print_summary) {
4794 write_psml_columns(edt, stdout, dissect_color);
4795 return !ferror(stdout);
4797 if (print_details) {
4798 write_pdml_proto_tree(output_fields, edt, &cf->cinfo, stdout, dissect_color);
4799 printf("\n");
4800 return !ferror(stdout);
4802 break;
4804 case WRITE_FIELDS:
4805 if (print_summary) {
4806 /*No non-verbose "fields" format */
4807 ws_assert_not_reached();
4809 if (print_details) {
4810 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
4811 printf("\n");
4812 return !ferror(stdout);
4814 break;
4816 case WRITE_JSON:
4817 if (print_summary)
4818 ws_assert_not_reached();
4819 if (print_details) {
4820 write_json_proto_tree(output_fields, print_dissections_expanded,
4821 print_hex, edt, &cf->cinfo, node_children_grouper, &jdumper);
4822 return !ferror(stdout);
4824 break;
4826 case WRITE_JSON_RAW:
4827 if (print_summary)
4828 ws_assert_not_reached();
4829 if (print_details) {
4830 write_json_proto_tree(output_fields, print_dissections_none,
4831 true, edt, &cf->cinfo, node_children_grouper, &jdumper);
4832 return !ferror(stdout);
4834 break;
4836 case WRITE_EK:
4837 write_ek_proto_tree(output_fields, print_summary, print_hex,
4838 edt, &cf->cinfo, stdout);
4839 return !ferror(stdout);
4841 default:
4842 ws_assert_not_reached();
4845 if (print_hex) {
4846 if (print_summary || print_details) {
4847 if (!print_line(print_stream, 0, ""))
4848 return false;
4850 if (!print_hex_data(print_stream, edt, hexdump_source_option | hexdump_ascii_option | hexdump_timestamp_option))
4851 return false;
4852 if (!print_line(print_stream, 0, separator))
4853 return false;
4855 return true;
4858 static bool
4859 write_finale(void)
4861 switch (output_action) {
4863 case WRITE_TEXT:
4864 return print_finale(print_stream);
4866 case WRITE_XML:
4867 if (print_details)
4868 write_pdml_finale(stdout);
4869 else
4870 write_psml_finale(stdout);
4871 return !ferror(stdout);
4873 case WRITE_FIELDS:
4874 write_fields_finale(output_fields, stdout);
4875 return !ferror(stdout);
4877 case WRITE_JSON:
4878 case WRITE_JSON_RAW:
4879 write_json_finale(&jdumper);
4880 return !ferror(stdout);
4882 case WRITE_EK:
4883 return true;
4885 default:
4886 ws_assert_not_reached();
4887 return false;
4891 void
4892 cf_close(capture_file *cf)
4894 if (cf->state == FILE_CLOSED)
4895 return; /* Nothing to do */
4897 if (cf->provider.wth != NULL) {
4898 wtap_close(cf->provider.wth);
4899 cf->provider.wth = NULL;
4901 /* We have no file open... */
4902 if (cf->filename != NULL) {
4903 /* If it's a temporary file, remove it. */
4904 if (cf->is_tempfile)
4905 ws_unlink(cf->filename);
4906 g_free(cf->filename);
4907 cf->filename = NULL;
4910 /* We have no file open. */
4911 cf->state = FILE_CLOSED;
4914 cf_status_t
4915 cf_open(capture_file *cf, const char *fname, unsigned int type, bool is_tempfile, int *err)
4917 wtap *wth;
4918 char *err_info;
4920 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
4921 if (wth == NULL)
4922 goto fail;
4924 /* The open succeeded. Fill in the information for this file. */
4926 cf->provider.wth = wth;
4927 cf->f_datalen = 0; /* not used, but set it anyway */
4929 /* Set the file name because we need it to set the follow stream filter.
4930 XXX - is that still true? We need it for other reasons, though,
4931 in any case. */
4932 cf->filename = g_strdup(fname);
4934 /* Indicate whether it's a permanent or temporary file. */
4935 cf->is_tempfile = is_tempfile;
4937 /* No user changes yet. */
4938 cf->unsaved_changes = false;
4940 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
4941 cf->open_type = type;
4942 cf->count = 0;
4943 cf->drops_known = false;
4944 cf->drops = 0;
4945 cf->snap = wtap_snapshot_length(cf->provider.wth);
4946 nstime_set_zero(&cf->elapsed_time);
4947 cf->provider.ref = NULL;
4948 cf->provider.prev_dis = NULL;
4949 cf->provider.prev_cap = NULL;
4951 cf->state = FILE_READ_IN_PROGRESS;
4953 /* Create new epan session for dissection. */
4954 epan_free(cf->epan);
4955 cf->epan = tshark_epan_new(cf);
4957 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
4958 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
4959 wtap_set_cb_new_secrets(cf->provider.wth, secrets_wtap_callback);
4961 return CF_OK;
4963 fail:
4964 cfile_open_failure_message(fname, *err, err_info);
4965 return CF_ERROR;
4968 static void
4969 show_print_file_io_error(void)
4971 switch (errno) {
4973 case ENOSPC:
4974 cmdarg_err("Not all the packets could be printed because there is "
4975 "no space left on the file system.");
4976 break;
4978 #ifdef EDQUOT
4979 case EDQUOT:
4980 cmdarg_err("Not all the packets could be printed because you are "
4981 "too close to, or over your disk quota.");
4982 break;
4983 #endif
4985 case EPIPE:
4987 * This almost certainly means "the next program after us in
4988 * the pipeline exited before we were finished writing", so
4989 * this isn't a real error, it just means we're done. (We
4990 * don't get SIGPIPE because libwireshark ignores SIGPIPE
4991 * to avoid getting killed if writing to the MaxMind process
4992 * gets SIGPIPE because that process died.)
4994 * Presumably either that program exited deliberately (for
4995 * example, "head -N" read N lines and printed them), in
4996 * which case there's no error to report, or it terminated
4997 * due to an error or a signal, in which case *that's* the
4998 * error and that error has been reported.
5000 break;
5002 default:
5003 #ifdef _WIN32
5004 if (errno == EINVAL && _doserrno == ERROR_NO_DATA) {
5006 * XXX - on Windows, a write to a pipe where the read side
5007 * has been closed apparently may return the Windows error
5008 * ERROR_BROKEN_PIPE, which the Visual Studio C library maps
5009 * to EPIPE, or may return the Windows error ERROR_NO_DATA,
5010 * which the Visual Studio C library maps to EINVAL.
5012 * Either of those almost certainly means "the next program
5013 * after us in the pipeline exited before we were finished
5014 * writing", so, if _doserrno is ERROR_NO_DATA, this isn't
5015 * a real error, it just means we're done. (Windows doesn't
5016 * SIGPIPE.)
5018 * Presumably either that program exited deliberately (for
5019 * example, "head -N" read N lines and printed them), in
5020 * which case there's no error to report, or it terminated
5021 * due to an error or a signal, in which case *that's* the
5022 * error and that error has been reported.
5024 break;
5028 * It's a different error; report it, but with the error
5029 * message for _doserrno, which will give more detail
5030 * than just "Invalid argument".
5032 cmdarg_err("An error occurred while printing packets: %s.",
5033 win32strerror(_doserrno));
5034 #else
5035 cmdarg_err("An error occurred while printing packets: %s.",
5036 g_strerror(errno));
5037 #endif
5038 break;
5042 static void
5043 reset_epan_mem(capture_file *cf,epan_dissect_t *edt, bool tree, bool visual)
5045 if (!epan_auto_reset || (cf->count < epan_auto_reset_count))
5046 return;
5048 fprintf(stderr, "resetting session.\n");
5050 epan_dissect_cleanup(edt);
5051 epan_free(cf->epan);
5053 cf->epan = tshark_epan_new(cf);
5054 epan_dissect_init(edt, cf->epan, tree, visual);
5055 cf->count = 0;