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
28 # include <winsock2.h>
35 #ifndef HAVE_GETOPT_LONG
36 #include "wsutil/wsgetopt.h"
41 #include <epan/exceptions.h>
42 #include <epan/epan.h>
44 #include <ui/clopts_common.h>
45 #include <ui/cmdarg_err.h>
47 #include <wsutil/filesystem.h>
48 #include <wsutil/file_util.h>
49 #include <wsutil/socket.h>
50 #include <wsutil/privileges.h>
51 #include <wsutil/report_message.h>
52 #include <wsutil/please_report_bug.h>
54 #include <version_info.h>
55 #include <wiretap/wtap_opttypes.h>
56 #include <wiretap/pcapng.h>
59 #include <epan/timestamp.h>
60 #include <epan/packet.h>
62 #include <epan/wslua/init_wslua.h>
64 #include "frame_tvbuff.h"
65 #include <epan/disabled_protos.h>
66 #include <epan/prefs.h>
67 #include <epan/column.h>
68 #include <epan/decode_as.h>
69 #include <epan/print.h>
70 #include <epan/addr_resolv.h>
72 #include "ui/capture_ui_utils.h"
76 #include "ui/ws_ui_util.h"
77 #include "ui/decode_as_utils.h"
78 #include "ui/filter_files.h"
79 #include "ui/cli/tshark-tap.h"
80 #include "ui/cli/tap-exportobject.h"
81 #include "ui/tap_export_pdu.h"
82 #include "ui/dissect_opts.h"
83 #include "ui/failure_message.h"
84 #if defined(HAVE_LIBSMI)
85 #include "epan/oids.h"
87 #include "epan/maxmind_db.h"
88 #include <epan/epan_dissect.h>
90 #include <epan/stat_tap_ui.h>
91 #include <epan/conversation_table.h>
92 #include <epan/srt_table.h>
93 #include <epan/rtd_table.h>
94 #include <epan/ex-opt.h>
95 #include <epan/exported_pdu.h>
96 #include <epan/secrets.h>
98 #include "capture_opts.h"
100 #include "caputils/capture-pcap-util.h"
103 #include "caputils/capture_ifinfo.h"
105 #include "caputils/capture-wpcap.h"
107 #include <capchild/capture_session.h>
108 #include <capchild/capture_sync.h>
109 #include <ui/capture_info.h>
110 #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>
121 #include <wsutil/plugins.h>
125 #define INVALID_OPTION 1
126 #define INVALID_INTERFACE 2
127 #define INVALID_FILE 2
128 #define INVALID_FILTER 2
129 #define INVALID_EXPORT 2
130 #define INVALID_CAPABILITY 2
131 #define INVALID_TAP 2
132 #define INVALID_DATA_LINK 2
133 #define INVALID_TIMESTAMP_TYPE 2
134 #define INVALID_CAPTURE 2
135 #define INIT_FAILED 2
137 #define LONGOPT_EXPORT_OBJECTS LONGOPT_BASE_APPLICATION+1
138 #define LONGOPT_COLOR LONGOPT_BASE_APPLICATION+2
139 #define LONGOPT_NO_DUPLICATE_KEYS LONGOPT_BASE_APPLICATION+3
140 #define LONGOPT_ELASTIC_MAPPING_FILTER LONGOPT_BASE_APPLICATION+4
143 #define tshark_debug(...) g_warning(__VA_ARGS__)
145 #define tshark_debug(...)
150 static guint32 cum_bytes;
151 static frame_data ref_frame;
152 static frame_data prev_dis_frame;
153 static frame_data prev_cap_frame;
155 static gboolean perform_two_pass_analysis;
156 static guint32 epan_auto_reset_count = 0;
157 static gboolean epan_auto_reset = FALSE;
160 * The way the packet decode is to be written.
163 WRITE_TEXT, /* summary or detail text */
164 WRITE_XML, /* PDML or PSML */
165 WRITE_FIELDS, /* User defined list of fields */
166 WRITE_JSON, /* JSON */
167 WRITE_JSON_RAW, /* JSON only raw hex */
168 WRITE_EK /* JSON bulk insert to Elasticsearch */
169 /* Add CSV and the like here */
172 static output_action_e output_action;
173 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
174 static gboolean print_packet_info; /* TRUE if we're to print packet information */
175 static gboolean print_summary; /* TRUE if we're to print packet summary information */
176 static gboolean print_details; /* TRUE if we're to print packet details information */
177 static gboolean print_hex; /* TRUE if we're to print hex/ascci information */
178 static gboolean line_buffered;
179 static gboolean really_quiet = FALSE;
180 static gchar* delimiter_char = " ";
181 static gboolean dissect_color = FALSE;
183 static print_format_e print_format = PR_FMT_TEXT;
184 static print_stream_t *print_stream = NULL;
186 static char *output_file_name;
188 static output_fields_t* output_fields = NULL;
189 static gchar **protocolfilter = NULL;
190 static pf_flags protocolfilter_flags = PF_NONE;
192 static gboolean no_duplicate_keys = FALSE;
193 static proto_node_children_grouper_func node_children_grouper = proto_node_group_children_by_unique;
195 static json_dumper jdumper;
197 /* The line separator used between packets, changeable via the -S option */
198 static const char *separator = "";
200 static gboolean prefs_loaded = FALSE;
204 * TRUE if we're to print packet counts to keep track of captured packets.
206 static gboolean print_packet_counts;
208 static capture_options global_capture_opts;
209 static capture_session global_capture_session;
210 static info_data_t global_info_data;
213 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
214 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
217 static gboolean capture(void);
218 static gboolean capture_input_new_file(capture_session *cap_session,
220 static void capture_input_new_packets(capture_session *cap_session,
222 static void capture_input_drops(capture_session *cap_session, guint32 dropped,
223 const char* interface_name);
224 static void capture_input_error(capture_session *cap_session,
225 char *error_msg, char *secondary_error_msg);
226 static void capture_input_cfilter_error(capture_session *cap_session,
227 guint i, const char *error_message);
228 static void capture_input_closed(capture_session *cap_session, gchar *msg);
230 static void report_counts(void);
232 static BOOL WINAPI capture_cleanup(DWORD);
234 static void capture_cleanup(int);
236 static void report_counts_siginfo(int);
239 #endif /* HAVE_LIBPCAP */
241 static void reset_epan_mem(capture_file *cf, epan_dissect_t *edt, gboolean tree, gboolean visual);
244 PROCESS_FILE_SUCCEEDED,
245 PROCESS_FILE_NO_FILE_PROCESSED,
247 PROCESS_FILE_INTERRUPTED
248 } process_file_status_t;
249 static process_file_status_t process_cap_file(capture_file *, char *, int, gboolean, int, gint64);
251 static gboolean process_packet_single_pass(capture_file *cf,
252 epan_dissect_t *edt, gint64 offset, wtap_rec *rec, Buffer *buf,
254 static void show_print_file_io_error(int err);
255 static gboolean write_preamble(capture_file *cf);
256 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
257 static gboolean write_finale(void);
259 static void failure_warning_message(const char *msg_format, va_list ap);
260 static void open_failure_message(const char *filename, int err,
261 gboolean for_writing);
262 static void read_failure_message(const char *filename, int err);
263 static void write_failure_message(const char *filename, int err);
264 static void failure_message_cont(const char *msg_format, va_list ap);
266 static GHashTable *output_only_tables = NULL;
269 const char *sstr; /* The short string */
270 const char *lstr; /* The long string */
274 string_compare(gconstpointer a, gconstpointer b)
276 return strcmp(((const struct string_elem *)a)->sstr,
277 ((const struct string_elem *)b)->sstr);
281 string_elem_print(gpointer data)
283 fprintf(stderr, " %s - %s\n",
284 ((struct string_elem *)data)->sstr,
285 ((struct string_elem *)data)->lstr);
289 list_capture_types(void) {
291 struct string_elem *captypes;
294 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
296 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
297 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
298 if (wtap_dump_can_open(i)) {
299 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
300 captypes[i].lstr = wtap_file_type_subtype_string(i);
301 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
304 g_slist_free_full(list, string_elem_print);
309 list_read_capture_types(void) {
311 struct string_elem *captypes;
313 const char *magic = "Magic-value-based";
314 const char *heuristic = "Heuristics-based";
316 /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
317 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
319 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
320 for (i = 0; open_routines[i].name != NULL; i++) {
321 captypes[i].sstr = open_routines[i].name;
322 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
323 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
325 g_slist_free_full(list, string_elem_print);
330 print_usage(FILE *output)
332 fprintf(output, "\n");
333 fprintf(output, "Usage: tshark [options] ...\n");
334 fprintf(output, "\n");
337 fprintf(output, "Capture interface:\n");
338 fprintf(output, " -i <interface>, --interface <interface>\n");
339 fprintf(output, " name or idx of interface (def: first non-loopback)\n");
340 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
341 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
342 #ifdef HAVE_PCAP_CREATE
343 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
345 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
347 fprintf(output, " -p, --no-promiscuous-mode\n");
348 fprintf(output, " don't capture in promiscuous mode\n");
349 #ifdef HAVE_PCAP_CREATE
350 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
352 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
353 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
354 fprintf(output, " size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
356 fprintf(output, " -y <link type>, --linktype <link type>\n");
357 fprintf(output, " link layer type (def: first appropriate)\n");
358 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
359 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
360 fprintf(output, " -L, --list-data-link-types\n");
361 fprintf(output, " print list of link-layer types of iface and exit\n");
362 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
363 fprintf(output, "\n");
364 fprintf(output, "Capture stop conditions:\n");
365 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
366 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
367 fprintf(output, " duration:NUM - stop after NUM seconds\n");
368 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
369 fprintf(output, " files:NUM - stop after NUM files\n");
370 fprintf(output, " packets:NUM - stop after NUM packets\n");
371 /*fprintf(output, "\n");*/
372 fprintf(output, "Capture output:\n");
373 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
374 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
375 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
376 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
377 fprintf(output, " packets:NUM - switch to next file after NUM packets\n");
378 fprintf(output, " interval:NUM - switch to next file when the time is\n");
379 fprintf(output, " an exact multiple of NUM secs\n");
380 #endif /* HAVE_LIBPCAP */
381 #ifdef HAVE_PCAP_REMOTE
382 fprintf(output, "RPCAP options:\n");
383 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
385 /*fprintf(output, "\n");*/
386 fprintf(output, "Input file:\n");
387 fprintf(output, " -r <infile>, --read-file <infile>\n");
388 fprintf(output, " set the filename to read from (or '-' for stdin)\n");
390 fprintf(output, "\n");
391 fprintf(output, "Processing:\n");
392 fprintf(output, " -2 perform a two-pass analysis\n");
393 fprintf(output, " -M <packet count> perform session auto reset\n");
394 fprintf(output, " -R <read filter>, --read-filter <read filter>\n");
395 fprintf(output, " packet Read filter in Wireshark display filter syntax\n");
396 fprintf(output, " (requires -2)\n");
397 fprintf(output, " -Y <display filter>, --display-filter <display filter>\n");
398 fprintf(output, " packet displaY filter in Wireshark display filter\n");
399 fprintf(output, " syntax\n");
400 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
401 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtdv\"\n");
402 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
403 fprintf(output, " \"Decode As\", see the man page for details\n");
404 fprintf(output, " Example: tcp.port==8888,http\n");
405 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
406 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
407 fprintf(output, " --enable-protocol <proto_name>\n");
408 fprintf(output, " enable dissection of proto_name\n");
409 fprintf(output, " --disable-protocol <proto_name>\n");
410 fprintf(output, " disable dissection of proto_name\n");
411 fprintf(output, " --enable-heuristic <short_name>\n");
412 fprintf(output, " enable dissection of heuristic protocol\n");
413 fprintf(output, " --disable-heuristic <short_name>\n");
414 fprintf(output, " disable dissection of heuristic protocol\n");
416 /*fprintf(output, "\n");*/
417 fprintf(output, "Output:\n");
418 fprintf(output, " -w <outfile|-> write packets to a pcapng-format file named \"outfile\"\n");
419 fprintf(output, " (or '-' for stdout)\n");
420 fprintf(output, " --capture-comment <comment>\n");
421 fprintf(output, " set the capture file comment, if supported\n");
422 fprintf(output, " -C <config profile> start with specified configuration profile\n");
423 fprintf(output, " -F <output file type> set the output file type, default is pcapng\n");
424 fprintf(output, " an empty \"-F\" option will list the file types\n");
425 fprintf(output, " -V add output of packet tree (Packet Details)\n");
426 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
427 fprintf(output, " separated\n");
428 fprintf(output, " -P, --print print packet summary even when writing to a file\n");
429 fprintf(output, " -S <separator> the line separator to print between packets\n");
430 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
431 fprintf(output, " -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?\n");
432 fprintf(output, " format of text output (def: text)\n");
433 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected\n");
434 fprintf(output, " (e.g. \"ip ip.flags text\", filter does not expand child\n");
435 fprintf(output, " nodes, unless child is specified also in the filter)\n");
436 fprintf(output, " -J <protocolfilter> top level protocol filter if -T ek|pdml|json selected\n");
437 fprintf(output, " (e.g. \"http tcp\", filter which expands all child nodes)\n");
438 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
439 fprintf(output, " _ws.col.Info)\n");
440 fprintf(output, " this option can be repeated to print multiple fields\n");
441 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
442 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
443 fprintf(output, " header=y|n switch headers on and off\n");
444 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
445 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
446 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
447 fprintf(output, " aggregator\n");
448 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
449 fprintf(output, " -t a|ad|adoy|d|dd|e|r|u|ud|udoy\n");
450 fprintf(output, " output format of time stamps (def: r: rel. to first)\n");
451 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
452 fprintf(output, " -l flush standard output after each packet\n");
453 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
454 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
455 fprintf(output, " -g enable group read access on the output file(s)\n");
456 fprintf(output, " -W n Save extra information in the file, if supported.\n");
457 fprintf(output, " n = write network address resolution information\n");
458 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
459 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
460 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
461 fprintf(output, " --export-objects <protocol>,<destdir>\n");
462 fprintf(output, " save exported objects for a protocol to a directory\n");
463 fprintf(output, " named \"destdir\"\n");
464 fprintf(output, " --color color output text similarly to the Wireshark GUI,\n");
465 fprintf(output, " requires a terminal with 24-bit color support\n");
466 fprintf(output, " Also supplies color attributes to pdml and psml formats\n");
467 fprintf(output, " (Note that attributes are nonstandard)\n");
468 fprintf(output, " --no-duplicate-keys If -T json is specified, merge duplicate keys in an object\n");
469 fprintf(output, " into a single key with as value a json array containing all\n");
470 fprintf(output, " values\n");
471 fprintf(output, " --elastic-mapping-filter <protocols> If -G elastic-mapping is specified, put only the\n");
472 fprintf(output, " specified protocols within the mapping file\n");
474 fprintf(output, "\n");
475 fprintf(output, "Miscellaneous:\n");
476 fprintf(output, " -h, --help display this help and exit\n");
477 fprintf(output, " -v, --version display version info and exit\n");
478 fprintf(output, " -o <name>:<value> ... override preference setting\n");
479 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
480 fprintf(output, " -G [report] dump one of several available reports and exit\n");
481 fprintf(output, " default report=\"fields\"\n");
482 fprintf(output, " use \"-G help\" for more help\n");
484 fprintf(output, "\n");
485 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
486 fprintf(output, "You might want to enable it by executing:\n");
487 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
488 fprintf(output, "Note that this can make your system less secure!\n");
494 glossary_option_help(void)
500 fprintf(output, "%s\n", get_appname_and_version());
502 fprintf(output, "\n");
503 fprintf(output, "Usage: tshark -G [report]\n");
504 fprintf(output, "\n");
505 fprintf(output, "Glossary table reports:\n");
506 fprintf(output, " -G column-formats dump column format codes and exit\n");
507 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
508 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
509 fprintf(output, " -G elastic-mapping dump ElasticSearch mapping file\n");
510 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
511 fprintf(output, " -G fields dump fields glossary and exit\n");
512 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
513 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
514 fprintf(output, " -G plugins dump installed plugins and exit\n");
515 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
516 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
517 fprintf(output, "\n");
518 fprintf(output, "Preference reports:\n");
519 fprintf(output, " -G currentprefs dump current preferences and exit\n");
520 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
521 fprintf(output, " -G folders dump about:folders\n");
522 fprintf(output, "\n");
526 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
527 const gchar *message, gpointer user_data)
529 /* ignore log message, if log_level isn't interesting based
530 upon the console log preferences.
531 If the preferences haven't been loaded yet, display the
534 The default console_log_level preference value is such that only
535 ERROR, CRITICAL and WARNING level messages are processed;
536 MESSAGE, INFO and DEBUG level messages are ignored.
538 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
539 ERROR and CRITICAL level messages so the current code is a behavioral
540 change. The current behavior is the same as in Wireshark.
542 if (prefs_loaded && (log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0) {
546 g_log_default_handler(log_domain, log_level, message, user_data);
551 print_current_user(void) {
552 gchar *cur_user, *cur_group;
554 if (started_with_special_privs()) {
555 cur_user = get_cur_username();
556 cur_group = get_cur_groupname();
557 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
558 cur_user, cur_group);
561 if (running_with_special_privs()) {
562 fprintf(stderr, " This could be dangerous.");
564 fprintf(stderr, "\n");
569 get_tshark_compiled_version_info(GString *str)
571 /* Capture libraries */
572 get_compiled_caplibs_version(str);
576 get_tshark_runtime_version_info(GString *str)
579 /* Capture libraries */
580 g_string_append(str, ", ");
581 get_runtime_caplibs_version(str);
584 /* stuff used by libwireshark */
585 epan_get_runtime_version_info(str);
591 const char *constpath;
599 * Fetching the "File" dialogs folder not implemented.
600 * This is arguably just a pwd for a ui/cli .
604 printf("%-21s\t%s\n", "Temp:", g_get_tmp_dir());
607 path = get_persconffile_path("", FALSE);
608 printf("%-21s\t%s\n", "Personal configuration:", path);
612 constpath = get_datafile_dir();
613 if (constpath != NULL) {
614 printf("%-21s\t%s\n", "Global configuration:", constpath);
618 constpath = get_systemfile_dir();
619 printf("%-21s\t%s\n", "System:", constpath);
622 constpath = get_progfile_dir();
623 printf("%-21s\t%s\n", "Program:", constpath);
627 printf("%-21s\t%s\n", "Personal Plugins:", get_plugins_pers_dir_with_version());
630 printf("%-21s\t%s\n", "Global Plugins:", get_plugins_dir_with_version());
634 /* pers lua plugins */
635 printf("%-21s\t%s\n", "Personal Lua Plugins:", get_plugins_pers_dir());
637 /* global lua plugins */
638 printf("%-21s\t%s\n", "Global Lua Plugins:", get_plugins_dir());
642 constpath = get_extcap_dir();
644 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
645 for(i = 0; resultArray[i]; i++)
646 printf("%-21s\t%s\n", "Extcap path:", g_strstrip(resultArray[i]));
648 g_strfreev(resultArray);
651 path = maxmind_db_get_paths();
653 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
655 for(i = 0; resultArray[i]; i++)
656 printf("%-21s\t%s\n", "MaxMind database path:", g_strstrip(resultArray[i]));
658 g_strfreev(resultArray);
663 path = oid_get_default_mib_path();
665 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 20);
667 for(i = 0; resultArray[i]; i++)
668 printf("%-21s\t%s\n", "MIB/PIB path:", g_strstrip(resultArray[i]));
670 g_strfreev(resultArray);
677 must_do_dissection(dfilter_t *rfcode, dfilter_t *dfcode,
678 gchar *volatile pdu_export_arg)
680 /* We have to dissect each packet if:
682 we're printing information about each packet;
684 we're using a read filter on the packets;
686 we're using a display filter on the packets;
688 we're exporting PDUs;
690 we're using any taps that need dissection. */
691 return print_packet_info || rfcode || dfcode || pdu_export_arg ||
692 tap_listeners_require_dissection() || dissect_color;
696 main(int argc, char *argv[])
700 static const struct option long_options[] = {
701 {"help", no_argument, NULL, 'h'},
702 {"version", no_argument, NULL, 'v'},
703 LONGOPT_CAPTURE_COMMON
704 LONGOPT_DISSECT_COMMON
705 {"print", no_argument, NULL, 'P'},
706 {"export-objects", required_argument, NULL, LONGOPT_EXPORT_OBJECTS},
707 {"color", no_argument, NULL, LONGOPT_COLOR},
708 {"no-duplicate-keys", no_argument, NULL, LONGOPT_NO_DUPLICATE_KEYS},
709 {"elastic-mapping-filter", required_argument, NULL, LONGOPT_ELASTIC_MAPPING_FILTER},
712 gboolean arg_error = FALSE;
716 gboolean exp_pdu_status;
717 volatile process_file_status_t status;
718 volatile gboolean draw_taps = FALSE;
719 volatile int exit_status = EXIT_SUCCESS;
721 int caps_queries = 0;
722 gboolean start_capture = FALSE;
725 struct bpf_program fcode;
727 gboolean capture_option_specified = FALSE;
728 volatile int max_packet_count = 0;
730 gboolean quiet = FALSE;
731 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
732 volatile gboolean out_file_name_res = FALSE;
733 volatile int in_file_type = WTAP_TYPE_AUTO;
734 gchar *volatile cf_name = NULL;
735 gchar *rfilter = NULL;
736 gchar *dfilter = NULL;
737 dfilter_t *rfcode = NULL;
738 dfilter_t *dfcode = NULL;
741 gchar *output_only = NULL;
742 gchar *volatile pdu_export_arg = NULL;
743 char *volatile exp_pdu_filename = NULL;
744 exp_pdu_t exp_pdu_tap_data;
745 const gchar* elastic_mapping_filter = NULL;
748 * The leading + ensures that getopt_long() does not permute the argv[]
751 * We have to make sure that the first getopt_long() preserves the content
752 * of argv[] for the subsequent getopt_long() call.
754 * We use getopt_long() in both cases to ensure that we're using a routine
755 * whose permutation behavior we can control in the same fashion on all
756 * platforms, and so that, if we ever need to process a long argument before
757 * doing further initialization, we can do so.
759 * Glibc and Solaris libc document that a leading + disables permutation
760 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
761 * and macOS don't document it, but do so anyway.
763 * We do *not* use a leading - because the behavior of a leading - is
764 * platform-dependent.
766 #define OPTSTRING "+2" OPTSTRING_CAPTURE_COMMON OPTSTRING_DISSECT_COMMON "M:C:e:E:F:gG:hH:j:J:lo:O:PqQr:R:S:T:U:vVw:W:xX:Y:z:"
768 static const char optstring[] = OPTSTRING;
771 * Set the C-language locale to the native environment and set the
772 * code page to UTF-8 on Windows.
775 setlocale(LC_ALL, ".UTF-8");
777 setlocale(LC_ALL, "");
780 tshark_debug("tshark started with %d args", argc);
782 cmdarg_err_init(failure_warning_message, failure_message_cont);
785 create_app_running_mutex();
789 * Get credential information for later use, and drop privileges
790 * before doing anything else.
791 * Let the user know if anything happened.
793 init_process_policies();
794 relinquish_special_privs_perm();
795 print_current_user();
798 * Attempt to get the pathname of the directory containing the
801 err_msg = init_progfile_dir(argv[0]);
802 if (err_msg != NULL) {
804 "tshark: Can't get pathname of directory containing the tshark program: %s.\n"
805 "It won't be possible to capture traffic.\n"
806 "Report this to the Wireshark developers.",
811 initialize_funnel_ops();
814 ws_init_dll_search_path();
816 /* Load wpcap if possible. Do this before collecting the run-time version information */
818 #endif /* HAVE_LIBPCAP */
821 /* Initialize the version information. */
822 ws_init_version_info("TShark (Wireshark)", get_tshark_compiled_version_info,
823 epan_get_compiled_version_info,
824 get_tshark_runtime_version_info);
826 /* Fail sometimes. Useful for testing fuzz scripts. */
827 /* if (g_random_int_range(0, 100) < 5) abort(); */
830 * In order to have the -X opts assigned before the wslua machine starts
831 * we need to call getopt_long before epan_init() gets called.
833 * In order to handle, for example, -o options, we also need to call it
834 * *after* epan_init() gets called, so that the dissectors have had a
835 * chance to register their preferences.
837 * XXX - can we do this all with one getopt_long() call, saving the
838 * arguments we can't handle until after initializing libwireshark,
839 * and then process them after initializing libwireshark?
843 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
845 case 'C': /* Configuration Profile */
846 if (profile_exists (optarg, FALSE)) {
847 set_profile_name (optarg);
849 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
850 exit_status = INVALID_OPTION;
854 case 'P': /* Print packet summary info even when writing to a file */
855 print_packet_info = TRUE;
856 print_summary = TRUE;
858 case 'O': /* Only output these protocols */
859 output_only = g_strdup(optarg);
861 case 'V': /* Verbose */
862 print_details = TRUE;
863 print_packet_info = TRUE;
865 case 'x': /* Print packet data in hex (and ASCII) */
867 /* The user asked for hex output, so let's ensure they get it,
868 * even if they're writing to a file.
870 print_packet_info = TRUE;
875 case LONGOPT_ELASTIC_MAPPING_FILTER:
876 elastic_mapping_filter = optarg;
883 /** Send All g_log messages to our own handler **/
887 G_LOG_LEVEL_CRITICAL|
892 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
894 g_log_set_handler(NULL,
895 (GLogLevelFlags)log_flags,
896 tshark_log_handler, NULL /* user_data */);
897 g_log_set_handler(LOG_DOMAIN_MAIN,
898 (GLogLevelFlags)log_flags,
899 tshark_log_handler, NULL /* user_data */);
902 g_log_set_handler(LOG_DOMAIN_CAPTURE,
903 (GLogLevelFlags)log_flags,
904 tshark_log_handler, NULL /* user_data */);
905 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
906 (GLogLevelFlags)log_flags,
907 tshark_log_handler, NULL /* user_data */);
910 init_report_message(failure_warning_message, failure_warning_message,
911 open_failure_message, read_failure_message,
912 write_failure_message);
915 capture_opts_init(&global_capture_opts);
916 capture_session_init(&global_capture_session, &cfile,
917 capture_input_new_file, capture_input_new_packets,
918 capture_input_drops, capture_input_error,
919 capture_input_cfilter_error, capture_input_closed);
922 timestamp_set_type(TS_RELATIVE);
923 timestamp_set_precision(TS_PREC_AUTO);
924 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
928 /* Register all dissectors; we must do this before checking for the
929 "-G" flag, as the "-G" flag dumps information registered by the
930 dissectors, and we must do it before we read the preferences, in
931 case any dissectors register preferences. */
932 if (!epan_init(NULL, NULL, TRUE)) {
933 exit_status = INIT_FAILED;
937 /* Register all tap listeners; we do this before we parse the arguments,
938 as the "-z" argument can specify a registered tap. */
940 /* we register the plugin taps before the other taps because
941 stats_tree taps plugins will be registered as tap listeners
942 by stats_tree_stat.c and need to registered before that */
944 register_all_plugin_tap_listeners();
946 /* Register all tap listeners. */
947 for (tap_reg_t *t = tap_reg_listener; t->cb_func != NULL; t++) {
950 conversation_table_set_gui_info(init_iousers);
951 hostlist_table_set_gui_info(init_hostlists);
952 srt_table_iterate_tables(register_srt_tables, NULL);
953 rtd_table_iterate_tables(register_rtd_tables, NULL);
954 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
956 /* If invoked with the "-G" flag, we dump out information based on
957 the argument to the "-G" flag; if no argument is specified,
958 for backwards compatibility we dump out a glossary of display
961 XXX - we do this here, for now, to support "-G" with no arguments.
962 If none of our build or other processes uses "-G" with no arguments,
963 we can just process it with the other arguments. */
964 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
965 proto_initialize_all_prefixes();
968 proto_registrar_dump_fields();
970 if (strcmp(argv[2], "column-formats") == 0)
971 column_dump_column_formats();
972 else if (strcmp(argv[2], "currentprefs") == 0) {
973 extcap_register_preferences();
974 epan_load_settings();
977 else if (strcmp(argv[2], "decodes") == 0)
978 dissector_dump_decodes();
979 else if (strcmp(argv[2], "defaultprefs") == 0)
981 else if (strcmp(argv[2], "dissector-tables") == 0)
982 dissector_dump_dissector_tables();
983 else if (strcmp(argv[2], "elastic-mapping") == 0)
984 proto_registrar_dump_elastic(elastic_mapping_filter);
985 else if (strcmp(argv[2], "fieldcount") == 0) {
986 /* return value for the test suite */
987 exit_status = proto_registrar_dump_fieldcount();
989 } else if (strcmp(argv[2], "fields") == 0)
990 proto_registrar_dump_fields();
991 else if (strcmp(argv[2], "folders") == 0) {
992 epan_load_settings();
994 } else if (strcmp(argv[2], "ftypes") == 0)
995 proto_registrar_dump_ftypes();
996 else if (strcmp(argv[2], "heuristic-decodes") == 0)
997 dissector_dump_heur_decodes();
998 else if (strcmp(argv[2], "plugins") == 0) {
1003 wslua_plugins_dump_all();
1007 else if (strcmp(argv[2], "protocols") == 0)
1008 proto_registrar_dump_protocols();
1009 else if (strcmp(argv[2], "values") == 0)
1010 proto_registrar_dump_values();
1011 else if (strcmp(argv[2], "help") == 0)
1012 glossary_option_help();
1013 /* These are supported only for backwards compatibility and may or may not work
1014 * for a given user in a given directory on a given operating system with a given
1015 * command-line interpreter.
1017 else if (strcmp(argv[2], "?") == 0)
1018 glossary_option_help();
1019 else if (strcmp(argv[2], "-?") == 0)
1020 glossary_option_help();
1022 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G help for more help.", argv[2]);
1023 exit_status = INVALID_OPTION;
1027 exit_status = EXIT_SUCCESS;
1031 tshark_debug("tshark reading settings");
1033 /* Load libwireshark settings from the current profile. */
1034 prefs_p = epan_load_settings();
1035 prefs_loaded = TRUE;
1037 read_filter_list(CFILTER_LIST);
1039 cap_file_init(&cfile);
1041 /* Print format defaults to this. */
1042 print_format = PR_FMT_TEXT;
1043 delimiter_char = " ";
1045 output_fields = output_fields_new();
1048 * To reset the options parser, set optreset to 1 on platforms that
1049 * have optreset (documented in *BSD and macOS, apparently present but
1050 * not documented in Solaris - the Illumos repository seems to
1051 * suggest that the first Solaris getopt_long(), at least as of 2004,
1052 * was based on the NetBSD one, it had optreset) and set optind to 1,
1053 * and set optind to 0 otherwise (documented as working in the GNU
1054 * getopt_long(). Setting optind to 0 didn't originally work in the
1055 * NetBSD one, but that was added later - we don't want to depend on
1056 * it if we have optreset).
1058 * Also reset opterr to 1, so that error messages are printed by
1061 #ifdef HAVE_OPTRESET
1069 /* Now get our args */
1070 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1072 case '2': /* Perform two pass analysis */
1073 if(epan_auto_reset){
1074 cmdarg_err("-2 does not support auto session reset.");
1077 perform_two_pass_analysis = TRUE;
1080 if(perform_two_pass_analysis){
1081 cmdarg_err("-M does not support two pass analysis.");
1084 epan_auto_reset_count = get_positive_int(optarg, "epan reset count");
1085 epan_auto_reset = TRUE;
1087 case 'a': /* autostop criteria */
1088 case 'b': /* Ringbuffer option */
1089 case 'f': /* capture filter */
1090 case 'g': /* enable group read access on file(s) */
1091 case 'i': /* Use interface x */
1092 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
1093 case 'p': /* Don't capture in promiscuous mode */
1094 #ifdef HAVE_PCAP_REMOTE
1095 case 'A': /* Authentication */
1097 #ifdef HAVE_PCAP_CREATE
1098 case 'I': /* Capture in monitor mode, if available */
1100 case 's': /* Set the snapshot (capture) length */
1101 case 'y': /* Set the pcap data link type */
1102 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
1103 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1104 case 'B': /* Buffer size */
1106 case LONGOPT_COMPRESS_TYPE: /* compress type */
1107 /* These are options only for packet capture. */
1109 exit_status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1110 if (exit_status != 0) {
1114 capture_option_specified = TRUE;
1118 case 'c': /* Stop after x packets */
1120 exit_status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1121 if (exit_status != 0) {
1125 max_packet_count = get_positive_int(optarg, "packet count");
1128 case 'w': /* Write to file x */
1129 output_file_name = g_strdup(optarg);
1131 exit_status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1132 if (exit_status != 0) {
1138 /* already processed; just ignore it now */
1140 case 'D': /* Print a list of capture devices and exit */
1142 if_list = capture_interface_list(&err, &err_str,NULL);
1143 if (if_list == NULL) {
1145 cmdarg_err("There are no interfaces on which a capture can be done");
1147 cmdarg_err("%s", err_str);
1150 exit_status = INVALID_INTERFACE;
1153 capture_opts_print_interfaces(if_list);
1154 free_interface_list(if_list);
1155 exit_status = EXIT_SUCCESS;
1158 capture_option_specified = TRUE;
1164 output_fields_add(output_fields, optarg);
1168 if (!output_fields_set_option(output_fields, optarg)) {
1169 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1170 output_fields_list_options(stderr);
1171 exit_status = INVALID_OPTION;
1176 out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1177 if (out_file_type < 0) {
1178 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1179 list_capture_types();
1180 exit_status = INVALID_OPTION;
1185 if (protocolfilter) {
1186 cmdarg_err("-j or -J was already specified! Overwriting previous protocol filter");
1188 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1191 if (protocolfilter) {
1192 cmdarg_err("-j or -J was already specified! Overwriting previous protocol filter");
1194 protocolfilter_flags = PF_INCLUDE_CHILDREN;
1195 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1197 case 'W': /* Select extra information to save in our capture file */
1198 /* This is patterned after the -N flag which may not be the best idea. */
1199 if (strchr(optarg, 'n')) {
1200 out_file_name_res = TRUE;
1202 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1203 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1204 exit_status = INVALID_OPTION;
1208 case 'H': /* Read address to name mappings from a hosts file */
1209 if (! add_hosts_file(optarg))
1211 cmdarg_err("Can't read host entries from \"%s\"", optarg);
1212 exit_status = INVALID_OPTION;
1215 out_file_name_res = TRUE;
1218 case 'h': /* Print help and exit */
1219 show_help_header("Dump and analyze network traffic.");
1220 print_usage(stdout);
1221 exit_status = EXIT_SUCCESS;
1224 case 'l': /* "Line-buffer" standard output */
1225 /* The ANSI C standard does not appear to *require* that a line-buffered
1226 stream be flushed to the host environment whenever a newline is
1227 written, it just says that, on such a stream, characters "are
1228 intended to be transmitted to or from the host environment as a
1229 block when a new-line character is encountered".
1231 The Visual C++ 6.0 C implementation doesn't do what is intended;
1232 even if you set a stream to be line-buffered, it still doesn't
1233 flush the buffer at the end of every line.
1235 The whole reason for the "-l" flag in either tcpdump or TShark
1236 is to allow the output of a live capture to be piped to a program
1237 or script and to have that script see the information for the
1238 packet as soon as it's printed, rather than having to wait until
1239 a standard I/O buffer fills up.
1241 So, if the "-l" flag is specified, we flush the standard output
1242 at the end of a packet. This will do the right thing if we're
1243 printing packet summary lines, and, as we print the entire protocol
1244 tree for a single packet without waiting for anything to happen,
1245 it should be as good as line-buffered mode if we're printing
1246 protocol trees - arguably even better, as it may do fewer
1248 line_buffered = TRUE;
1250 case 'L': /* Print list of link-layer types and exit */
1252 caps_queries |= CAPS_QUERY_LINK_TYPES;
1254 capture_option_specified = TRUE;
1258 case LONGOPT_LIST_TSTAMP_TYPES: /* List possible timestamp types */
1260 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
1262 capture_option_specified = TRUE;
1266 case 'o': /* Override preference from command line */
1268 char *errmsg = NULL;
1270 switch (prefs_set_pref(optarg, &errmsg)) {
1275 case PREFS_SET_SYNTAX_ERR:
1276 cmdarg_err("Invalid -o flag \"%s\"%s%s", optarg,
1277 errmsg ? ": " : "", errmsg ? errmsg : "");
1279 exit_status = INVALID_OPTION;
1283 case PREFS_SET_NO_SUCH_PREF:
1284 case PREFS_SET_OBSOLETE:
1285 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1286 exit_status = INVALID_OPTION;
1292 case 'q': /* Quiet */
1295 case 'Q': /* Really quiet */
1297 really_quiet = TRUE;
1299 case 'r': /* Read capture file x */
1300 cf_name = g_strdup(optarg);
1302 case 'R': /* Read file filter */
1306 /* already processed; just ignore it now */
1308 case 'S': /* Set the line Separator to be printed between packets */
1311 case 'T': /* printing Type */
1312 print_packet_info = TRUE;
1313 if (strcmp(optarg, "text") == 0) {
1314 output_action = WRITE_TEXT;
1315 print_format = PR_FMT_TEXT;
1316 } else if (strcmp(optarg, "tabs") == 0) {
1317 output_action = WRITE_TEXT;
1318 print_format = PR_FMT_TEXT;
1319 delimiter_char = "\t";
1320 } else if (strcmp(optarg, "ps") == 0) {
1321 output_action = WRITE_TEXT;
1322 print_format = PR_FMT_PS;
1323 } else if (strcmp(optarg, "pdml") == 0) {
1324 output_action = WRITE_XML;
1325 print_details = TRUE; /* Need details */
1326 print_summary = FALSE; /* Don't allow summary */
1327 } else if (strcmp(optarg, "psml") == 0) {
1328 output_action = WRITE_XML;
1329 print_details = FALSE; /* Don't allow details */
1330 print_summary = TRUE; /* Need summary */
1331 } else if (strcmp(optarg, "fields") == 0) {
1332 output_action = WRITE_FIELDS;
1333 print_details = TRUE; /* Need full tree info */
1334 print_summary = FALSE; /* Don't allow summary */
1335 } else if (strcmp(optarg, "json") == 0) {
1336 output_action = WRITE_JSON;
1337 print_details = TRUE; /* Need details */
1338 print_summary = FALSE; /* Don't allow summary */
1339 } else if (strcmp(optarg, "ek") == 0) {
1340 output_action = WRITE_EK;
1342 print_details = TRUE;
1343 } else if (strcmp(optarg, "jsonraw") == 0) {
1344 output_action = WRITE_JSON_RAW;
1345 print_details = TRUE; /* Need details */
1346 print_summary = FALSE; /* Don't allow summary */
1349 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg); /* x */
1350 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1351 "\t specified by the -E option.\n"
1352 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1353 "\t details of a decoded packet. This information is equivalent to\n"
1354 "\t the packet details printed with the -V flag.\n"
1355 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1356 "\t the packets, or a multi-line view of the details of each of\n"
1357 "\t the packets, depending on whether the -V flag was specified.\n"
1358 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1359 "\t summary information of a decoded packet. This information is\n"
1360 "\t equivalent to the information shown in the one-line summary\n"
1361 "\t printed by default.\n"
1362 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1363 "\t summary information of a decoded packet. This information is \n"
1364 "\t equivalent to the packet details printed with the -V flag.\n"
1365 "\t\"jsonraw\" Packet Details, a JSON-based format for machine parsing\n"
1366 "\t including only raw hex decoded fields (same as -T json -x but\n"
1367 "\t without text decoding, only raw fields included). \n"
1368 "\t\"ek\" Packet Details, an EK JSON-based format for the bulk insert \n"
1369 "\t into elastic search cluster. This information is \n"
1370 "\t equivalent to the packet details printed with the -V flag.\n"
1371 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1372 "\t packets, or a multi-line view of the details of each of the\n"
1373 "\t packets, depending on whether the -V flag was specified.\n"
1374 "\t This is the default.\n"
1375 "\t\"tabs\" Similar to the text report except that each column of the\n"
1376 "\t human-readable one-line summary is delimited with an ASCII\n"
1377 "\t horizontal tab character.");
1378 exit_status = INVALID_OPTION;
1382 case 'U': /* Export PDUs to file */
1384 GSList *export_pdu_tap_name_list = NULL;
1387 cmdarg_err("A tap name is required. Valid names are:");
1388 for (export_pdu_tap_name_list = get_export_pdu_tap_list(); export_pdu_tap_name_list; export_pdu_tap_name_list = g_slist_next(export_pdu_tap_name_list)) {
1389 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1391 exit_status = INVALID_OPTION;
1394 pdu_export_arg = g_strdup(optarg);
1397 case 'v': /* Show version and exit */
1399 /* We don't really have to cleanup here, but it's a convenient way to test
1400 * start-up and shut-down of the epan library without any UI-specific
1401 * cruft getting in the way. Makes the results of running
1402 * $ ./tools/valgrind-wireshark -n
1403 * much more useful. */
1406 exit_status = EXIT_SUCCESS;
1408 case 'O': /* Only output these protocols */
1409 /* already processed; just ignore it now */
1411 case 'V': /* Verbose */
1412 /* already processed; just ignore it now */
1414 case 'x': /* Print packet data in hex (and ASCII) */
1415 /* already processed; just ignore it now */
1418 /* already processed; just ignore it now */
1424 /* We won't call the init function for the stat this soon
1425 as it would disallow MATE's fields (which are registered
1426 by the preferences set callback) from being used as
1427 part of a tap filter. Instead, we just add the argument
1428 to a list of stat arguments. */
1429 if (strcmp("help", optarg) == 0) {
1430 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1431 list_stat_cmd_args();
1432 exit_status = EXIT_SUCCESS;
1435 if (!process_stat_cmd_arg(optarg)) {
1436 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1437 list_stat_cmd_args();
1438 exit_status = INVALID_OPTION;
1442 case 'd': /* Decode as rule */
1443 case 'K': /* Kerberos keytab file */
1444 case 'n': /* No name resolution */
1445 case 'N': /* Select what types of addresses/port #s to resolve */
1446 case 't': /* Time stamp type */
1447 case 'u': /* Seconds type */
1448 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1449 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1450 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1451 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
1452 if (!dissect_opts_handle_opt(opt, optarg)) {
1453 exit_status = INVALID_OPTION;
1457 case LONGOPT_EXPORT_OBJECTS: /* --export-objects */
1458 if (strcmp("help", optarg) == 0) {
1459 fprintf(stderr, "tshark: The available export object types for the \"--export-objects\" option are:\n");
1460 eo_list_object_types();
1461 exit_status = EXIT_SUCCESS;
1464 if (!eo_tap_opt_add(optarg)) {
1465 exit_status = INVALID_OPTION;
1469 case LONGOPT_COLOR: /* print in color where appropriate */
1470 dissect_color = TRUE;
1472 case LONGOPT_NO_DUPLICATE_KEYS:
1473 no_duplicate_keys = TRUE;
1474 node_children_grouper = proto_node_group_children_by_json_key;
1477 case '?': /* Bad flag - print usage message */
1480 list_capture_types();
1483 print_usage(stderr);
1485 exit_status = INVALID_OPTION;
1492 * Print packet summary information is the default if neither -V or -x
1493 * were specified. Note that this is new behavior, which allows for the
1494 * possibility of printing only hex/ascii output without necessarily
1495 * requiring that either the summary or details be printed too.
1497 if (!print_summary && !print_details && !print_hex)
1498 print_summary = TRUE;
1500 if (no_duplicate_keys && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW) {
1501 cmdarg_err("--no-duplicate-keys can only be used with \"-T json\" and \"-T jsonraw\"");
1502 exit_status = INVALID_OPTION;
1506 /* If we specified output fields, but not the output field type... */
1507 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1508 cmdarg_err("Output fields were specified with \"-e\", "
1509 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1510 exit_status = INVALID_OPTION;
1512 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1513 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1514 "specified with \"-e\".");
1516 exit_status = INVALID_OPTION;
1520 if (dissect_color) {
1521 if (!color_filters_init(&err_msg, NULL)) {
1522 fprintf(stderr, "%s\n", err_msg);
1527 /* If no capture filter or display filter has been specified, and there are
1528 still command-line arguments, treat them as the tokens of a capture
1529 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1530 flag was specified. */
1531 if (optind < argc) {
1532 if (cf_name != NULL) {
1533 if (dfilter != NULL) {
1534 cmdarg_err("Display filters were specified both with \"-Y\" "
1535 "and with additional command-line arguments.");
1536 exit_status = INVALID_OPTION;
1539 dfilter = get_args_as_string(argc, argv, optind);
1544 if (global_capture_opts.default_options.cfilter) {
1545 cmdarg_err("A default capture filter was specified both with \"-f\""
1546 " and with additional command-line arguments.");
1547 exit_status = INVALID_OPTION;
1550 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1551 interface_options *interface_opts;
1552 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
1553 if (interface_opts->cfilter == NULL) {
1554 interface_opts->cfilter = get_args_as_string(argc, argv, optind);
1556 cmdarg_err("A capture filter was specified both with \"-f\""
1557 " and with additional command-line arguments.");
1558 exit_status = INVALID_OPTION;
1562 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1564 capture_option_specified = TRUE;
1569 if (!output_file_name) {
1570 /* We're not saving the capture to a file; if "-q" wasn't specified,
1571 we should print packet information */
1573 print_packet_info = TRUE;
1575 const char *save_file = output_file_name;
1576 /* We're saving to a file; if we're writing to the standard output.
1577 and we'll also be writing dissected packets to the standard
1578 output, reject the request. At best, we could redirect that
1579 to the standard error; we *can't* write both to the standard
1580 output and have either of them be useful. */
1581 if (strcmp(save_file, "-") == 0 && print_packet_info) {
1582 cmdarg_err("You can't write both raw packet data and dissected packets"
1583 " to the standard output.");
1584 exit_status = INVALID_OPTION;
1589 #ifndef HAVE_LIBPCAP
1590 if (capture_option_specified)
1591 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1594 print_usage(stderr);
1595 exit_status = INVALID_OPTION;
1600 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW && output_action != WRITE_EK) {
1601 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON, JSONRAW or EK JSON");
1602 exit_status = INVALID_OPTION;
1607 if (output_only != NULL) {
1610 if (!print_details) {
1611 cmdarg_err("-O requires -V");
1612 exit_status = INVALID_OPTION;
1616 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1617 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1618 const char *name = ps;
1619 header_field_info *hfi = proto_registrar_get_byalias(name);
1623 g_hash_table_insert(output_only_tables, (gpointer)name, (gpointer)name);
1627 if (rfilter != NULL && !perform_two_pass_analysis) {
1628 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1629 exit_status = INVALID_OPTION;
1635 /* We're supposed to list the link-layer/timestamp types for an interface;
1636 did the user also specify a capture file to be read? */
1638 /* Yes - that's bogus. */
1639 cmdarg_err("You can't specify %s and a capture file to be read.",
1640 caps_queries & CAPS_QUERY_LINK_TYPES ? "-L" : "--list-time-stamp-types");
1641 exit_status = INVALID_OPTION;
1644 /* No - did they specify a ring buffer option? */
1645 if (global_capture_opts.multi_files_on) {
1646 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1647 exit_status = INVALID_OPTION;
1653 * "-r" was specified, so we're reading a capture file.
1654 * Capture options don't apply here.
1657 /* We don't support capture filters when reading from a capture file
1658 (the BPF compiler doesn't support all link-layer types that we
1659 support in capture files we read). */
1660 if (global_capture_opts.default_options.cfilter) {
1661 cmdarg_err("Only read filters, not capture filters, "
1662 "can be specified when reading a capture file.");
1663 exit_status = INVALID_OPTION;
1666 if (global_capture_opts.multi_files_on) {
1667 cmdarg_err("Multiple capture files requested, but "
1668 "a capture isn't being done.");
1669 exit_status = INVALID_OPTION;
1672 if (global_capture_opts.has_file_duration) {
1673 cmdarg_err("Switching capture files after a time period was specified, but "
1674 "a capture isn't being done.");
1675 exit_status = INVALID_OPTION;
1678 if (global_capture_opts.has_file_interval) {
1679 cmdarg_err("Switching capture files after a time interval was specified, but "
1680 "a capture isn't being done.");
1681 exit_status = INVALID_OPTION;
1684 if (global_capture_opts.has_ring_num_files) {
1685 cmdarg_err("A ring buffer of capture files was specified, but "
1686 "a capture isn't being done.");
1687 exit_status = INVALID_OPTION;
1690 if (global_capture_opts.has_autostop_files) {
1691 cmdarg_err("A maximum number of capture files was specified, but "
1692 "a capture isn't being done.");
1693 exit_status = INVALID_OPTION;
1696 if (global_capture_opts.capture_comment) {
1697 cmdarg_err("A capture comment was specified, but "
1698 "a capture isn't being done.\nThere's no support for adding "
1699 "a capture comment to an existing capture file.");
1700 exit_status = INVALID_OPTION;
1704 /* Note: TShark now allows the restriction of a _read_ file by packet count
1705 * and byte count as well as a write file. Other autostop options remain valid
1706 * only for a write file.
1708 if (global_capture_opts.has_autostop_duration) {
1709 cmdarg_err("A maximum capture time was specified, but "
1710 "a capture isn't being done.");
1711 exit_status = INVALID_OPTION;
1716 * "-r" wasn't specified, so we're doing a live capture.
1718 if (perform_two_pass_analysis) {
1719 /* Two-pass analysis doesn't work with live capture since it requires us
1720 * to buffer packets until we've read all of them, but a live capture
1721 * has no useful/meaningful definition of "all" */
1722 cmdarg_err("Live captures do not support two-pass analysis.");
1723 exit_status = INVALID_OPTION;
1727 if (global_capture_opts.saving_to_file) {
1728 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1730 /* When capturing, we only support writing pcap or pcapng format. */
1731 if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1732 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1733 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1734 exit_status = INVALID_OPTION;
1737 if (global_capture_opts.capture_comment &&
1738 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1739 cmdarg_err("A capture comment can only be written to a pcapng file.");
1740 exit_status = INVALID_OPTION;
1743 if (global_capture_opts.multi_files_on) {
1744 /* Multiple-file mode doesn't work under certain conditions:
1745 a) it doesn't work if you're writing to the standard output;
1746 b) it doesn't work if you're writing to a pipe;
1748 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1749 cmdarg_err("Multiple capture files requested, but "
1750 "the capture is being written to the standard output.");
1751 exit_status = INVALID_OPTION;
1754 if (global_capture_opts.output_to_pipe) {
1755 cmdarg_err("Multiple capture files requested, but "
1756 "the capture file is a pipe.");
1757 exit_status = INVALID_OPTION;
1760 if (!global_capture_opts.has_autostop_filesize &&
1761 !global_capture_opts.has_file_duration &&
1762 !global_capture_opts.has_file_interval) {
1763 cmdarg_err("Multiple capture files requested, but "
1764 "no maximum capture file size, duration or interval was specified.");
1765 exit_status = INVALID_OPTION;
1769 /* Currently, we don't support read or display filters when capturing
1770 and saving the packets. */
1771 if (rfilter != NULL) {
1772 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1773 exit_status = INVALID_OPTION;
1776 if (dfilter != NULL) {
1777 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1778 exit_status = INVALID_OPTION;
1781 global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1783 /* They didn't specify a "-w" flag, so we won't be saving to a
1784 capture file. Check for options that only make sense if
1785 we're saving to a file. */
1786 if (global_capture_opts.has_autostop_filesize) {
1787 cmdarg_err("Maximum capture file size specified, but "
1788 "capture isn't being saved to a file.");
1789 exit_status = INVALID_OPTION;
1792 if (global_capture_opts.multi_files_on) {
1793 cmdarg_err("Multiple capture files requested, but "
1794 "the capture isn't being saved to a file.");
1795 exit_status = INVALID_OPTION;
1798 if (global_capture_opts.capture_comment) {
1799 cmdarg_err("A capture comment was specified, but "
1800 "the capture isn't being saved to a file.");
1801 exit_status = INVALID_OPTION;
1809 err_msg = ws_init_sockets();
1810 if (err_msg != NULL)
1812 cmdarg_err("%s", err_msg);
1814 cmdarg_err_cont("%s", please_report_bug());
1815 exit_status = INIT_FAILED;
1819 /* Notify all registered modules that have had any of their preferences
1820 changed either from one of the preferences file or from the command
1821 line that their preferences have changed. */
1824 /* We can also enable specified taps for export object */
1825 start_exportobjects();
1827 /* At this point MATE will have registered its field array so we can
1828 check if the fields specified by the user are all good.
1832 GSList *invalid_fields = output_fields_valid(output_fields);
1833 if (invalid_fields != NULL) {
1835 cmdarg_err("Some fields aren't valid:");
1836 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1837 cmdarg_err_cont("\t%s", (gchar *)it->data);
1839 g_slist_free(invalid_fields);
1840 exit_status = INVALID_OPTION;
1845 /* We currently don't support taps, or printing dissected packets,
1846 if we're writing to a pipe. */
1847 if (global_capture_opts.saving_to_file &&
1848 global_capture_opts.output_to_pipe) {
1849 if (tap_listeners_require_dissection()) {
1850 cmdarg_err("Taps aren't supported when saving to a pipe.");
1851 exit_status = INVALID_OPTION;
1854 if (print_packet_info) {
1855 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1856 exit_status = INVALID_OPTION;
1862 if (ex_opt_count("read_format") > 0) {
1863 const gchar* name = ex_opt_get_next("read_format");
1864 in_file_type = open_info_name_to_type(name);
1865 if (in_file_type == WTAP_TYPE_AUTO) {
1866 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1867 list_read_capture_types();
1868 exit_status = INVALID_OPTION;
1873 timestamp_set_type(global_dissect_options.time_format);
1876 * Enabled and disabled protocols and heuristic dissectors as per
1877 * command-line options.
1879 if (!setup_enabled_and_disabled_protocols()) {
1880 exit_status = INVALID_OPTION;
1884 /* Build the column format array */
1885 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1888 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1889 capture_opts_trim_ring_num_files(&global_capture_opts);
1892 if (rfilter != NULL) {
1893 tshark_debug("Compiling read filter: '%s'", rfilter);
1894 if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1895 cmdarg_err("%s", err_msg);
1902 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1904 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1906 " Note: That read filter code looks like a valid capture filter;\n"
1907 " maybe you mixed them up?");
1913 exit_status = INVALID_INTERFACE;
1917 cfile.rfcode = rfcode;
1919 if (dfilter != NULL) {
1920 tshark_debug("Compiling display filter: '%s'", dfilter);
1921 if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1922 cmdarg_err("%s", err_msg);
1929 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1931 if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1933 " Note: That display filter code looks like a valid capture filter;\n"
1934 " maybe you mixed them up?");
1940 exit_status = INVALID_FILTER;
1944 cfile.dfcode = dfcode;
1946 if (print_packet_info) {
1947 /* If we're printing as text or PostScript, we have
1948 to create a print stream. */
1949 if (output_action == WRITE_TEXT) {
1950 switch (print_format) {
1953 print_stream = print_stream_text_stdio_new(stdout);
1957 print_stream = print_stream_ps_stdio_new(stdout);
1961 g_assert_not_reached();
1966 /* PDU export requested. Take the ownership of the '-w' file, apply tap
1967 * filters and start tapping. */
1968 if (pdu_export_arg) {
1969 const char *exp_pdu_tap_name = pdu_export_arg;
1970 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1971 char *exp_pdu_error;
1976 cmdarg_err("PDUs export requires a capture file (specify with -r).");
1977 exit_status = INVALID_OPTION;
1980 /* Take ownership of the '-w' output file. */
1981 exp_pdu_filename = output_file_name;
1982 output_file_name = NULL;
1984 global_capture_opts.save_file = NULL;
1986 if (exp_pdu_filename == NULL) {
1987 cmdarg_err("PDUs export requires an output file (-w).");
1988 exit_status = INVALID_OPTION;
1992 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1994 if (exp_pdu_error) {
1995 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1996 g_free(exp_pdu_error);
1997 exit_status = INVALID_TAP;
2001 if (strcmp(exp_pdu_filename, "-") == 0) {
2002 /* Write to the standard output. */
2005 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2007 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
2008 exit_status = INVALID_FILE;
2013 /* Activate the export PDU tap */
2014 comment = g_strdup_printf("Dump of PDUs from %s", cf_name);
2015 exp_pdu_status = exp_pdu_open(&exp_pdu_tap_data, exp_fd, comment,
2018 if (!exp_pdu_status) {
2019 cfile_dump_open_failure_message("TShark", exp_pdu_filename,
2021 WTAP_FILE_TYPE_SUBTYPE_PCAPNG);
2022 exit_status = INVALID_EXPORT;
2027 tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2030 tshark_debug("tshark: Opening capture file: %s", cf_name);
2032 * We're reading a capture file.
2034 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
2037 exit_status = INVALID_FILE;
2041 /* Start statistics taps; we do so after successfully opening the
2042 capture file, so we know we have something to compute stats
2043 on, and after registering all dissectors, so that MATE will
2044 have registered its field array so we can have a tap filter
2045 with one of MATE's late-registered fields as part of the
2047 start_requested_stats();
2049 /* Do we need to do dissection of packets? That depends on, among
2050 other things, what taps are listening, so determine that after
2051 starting the statistics taps. */
2052 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2054 /* Process the packets in the file */
2055 tshark_debug("tshark: invoking process_cap_file() to process the packets");
2057 status = process_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res,
2059 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
2060 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
2066 CATCH(OutOfMemoryError) {
2070 "Sorry, but TShark has to terminate now.\n"
2072 "More information and workarounds can be found at\n"
2073 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
2074 status = PROCESS_FILE_ERROR;
2080 case PROCESS_FILE_SUCCEEDED:
2081 /* Everything worked OK; draw the taps. */
2085 case PROCESS_FILE_NO_FILE_PROCESSED:
2086 /* We never got to try to read the file, so there are no tap
2087 results to dump. Exit with an error status. */
2091 case PROCESS_FILE_ERROR:
2092 /* We still dump out the results of taps, etc., as we might have
2093 read some packets; however, we exit with an error status. */
2098 case PROCESS_FILE_INTERRUPTED:
2099 /* The user interrupted the read process; Don't dump out the
2100 result of taps, etc., and exit with an error status. */
2105 if (pdu_export_arg) {
2106 if (!exp_pdu_close(&exp_pdu_tap_data, &err, &err_info)) {
2107 cfile_close_failure_message(exp_pdu_filename, err, err_info);
2110 g_free(pdu_export_arg);
2111 g_free(exp_pdu_filename);
2114 tshark_debug("tshark: no capture file specified");
2115 /* No capture file specified, so we're supposed to do a live capture
2116 or get a list of link-layer types for a live capture device;
2117 do we have support for live captures? */
2120 /* Warn the user if npf.sys isn't loaded. */
2121 if (!npf_sys_is_running()) {
2122 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
2123 "capturing or\nlisting interfaces.\n");
2127 /* if no interface was specified, pick a default */
2128 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
2129 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
2130 if (exit_status != 0) {
2134 /* if requested, list the link layer types and exit */
2138 /* Get the list of link-layer types for the capture devices. */
2139 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2140 interface_options *interface_opts;
2141 if_capabilities_t *caps;
2142 char *auth_str = NULL;
2143 int if_caps_queries = caps_queries;
2145 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2146 #ifdef HAVE_PCAP_REMOTE
2147 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
2148 auth_str = g_strdup_printf("%s:%s", interface_opts->auth_username, interface_opts->auth_password);
2151 caps = capture_get_if_capabilities(interface_opts->name, interface_opts->monitor_mode, auth_str, &err_str, NULL);
2154 cmdarg_err("%s", err_str);
2156 exit_status = INVALID_CAPABILITY;
2159 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
2160 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
2161 exit_status = INVALID_DATA_LINK;
2164 if ((if_caps_queries & CAPS_QUERY_TIMESTAMP_TYPES) && caps->timestamp_types == NULL) {
2165 cmdarg_err("The capture device \"%s\" has no timestamp types.", interface_opts->name);
2166 exit_status = INVALID_TIMESTAMP_TYPE;
2169 if (interface_opts->monitor_mode)
2170 if_caps_queries |= CAPS_MONITOR_MODE;
2171 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
2172 free_if_capabilities(caps);
2174 exit_status = EXIT_SUCCESS;
2179 * If the standard error isn't a terminal, don't print packet counts,
2180 * as they won't show up on the user's terminal and they'll get in
2181 * the way of error messages in the file (to which we assume the
2182 * standard error was redirected; if it's redirected to the null
2183 * device, there's no point in printing packet counts anyway).
2185 * Otherwise, if we're printing packet information and the standard
2186 * output is a terminal (which we assume means the standard output and
2187 * error are going to the same terminal), don't print packet counts,
2188 * as they'll get in the way of the packet information.
2190 * Otherwise, if the user specified -q, don't print packet counts.
2192 * Otherwise, print packet counts.
2194 * XXX - what if the user wants to do a live capture, doesn't want
2195 * to save it to a file, doesn't want information printed for each
2196 * packet, does want some "-z" statistic, and wants packet counts
2197 * so they know whether they're seeing any packets? -q will
2198 * suppress the information printed for each packet, but it'll
2199 * also suppress the packet counts.
2201 if (!ws_isatty(ws_fileno(stderr)))
2202 print_packet_counts = FALSE;
2203 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
2204 print_packet_counts = FALSE;
2206 print_packet_counts = FALSE;
2208 print_packet_counts = TRUE;
2210 if (print_packet_info) {
2211 if (!write_preamble(&cfile)) {
2212 show_print_file_io_error(errno);
2213 exit_status = INVALID_FILE;
2218 tshark_debug("tshark: performing live capture");
2220 /* Start statistics taps; we should only do so after the capture
2221 started successfully, so we know we have something to compute
2222 stats, but we currently don't check for that - see below.
2224 We do so after registering all dissectors, so that MATE will
2225 have registered its field array so we can have a tap filter
2226 with one of MATE's late-registered fields as part of the
2228 start_requested_stats();
2230 /* Do we need to do dissection of packets? That depends on, among
2231 other things, what taps are listening, so determine that after
2232 starting the statistics taps. */
2233 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2236 * XXX - this returns FALSE if an error occurred, but it also
2237 * returns FALSE if the capture stops because a time limit
2238 * was reached (and possibly other limits), so we can't assume
2239 * it means an error.
2241 * The capture code is a bit twisty, so it doesn't appear to
2242 * be an easy fix. We just ignore the return value for now.
2243 * Instead, pass on the exit status from the capture child.
2246 exit_status = global_capture_session.fork_child_status;
2248 if (print_packet_info) {
2249 if (!write_finale()) {
2250 show_print_file_io_error(errno);
2255 * If we never got a capture file, don't draw the taps; we not only
2256 * didn't capture any packets, we never even did any capturing.
2258 if (cfile.filename != NULL)
2261 /* No - complain. */
2262 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2263 exit_status = INVALID_CAPTURE;
2268 if (cfile.provider.frames != NULL) {
2269 free_frame_data_sequence(cfile.provider.frames);
2270 cfile.provider.frames = NULL;
2274 draw_tap_listeners(TRUE);
2275 /* Memory cleanup */
2276 reset_tap_listeners();
2277 funnel_dump_all_text_windows();
2278 epan_free(cfile.epan);
2282 output_fields_free(output_fields);
2283 output_fields = NULL;
2288 destroy_print_stream(print_stream);
2289 g_free(output_file_name);
2291 capture_opts_cleanup(&global_capture_opts);
2293 col_cleanup(&cfile.cinfo);
2294 free_filter_lists();
2297 dfilter_free(dfcode);
2301 /*#define USE_BROKEN_G_MAIN_LOOP*/
2303 #ifdef USE_BROKEN_G_MAIN_LOOP
2306 gboolean loop_running = FALSE;
2308 guint32 packet_count = 0;
2311 typedef struct pipe_input_tag {
2314 ws_process_id *child_process;
2315 pipe_input_cb_t input_cb;
2316 guint pipe_input_id;
2318 GMutex *callback_running;
2322 static pipe_input_t pipe_input;
2325 /* The timer has expired, see if there's stuff to read from the pipe,
2326 if so, do the callback */
2328 pipe_timer_cb(gpointer data)
2334 pipe_input_t *pipe_input_p = data;
2335 gint iterations = 0;
2337 g_mutex_lock (pipe_input_p->callback_running);
2339 /* try to read data from the pipe only 5 times, to avoid blocking */
2340 while(iterations < 5) {
2341 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2343 /* Oddly enough although Named pipes don't work on win9x,
2344 PeekNamedPipe does !!! */
2345 handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2346 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2348 /* Get the child process exit status */
2349 GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2352 /* If the Peek returned an error, or there are bytes to be read
2353 or the childwatcher thread has terminated then call the normal
2355 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2357 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2359 /* And call the real handler */
2360 if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2361 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2362 /* pipe closed, return false so that the timer is stopped */
2363 g_mutex_unlock (pipe_input_p->callback_running);
2368 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2369 /* No data, stop now */
2376 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2378 g_mutex_unlock (pipe_input_p->callback_running);
2380 /* we didn't stopped the timer, so let it run */
2387 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2390 pipe_input.source = source;
2391 pipe_input.child_process = child_process;
2392 pipe_input.user_data = user_data;
2393 pipe_input.input_cb = input_cb;
2396 pipe_input.callback_running = g_malloc(sizeof(GMutex));
2397 g_mutex_init(pipe_input.callback_running);
2398 /* Tricky to use pipes in win9x, as no concept of wait. NT can
2399 do this but that doesn't cover all win32 platforms. GTK can do
2400 this but doesn't seem to work over processes. Attempt to do
2401 something similar here, start a timer and check for data on every
2403 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2404 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2408 static const nstime_t *
2409 tshark_get_frame_ts(struct packet_provider_data *prov, guint32 frame_num)
2411 if (prov->ref && prov->ref->num == frame_num)
2412 return &prov->ref->abs_ts;
2414 if (prov->prev_dis && prov->prev_dis->num == frame_num)
2415 return &prov->prev_dis->abs_ts;
2417 if (prov->prev_cap && prov->prev_cap->num == frame_num)
2418 return &prov->prev_cap->abs_ts;
2421 frame_data *fd = frame_data_sequence_find(prov->frames, frame_num);
2423 return (fd) ? &fd->abs_ts : NULL;
2430 tshark_epan_new(capture_file *cf)
2432 static const struct packet_provider_funcs funcs = {
2433 tshark_get_frame_ts,
2434 cap_file_provider_get_interface_name,
2435 cap_file_provider_get_interface_description,
2439 return epan_new(&cf->provider, &funcs);
2446 volatile gboolean ret = TRUE;
2449 #ifdef USE_TSHARK_SELECT
2453 struct sigaction action, oldaction;
2456 /* Create new dissection section. */
2457 epan_free(cfile.epan);
2458 cfile.epan = tshark_epan_new(&cfile);
2461 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2462 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2464 /* Catch SIGINT and SIGTERM and, if we get either of them,
2465 clean up and exit. If SIGHUP isn't being ignored, catch
2466 it too and, if we get it, clean up and exit.
2468 We restart any read that was in progress, so that it doesn't
2469 disrupt reading from the sync pipe. The signal handler tells
2470 the capture child to finish; it will report that it finished,
2471 or will exit abnormally, so we'll stop reading from the sync
2472 pipe, pick up the exit status, and quit. */
2473 memset(&action, 0, sizeof(action));
2474 action.sa_handler = capture_cleanup;
2475 action.sa_flags = SA_RESTART;
2476 sigemptyset(&action.sa_mask);
2477 sigaction(SIGTERM, &action, NULL);
2478 sigaction(SIGINT, &action, NULL);
2479 sigaction(SIGHUP, NULL, &oldaction);
2480 if (oldaction.sa_handler == SIG_DFL)
2481 sigaction(SIGHUP, &action, NULL);
2484 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2485 quiet mode, report the number of packets we've captured.
2487 Again, restart any read that was in progress, so that it doesn't
2488 disrupt reading from the sync pipe. */
2489 action.sa_handler = report_counts_siginfo;
2490 action.sa_flags = SA_RESTART;
2491 sigemptyset(&action.sa_mask);
2492 sigaction(SIGINFO, &action, NULL);
2493 #endif /* SIGINFO */
2496 global_capture_session.state = CAPTURE_PREPARING;
2498 /* Let the user know which interfaces were chosen. */
2499 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2500 interface_options *interface_opts;
2502 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2503 g_free(interface_opts->descr);
2504 interface_opts->descr = get_interface_descriptive_name(interface_opts->name);
2506 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2507 if (really_quiet == FALSE)
2508 fprintf(stderr, "Capturing on %s\n", str->str);
2510 g_string_free(str, TRUE);
2512 ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2518 * Force synchronous resolution of IP addresses; we're doing only
2519 * one pass, so we can't do it in the background and fix up past
2522 set_resolution_synchrony(TRUE);
2524 /* the actual capture loop
2526 * XXX - glib doesn't seem to provide any event based loop handling.
2528 * XXX - for whatever reason,
2529 * calling g_main_loop_new() ends up in 100% cpu load.
2531 * But that doesn't matter: in UNIX we can use select() to find an input
2532 * source with something to do.
2534 * But that doesn't matter because we're in a CLI (that doesn't need to
2535 * update a GUI or something at the same time) so it's OK if we block
2536 * trying to read from the pipe.
2538 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2539 * wrong (but I leave it there in case I am...).
2542 #ifdef USE_TSHARK_SELECT
2544 FD_SET(pipe_input.source, &readfds);
2547 loop_running = TRUE;
2551 while (loop_running)
2553 #ifdef USE_TSHARK_SELECT
2554 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2558 fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2560 loop_running = FALSE;
2561 } else if (ret == 1) {
2563 /* Call the real handler */
2564 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2565 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2567 loop_running = FALSE;
2569 #ifdef USE_TSHARK_SELECT
2574 CATCH(OutOfMemoryError) {
2578 "Sorry, but TShark has to terminate now.\n"
2580 "More information and workarounds can be found at\n"
2581 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
2588 /* capture child detected an error */
2590 capture_input_error(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2592 cmdarg_err("%s", error_msg);
2593 cmdarg_err_cont("%s", secondary_error_msg);
2597 /* capture child detected an capture filter related error */
2599 capture_input_cfilter_error(capture_session *cap_session, guint i, const char *error_message)
2601 capture_options *capture_opts = cap_session->capture_opts;
2602 dfilter_t *rfcode = NULL;
2603 interface_options *interface_opts;
2605 g_assert(i < capture_opts->ifaces->len);
2606 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2608 if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
2610 "Invalid capture filter \"%s\" for interface '%s'.\n"
2612 "That string looks like a valid display filter; however, it isn't a valid\n"
2613 "capture filter (%s).\n"
2615 "Note that display filters and capture filters don't have the same syntax,\n"
2616 "so you can't use most display filter expressions as capture filters.\n"
2618 "See the User's Guide for a description of the capture filter syntax.",
2619 interface_opts->cfilter, interface_opts->descr, error_message);
2620 dfilter_free(rfcode);
2623 "Invalid capture filter \"%s\" for interface '%s'.\n"
2625 "That string isn't a valid capture filter (%s).\n"
2626 "See the User's Guide for a description of the capture filter syntax.",
2627 interface_opts->cfilter, interface_opts->descr, error_message);
2632 /* capture child tells us we have a new (or the first) capture file */
2634 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2636 capture_options *capture_opts = cap_session->capture_opts;
2637 capture_file *cf = cap_session->cf;
2638 gboolean is_tempfile;
2641 if (cap_session->state == CAPTURE_PREPARING) {
2642 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2644 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2646 g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2648 /* free the old filename */
2649 if (capture_opts->save_file != NULL) {
2651 /* we start a new capture file, close the old one (if we had one before) */
2652 if (cf->state != FILE_CLOSED) {
2656 g_free(capture_opts->save_file);
2657 is_tempfile = FALSE;
2659 epan_free(cf->epan);
2660 cf->epan = tshark_epan_new(cf);
2662 /* we didn't had a save_file before, must be a tempfile */
2666 /* save the new filename */
2667 capture_opts->save_file = g_strdup(new_file);
2669 /* if we are in real-time mode, open the new file now */
2670 if (do_dissection) {
2671 /* this is probably unecessary, but better safe than sorry */
2672 cap_session->cf->open_type = WTAP_TYPE_AUTO;
2673 /* Attempt to open the capture file and set up to read from it. */
2674 switch(cf_open(cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2678 /* Don't unlink (delete) the save file - leave it around,
2679 for debugging purposes. */
2680 g_free(capture_opts->save_file);
2681 capture_opts->save_file = NULL;
2686 cap_session->state = CAPTURE_RUNNING;
2692 /* capture child tells us we have new packets to read */
2694 capture_input_new_packets(capture_session *cap_session, int to_read)
2700 capture_file *cf = cap_session->cf;
2701 gboolean filtering_tap_listeners;
2706 * Prevent a SIGINFO handler from writing to the standard error while
2707 * we're doing so or writing to the standard output; instead, have it
2708 * just set a flag telling us to print that information when we're done.
2711 #endif /* SIGINFO */
2713 /* Do we have any tap listeners with filters? */
2714 filtering_tap_listeners = have_filtering_tap_listeners();
2716 /* Get the union of the flags for all tap listeners. */
2717 tap_flags = union_of_tap_listener_flags();
2719 if (do_dissection) {
2720 gboolean create_proto_tree;
2721 epan_dissect_t *edt;
2726 * Determine whether we need to create a protocol tree.
2729 * we're going to apply a read filter;
2731 * we're going to apply a display filter;
2733 * we're going to print the protocol tree;
2735 * one of the tap listeners is going to apply a filter;
2737 * one of the tap listeners requires a protocol tree;
2739 * a postdissector wants field values or protocols
2740 * on the first pass;
2742 * we have custom columns (which require field values, which
2743 * currently requires that we build a protocol tree).
2746 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2747 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
2748 have_custom_cols(&cf->cinfo) || dissect_color);
2750 /* The protocol tree will be "visible", i.e., printed, only if we're
2751 printing packet details, which is true if we're printing stuff
2752 ("print_packet_info" is true) and we're in verbose mode
2753 ("packet_details" is true). */
2754 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2756 wtap_rec_init(&rec);
2757 ws_buffer_init(&buf, 1514);
2759 while (to_read-- && cf->provider.wth) {
2760 wtap_cleareof(cf->provider.wth);
2761 ret = wtap_read(cf->provider.wth, &rec, &buf, &err, &err_info, &data_offset);
2762 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
2764 /* read from file failed, tell the capture child to stop */
2765 sync_pipe_stop(cap_session);
2766 wtap_close(cf->provider.wth);
2767 cf->provider.wth = NULL;
2769 ret = process_packet_single_pass(cf, edt, data_offset, &rec, &buf,
2773 /* packet successfully read and gone through the "Read Filter" */
2778 epan_dissect_free(edt);
2780 wtap_rec_cleanup(&rec);
2781 ws_buffer_free(&buf);
2785 * Dumpcap's doing all the work; we're not doing any dissection.
2786 * Count all the packets it wrote.
2788 packet_count += to_read;
2791 if (print_packet_counts) {
2792 /* We're printing packet counts. */
2793 if (packet_count != 0) {
2794 fprintf(stderr, "\r%u ", packet_count);
2795 /* stderr could be line buffered */
2802 * Allow SIGINFO handlers to write.
2807 * If a SIGINFO handler asked us to write out capture counts, do so.
2811 #endif /* SIGINFO */
2817 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2818 /* Report the count only if we aren't printing a packet count
2819 as packets arrive. */
2820 fprintf(stderr, "%u packet%s captured\n", packet_count,
2821 plurality(packet_count, "", "s"));
2824 infoprint = FALSE; /* we just reported it */
2825 #endif /* SIGINFO */
2830 report_counts_siginfo(int signum _U_)
2832 int sav_errno = errno;
2833 /* If we've been told to delay printing, just set a flag asking
2834 that we print counts (if we're supposed to), otherwise print
2835 the count of packets captured (if we're supposed to). */
2842 #endif /* SIGINFO */
2845 /* capture child detected any packet drops? */
2847 capture_input_drops(capture_session *cap_session _U_, guint32 dropped, const char* interface_name)
2849 if (print_packet_counts) {
2850 /* We're printing packet counts to stderr.
2851 Send a newline so that we move to the line after the packet count. */
2852 fprintf(stderr, "\n");
2856 /* We're printing packet counts to stderr.
2857 Send a newline so that we move to the line after the packet count. */
2858 if (interface_name != NULL) {
2859 fprintf(stderr, "%u packet%s dropped from %s\n", dropped, plurality(dropped, "", "s"), interface_name);
2861 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2868 * Capture child closed its side of the pipe, report any error and
2869 * do the required cleanup.
2872 capture_input_closed(capture_session *cap_session _U_, gchar *msg)
2875 fprintf(stderr, "tshark: %s\n", msg);
2879 #ifdef USE_BROKEN_G_MAIN_LOOP
2880 /*g_main_loop_quit(loop);*/
2881 g_main_loop_quit(loop);
2883 loop_running = FALSE;
2889 capture_cleanup(DWORD ctrltype _U_)
2891 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2892 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2893 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2894 like SIGTERM at least when the machine's shutting down.
2896 For now, we handle them all as indications that we should clean up
2897 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2900 We must return TRUE so that no other handler - such as one that would
2901 terminate the process - gets called.
2903 XXX - for some reason, typing ^C to TShark, if you run this in
2904 a Cygwin console window in at least some versions of Cygwin,
2905 causes TShark to terminate immediately; this routine gets
2906 called, but the main loop doesn't get a chance to run and
2907 exit cleanly, at least if this is compiled with Microsoft Visual
2908 C++ (i.e., it's a property of the Cygwin console window or Bash;
2909 it happens if TShark is not built with Cygwin - for all I know,
2910 building it with Cygwin may make the problem go away). */
2912 /* tell the capture child to stop */
2913 sync_pipe_stop(&global_capture_session);
2915 /* don't stop our own loop already here, otherwise status messages and
2916 * cleanup wouldn't be done properly. The child will indicate the stop of
2917 * everything by calling capture_input_closed() later */
2923 capture_cleanup(int signum _U_)
2925 /* tell the capture child to stop */
2926 sync_pipe_stop(&global_capture_session);
2928 /* don't stop our own loop already here, otherwise status messages and
2929 * cleanup wouldn't be done properly. The child will indicate the stop of
2930 * everything by calling capture_input_closed() later */
2933 #endif /* HAVE_LIBPCAP */
2936 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2937 gint64 offset, wtap_rec *rec, Buffer *buf)
2943 /* The frame number of this packet is one more than the count of
2944 frames in this packet. */
2945 framenum = cf->count + 1;
2947 /* If we're not running a display filter and we're not printing any
2948 packet information, we don't need to do a dissection. This means
2949 that all packets can be marked as 'passed'. */
2952 frame_data_init(&fdlocal, framenum, rec, offset, cum_bytes);
2954 /* If we're going to run a read filter or a display filter, set up to
2955 do a dissection and do so. (This is the first pass of two passes
2956 over the packets, so we will not be printing any information
2957 from the dissection or running taps on the packet; if we're doing
2958 any of that, we'll do it in the second pass.) */
2960 /* If we're running a read filter, prime the epan_dissect_t with that
2963 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
2966 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2968 /* This is the first pass, so prime the epan_dissect_t with the
2969 hfids postdissectors want on the first pass. */
2970 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
2972 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2973 &cf->provider.ref, cf->provider.prev_dis);
2974 if (cf->provider.ref == &fdlocal) {
2975 ref_frame = fdlocal;
2976 cf->provider.ref = &ref_frame;
2979 epan_dissect_run(edt, cf->cd_t, rec,
2980 frame_tvbuff_new_buffer(&cf->provider, &fdlocal, buf),
2983 /* Run the read filter if we have one. */
2985 passed = dfilter_apply_edt(cf->rfcode, edt);
2989 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2990 cf->provider.prev_cap = cf->provider.prev_dis = frame_data_sequence_add(cf->provider.frames, &fdlocal);
2992 /* If we're not doing dissection then there won't be any dependent frames.
2993 * More importantly, edt.pi.dependent_frames won't be initialized because
2994 * epan hasn't been initialized.
2995 * if we *are* doing dissection, then mark the dependent frames, but only
2996 * if a display filter was given and it matches this packet.
2998 if (edt && cf->dfcode) {
2999 if (dfilter_apply_edt(cf->dfcode, edt)) {
3000 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
3006 /* if we don't add it to the frame_data_sequence, clean it up right now
3008 frame_data_destroy(&fdlocal);
3012 epan_dissect_reset(edt);
3018 * Set if reading a file was interrupted by a CTRL_ event on Windows or
3021 static gboolean read_interrupted = FALSE;
3025 read_cleanup(DWORD ctrltype _U_)
3027 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
3028 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
3029 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
3030 like SIGTERM at least when the machine's shutting down.
3032 For now, we handle them all as indications that we should clean up
3033 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
3036 We must return TRUE so that no other handler - such as one that would
3037 terminate the process - gets called.
3039 XXX - for some reason, typing ^C to TShark, if you run this in
3040 a Cygwin console window in at least some versions of Cygwin,
3041 causes TShark to terminate immediately; this routine gets
3042 called, but the main loop doesn't get a chance to run and
3043 exit cleanly, at least if this is compiled with Microsoft Visual
3044 C++ (i.e., it's a property of the Cygwin console window or Bash;
3045 it happens if TShark is not built with Cygwin - for all I know,
3046 building it with Cygwin may make the problem go away). */
3048 /* tell the read to stop */
3049 read_interrupted = TRUE;
3055 read_cleanup(int signum _U_)
3057 /* tell the read to stop */
3058 read_interrupted = TRUE;
3069 static pass_status_t
3070 process_cap_file_first_pass(capture_file *cf, int max_packet_count,
3071 gint64 max_byte_count, int *err, gchar **err_info)
3075 epan_dissect_t *edt = NULL;
3077 pass_status_t status = PASS_SUCCEEDED;
3079 wtap_rec_init(&rec);
3080 ws_buffer_init(&buf, 1514);
3082 /* Allocate a frame_data_sequence for all the frames. */
3083 cf->provider.frames = new_frame_data_sequence();
3085 if (do_dissection) {
3086 gboolean create_proto_tree;
3089 * Determine whether we need to create a protocol tree.
3092 * we're going to apply a read filter;
3094 * we're going to apply a display filter;
3096 * a postdissector wants field values or protocols
3097 * on the first pass.
3100 (cf->rfcode != NULL || cf->dfcode != NULL || postdissectors_want_hfids() || dissect_color);
3102 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3104 /* We're not going to display the protocol tree on this pass,
3105 so it's not going to be "visible". */
3106 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
3109 tshark_debug("tshark: reading records for first pass");
3111 while (wtap_read(cf->provider.wth, &rec, &buf, err, err_info, &data_offset)) {
3112 if (read_interrupted) {
3113 status = PASS_INTERRUPTED;
3116 if (process_packet_first_pass(cf, edt, data_offset, &rec, &buf)) {
3117 /* Stop reading if we have the maximum number of packets;
3118 * When the -c option has not been used, max_packet_count
3119 * starts at 0, which practically means, never stop reading.
3120 * (unless we roll over max_packet_count ?)
3122 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3123 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3124 max_packet_count, data_offset, max_byte_count);
3125 *err = 0; /* This is not an error */
3131 status = PASS_READ_ERROR;
3134 epan_dissect_free(edt);
3136 /* Close the sequential I/O side, to free up memory it requires. */
3137 wtap_sequential_close(cf->provider.wth);
3139 /* Allow the protocol dissectors to free up memory that they
3140 * don't need after the sequential run-through of the packets. */
3141 postseq_cleanup_all_protocols();
3143 cf->provider.prev_dis = NULL;
3144 cf->provider.prev_cap = NULL;
3146 ws_buffer_free(&buf);
3147 wtap_rec_cleanup(&rec);
3153 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
3154 frame_data *fdata, wtap_rec *rec,
3155 Buffer *buf, guint tap_flags)
3160 /* If we're not running a display filter and we're not printing any
3161 packet information, we don't need to do a dissection. This means
3162 that all packets can be marked as 'passed'. */
3165 /* If we're going to print packet information, or we're going to
3166 run a read filter, or we're going to process taps, set up to
3167 do a dissection and do so. (This is the second pass of two
3168 passes over the packets; that's the pass where we print
3169 packet information or run taps.) */
3171 /* If we're running a display filter, prime the epan_dissect_t with that
3174 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3176 col_custom_prime_edt(edt, &cf->cinfo);
3178 /* We only need the columns if either
3179 1) some tap needs the columns
3181 2) we're printing packet info but we're *not* verbose; in verbose
3182 mode, we print the protocol tree, not the protocol summary.
3184 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3189 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
3190 &cf->provider.ref, cf->provider.prev_dis);
3191 if (cf->provider.ref == fdata) {
3193 cf->provider.ref = &ref_frame;
3196 if (dissect_color) {
3197 color_filters_prime_edt(edt);
3198 fdata->need_colorize = 1;
3201 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
3202 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3205 /* Run the read/display filter if we have one. */
3207 passed = dfilter_apply_edt(cf->dfcode, edt);
3211 frame_data_set_after_dissect(fdata, &cum_bytes);
3212 /* Process this packet. */
3213 if (print_packet_info) {
3214 /* We're printing packet information; print the information for
3216 print_packet(cf, edt);
3218 /* If we're doing "line-buffering", flush the standard output
3219 after every packet. See the comment above, for the "-l"
3220 option, for an explanation of why we do that. */
3224 if (ferror(stdout)) {
3225 show_print_file_io_error(errno);
3229 cf->provider.prev_dis = fdata;
3231 cf->provider.prev_cap = fdata;
3234 epan_dissect_reset(edt);
3236 return passed || fdata->dependent_of_displayed;
3240 process_new_idbs(wtap *wth, wtap_dumper *pdh, int *err, gchar **err_info)
3242 wtap_block_t if_data;
3244 while ((if_data = wtap_get_next_interface_description(wth)) != NULL) {
3246 * Only add IDBs if we're writing to a file and the output file
3247 * requires interface IDs; otherwise, it doesn't support writing IDBs.
3250 if (wtap_uses_interface_ids(wtap_dump_file_type_subtype(pdh))) {
3251 if (!wtap_dump_add_idb(pdh, if_data, err, err_info))
3259 static pass_status_t
3260 process_cap_file_second_pass(capture_file *cf, wtap_dumper *pdh,
3261 int *err, gchar **err_info,
3262 volatile guint32 *err_framenum)
3268 gboolean filtering_tap_listeners;
3270 epan_dissect_t *edt = NULL;
3271 pass_status_t status = PASS_SUCCEEDED;
3274 * Process whatever IDBs we haven't seen yet. This will be all
3275 * the IDBs in the file, as we've finished reading it; they'll
3276 * all be at the beginning of the output file.
3278 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3280 return PASS_WRITE_ERROR;
3283 wtap_rec_init(&rec);
3284 ws_buffer_init(&buf, 1514);
3286 /* Do we have any tap listeners with filters? */
3287 filtering_tap_listeners = have_filtering_tap_listeners();
3289 /* Get the union of the flags for all tap listeners. */
3290 tap_flags = union_of_tap_listener_flags();
3292 if (do_dissection) {
3293 gboolean create_proto_tree;
3296 * Determine whether we need to create a protocol tree.
3299 * we're going to apply a display filter;
3301 * we're going to print the protocol tree;
3303 * one of the tap listeners requires a protocol tree;
3305 * we have custom columns (which require field values, which
3306 * currently requires that we build a protocol tree).
3309 (cf->dfcode || print_details || filtering_tap_listeners ||
3310 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo) || dissect_color);
3312 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3314 /* The protocol tree will be "visible", i.e., printed, only if we're
3315 printing packet details, which is true if we're printing stuff
3316 ("print_packet_info" is true) and we're in verbose mode
3317 ("packet_details" is true). */
3318 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3322 * Force synchronous resolution of IP addresses; in this pass, we
3323 * can't do it in the background and fix up past dissections.
3325 set_resolution_synchrony(TRUE);
3327 for (framenum = 1; framenum <= cf->count; framenum++) {
3328 if (read_interrupted) {
3329 status = PASS_INTERRUPTED;
3332 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3333 if (!wtap_seek_read(cf->provider.wth, fdata->file_off, &rec, &buf, err,
3335 /* Error reading from the input file. */
3336 status = PASS_READ_ERROR;
3339 tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3340 if (process_packet_second_pass(cf, edt, fdata, &rec, &buf, tap_flags)) {
3341 /* Either there's no read filtering or this packet passed the
3342 filter, so, if we're writing to a capture file, write
3345 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3346 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&buf), err, err_info)) {
3347 /* Error writing to the output file. */
3348 tshark_debug("tshark: error writing to a capture file (%d)", *err);
3349 *err_framenum = framenum;
3350 status = PASS_WRITE_ERROR;
3358 epan_dissect_free(edt);
3360 ws_buffer_free(&buf);
3361 wtap_rec_cleanup(&rec);
3366 static pass_status_t
3367 process_cap_file_single_pass(capture_file *cf, wtap_dumper *pdh,
3368 int max_packet_count, gint64 max_byte_count,
3369 int *err, gchar **err_info,
3370 volatile guint32 *err_framenum)
3374 gboolean create_proto_tree = FALSE;
3375 gboolean filtering_tap_listeners;
3378 epan_dissect_t *edt = NULL;
3380 pass_status_t status = PASS_SUCCEEDED;
3382 wtap_rec_init(&rec);
3383 ws_buffer_init(&buf, 1514);
3387 /* Do we have any tap listeners with filters? */
3388 filtering_tap_listeners = have_filtering_tap_listeners();
3390 /* Get the union of the flags for all tap listeners. */
3391 tap_flags = union_of_tap_listener_flags();
3393 if (do_dissection) {
3395 * Determine whether we need to create a protocol tree.
3398 * we're going to apply a read filter;
3400 * we're going to apply a display filter;
3402 * we're going to print the protocol tree;
3404 * one of the tap listeners is going to apply a filter;
3406 * one of the tap listeners requires a protocol tree;
3408 * a postdissector wants field values or protocols
3409 * on the first pass;
3411 * we have custom columns (which require field values, which
3412 * currently requires that we build a protocol tree).
3415 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3416 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3417 have_custom_cols(&cf->cinfo) || dissect_color);
3419 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3421 /* The protocol tree will be "visible", i.e., printed, only if we're
3422 printing packet details, which is true if we're printing stuff
3423 ("print_packet_info" is true) and we're in verbose mode
3424 ("packet_details" is true). */
3425 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3429 * Force synchronous resolution of IP addresses; we're doing only
3430 * one pass, so we can't do it in the background and fix up past
3433 set_resolution_synchrony(TRUE);
3436 while (wtap_read(cf->provider.wth, &rec, &buf, err, err_info, &data_offset)) {
3437 if (read_interrupted) {
3438 status = PASS_INTERRUPTED;
3444 * Process whatever IDBs we haven't seen yet.
3446 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3447 *err_framenum = framenum;
3448 status = PASS_WRITE_ERROR;
3452 tshark_debug("tshark: processing packet #%d", framenum);
3454 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3456 if (process_packet_single_pass(cf, edt, data_offset, &rec, &buf, tap_flags)) {
3457 /* Either there's no read filtering or this packet passed the
3458 filter, so, if we're writing to a capture file, write
3461 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3462 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&buf), err, err_info)) {
3463 /* Error writing to the output file. */
3464 tshark_debug("tshark: error writing to a capture file (%d)", *err);
3465 *err_framenum = framenum;
3466 status = PASS_WRITE_ERROR;
3471 /* Stop reading if we have the maximum number of packets;
3472 * When the -c option has not been used, max_packet_count
3473 * starts at 0, which practically means, never stop reading.
3474 * (unless we roll over max_packet_count ?)
3476 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3477 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3478 max_packet_count, data_offset, max_byte_count);
3479 *err = 0; /* This is not an error */
3483 if (*err != 0 && status == PASS_SUCCEEDED) {
3484 /* Error reading from the input file. */
3485 status = PASS_READ_ERROR;
3489 epan_dissect_free(edt);
3491 ws_buffer_free(&buf);
3492 wtap_rec_cleanup(&rec);
3497 static process_file_status_t
3498 process_cap_file(capture_file *cf, char *save_file, int out_file_type,
3499 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
3501 process_file_status_t status = PROCESS_FILE_SUCCEEDED;
3504 struct sigaction action, oldaction;
3506 int err = 0, err_pass1 = 0;
3507 gchar *err_info = NULL, *err_info_pass1 = NULL;
3508 volatile guint32 err_framenum;
3509 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
3510 char *shb_user_appl;
3511 pass_status_t first_pass_status, second_pass_status;
3513 if (save_file != NULL) {
3514 /* Set up to write to the capture file. */
3515 wtap_dump_params_init_no_idbs(¶ms, cf->provider.wth);
3517 /* If we don't have an application name add Tshark */
3518 if (wtap_block_get_string_option_value(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
3519 /* this is free'd by wtap_block_free() later */
3520 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
3523 tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
3524 if (strcmp(save_file, "-") == 0) {
3525 /* Write to the standard output. */
3526 pdh = wtap_dump_open_stdout(out_file_type, WTAP_UNCOMPRESSED, ¶ms,
3529 pdh = wtap_dump_open(save_file, out_file_type, WTAP_UNCOMPRESSED, ¶ms,
3533 g_free(params.idb_inf);
3534 params.idb_inf = NULL;
3537 /* We couldn't set up to write to the capture file. */
3538 cfile_dump_open_failure_message("TShark", save_file, err, err_info,
3540 status = PROCESS_FILE_NO_FILE_PROCESSED;
3544 /* Set up to print packet information. */
3545 if (print_packet_info) {
3546 if (!write_preamble(cf)) {
3547 show_print_file_io_error(errno);
3548 status = PROCESS_FILE_NO_FILE_PROCESSED;
3556 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
3557 SetConsoleCtrlHandler(read_cleanup, TRUE);
3559 /* Catch SIGINT and SIGTERM and, if we get either of them,
3560 clean up and exit. If SIGHUP isn't being ignored, catch
3561 it too and, if we get it, clean up and exit.
3563 We restart any read that was in progress, so that it doesn't
3564 disrupt reading from the sync pipe. The signal handler tells
3565 the capture child to finish; it will report that it finished,
3566 or will exit abnormally, so we'll stop reading from the sync
3567 pipe, pick up the exit status, and quit. */
3568 memset(&action, 0, sizeof(action));
3569 action.sa_handler = read_cleanup;
3570 action.sa_flags = SA_RESTART;
3571 sigemptyset(&action.sa_mask);
3572 sigaction(SIGTERM, &action, NULL);
3573 sigaction(SIGINT, &action, NULL);
3574 sigaction(SIGHUP, NULL, &oldaction);
3575 if (oldaction.sa_handler == SIG_DFL)
3576 sigaction(SIGHUP, &action, NULL);
3579 if (perform_two_pass_analysis) {
3580 tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3582 first_pass_status = process_cap_file_first_pass(cf, max_packet_count,
3587 tshark_debug("tshark: done with first pass");
3589 if (first_pass_status == PASS_INTERRUPTED) {
3590 /* The first pass was interrupted; skip the second pass.
3591 It won't be run, so it won't get an error. */
3592 second_pass_status = PASS_SUCCEEDED;
3595 * If we got a read error on the first pass, we still do the second
3596 * pass, so we can at least process the packets we read, and then
3597 * report the first-pass error after the second pass (and before
3598 * we report any second-pass errors), so all the the errors show up
3601 second_pass_status = process_cap_file_second_pass(cf, pdh, &err, &err_info,
3604 tshark_debug("tshark: done with second pass");
3608 /* !perform_two_pass_analysis */
3609 tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3611 first_pass_status = PASS_SUCCEEDED; /* There is no first pass */
3612 second_pass_status = process_cap_file_single_pass(cf, pdh,
3619 if (first_pass_status != PASS_SUCCEEDED ||
3620 second_pass_status != PASS_SUCCEEDED) {
3622 * At least one of the passes didn't succeed; either it got a failure
3623 * or it was interrupted.
3625 if (first_pass_status != PASS_INTERRUPTED ||
3626 second_pass_status != PASS_INTERRUPTED) {
3627 /* At least one of the passes got an error. */
3628 tshark_debug("tshark: something failed along the line (%d)", err);
3630 * If we're printing packet data, and the standard output and error
3631 * are going to the same place, flush the standard output, so everything
3632 * buffered up is written, and then print a newline to the standard
3633 * error before printing the error message, to separate it from the
3634 * packet data. (Alas, that only works on UN*X; st_dev is meaningless,
3635 * and the _fstat() documentation at Microsoft doesn't indicate whether
3636 * st_ino is even supported.)
3639 if (print_packet_info) {
3640 ws_statb64 stat_stdout, stat_stderr;
3642 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3643 if (stat_stdout.st_dev == stat_stderr.st_dev &&
3644 stat_stdout.st_ino == stat_stderr.st_ino) {
3646 fprintf(stderr, "\n");
3652 /* Report status of pass 1 of two-pass processing. */
3653 switch (first_pass_status) {
3655 case PASS_SUCCEEDED:
3659 case PASS_READ_ERROR:
3661 cfile_read_failure_message("TShark", cf->filename, err_pass1,
3663 status = PROCESS_FILE_ERROR;
3666 case PASS_WRITE_ERROR:
3667 /* Won't happen on the first pass. */
3670 case PASS_INTERRUPTED:
3671 /* Not an error, so nothing to report. */
3672 status = PROCESS_FILE_INTERRUPTED;
3676 /* Report status of pass 2 of two-pass processing or the only pass
3677 of one-pass processing. */
3678 switch (second_pass_status) {
3680 case PASS_SUCCEEDED:
3684 case PASS_READ_ERROR:
3686 cfile_read_failure_message("TShark", cf->filename, err, err_info);
3687 status = PROCESS_FILE_ERROR;
3690 case PASS_WRITE_ERROR:
3692 XXX - framenum is not necessarily the frame number in
3693 the input file if there was a read filter. */
3694 cfile_write_failure_message("TShark", cf->filename, save_file,
3695 err, err_info, err_framenum, out_file_type);
3696 status = PROCESS_FILE_ERROR;
3699 case PASS_INTERRUPTED:
3700 /* Not an error, so nothing to report. */
3701 status = PROCESS_FILE_INTERRUPTED;
3705 if (save_file != NULL) {
3706 if (second_pass_status != PASS_WRITE_ERROR) {
3707 if (pdh && out_file_name_res) {
3708 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3709 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3710 wtap_file_type_subtype_short_string(out_file_type));
3713 /* Now close the capture file. */
3714 if (!wtap_dump_close(pdh, &err, &err_info)) {
3715 cfile_close_failure_message(save_file, err, err_info);
3716 status = PROCESS_FILE_ERROR;
3719 /* We got a write error; it was reported, so just close the dump file
3720 without bothering to check for further errors. */
3721 wtap_dump_close(pdh, &err, &err_info);
3723 status = PROCESS_FILE_ERROR;
3726 if (print_packet_info) {
3727 if (!write_finale()) {
3728 show_print_file_io_error(errno);
3729 status = PROCESS_FILE_ERROR;
3735 wtap_close(cf->provider.wth);
3736 cf->provider.wth = NULL;
3738 wtap_dump_params_cleanup(¶ms);
3744 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, gint64 offset,
3745 wtap_rec *rec, Buffer *buf, guint tap_flags)
3751 /* Count this packet. */
3754 /* If we're not running a display filter and we're not printing any
3755 packet information, we don't need to do a dissection. This means
3756 that all packets can be marked as 'passed'. */
3759 frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
3761 /* If we're going to print packet information, or we're going to
3762 run a read filter, or we're going to process taps, set up to
3763 do a dissection and do so. (This is the one and only pass
3764 over the packets, so, if we'll be printing packet information
3765 or running taps, we'll be doing it here.) */
3767 /* If we're running a filter, prime the epan_dissect_t with that
3770 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3772 /* This is the first and only pass, so prime the epan_dissect_t
3773 with the hfids postdissectors want on the first pass. */
3774 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
3776 col_custom_prime_edt(edt, &cf->cinfo);
3778 /* We only need the columns if either
3779 1) some tap needs the columns
3781 2) we're printing packet info but we're *not* verbose; in verbose
3782 mode, we print the protocol tree, not the protocol summary.
3784 3) there is a column mapped as an individual field */
3785 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3790 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3791 &cf->provider.ref, cf->provider.prev_dis);
3792 if (cf->provider.ref == &fdata) {
3794 cf->provider.ref = &ref_frame;
3797 if (dissect_color) {
3798 color_filters_prime_edt(edt);
3799 fdata.need_colorize = 1;
3802 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
3803 frame_tvbuff_new_buffer(&cf->provider, &fdata, buf),
3806 /* Run the filter if we have it. */
3808 passed = dfilter_apply_edt(cf->dfcode, edt);
3812 frame_data_set_after_dissect(&fdata, &cum_bytes);
3814 /* Process this packet. */
3815 if (print_packet_info) {
3816 /* We're printing packet information; print the information for
3819 print_packet(cf, edt);
3821 /* If we're doing "line-buffering", flush the standard output
3822 after every packet. See the comment above, for the "-l"
3823 option, for an explanation of why we do that. */
3827 if (ferror(stdout)) {
3828 show_print_file_io_error(errno);
3833 /* this must be set after print_packet() [bug #8160] */
3834 prev_dis_frame = fdata;
3835 cf->provider.prev_dis = &prev_dis_frame;
3838 prev_cap_frame = fdata;
3839 cf->provider.prev_cap = &prev_cap_frame;
3842 epan_dissect_reset(edt);
3843 frame_data_destroy(&fdata);
3849 write_preamble(capture_file *cf)
3851 switch (output_action) {
3854 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3858 write_pdml_preamble(stdout, cf->filename);
3860 write_psml_preamble(&cf->cinfo, stdout);
3861 return !ferror(stdout);
3864 write_fields_preamble(output_fields, stdout);
3865 return !ferror(stdout);
3868 case WRITE_JSON_RAW:
3869 jdumper = write_json_preamble(stdout);
3870 return !ferror(stdout);
3876 g_assert_not_reached();
3882 get_line_buf(size_t len)
3884 static char *line_bufp = NULL;
3885 static size_t line_buf_len = 256;
3886 size_t new_line_buf_len;
3888 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3889 new_line_buf_len *= 2)
3891 if (line_bufp == NULL) {
3892 line_buf_len = new_line_buf_len;
3893 line_bufp = (char *)g_malloc(line_buf_len + 1);
3895 if (new_line_buf_len > line_buf_len) {
3896 line_buf_len = new_line_buf_len;
3897 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3904 put_string(char *dest, const char *str, size_t str_len)
3906 memcpy(dest, str, str_len);
3907 dest[str_len] = '\0';
3911 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3915 for (i = str_len; i < str_with_spaces; i++)
3918 put_string(dest, str, str_len);
3922 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3926 memcpy(dest, str, str_len);
3927 for (i = str_len; i < str_with_spaces; i++)
3930 dest[str_with_spaces] = '\0';
3934 print_columns(capture_file *cf, const epan_dissect_t *edt)
3941 col_item_t* col_item;
3942 gchar str_format[11];
3943 const color_filter_t *color_filter = NULL;
3945 line_bufp = get_line_buf(256);
3950 color_filter = edt->pi.fd->color_filter;
3952 for (i = 0; i < cf->cinfo.num_cols; i++) {
3953 col_item = &cf->cinfo.columns[i];
3954 /* Skip columns not marked as visible. */
3955 if (!get_column_visible(i))
3957 switch (col_item->col_fmt) {
3959 column_len = col_len = strlen(col_item->col_data);
3962 line_bufp = get_line_buf(buf_offset + column_len);
3963 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3969 case COL_ABS_YMD_TIME: /* XXX - wider */
3970 case COL_ABS_YDOY_TIME: /* XXX - wider */
3972 case COL_UTC_YMD_TIME: /* XXX - wider */
3973 case COL_UTC_YDOY_TIME: /* XXX - wider */
3974 column_len = col_len = strlen(col_item->col_data);
3975 if (column_len < 10)
3977 line_bufp = get_line_buf(buf_offset + column_len);
3978 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3984 case COL_DEF_DL_SRC:
3985 case COL_RES_DL_SRC:
3986 case COL_UNRES_DL_SRC:
3987 case COL_DEF_NET_SRC:
3988 case COL_RES_NET_SRC:
3989 case COL_UNRES_NET_SRC:
3990 column_len = col_len = strlen(col_item->col_data);
3991 if (column_len < 12)
3993 line_bufp = get_line_buf(buf_offset + column_len);
3994 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
4000 case COL_DEF_DL_DST:
4001 case COL_RES_DL_DST:
4002 case COL_UNRES_DL_DST:
4003 case COL_DEF_NET_DST:
4004 case COL_RES_NET_DST:
4005 case COL_UNRES_NET_DST:
4006 column_len = col_len = strlen(col_item->col_data);
4007 if (column_len < 12)
4009 line_bufp = get_line_buf(buf_offset + column_len);
4010 put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
4014 column_len = strlen(col_item->col_data);
4015 line_bufp = get_line_buf(buf_offset + column_len);
4016 put_string(line_bufp + buf_offset, col_item->col_data, column_len);
4019 buf_offset += column_len;
4020 if (i != cf->cinfo.num_cols - 1) {
4022 * This isn't the last column, so we need to print a
4023 * separator between this column and the next.
4025 * If we printed a network source and are printing a
4026 * network destination of the same type next, separate
4027 * them with a UTF-8 right arrow; if we printed a network
4028 * destination and are printing a network source of the same
4029 * type next, separate them with a UTF-8 left arrow;
4030 * otherwise separate them with a space.
4032 * We add enough space to the buffer for " \xe2\x86\x90 "
4033 * or " \xe2\x86\x92 ", even if we're only adding " ".
4035 line_bufp = get_line_buf(buf_offset + 5);
4036 switch (col_item->col_fmt) {
4041 switch (cf->cinfo.columns[i+1].col_fmt) {
4046 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4047 put_string(line_bufp + buf_offset, str_format, 5);
4052 put_string(line_bufp + buf_offset, delimiter_char, 1);
4058 case COL_DEF_DL_SRC:
4059 case COL_RES_DL_SRC:
4060 case COL_UNRES_DL_SRC:
4061 switch (cf->cinfo.columns[i+1].col_fmt) {
4063 case COL_DEF_DL_DST:
4064 case COL_RES_DL_DST:
4065 case COL_UNRES_DL_DST:
4066 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4067 put_string(line_bufp + buf_offset, str_format, 5);
4072 put_string(line_bufp + buf_offset, delimiter_char, 1);
4078 case COL_DEF_NET_SRC:
4079 case COL_RES_NET_SRC:
4080 case COL_UNRES_NET_SRC:
4081 switch (cf->cinfo.columns[i+1].col_fmt) {
4083 case COL_DEF_NET_DST:
4084 case COL_RES_NET_DST:
4085 case COL_UNRES_NET_DST:
4086 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4087 put_string(line_bufp + buf_offset, str_format, 5);
4092 put_string(line_bufp + buf_offset, delimiter_char, 1);
4101 switch (cf->cinfo.columns[i+1].col_fmt) {
4106 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4107 put_string(line_bufp + buf_offset, str_format, 5);
4112 put_string(line_bufp + buf_offset, delimiter_char, 1);
4118 case COL_DEF_DL_DST:
4119 case COL_RES_DL_DST:
4120 case COL_UNRES_DL_DST:
4121 switch (cf->cinfo.columns[i+1].col_fmt) {
4123 case COL_DEF_DL_SRC:
4124 case COL_RES_DL_SRC:
4125 case COL_UNRES_DL_SRC:
4126 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4127 put_string(line_bufp + buf_offset, str_format, 5);
4132 put_string(line_bufp + buf_offset, delimiter_char, 1);
4138 case COL_DEF_NET_DST:
4139 case COL_RES_NET_DST:
4140 case COL_UNRES_NET_DST:
4141 switch (cf->cinfo.columns[i+1].col_fmt) {
4143 case COL_DEF_NET_SRC:
4144 case COL_RES_NET_SRC:
4145 case COL_UNRES_NET_SRC:
4146 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4147 put_string(line_bufp + buf_offset, str_format, 5);
4152 put_string(line_bufp + buf_offset, delimiter_char, 1);
4159 put_string(line_bufp + buf_offset, delimiter_char, 1);
4166 if (dissect_color && color_filter != NULL)
4167 return print_line_color(print_stream, 0, line_bufp, &color_filter->fg_color, &color_filter->bg_color);
4169 return print_line(print_stream, 0, line_bufp);
4173 print_packet(capture_file *cf, epan_dissect_t *edt)
4175 if (print_summary || output_fields_has_cols(output_fields))
4176 /* Just fill in the columns. */
4177 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
4179 /* Print summary columns and/or protocol tree */
4180 switch (output_action) {
4183 if (print_summary && !print_columns(cf, edt))
4185 if (print_details) {
4186 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
4187 print_hex, edt, output_only_tables, print_stream))
4190 if (!print_line(print_stream, 0, separator))
4197 if (print_summary) {
4198 write_psml_columns(edt, stdout, dissect_color);
4199 return !ferror(stdout);
4201 if (print_details) {
4202 write_pdml_proto_tree(output_fields, protocolfilter, protocolfilter_flags, edt, &cf->cinfo, stdout, dissect_color);
4204 return !ferror(stdout);
4209 if (print_summary) {
4210 /*No non-verbose "fields" format */
4211 g_assert_not_reached();
4213 if (print_details) {
4214 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
4216 return !ferror(stdout);
4222 g_assert_not_reached();
4223 if (print_details) {
4224 write_json_proto_tree(output_fields, print_dissections_expanded,
4225 print_hex, protocolfilter, protocolfilter_flags,
4226 edt, &cf->cinfo, node_children_grouper, &jdumper);
4227 return !ferror(stdout);
4231 case WRITE_JSON_RAW:
4233 g_assert_not_reached();
4234 if (print_details) {
4235 write_json_proto_tree(output_fields, print_dissections_none, TRUE,
4236 protocolfilter, protocolfilter_flags,
4237 edt, &cf->cinfo, node_children_grouper, &jdumper);
4238 return !ferror(stdout);
4243 write_ek_proto_tree(output_fields, print_summary, print_hex, protocolfilter,
4244 protocolfilter_flags, edt, &cf->cinfo, stdout);
4245 return !ferror(stdout);
4249 if (print_summary || print_details) {
4250 if (!print_line(print_stream, 0, ""))
4253 if (!print_hex_data(print_stream, edt))
4255 if (!print_line(print_stream, 0, separator))
4264 switch (output_action) {
4267 return print_finale(print_stream);
4271 write_pdml_finale(stdout);
4273 write_psml_finale(stdout);
4274 return !ferror(stdout);
4277 write_fields_finale(output_fields, stdout);
4278 return !ferror(stdout);
4281 case WRITE_JSON_RAW:
4282 write_json_finale(&jdumper);
4283 return !ferror(stdout);
4289 g_assert_not_reached();
4295 cf_close(capture_file *cf)
4297 if (cf->state == FILE_CLOSED)
4298 return; /* Nothing to do */
4300 if (cf->provider.wth != NULL) {
4301 wtap_close(cf->provider.wth);
4302 cf->provider.wth = NULL;
4304 /* We have no file open... */
4305 if (cf->filename != NULL) {
4306 /* If it's a temporary file, remove it. */
4307 if (cf->is_tempfile)
4308 ws_unlink(cf->filename);
4309 g_free(cf->filename);
4310 cf->filename = NULL;
4313 /* We have no file open. */
4314 cf->state = FILE_CLOSED;
4318 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
4323 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
4327 /* The open succeeded. Fill in the information for this file. */
4329 cf->provider.wth = wth;
4330 cf->f_datalen = 0; /* not used, but set it anyway */
4332 /* Set the file name because we need it to set the follow stream filter.
4333 XXX - is that still true? We need it for other reasons, though,
4335 cf->filename = g_strdup(fname);
4337 /* Indicate whether it's a permanent or temporary file. */
4338 cf->is_tempfile = is_tempfile;
4340 /* No user changes yet. */
4341 cf->unsaved_changes = FALSE;
4343 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
4344 cf->open_type = type;
4346 cf->drops_known = FALSE;
4348 cf->snap = wtap_snapshot_length(cf->provider.wth);
4349 nstime_set_zero(&cf->elapsed_time);
4350 cf->provider.ref = NULL;
4351 cf->provider.prev_dis = NULL;
4352 cf->provider.prev_cap = NULL;
4354 cf->state = FILE_READ_IN_PROGRESS;
4356 /* Create new epan session for dissection. */
4357 epan_free(cf->epan);
4358 cf->epan = tshark_epan_new(cf);
4360 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
4361 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
4362 wtap_set_cb_new_secrets(cf->provider.wth, secrets_wtap_callback);
4367 cfile_open_failure_message("TShark", fname, *err, err_info);
4372 show_print_file_io_error(int err)
4377 cmdarg_err("Not all the packets could be printed because there is "
4378 "no space left on the file system.");
4383 cmdarg_err("Not all the packets could be printed because you are "
4384 "too close to, or over your disk quota.");
4390 * This almost certainly means "the next program after us in
4391 * the pipeline exited before we were finished writing", so
4392 * this isn't a real error, it just means we're done. (We
4393 * don't get SIGPIPE because libwireshark ignores SIGPIPE
4394 * to avoid getting killed if writing to the MaxMind process
4395 * gets SIGPIPE because that process died.)
4397 * Presumably either that program exited deliberately (for
4398 * example, "head -N" read N lines and printed them), in
4399 * which case there's no error to report, or it terminated
4400 * due to an error or a signal, in which case *that's* the
4401 * error and that error has been reported.
4406 cmdarg_err("An error occurred while printing packets: %s.",
4413 * General errors and warnings are reported with an console message
4417 failure_warning_message(const char *msg_format, va_list ap)
4419 fprintf(stderr, "tshark: ");
4420 vfprintf(stderr, msg_format, ap);
4421 fprintf(stderr, "\n");
4425 * Open/create errors are reported with an console message in TShark.
4428 open_failure_message(const char *filename, int err, gboolean for_writing)
4430 fprintf(stderr, "tshark: ");
4431 fprintf(stderr, file_open_error_message(err, for_writing), filename);
4432 fprintf(stderr, "\n");
4436 * Read errors are reported with an console message in TShark.
4439 read_failure_message(const char *filename, int err)
4441 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4442 filename, g_strerror(err));
4446 * Write errors are reported with an console message in TShark.
4449 write_failure_message(const char *filename, int err)
4451 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4452 filename, g_strerror(err));
4455 static void reset_epan_mem(capture_file *cf,epan_dissect_t *edt, gboolean tree, gboolean visual)
4457 if (!epan_auto_reset || (cf->count < epan_auto_reset_count))
4460 fprintf(stderr, "resetting session.\n");
4462 epan_dissect_cleanup(edt);
4463 epan_free(cf->epan);
4465 cf->epan = tshark_epan_new(cf);
4466 epan_dissect_init(edt, cf->epan, tree, visual);
4471 * Report additional information for an error in command-line arguments.
4474 failure_message_cont(const char *msg_format, va_list ap)
4476 vfprintf(stderr, msg_format, ap);
4477 fprintf(stderr, "\n");
4481 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4486 * indent-tabs-mode: nil
4489 * vi: set shiftwidth=2 tabstop=8 expandtab:
4490 * :indentSize=2:tabSize=8:noTabs=true: