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+
28 # include <winsock2.h>
36 # include <sys/capability.h>
39 #ifndef HAVE_GETOPT_LONG
40 #include "wsutil/wsgetopt.h"
45 #include <epan/exceptions.h>
46 #include <epan/epan-int.h>
47 #include <epan/epan.h>
49 #include <wsutil/clopts_common.h>
50 #include <wsutil/cmdarg_err.h>
51 #include <wsutil/crash_info.h>
52 #include <wsutil/filesystem.h>
53 #include <wsutil/file_util.h>
54 #include <wsutil/privileges.h>
55 #include <wsutil/report_message.h>
56 #include <version_info.h>
57 #include <wiretap/wtap_opttypes.h>
58 #include <wiretap/pcapng.h>
61 #include <epan/timestamp.h>
62 #include <epan/packet.h>
64 #include <epan/wslua/init_wslua.h>
66 #include "frame_tvbuff.h"
67 #include <epan/disabled_protos.h>
68 #include <epan/prefs.h>
69 #include <epan/column.h>
70 #include <epan/decode_as.h>
71 #include <epan/print.h>
72 #include <epan/addr_resolv.h>
74 #include "ui/capture_ui_utils.h"
77 #include "ui/ws_ui_util.h"
78 #include "ui/decode_as_utils.h"
79 #include "ui/filter_files.h"
80 #include "ui/cli/tshark-tap.h"
81 #include "ui/cli/tap-exportobject.h"
82 #include "ui/tap_export_pdu.h"
83 #include "ui/dissect_opts.h"
84 #include "ui/failure_message.h"
85 #if defined(HAVE_LIBSMI)
86 #include "epan/oids.h"
88 #if defined(HAVE_GEOIP)
89 #include "epan/geoip_db.h"
92 #include <epan/epan_dissect.h>
94 #include <epan/stat_tap_ui.h>
95 #include <epan/conversation_table.h>
96 #include <epan/srt_table.h>
97 #include <epan/rtd_table.h>
98 #include <epan/ex-opt.h>
99 #include <epan/exported_pdu.h>
101 #include "capture_opts.h"
103 #include "caputils/capture-pcap-util.h"
106 #include "caputils/capture_ifinfo.h"
108 #include "caputils/capture-wpcap.h"
109 #include <wsutil/os_version_info.h>
110 #include <wsutil/unicode-utils.h>
112 #include <capchild/capture_session.h>
113 #include <capchild/capture_sync.h>
114 #include <capture_info.h>
115 #endif /* HAVE_LIBPCAP */
117 #include <epan/funnel.h>
119 #include <wsutil/str_util.h>
120 #include <wsutil/utf8_entities.h>
127 #include <wsutil/plugins.h>
131 #define INVALID_OPTION 1
132 #define INVALID_INTERFACE 2
133 #define INVALID_FILE 2
134 #define INVALID_FILTER 2
135 #define INVALID_EXPORT 2
136 #define INVALID_CAPABILITY 2
137 #define INVALID_TAP 2
138 #define INVALID_DATA_LINK 2
139 #define INVALID_TIMESTAMP_TYPE 2
140 #define INVALID_CAPTURE 2
141 #define INIT_FAILED 2
144 * values 128..65535 are capture+dissect options, 65536 is used by
145 * ui/commandline.c, so start tshark-specific options 1000 after this
147 #define LONGOPT_COLOR (65536+1000)
148 #define LONGOPT_NO_DUPLICATE_KEYS (65536+1001)
151 #define tshark_debug(...) g_warning(__VA_ARGS__)
153 #define tshark_debug(...)
156 static guint32 cum_bytes;
157 static const frame_data *ref;
158 static frame_data ref_frame;
159 static frame_data *prev_dis;
160 static frame_data prev_dis_frame;
161 static frame_data *prev_cap;
162 static frame_data prev_cap_frame;
164 static gboolean perform_two_pass_analysis;
165 static guint32 epan_auto_reset_count = 0;
166 static gboolean epan_auto_reset = FALSE;
169 * The way the packet decode is to be written.
172 WRITE_TEXT, /* summary or detail text */
173 WRITE_XML, /* PDML or PSML */
174 WRITE_FIELDS, /* User defined list of fields */
175 WRITE_JSON, /* JSON */
176 WRITE_JSON_RAW, /* JSON only raw hex */
177 WRITE_EK /* JSON bulk insert to Elasticsearch */
178 /* Add CSV and the like here */
181 static output_action_e output_action;
182 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
183 static gboolean print_packet_info; /* TRUE if we're to print packet information */
184 static gboolean print_summary; /* TRUE if we're to print packet summary information */
185 static gboolean print_details; /* TRUE if we're to print packet details information */
186 static gboolean print_hex; /* TRUE if we're to print hex/ascci information */
187 static gboolean line_buffered;
188 static gboolean really_quiet = FALSE;
189 static gchar* delimiter_char = " ";
190 static gboolean dissect_color = FALSE;
192 static print_format_e print_format = PR_FMT_TEXT;
193 static print_stream_t *print_stream = NULL;
195 static output_fields_t* output_fields = NULL;
196 static gchar **protocolfilter = NULL;
197 static pf_flags protocolfilter_flags = PF_NONE;
199 static gboolean no_duplicate_keys = FALSE;
200 static proto_node_children_grouper_func node_children_grouper = proto_node_group_children_by_unique;
202 /* The line separator used between packets, changeable via the -S option */
203 static const char *separator = "";
205 static gboolean prefs_loaded = FALSE;
209 * TRUE if we're to print packet counts to keep track of captured packets.
211 static gboolean print_packet_counts;
213 static capture_options global_capture_opts;
214 static capture_session global_capture_session;
215 static info_data_t global_info_data;
218 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
219 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
222 static gboolean capture(void);
223 static void report_counts(void);
225 static BOOL WINAPI capture_cleanup(DWORD);
227 static void capture_cleanup(int);
229 static void report_counts_siginfo(int);
233 #else /* HAVE_LIBPCAP */
235 static char *output_file_name;
237 #endif /* HAVE_LIBPCAP */
239 static void reset_epan_mem(capture_file *cf, epan_dissect_t *edt, gboolean tree, gboolean visual);
240 static gboolean process_cap_file(capture_file *, char *, int, gboolean, int, gint64);
241 static gboolean process_packet_single_pass(capture_file *cf,
242 epan_dissect_t *edt, gint64 offset, struct wtap_pkthdr *whdr,
243 const guchar *pd, guint tap_flags);
244 static void show_print_file_io_error(int err);
245 static gboolean write_preamble(capture_file *cf);
246 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
247 static gboolean write_finale(void);
249 static void failure_warning_message(const char *msg_format, va_list ap);
250 static void open_failure_message(const char *filename, int err,
251 gboolean for_writing);
252 static void read_failure_message(const char *filename, int err);
253 static void write_failure_message(const char *filename, int err);
254 static void failure_message_cont(const char *msg_format, va_list ap);
258 static GHashTable *output_only_tables = NULL;
261 const char *sstr; /* The short string */
262 const char *lstr; /* The long string */
266 string_compare(gconstpointer a, gconstpointer b)
268 return strcmp(((const struct string_elem *)a)->sstr,
269 ((const struct string_elem *)b)->sstr);
273 string_elem_print(gpointer data, gpointer not_used _U_)
275 fprintf(stderr, " %s - %s\n",
276 ((struct string_elem *)data)->sstr,
277 ((struct string_elem *)data)->lstr);
281 list_capture_types(void) {
283 struct string_elem *captypes;
286 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
288 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
289 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
290 if (wtap_dump_can_open(i)) {
291 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
292 captypes[i].lstr = wtap_file_type_subtype_string(i);
293 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
296 g_slist_foreach(list, string_elem_print, NULL);
302 list_read_capture_types(void) {
304 struct string_elem *captypes;
306 const char *magic = "Magic-value-based";
307 const char *heuristic = "Heuristics-based";
309 /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
310 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
312 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
313 for (i = 0; open_routines[i].name != NULL; i++) {
314 captypes[i].sstr = open_routines[i].name;
315 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
316 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
318 g_slist_foreach(list, string_elem_print, NULL);
324 print_usage(FILE *output)
326 fprintf(output, "\n");
327 fprintf(output, "Usage: tshark [options] ...\n");
328 fprintf(output, "\n");
331 fprintf(output, "Capture interface:\n");
332 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
333 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
334 #ifdef HAVE_PCAP_CREATE
335 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
337 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
339 fprintf(output, " -p don't capture in promiscuous mode\n");
340 #ifdef HAVE_PCAP_CREATE
341 fprintf(output, " -I capture in monitor mode, if available\n");
343 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
344 fprintf(output, " -B <buffer size> size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
346 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
347 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
348 fprintf(output, " -D print list of interfaces and exit\n");
349 fprintf(output, " -L print list of link-layer types of iface and exit\n");
350 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
351 fprintf(output, "\n");
352 fprintf(output, "Capture stop conditions:\n");
353 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
354 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
355 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
356 fprintf(output, " files:NUM - stop after NUM files\n");
357 /*fprintf(output, "\n");*/
358 fprintf(output, "Capture output:\n");
359 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
360 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
361 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
362 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
363 #endif /* HAVE_LIBPCAP */
364 #ifdef HAVE_PCAP_REMOTE
365 fprintf(output, "RPCAP options:\n");
366 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
368 /*fprintf(output, "\n");*/
369 fprintf(output, "Input file:\n");
370 fprintf(output, " -r <infile> set the filename to read from (- to read from stdin)\n");
372 fprintf(output, "\n");
373 fprintf(output, "Processing:\n");
374 fprintf(output, " -2 perform a two-pass analysis\n");
375 fprintf(output, " -M <packet count> perform session auto reset\n");
376 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
377 fprintf(output, " (requires -2)\n");
378 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
379 fprintf(output, " syntax\n");
380 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
381 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtCd\"\n");
382 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
383 fprintf(output, " \"Decode As\", see the man page for details\n");
384 fprintf(output, " Example: tcp.port==8888,http\n");
385 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
386 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
387 fprintf(output, " --enable-protocol <proto_name>\n");
388 fprintf(output, " enable dissection of proto_name\n");
389 fprintf(output, " --disable-protocol <proto_name>\n");
390 fprintf(output, " disable dissection of proto_name\n");
391 fprintf(output, " --enable-heuristic <short_name>\n");
392 fprintf(output, " enable dissection of heuristic protocol\n");
393 fprintf(output, " --disable-heuristic <short_name>\n");
394 fprintf(output, " disable dissection of heuristic protocol\n");
396 /*fprintf(output, "\n");*/
397 fprintf(output, "Output:\n");
398 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
399 fprintf(output, " (or to the standard output for \"-\")\n");
400 fprintf(output, " -C <config profile> start with specified configuration profile\n");
401 fprintf(output, " -F <output file type> set the output file type, default is pcapng\n");
402 fprintf(output, " an empty \"-F\" option will list the file types\n");
403 fprintf(output, " -V add output of packet tree (Packet Details)\n");
404 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
405 fprintf(output, " separated\n");
406 fprintf(output, " -P print packet summary even when writing to a file\n");
407 fprintf(output, " -S <separator> the line separator to print between packets\n");
408 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
409 fprintf(output, " -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?\n");
410 fprintf(output, " format of text output (def: text)\n");
411 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected\n");
412 fprintf(output, " (e.g. \"ip ip.flags text\", filter does not expand child\n");
413 fprintf(output, " nodes, unless child is specified also in the filter)\n");
414 fprintf(output, " -J <protocolfilter> top level protocol filter if -T ek|pdml|json selected\n");
415 fprintf(output, " (e.g. \"http tcp\", filter which expands all child nodes)\n");
416 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
417 fprintf(output, " _ws.col.Info)\n");
418 fprintf(output, " this option can be repeated to print multiple fields\n");
419 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
420 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
421 fprintf(output, " header=y|n switch headers on and off\n");
422 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
423 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
424 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
425 fprintf(output, " aggregator\n");
426 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
427 fprintf(output, " -t a|ad|d|dd|e|r|u|ud|? output format of time stamps (def: r: rel. to first)\n");
428 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
429 fprintf(output, " -l flush standard output after each packet\n");
430 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
431 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
432 fprintf(output, " -g enable group read access on the output file(s)\n");
433 fprintf(output, " -W n Save extra information in the file, if supported.\n");
434 fprintf(output, " n = write network address resolution information\n");
435 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
436 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
437 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
438 fprintf(output, " --capture-comment <comment>\n");
439 fprintf(output, " add a capture comment to the newly created\n");
440 fprintf(output, " output file (only for pcapng)\n");
441 fprintf(output, " --export-objects <protocol>,<destdir> save exported objects for a protocol to\n");
442 fprintf(output, " a directory named \"destdir\"\n");
443 fprintf(output, " --color color output text similarly to the Wireshark GUI,\n");
444 fprintf(output, " requires a terminal with 24-bit color support\n");
445 fprintf(output, " Also supplies color attributes to pdml and psml formats\n");
446 fprintf(output, " (Note that attributes are nonstandard)\n");
447 fprintf(output, " --no-duplicate-keys If -T json is specified, merge duplicate keys in an object\n");
448 fprintf(output, " into a single key with as value a json array containing all\n");
449 fprintf(output, " values");
451 fprintf(output, "\n");
452 fprintf(output, "Miscellaneous:\n");
453 fprintf(output, " -h display this help and exit\n");
454 fprintf(output, " -v display version info and exit\n");
455 fprintf(output, " -o <name>:<value> ... override preference setting\n");
456 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
457 fprintf(output, " -G [report] dump one of several available reports and exit\n");
458 fprintf(output, " default report=\"fields\"\n");
459 fprintf(output, " use \"-G help\" for more help\n");
461 fprintf(output, "\n");
462 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
463 fprintf(output, "You might want to reset it\n");
464 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
470 glossary_option_help(void)
476 fprintf(output, "TShark (Wireshark) %s\n", get_ws_vcs_version_info());
478 fprintf(output, "\n");
479 fprintf(output, "Usage: tshark -G [report]\n");
480 fprintf(output, "\n");
481 fprintf(output, "Glossary table reports:\n");
482 fprintf(output, " -G column-formats dump column format codes and exit\n");
483 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
484 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
485 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
486 fprintf(output, " -G fields dump fields glossary and exit\n");
487 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
488 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
489 fprintf(output, " -G plugins dump installed plugins and exit\n");
490 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
491 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
492 fprintf(output, "\n");
493 fprintf(output, "Preference reports:\n");
494 fprintf(output, " -G currentprefs dump current preferences and exit\n");
495 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
496 fprintf(output, " -G folders dump about:folders\n");
497 fprintf(output, "\n");
501 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
502 const gchar *message, gpointer user_data)
504 /* ignore log message, if log_level isn't interesting based
505 upon the console log preferences.
506 If the preferences haven't been loaded yet, display the
509 The default console_log_level preference value is such that only
510 ERROR, CRITICAL and WARNING level messages are processed;
511 MESSAGE, INFO and DEBUG level messages are ignored.
513 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
514 ERROR and CRITICAL level messages so the current code is a behavioral
515 change. The current behavior is the same as in Wireshark.
517 if (prefs_loaded && (log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0) {
521 g_log_default_handler(log_domain, log_level, message, user_data);
526 print_current_user(void) {
527 gchar *cur_user, *cur_group;
529 if (started_with_special_privs()) {
530 cur_user = get_cur_username();
531 cur_group = get_cur_groupname();
532 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
533 cur_user, cur_group);
536 if (running_with_special_privs()) {
537 fprintf(stderr, " This could be dangerous.");
539 fprintf(stderr, "\n");
544 get_tshark_compiled_version_info(GString *str)
546 /* Capture libraries */
547 get_compiled_caplibs_version(str);
551 get_tshark_runtime_version_info(GString *str)
554 /* Capture libraries */
555 g_string_append(str, ", ");
556 get_runtime_caplibs_version(str);
559 /* stuff used by libwireshark */
560 epan_get_runtime_version_info(str);
566 const char *constpath;
568 #if defined(HAVE_LIBSMI) || defined(HAVE_GEOIP) || defined(HAVE_EXTCAP)
576 * Fetching the "File" dialogs folder not implemented.
577 * This is arguably just a pwd for a ui/cli .
581 printf("%-21s\t%s\n", "Temp:", g_get_tmp_dir());
584 path = get_persconffile_path("", FALSE);
585 printf("%-21s\t%s\n", "Personal configuration:", path);
589 constpath = get_datafile_dir();
590 if (constpath != NULL) {
591 printf("%-21s\t%s\n", "Global configuration:", constpath);
595 constpath = get_systemfile_dir();
596 printf("%-21s\t%s\n", "System:", constpath);
599 constpath = get_progfile_dir();
600 printf("%-21s\t%s\n", "Program:", constpath);
604 printf("%-21s\t%s\n", "Personal Plugins:", get_plugins_pers_dir_with_version());
607 printf("%-21s\t%s\n", "Global Plugins:", get_plugins_dir_with_version());
611 /* pers lua plugins */
612 printf("%-21s\t%s\n", "Personal Lua Plugins:", get_plugins_pers_dir());
614 /* global lua plugins */
615 printf("%-21s\t%s\n", "Global Lua Plugins:", get_plugins_dir());
620 constpath = get_extcap_dir();
622 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
623 for(i = 0; resultArray[i]; i++)
624 printf("%-21s\t%s\n", "Extcap path:", g_strstrip(resultArray[i]));
626 g_strfreev(resultArray);
631 path = geoip_db_get_paths();
633 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
635 for(i = 0; resultArray[i]; i++)
636 printf("%-21s\t%s\n", "GeoIP path:", g_strstrip(resultArray[i]));
638 g_strfreev(resultArray);
644 path = oid_get_default_mib_path();
645 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
647 for(i = 0; resultArray[i]; i++)
648 printf("%-21s\t%s\n", "MIB/PIB path:", g_strstrip(resultArray[i]));
650 g_strfreev(resultArray);
657 main(int argc, char *argv[])
659 GString *comp_info_str;
660 GString *runtime_info_str;
661 char *init_progfile_dir_error;
663 static const struct option long_options[] = {
664 {"help", no_argument, NULL, 'h'},
665 {"version", no_argument, NULL, 'v'},
666 LONGOPT_CAPTURE_COMMON
667 LONGOPT_DISSECT_COMMON
668 {"print", no_argument, NULL, 'P'},
669 {"export-objects", required_argument, NULL, LONGOPT_EXPORT_OBJECTS},
670 {"color", no_argument, NULL, LONGOPT_COLOR},
671 {"no-duplicate-keys", no_argument, NULL, LONGOPT_NO_DUPLICATE_KEYS},
674 gboolean arg_error = FALSE;
682 volatile gboolean success;
683 volatile int exit_status = EXIT_SUCCESS;
685 int caps_queries = 0;
686 gboolean start_capture = FALSE;
690 gboolean capture_option_specified = FALSE;
692 gboolean quiet = FALSE;
693 #ifdef PCAP_NG_DEFAULT
694 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
696 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAP;
698 volatile gboolean out_file_name_res = FALSE;
699 volatile int in_file_type = WTAP_TYPE_AUTO;
700 gchar *volatile cf_name = NULL;
701 gchar *rfilter = NULL;
702 gchar *dfilter = NULL;
703 #ifdef HAVE_PCAP_OPEN_DEAD
704 struct bpf_program fcode;
706 dfilter_t *rfcode = NULL;
707 dfilter_t *dfcode = NULL;
711 gchar *output_only = NULL;
712 gchar *volatile pdu_export_arg = NULL;
713 const char *volatile exp_pdu_filename = NULL;
714 exp_pdu_t exp_pdu_tap_data;
717 * The leading + ensures that getopt_long() does not permute the argv[]
720 * We have to make sure that the first getopt_long() preserves the content
721 * of argv[] for the subsequent getopt_long() call.
723 * We use getopt_long() in both cases to ensure that we're using a routine
724 * whose permutation behavior we can control in the same fashion on all
725 * platforms, and so that, if we ever need to process a long argument before
726 * doing further initialization, we can do so.
728 * Glibc and Solaris libc document that a leading + disables permutation
729 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
730 * and macOS don't document it, but do so anyway.
732 * We do *not* use a leading - because the behavior of a leading - is
733 * platform-dependent.
735 #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:"
737 static const char optstring[] = OPTSTRING;
739 tshark_debug("tshark started with %d args", argc);
741 /* Set the C-language locale to the native environment. */
742 setlocale(LC_ALL, "");
744 cmdarg_err_init(failure_warning_message, failure_message_cont);
747 arg_list_utf_16to8(argc, argv);
748 create_app_running_mutex();
749 #if !GLIB_CHECK_VERSION(2,31,0)
755 * Get credential information for later use, and drop privileges
756 * before doing anything else.
757 * Let the user know if anything happened.
759 init_process_policies();
760 relinquish_special_privs_perm();
761 print_current_user();
764 * Attempt to get the pathname of the directory containing the
767 init_progfile_dir_error = init_progfile_dir(argv[0], main);
768 if (init_progfile_dir_error != NULL) {
770 "tshark: Can't get pathname of directory containing the tshark program: %s.\n"
771 "It won't be possible to capture traffic.\n"
772 "Report this to the Wireshark developers.",
773 init_progfile_dir_error);
774 g_free(init_progfile_dir_error);
777 initialize_funnel_ops();
780 ws_init_dll_search_path();
782 /* Load wpcap if possible. Do this before collecting the run-time version information */
785 /* Warn the user if npf.sys isn't loaded. */
786 if (!npf_sys_is_running() && get_windows_major_version() >= 6) {
787 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
788 "capturing or\nlisting interfaces.\n");
790 #endif /* HAVE_LIBPCAP */
793 /* Get the compile-time version information string */
794 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
795 epan_get_compiled_version_info);
797 /* Get the run-time version information string */
798 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
800 /* Add it to the information to be reported on a crash. */
801 ws_add_crash_info("TShark (Wireshark) %s\n"
806 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
807 g_string_free(comp_info_str, TRUE);
808 g_string_free(runtime_info_str, TRUE);
810 /* Fail sometimes. Useful for testing fuzz scripts. */
811 /* if (g_random_int_range(0, 100) < 5) abort(); */
814 * In order to have the -X opts assigned before the wslua machine starts
815 * we need to call getopt_long before epan_init() gets called.
817 * In order to handle, for example, -o options, we also need to call it
818 * *after* epan_init() gets called, so that the dissectors have had a
819 * chance to register their preferences.
821 * XXX - can we do this all with one getopt_long() call, saving the
822 * arguments we can't handle until after initializing libwireshark,
823 * and then process them after initializing libwireshark?
827 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
829 case 'C': /* Configuration Profile */
830 if (profile_exists (optarg, FALSE)) {
831 set_profile_name (optarg);
833 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
834 exit_status = INVALID_OPTION;
838 case 'P': /* Print packet summary info even when writing to a file */
839 print_packet_info = TRUE;
840 print_summary = TRUE;
842 case 'O': /* Only output these protocols */
843 output_only = g_strdup(optarg);
845 case 'V': /* Verbose */
846 print_details = TRUE;
847 print_packet_info = TRUE;
849 case 'x': /* Print packet data in hex (and ASCII) */
851 /* The user asked for hex output, so let's ensure they get it,
852 * even if they're writing to a file.
854 print_packet_info = TRUE;
864 /** Send All g_log messages to our own handler **/
868 G_LOG_LEVEL_CRITICAL|
873 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
875 g_log_set_handler(NULL,
876 (GLogLevelFlags)log_flags,
877 tshark_log_handler, NULL /* user_data */);
878 g_log_set_handler(LOG_DOMAIN_MAIN,
879 (GLogLevelFlags)log_flags,
880 tshark_log_handler, NULL /* user_data */);
883 g_log_set_handler(LOG_DOMAIN_CAPTURE,
884 (GLogLevelFlags)log_flags,
885 tshark_log_handler, NULL /* user_data */);
886 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
887 (GLogLevelFlags)log_flags,
888 tshark_log_handler, NULL /* user_data */);
891 init_report_message(failure_warning_message, failure_warning_message,
892 open_failure_message, read_failure_message,
893 write_failure_message);
896 capture_opts_init(&global_capture_opts);
897 capture_session_init(&global_capture_session, &cfile);
900 timestamp_set_type(TS_RELATIVE);
901 timestamp_set_precision(TS_PREC_AUTO);
902 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
907 /* Register all the plugin types we have. */
908 epan_register_plugin_types(); /* Types known to libwireshark */
910 /* Scan for plugins. This does *not* call their registration routines;
911 that's done later. */
912 scan_plugins(REPORT_LOAD_FAILURE);
914 /* Register all libwiretap plugin modules. */
915 register_all_wiretap_modules();
918 /* Register all dissectors; we must do this before checking for the
919 "-G" flag, as the "-G" flag dumps information registered by the
920 dissectors, and we must do it before we read the preferences, in
921 case any dissectors register preferences. */
922 if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
924 exit_status = INIT_FAILED;
928 /* Register all tap listeners; we do this before we parse the arguments,
929 as the "-z" argument can specify a registered tap. */
931 /* we register the plugin taps before the other taps because
932 stats_tree taps plugins will be registered as tap listeners
933 by stats_tree_stat.c and need to registered before that */
935 register_all_plugin_tap_listeners();
938 extcap_register_preferences();
940 register_all_tap_listeners();
941 conversation_table_set_gui_info(init_iousers);
942 hostlist_table_set_gui_info(init_hostlists);
943 srt_table_iterate_tables(register_srt_tables, NULL);
944 rtd_table_iterate_tables(register_rtd_tables, NULL);
945 new_stat_tap_iterate_tables(register_simple_stat_tables, NULL);
947 /* If invoked with the "-G" flag, we dump out information based on
948 the argument to the "-G" flag; if no argument is specified,
949 for backwards compatibility we dump out a glossary of display
952 XXX - we do this here, for now, to support "-G" with no arguments.
953 If none of our build or other processes uses "-G" with no arguments,
954 we can just process it with the other arguments. */
955 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
956 proto_initialize_all_prefixes();
959 proto_registrar_dump_fields();
961 if (strcmp(argv[2], "column-formats") == 0)
962 column_dump_column_formats();
963 else if (strcmp(argv[2], "currentprefs") == 0) {
964 epan_load_settings();
967 else if (strcmp(argv[2], "decodes") == 0)
968 dissector_dump_decodes();
969 else if (strcmp(argv[2], "defaultprefs") == 0)
971 else if (strcmp(argv[2], "dissector-tables") == 0)
972 dissector_dump_dissector_tables();
973 else if (strcmp(argv[2], "fieldcount") == 0) {
974 /* return value for the test suite */
975 exit_status = proto_registrar_dump_fieldcount();
977 } else if (strcmp(argv[2], "fields") == 0)
978 proto_registrar_dump_fields();
979 else if (strcmp(argv[2], "folders") == 0)
981 else if (strcmp(argv[2], "ftypes") == 0)
982 proto_registrar_dump_ftypes();
983 else if (strcmp(argv[2], "heuristic-decodes") == 0)
984 dissector_dump_heur_decodes();
985 else if (strcmp(argv[2], "plugins") == 0) {
990 wslua_plugins_dump_all();
993 else if (strcmp(argv[2], "protocols") == 0)
994 proto_registrar_dump_protocols();
995 else if (strcmp(argv[2], "values") == 0)
996 proto_registrar_dump_values();
997 else if (strcmp(argv[2], "help") == 0)
998 glossary_option_help();
999 /* These are supported only for backwards compatibility and may or may not work
1000 * for a given user in a given directory on a given operating system with a given
1001 * command-line interpreter.
1003 else if (strcmp(argv[2], "?") == 0)
1004 glossary_option_help();
1005 else if (strcmp(argv[2], "-?") == 0)
1006 glossary_option_help();
1008 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G help for more help.", argv[2]);
1009 exit_status = INVALID_OPTION;
1013 exit_status = EXIT_SUCCESS;
1017 tshark_debug("tshark reading settings");
1019 /* Load libwireshark settings from the current profile. */
1020 prefs_p = epan_load_settings();
1021 prefs_loaded = TRUE;
1023 read_filter_list(CFILTER_LIST);
1025 cap_file_init(&cfile);
1027 /* Print format defaults to this. */
1028 print_format = PR_FMT_TEXT;
1029 delimiter_char = " ";
1031 output_fields = output_fields_new();
1034 * To reset the options parser, set optreset to 1 on platforms that
1035 * have optreset (documented in *BSD and macOS, apparently present but
1036 * not documented in Solaris - the Illumos repository seems to
1037 * suggest that the first Solaris getopt_long(), at least as of 2004,
1038 * was based on the NetBSD one, it had optreset) and set optind to 1,
1039 * and set optind to 0 otherwise (documented as working in the GNU
1040 * getopt_long(). Setting optind to 0 didn't originally work in the
1041 * NetBSD one, but that was added later - we don't want to depend on
1042 * it if we have optreset).
1044 * Also reset opterr to 1, so that error messages are printed by
1047 #ifdef HAVE_OPTRESET
1055 /* Now get our args */
1056 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1058 case '2': /* Perform two pass analysis */
1059 if(epan_auto_reset){
1060 cmdarg_err("-2 does not support auto session reset.");
1063 perform_two_pass_analysis = TRUE;
1066 if(perform_two_pass_analysis){
1067 cmdarg_err("-M does not support two pass analysis.");
1070 epan_auto_reset_count = get_positive_int(optarg, "epan reset count");
1071 epan_auto_reset = TRUE;
1073 case 'a': /* autostop criteria */
1074 case 'b': /* Ringbuffer option */
1075 case 'c': /* Capture x packets */
1076 case 'f': /* capture filter */
1077 case 'g': /* enable group read access on file(s) */
1078 case 'i': /* Use interface x */
1079 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
1080 case 'p': /* Don't capture in promiscuous mode */
1081 #ifdef HAVE_PCAP_REMOTE
1082 case 'A': /* Authentication */
1084 #ifdef HAVE_PCAP_CREATE
1085 case 'I': /* Capture in monitor mode, if available */
1087 case 's': /* Set the snapshot (capture) length */
1088 case 'w': /* Write to capture file x */
1089 case 'y': /* Set the pcap data link type */
1090 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
1091 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1092 case 'B': /* Buffer size */
1095 exit_status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1096 if (exit_status != 0) {
1102 * Output file name, if we're reading a file and writing to another
1105 output_file_name = optarg;
1107 capture_option_specified = TRUE;
1113 /* already processed; just ignore it now */
1115 case 'D': /* Print a list of capture devices and exit */
1117 if_list = capture_interface_list(&err, &err_str,NULL);
1118 if (if_list == NULL) {
1120 cmdarg_err("There are no interfaces on which a capture can be done");
1122 cmdarg_err("%s", err_str);
1125 exit_status = INVALID_INTERFACE;
1128 capture_opts_print_interfaces(if_list);
1129 free_interface_list(if_list);
1130 exit_status = EXIT_SUCCESS;
1133 capture_option_specified = TRUE;
1139 output_fields_add(output_fields, optarg);
1143 if (!output_fields_set_option(output_fields, optarg)) {
1144 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1145 output_fields_list_options(stderr);
1146 exit_status = INVALID_OPTION;
1151 out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1152 if (out_file_type < 0) {
1153 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1154 list_capture_types();
1155 exit_status = INVALID_OPTION;
1160 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1163 protocolfilter_flags = PF_INCLUDE_CHILDREN;
1164 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1166 case 'W': /* Select extra information to save in our capture file */
1167 /* This is patterned after the -N flag which may not be the best idea. */
1168 if (strchr(optarg, 'n')) {
1169 out_file_name_res = TRUE;
1171 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1172 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1173 exit_status = INVALID_OPTION;
1177 case 'H': /* Read address to name mappings from a hosts file */
1178 if (! add_hosts_file(optarg))
1180 cmdarg_err("Can't read host entries from \"%s\"", optarg);
1181 exit_status = INVALID_OPTION;
1184 out_file_name_res = TRUE;
1187 case 'h': /* Print help and exit */
1188 printf("TShark (Wireshark) %s\n"
1189 "Dump and analyze network traffic.\n"
1190 "See https://www.wireshark.org for more information.\n",
1191 get_ws_vcs_version_info());
1192 print_usage(stdout);
1193 exit_status = EXIT_SUCCESS;
1196 case 'l': /* "Line-buffer" standard output */
1197 /* The ANSI C standard does not appear to *require* that a line-buffered
1198 stream be flushed to the host environment whenever a newline is
1199 written, it just says that, on such a stream, characters "are
1200 intended to be transmitted to or from the host environment as a
1201 block when a new-line character is encountered".
1203 The Visual C++ 6.0 C implementation doesn't do what is intended;
1204 even if you set a stream to be line-buffered, it still doesn't
1205 flush the buffer at the end of every line.
1207 The whole reason for the "-l" flag in either tcpdump or TShark
1208 is to allow the output of a live capture to be piped to a program
1209 or script and to have that script see the information for the
1210 packet as soon as it's printed, rather than having to wait until
1211 a standard I/O buffer fills up.
1213 So, if the "-l" flag is specified, we flush the standard output
1214 at the end of a packet. This will do the right thing if we're
1215 printing packet summary lines, and, as we print the entire protocol
1216 tree for a single packet without waiting for anything to happen,
1217 it should be as good as line-buffered mode if we're printing
1218 protocol trees - arguably even better, as it may do fewer
1220 line_buffered = TRUE;
1222 case 'L': /* Print list of link-layer types and exit */
1224 caps_queries |= CAPS_QUERY_LINK_TYPES;
1226 capture_option_specified = TRUE;
1230 case LONGOPT_LIST_TSTAMP_TYPES: /* List possible timestamp types */
1232 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
1234 capture_option_specified = TRUE;
1238 case 'o': /* Override preference from command line */
1240 char *errmsg = NULL;
1242 switch (prefs_set_pref(optarg, &errmsg)) {
1247 case PREFS_SET_SYNTAX_ERR:
1248 cmdarg_err("Invalid -o flag \"%s\"%s%s", optarg,
1249 errmsg ? ": " : "", errmsg ? errmsg : "");
1251 exit_status = INVALID_OPTION;
1255 case PREFS_SET_NO_SUCH_PREF:
1256 case PREFS_SET_OBSOLETE:
1257 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1258 exit_status = INVALID_OPTION;
1264 case 'q': /* Quiet */
1267 case 'Q': /* Really quiet */
1269 really_quiet = TRUE;
1271 case 'r': /* Read capture file x */
1272 cf_name = g_strdup(optarg);
1274 case 'R': /* Read file filter */
1278 /* already processed; just ignore it now */
1280 case 'S': /* Set the line Separator to be printed between packets */
1283 case 'T': /* printing Type */
1284 print_packet_info = TRUE;
1285 if (strcmp(optarg, "text") == 0) {
1286 output_action = WRITE_TEXT;
1287 print_format = PR_FMT_TEXT;
1288 } else if (strcmp(optarg, "tabs") == 0) {
1289 output_action = WRITE_TEXT;
1290 print_format = PR_FMT_TEXT;
1291 delimiter_char = "\t";
1292 } else if (strcmp(optarg, "ps") == 0) {
1293 output_action = WRITE_TEXT;
1294 print_format = PR_FMT_PS;
1295 } else if (strcmp(optarg, "pdml") == 0) {
1296 output_action = WRITE_XML;
1297 print_details = TRUE; /* Need details */
1298 print_summary = FALSE; /* Don't allow summary */
1299 } else if (strcmp(optarg, "psml") == 0) {
1300 output_action = WRITE_XML;
1301 print_details = FALSE; /* Don't allow details */
1302 print_summary = TRUE; /* Need summary */
1303 } else if (strcmp(optarg, "fields") == 0) {
1304 output_action = WRITE_FIELDS;
1305 print_details = TRUE; /* Need full tree info */
1306 print_summary = FALSE; /* Don't allow summary */
1307 } else if (strcmp(optarg, "json") == 0) {
1308 output_action = WRITE_JSON;
1309 print_details = TRUE; /* Need details */
1310 print_summary = FALSE; /* Don't allow summary */
1311 } else if (strcmp(optarg, "ek") == 0) {
1312 output_action = WRITE_EK;
1314 print_details = TRUE;
1315 } else if (strcmp(optarg, "jsonraw") == 0) {
1316 output_action = WRITE_JSON_RAW;
1317 print_details = TRUE; /* Need details */
1318 print_summary = FALSE; /* Don't allow summary */
1321 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg); /* x */
1322 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1323 "\t specified by the -E option.\n"
1324 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1325 "\t details of a decoded packet. This information is equivalent to\n"
1326 "\t the packet details printed with the -V flag.\n"
1327 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1328 "\t the packets, or a multi-line view of the details of each of\n"
1329 "\t the packets, depending on whether the -V flag was specified.\n"
1330 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1331 "\t summary information of a decoded packet. This information is\n"
1332 "\t equivalent to the information shown in the one-line summary\n"
1333 "\t printed by default.\n"
1334 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1335 "\t summary information of a decoded packet. This information is \n"
1336 "\t equivalent to the packet details printed with the -V flag.\n"
1337 "\t\"jsonraw\" Packet Details, a JSON-based format for machine parsing\n"
1338 "\t including only raw hex decoded fields (same as -T json -x but\n"
1339 "\t without text decoding, only raw fields included). \n"
1340 "\t\"ek\" Packet Details, an EK JSON-based format for the bulk insert \n"
1341 "\t into elastic search cluster. This information is \n"
1342 "\t equivalent to the packet details printed with the -V flag.\n"
1343 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1344 "\t packets, or a multi-line view of the details of each of the\n"
1345 "\t packets, depending on whether the -V flag was specified.\n"
1346 "\t This is the default.\n"
1347 "\t\"tabs\" Similar to the text report except that each column of the\n"
1348 "\t human-readable one-line summary is delimited with an ASCII\n"
1349 "\t horizontal tab character.");
1350 exit_status = INVALID_OPTION;
1354 case 'U': /* Export PDUs to file */
1356 GSList *export_pdu_tap_name_list = NULL;
1359 cmdarg_err("A tap name is required. Valid names are:");
1360 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)) {
1361 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1363 exit_status = INVALID_OPTION;
1366 pdu_export_arg = g_strdup(optarg);
1369 case 'v': /* Show version and exit */
1370 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
1371 epan_get_compiled_version_info);
1372 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
1373 show_version("TShark (Wireshark)", comp_info_str, runtime_info_str);
1374 g_string_free(comp_info_str, TRUE);
1375 g_string_free(runtime_info_str, TRUE);
1376 /* We don't really have to cleanup here, but it's a convenient way to test
1377 * start-up and shut-down of the epan library without any UI-specific
1378 * cruft getting in the way. Makes the results of running
1379 * $ ./tools/valgrind-wireshark -n
1380 * much more useful. */
1385 exit_status = EXIT_SUCCESS;
1387 case 'O': /* Only output these protocols */
1388 /* already processed; just ignore it now */
1390 case 'V': /* Verbose */
1391 /* already processed; just ignore it now */
1393 case 'x': /* Print packet data in hex (and ASCII) */
1394 /* already processed; just ignore it now */
1397 /* already processed; just ignore it now */
1403 /* We won't call the init function for the stat this soon
1404 as it would disallow MATE's fields (which are registered
1405 by the preferences set callback) from being used as
1406 part of a tap filter. Instead, we just add the argument
1407 to a list of stat arguments. */
1408 if (strcmp("help", optarg) == 0) {
1409 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1410 list_stat_cmd_args();
1411 exit_status = EXIT_SUCCESS;
1414 if (!process_stat_cmd_arg(optarg)) {
1415 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1416 list_stat_cmd_args();
1417 exit_status = INVALID_OPTION;
1421 case 'd': /* Decode as rule */
1422 case 'K': /* Kerberos keytab file */
1423 case 'n': /* No name resolution */
1424 case 'N': /* Select what types of addresses/port #s to resolve */
1425 case 't': /* Time stamp type */
1426 case 'u': /* Seconds type */
1427 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1428 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1429 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1430 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
1431 if (!dissect_opts_handle_opt(opt, optarg)) {
1432 exit_status = INVALID_OPTION;
1436 case LONGOPT_EXPORT_OBJECTS: /* --export-objects */
1437 if (strcmp("help", optarg) == 0) {
1438 fprintf(stderr, "tshark: The available export object types for the \"--export-objects\" option are:\n");
1439 eo_list_object_types();
1440 exit_status = EXIT_SUCCESS;
1443 if (!eo_tap_opt_add(optarg)) {
1444 exit_status = INVALID_OPTION;
1448 case LONGOPT_COLOR: /* print in color where appropriate */
1449 dissect_color = TRUE;
1451 case LONGOPT_NO_DUPLICATE_KEYS:
1452 no_duplicate_keys = TRUE;
1453 node_children_grouper = proto_node_group_children_by_json_key;
1456 case '?': /* Bad flag - print usage message */
1459 list_capture_types();
1462 print_usage(stderr);
1464 exit_status = INVALID_OPTION;
1471 * Print packet summary information is the default if neither -V or -x
1472 * were specified. Note that this is new behavior, which allows for the
1473 * possibility of printing only hex/ascii output without necessarily
1474 * requiring that either the summary or details be printed too.
1476 if (!print_summary && !print_details && !print_hex)
1477 print_summary = TRUE;
1479 if (no_duplicate_keys && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW) {
1480 cmdarg_err("--no-duplicate-keys can only be used with \"-T json\" and \"-T jsonraw\"");
1481 exit_status = INVALID_OPTION;
1485 /* If we specified output fields, but not the output field type... */
1486 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1487 cmdarg_err("Output fields were specified with \"-e\", "
1488 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1489 exit_status = INVALID_OPTION;
1491 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1492 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1493 "specified with \"-e\".");
1495 exit_status = INVALID_OPTION;
1499 if (dissect_color) {
1500 if (!color_filters_init(&err_msg, NULL)) {
1501 fprintf(stderr, "%s\n", err_msg);
1506 /* If no capture filter or display filter has been specified, and there are
1507 still command-line arguments, treat them as the tokens of a capture
1508 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1509 flag was specified. */
1510 if (optind < argc) {
1511 if (cf_name != NULL) {
1512 if (dfilter != NULL) {
1513 cmdarg_err("Display filters were specified both with \"-d\" "
1514 "and with additional command-line arguments.");
1515 exit_status = INVALID_OPTION;
1518 dfilter = get_args_as_string(argc, argv, optind);
1523 if (global_capture_opts.default_options.cfilter) {
1524 cmdarg_err("A default capture filter was specified both with \"-f\""
1525 " and with additional command-line arguments.");
1526 exit_status = INVALID_OPTION;
1529 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1530 interface_options *interface_opts;
1531 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
1532 if (interface_opts->cfilter == NULL) {
1533 interface_opts->cfilter = get_args_as_string(argc, argv, optind);
1535 cmdarg_err("A capture filter was specified both with \"-f\""
1536 " and with additional command-line arguments.");
1537 exit_status = INVALID_OPTION;
1541 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1543 capture_option_specified = TRUE;
1549 if (!global_capture_opts.saving_to_file) {
1550 /* We're not saving the capture to a file; if "-q" wasn't specified,
1551 we should print packet information */
1553 print_packet_info = TRUE;
1555 /* We're saving to a file; if we're writing to the standard output.
1556 and we'll also be writing dissected packets to the standard
1557 output, reject the request. At best, we could redirect that
1558 to the standard error; we *can't* write both to the standard
1559 output and have either of them be useful. */
1560 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1561 cmdarg_err("You can't write both raw packet data and dissected packets"
1562 " to the standard output.");
1563 exit_status = INVALID_OPTION;
1568 /* We're not saving the capture to a file; if "-q" wasn't specified,
1569 we should print packet information */
1571 print_packet_info = TRUE;
1574 #ifndef HAVE_LIBPCAP
1575 if (capture_option_specified)
1576 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1579 print_usage(stderr);
1580 exit_status = INVALID_OPTION;
1585 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW && output_action != WRITE_EK) {
1586 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON, JSONRAW or EK JSON");
1587 exit_status = INVALID_OPTION;
1592 if (output_only != NULL) {
1595 if (!print_details) {
1596 cmdarg_err("-O requires -V");
1597 exit_status = INVALID_OPTION;
1601 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1602 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1603 g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1607 if (rfilter != NULL && !perform_two_pass_analysis) {
1608 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1609 exit_status = INVALID_OPTION;
1615 /* We're supposed to list the link-layer/timestamp types for an interface;
1616 did the user also specify a capture file to be read? */
1618 /* Yes - that's bogus. */
1619 cmdarg_err("You can't specify %s and a capture file to be read.",
1620 caps_queries & CAPS_QUERY_LINK_TYPES ? "-L" : "--list-time-stamp-types");
1621 exit_status = INVALID_OPTION;
1624 /* No - did they specify a ring buffer option? */
1625 if (global_capture_opts.multi_files_on) {
1626 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1627 exit_status = INVALID_OPTION;
1633 * "-r" was specified, so we're reading a capture file.
1634 * Capture options don't apply here.
1637 /* We don't support capture filters when reading from a capture file
1638 (the BPF compiler doesn't support all link-layer types that we
1639 support in capture files we read). */
1640 if (global_capture_opts.default_options.cfilter) {
1641 cmdarg_err("Only read filters, not capture filters, "
1642 "can be specified when reading a capture file.");
1643 exit_status = INVALID_OPTION;
1646 if (global_capture_opts.multi_files_on) {
1647 cmdarg_err("Multiple capture files requested, but "
1648 "a capture isn't being done.");
1649 exit_status = INVALID_OPTION;
1652 if (global_capture_opts.has_file_duration) {
1653 cmdarg_err("Switching capture files after a time period was specified, but "
1654 "a capture isn't being done.");
1655 exit_status = INVALID_OPTION;
1658 if (global_capture_opts.has_file_interval) {
1659 cmdarg_err("Switching capture files after a time interval was specified, but "
1660 "a capture isn't being done.");
1661 exit_status = INVALID_OPTION;
1664 if (global_capture_opts.has_ring_num_files) {
1665 cmdarg_err("A ring buffer of capture files was specified, but "
1666 "a capture isn't being done.");
1667 exit_status = INVALID_OPTION;
1670 if (global_capture_opts.has_autostop_files) {
1671 cmdarg_err("A maximum number of capture files was specified, but "
1672 "a capture isn't being done.");
1673 exit_status = INVALID_OPTION;
1676 if (global_capture_opts.capture_comment) {
1677 cmdarg_err("A capture comment was specified, but "
1678 "a capture isn't being done.\nThere's no support for adding "
1679 "a capture comment to an existing capture file.");
1680 exit_status = INVALID_OPTION;
1684 /* Note: TShark now allows the restriction of a _read_ file by packet count
1685 * and byte count as well as a write file. Other autostop options remain valid
1686 * only for a write file.
1688 if (global_capture_opts.has_autostop_duration) {
1689 cmdarg_err("A maximum capture time was specified, but "
1690 "a capture isn't being done.");
1691 exit_status = INVALID_OPTION;
1696 * "-r" wasn't specified, so we're doing a live capture.
1698 if (perform_two_pass_analysis) {
1699 /* Two-pass analysis doesn't work with live capture since it requires us
1700 * to buffer packets until we've read all of them, but a live capture
1701 * has no useful/meaningful definition of "all" */
1702 cmdarg_err("Live captures do not support two-pass analysis.");
1703 exit_status = INVALID_OPTION;
1707 if (global_capture_opts.saving_to_file) {
1708 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1710 /* When capturing, we only support writing pcap or pcap-ng format. */
1711 if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1712 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1713 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1714 exit_status = INVALID_OPTION;
1717 if (global_capture_opts.capture_comment &&
1718 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1719 cmdarg_err("A capture comment can only be written to a pcapng file.");
1720 exit_status = INVALID_OPTION;
1723 if (global_capture_opts.multi_files_on) {
1724 /* Multiple-file mode doesn't work under certain conditions:
1725 a) it doesn't work if you're writing to the standard output;
1726 b) it doesn't work if you're writing to a pipe;
1728 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1729 cmdarg_err("Multiple capture files requested, but "
1730 "the capture is being written to the standard output.");
1731 exit_status = INVALID_OPTION;
1734 if (global_capture_opts.output_to_pipe) {
1735 cmdarg_err("Multiple capture files requested, but "
1736 "the capture file is a pipe.");
1737 exit_status = INVALID_OPTION;
1740 if (!global_capture_opts.has_autostop_filesize &&
1741 !global_capture_opts.has_file_duration &&
1742 !global_capture_opts.has_file_interval) {
1743 cmdarg_err("Multiple capture files requested, but "
1744 "no maximum capture file size, duration or interval was specified.");
1745 exit_status = INVALID_OPTION;
1749 /* Currently, we don't support read or display filters when capturing
1750 and saving the packets. */
1751 if (rfilter != NULL) {
1752 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1753 exit_status = INVALID_OPTION;
1756 if (dfilter != NULL) {
1757 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1758 exit_status = INVALID_OPTION;
1761 global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1763 /* They didn't specify a "-w" flag, so we won't be saving to a
1764 capture file. Check for options that only make sense if
1765 we're saving to a file. */
1766 if (global_capture_opts.has_autostop_filesize) {
1767 cmdarg_err("Maximum capture file size specified, but "
1768 "capture isn't being saved to a file.");
1769 exit_status = INVALID_OPTION;
1772 if (global_capture_opts.multi_files_on) {
1773 cmdarg_err("Multiple capture files requested, but "
1774 "the capture isn't being saved to a file.");
1775 exit_status = INVALID_OPTION;
1778 if (global_capture_opts.capture_comment) {
1779 cmdarg_err("A capture comment was specified, but "
1780 "the capture isn't being saved to a file.");
1781 exit_status = INVALID_OPTION;
1790 /* Start windows sockets */
1791 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1794 exit_status = INIT_FAILED;
1799 /* Notify all registered modules that have had any of their preferences
1800 changed either from one of the preferences file or from the command
1801 line that their preferences have changed. */
1804 /* At this point MATE will have registered its field array so we can
1805 have a tap filter with one of MATE's late-registered fields as part
1806 of the filter. We can now process all the "-z" arguments. */
1807 start_requested_stats();
1809 /* We can also enable specified taps for export object */
1810 start_exportobjects();
1812 /* At this point MATE will have registered its field array so we can
1813 check if the fields specified by the user are all good.
1817 GSList *invalid_fields = output_fields_valid(output_fields);
1818 if (invalid_fields != NULL) {
1820 cmdarg_err("Some fields aren't valid:");
1821 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1822 cmdarg_err_cont("\t%s", (gchar *)it->data);
1824 g_slist_free(invalid_fields);
1825 exit_status = INVALID_OPTION;
1830 /* We currently don't support taps, or printing dissected packets,
1831 if we're writing to a pipe. */
1832 if (global_capture_opts.saving_to_file &&
1833 global_capture_opts.output_to_pipe) {
1834 if (tap_listeners_require_dissection()) {
1835 cmdarg_err("Taps aren't supported when saving to a pipe.");
1836 exit_status = INVALID_OPTION;
1839 if (print_packet_info) {
1840 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1841 exit_status = INVALID_OPTION;
1847 if (ex_opt_count("read_format") > 0) {
1848 const gchar* name = ex_opt_get_next("read_format");
1849 in_file_type = open_info_name_to_type(name);
1850 if (in_file_type == WTAP_TYPE_AUTO) {
1851 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1852 list_read_capture_types();
1853 exit_status = INVALID_OPTION;
1858 timestamp_set_type(global_dissect_options.time_format);
1861 * Enabled and disabled protocols and heuristic dissectors as per
1862 * command-line options.
1864 if (!setup_enabled_and_disabled_protocols()) {
1865 exit_status = INVALID_OPTION;
1869 /* Build the column format array */
1870 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1873 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1874 capture_opts_trim_ring_num_files(&global_capture_opts);
1877 if (rfilter != NULL) {
1878 tshark_debug("Compiling read filter: '%s'", rfilter);
1879 if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1880 cmdarg_err("%s", err_msg);
1886 #ifdef HAVE_PCAP_OPEN_DEAD
1890 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1892 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1894 " Note: That read filter code looks like a valid capture filter;\n"
1895 " maybe you mixed them up?");
1901 exit_status = INVALID_INTERFACE;
1905 cfile.rfcode = rfcode;
1907 if (dfilter != NULL) {
1908 tshark_debug("Compiling display filter: '%s'", dfilter);
1909 if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1910 cmdarg_err("%s", err_msg);
1916 #ifdef HAVE_PCAP_OPEN_DEAD
1920 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1922 if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1924 " Note: That display filter code looks like a valid capture filter;\n"
1925 " maybe you mixed them up?");
1931 exit_status = INVALID_FILTER;
1935 cfile.dfcode = dfcode;
1937 if (print_packet_info) {
1938 /* If we're printing as text or PostScript, we have
1939 to create a print stream. */
1940 if (output_action == WRITE_TEXT) {
1941 switch (print_format) {
1944 print_stream = print_stream_text_stdio_new(stdout);
1948 print_stream = print_stream_ps_stdio_new(stdout);
1952 g_assert_not_reached();
1957 /* PDU export requested. Take the ownership of the '-w' file, apply tap
1958 * filters and start tapping. */
1959 if (pdu_export_arg) {
1960 const char *exp_pdu_tap_name = pdu_export_arg;
1961 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1962 char *exp_pdu_error;
1967 cmdarg_err("PDUs export requires a capture file (specify with -r).");
1968 exit_status = INVALID_OPTION;
1971 /* Take ownership of the '-w' output file. */
1973 exp_pdu_filename = global_capture_opts.save_file;
1974 global_capture_opts.save_file = NULL;
1976 exp_pdu_filename = output_file_name;
1977 output_file_name = NULL;
1979 if (exp_pdu_filename == NULL) {
1980 cmdarg_err("PDUs export requires an output file (-w).");
1981 exit_status = INVALID_OPTION;
1985 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1987 if (exp_pdu_error) {
1988 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1989 g_free(exp_pdu_error);
1990 exit_status = INVALID_TAP;
1994 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1996 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
1997 exit_status = INVALID_FILE;
2001 /* Activate the export PDU tap */
2002 comment = g_strdup_printf("Dump of PDUs from %s", cf_name);
2003 err = exp_pdu_open(&exp_pdu_tap_data, exp_fd, comment);
2005 cfile_dump_open_failure_message("TShark", exp_pdu_filename, err,
2006 WTAP_FILE_TYPE_SUBTYPE_PCAPNG);
2008 exit_status = INVALID_EXPORT;
2013 /* We have to dissect each packet if:
2015 we're printing information about each packet;
2017 we're using a read filter on the packets;
2019 we're using a display filter on the packets;
2021 we're exporting PDUs;
2023 we're using any taps that need dissection. */
2024 do_dissection = print_packet_info || rfcode || dfcode || pdu_export_arg ||
2025 tap_listeners_require_dissection() || dissect_color;
2026 tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2029 tshark_debug("tshark: Opening capture file: %s", cf_name);
2031 * We're reading a capture file.
2033 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
2038 exit_status = INVALID_FILE;
2042 /* Process the packets in the file */
2043 tshark_debug("tshark: invoking process_cap_file() to process the packets");
2046 success = process_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
2047 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
2048 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
2050 success = process_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, 0, 0);
2053 CATCH(OutOfMemoryError) {
2057 "Sorry, but TShark has to terminate now.\n"
2059 "More information and workarounds can be found at\n"
2060 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2066 /* We still dump out the results of taps, etc., as we might have
2067 read some packets; however, we exit with an error status. */
2071 if (pdu_export_arg) {
2072 err = exp_pdu_close(&exp_pdu_tap_data);
2074 cfile_close_failure_message(exp_pdu_filename, err);
2077 g_free(pdu_export_arg);
2080 tshark_debug("tshark: no capture file specified");
2081 /* No capture file specified, so we're supposed to do a live capture
2082 or get a list of link-layer types for a live capture device;
2083 do we have support for live captures? */
2085 /* if no interface was specified, pick a default */
2086 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
2087 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
2088 if (exit_status != 0) {
2092 /* if requested, list the link layer types and exit */
2096 /* Get the list of link-layer types for the capture devices. */
2097 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2098 interface_options *interface_opts;
2099 if_capabilities_t *caps;
2100 char *auth_str = NULL;
2101 int if_caps_queries = caps_queries;
2103 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2104 #ifdef HAVE_PCAP_REMOTE
2105 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
2106 auth_str = g_strdup_printf("%s:%s", interface_opts->auth_username, interface_opts->auth_password);
2109 caps = capture_get_if_capabilities(interface_opts->name, interface_opts->monitor_mode, auth_str, &err_str, NULL);
2112 cmdarg_err("%s", err_str);
2114 exit_status = INVALID_CAPABILITY;
2117 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
2118 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
2119 exit_status = INVALID_DATA_LINK;
2122 if ((if_caps_queries & CAPS_QUERY_TIMESTAMP_TYPES) && caps->timestamp_types == NULL) {
2123 cmdarg_err("The capture device \"%s\" has no timestamp types.", interface_opts->name);
2124 exit_status = INVALID_TIMESTAMP_TYPE;
2127 if (interface_opts->monitor_mode)
2128 if_caps_queries |= CAPS_MONITOR_MODE;
2129 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
2130 free_if_capabilities(caps);
2132 exit_status = EXIT_SUCCESS;
2137 * If the standard error isn't a terminal, don't print packet counts,
2138 * as they won't show up on the user's terminal and they'll get in
2139 * the way of error messages in the file (to which we assume the
2140 * standard error was redirected; if it's redirected to the null
2141 * device, there's no point in printing packet counts anyway).
2143 * Otherwise, if we're printing packet information and the standard
2144 * output is a terminal (which we assume means the standard output and
2145 * error are going to the same terminal), don't print packet counts,
2146 * as they'll get in the way of the packet information.
2148 * Otherwise, if the user specified -q, don't print packet counts.
2150 * Otherwise, print packet counts.
2152 * XXX - what if the user wants to do a live capture, doesn't want
2153 * to save it to a file, doesn't want information printed for each
2154 * packet, does want some "-z" statistic, and wants packet counts
2155 * so they know whether they're seeing any packets? -q will
2156 * suppress the information printed for each packet, but it'll
2157 * also suppress the packet counts.
2159 if (!ws_isatty(ws_fileno(stderr)))
2160 print_packet_counts = FALSE;
2161 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
2162 print_packet_counts = FALSE;
2164 print_packet_counts = FALSE;
2166 print_packet_counts = TRUE;
2168 if (print_packet_info) {
2169 if (!write_preamble(&cfile)) {
2170 show_print_file_io_error(errno);
2171 exit_status = INVALID_FILE;
2176 tshark_debug("tshark: performing live capture");
2178 * XXX - this returns FALSE if an error occurred, but it also
2179 * returns FALSE if the capture stops because a time limit
2180 * was reached (and possibly other limits), so we can't assume
2181 * it means an error.
2183 * The capture code is a bit twisty, so it doesn't appear to
2184 * be an easy fix. We just ignore the return value for now.
2185 * Instead, pass on the exit status from the capture child.
2188 exit_status = global_capture_session.fork_child_status;
2190 if (print_packet_info) {
2191 if (!write_finale()) {
2192 show_print_file_io_error(errno);
2196 /* No - complain. */
2197 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2198 exit_status = INVALID_CAPTURE;
2205 if (cfile.frames != NULL) {
2206 free_frame_data_sequence(cfile.frames);
2207 cfile.frames = NULL;
2210 draw_tap_listeners(TRUE);
2211 funnel_dump_all_text_windows();
2212 epan_free(cfile.epan);
2218 output_fields_free(output_fields);
2219 output_fields = NULL;
2222 destroy_print_stream(print_stream);
2224 capture_opts_cleanup(&global_capture_opts);
2226 col_cleanup(&cfile.cinfo);
2227 free_filter_lists();
2237 /*#define USE_BROKEN_G_MAIN_LOOP*/
2239 #ifdef USE_BROKEN_G_MAIN_LOOP
2242 gboolean loop_running = FALSE;
2244 guint32 packet_count = 0;
2247 typedef struct pipe_input_tag {
2250 ws_process_id *child_process;
2251 pipe_input_cb_t input_cb;
2252 guint pipe_input_id;
2254 GMutex *callback_running;
2258 static pipe_input_t pipe_input;
2261 /* The timer has expired, see if there's stuff to read from the pipe,
2262 if so, do the callback */
2264 pipe_timer_cb(gpointer data)
2270 pipe_input_t *pipe_input_p = data;
2271 gint iterations = 0;
2273 g_mutex_lock (pipe_input_p->callback_running);
2275 /* try to read data from the pipe only 5 times, to avoid blocking */
2276 while(iterations < 5) {
2277 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2279 /* Oddly enough although Named pipes don't work on win9x,
2280 PeekNamedPipe does !!! */
2281 handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2282 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2284 /* Get the child process exit status */
2285 GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2288 /* If the Peek returned an error, or there are bytes to be read
2289 or the childwatcher thread has terminated then call the normal
2291 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2293 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2295 /* And call the real handler */
2296 if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2297 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2298 /* pipe closed, return false so that the timer is stopped */
2299 g_mutex_unlock (pipe_input_p->callback_running);
2304 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2305 /* No data, stop now */
2312 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2314 g_mutex_unlock (pipe_input_p->callback_running);
2316 /* we didn't stopped the timer, so let it run */
2323 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2326 pipe_input.source = source;
2327 pipe_input.child_process = child_process;
2328 pipe_input.user_data = user_data;
2329 pipe_input.input_cb = input_cb;
2332 #if GLIB_CHECK_VERSION(2,31,0)
2333 pipe_input.callback_running = g_malloc(sizeof(GMutex));
2334 g_mutex_init(pipe_input.callback_running);
2336 pipe_input.callback_running = g_mutex_new();
2338 /* Tricky to use pipes in win9x, as no concept of wait. NT can
2339 do this but that doesn't cover all win32 platforms. GTK can do
2340 this but doesn't seem to work over processes. Attempt to do
2341 something similar here, start a timer and check for data on every
2343 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2344 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2348 static const nstime_t *
2349 tshark_get_frame_ts(void *data, guint32 frame_num)
2351 capture_file *cf = (capture_file *) data;
2353 if (ref && ref->num == frame_num)
2354 return &ref->abs_ts;
2356 if (prev_dis && prev_dis->num == frame_num)
2357 return &prev_dis->abs_ts;
2359 if (prev_cap && prev_cap->num == frame_num)
2360 return &prev_cap->abs_ts;
2363 frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);
2365 return (fd) ? &fd->abs_ts : NULL;
2372 tshark_epan_new(capture_file *cf)
2374 epan_t *epan = epan_new();
2377 epan->get_frame_ts = tshark_get_frame_ts;
2378 epan->get_interface_name = cap_file_get_interface_name;
2379 epan->get_interface_description = cap_file_get_interface_description;
2380 epan->get_user_comment = NULL;
2392 #ifdef USE_TSHARK_SELECT
2396 struct sigaction action, oldaction;
2399 /* Create new dissection section. */
2400 epan_free(cfile.epan);
2401 cfile.epan = tshark_epan_new(&cfile);
2404 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2405 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2407 /* Catch SIGINT and SIGTERM and, if we get either of them,
2408 clean up and exit. If SIGHUP isn't being ignored, catch
2409 it too and, if we get it, clean up and exit.
2411 We restart any read that was in progress, so that it doesn't
2412 disrupt reading from the sync pipe. The signal handler tells
2413 the capture child to finish; it will report that it finished,
2414 or will exit abnormally, so we'll stop reading from the sync
2415 pipe, pick up the exit status, and quit. */
2416 memset(&action, 0, sizeof(action));
2417 action.sa_handler = capture_cleanup;
2418 action.sa_flags = SA_RESTART;
2419 sigemptyset(&action.sa_mask);
2420 sigaction(SIGTERM, &action, NULL);
2421 sigaction(SIGINT, &action, NULL);
2422 sigaction(SIGHUP, NULL, &oldaction);
2423 if (oldaction.sa_handler == SIG_DFL)
2424 sigaction(SIGHUP, &action, NULL);
2427 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2428 quiet mode, report the number of packets we've captured.
2430 Again, restart any read that was in progress, so that it doesn't
2431 disrupt reading from the sync pipe. */
2432 action.sa_handler = report_counts_siginfo;
2433 action.sa_flags = SA_RESTART;
2434 sigemptyset(&action.sa_mask);
2435 sigaction(SIGINFO, &action, NULL);
2436 #endif /* SIGINFO */
2439 global_capture_session.state = CAPTURE_PREPARING;
2441 /* Let the user know which interfaces were chosen. */
2442 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2443 interface_options *interface_opts;
2445 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2446 interface_opts->descr = get_interface_descriptive_name(interface_opts->name);
2448 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2449 if (really_quiet == FALSE)
2450 fprintf(stderr, "Capturing on %s\n", str->str);
2452 g_string_free(str, TRUE);
2454 ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2459 /* the actual capture loop
2461 * XXX - glib doesn't seem to provide any event based loop handling.
2463 * XXX - for whatever reason,
2464 * calling g_main_loop_new() ends up in 100% cpu load.
2466 * But that doesn't matter: in UNIX we can use select() to find an input
2467 * source with something to do.
2469 * But that doesn't matter because we're in a CLI (that doesn't need to
2470 * update a GUI or something at the same time) so it's OK if we block
2471 * trying to read from the pipe.
2473 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2474 * wrong (but I leave it there in case I am...).
2477 #ifdef USE_TSHARK_SELECT
2479 FD_SET(pipe_input.source, &readfds);
2482 loop_running = TRUE;
2486 while (loop_running)
2488 #ifdef USE_TSHARK_SELECT
2489 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2493 fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2495 } else if (ret == 1) {
2497 /* Call the real handler */
2498 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2499 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2502 #ifdef USE_TSHARK_SELECT
2507 CATCH(OutOfMemoryError) {
2511 "Sorry, but TShark has to terminate now.\n"
2513 "More information and workarounds can be found at\n"
2514 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2521 /* capture child detected an error */
2523 capture_input_error_message(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2525 cmdarg_err("%s", error_msg);
2526 cmdarg_err_cont("%s", secondary_error_msg);
2530 /* capture child detected an capture filter related error */
2532 capture_input_cfilter_error_message(capture_session *cap_session, guint i, char *error_message)
2534 capture_options *capture_opts = cap_session->capture_opts;
2535 dfilter_t *rfcode = NULL;
2536 interface_options *interface_opts;
2538 g_assert(i < capture_opts->ifaces->len);
2539 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2541 if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
2543 "Invalid capture filter \"%s\" for interface '%s'.\n"
2545 "That string looks like a valid display filter; however, it isn't a valid\n"
2546 "capture filter (%s).\n"
2548 "Note that display filters and capture filters don't have the same syntax,\n"
2549 "so you can't use most display filter expressions as capture filters.\n"
2551 "See the User's Guide for a description of the capture filter syntax.",
2552 interface_opts->cfilter, interface_opts->descr, error_message);
2553 dfilter_free(rfcode);
2556 "Invalid capture filter \"%s\" for interface '%s'.\n"
2558 "That string isn't a valid capture filter (%s).\n"
2559 "See the User's Guide for a description of the capture filter syntax.",
2560 interface_opts->cfilter, interface_opts->descr, error_message);
2565 /* capture child tells us we have a new (or the first) capture file */
2567 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2569 capture_options *capture_opts = cap_session->capture_opts;
2570 capture_file *cf = (capture_file *) cap_session->cf;
2571 gboolean is_tempfile;
2574 if (cap_session->state == CAPTURE_PREPARING) {
2575 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2577 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2579 g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2581 /* free the old filename */
2582 if (capture_opts->save_file != NULL) {
2584 /* we start a new capture file, close the old one (if we had one before) */
2585 if (cf->state != FILE_CLOSED) {
2586 if (cf->wth != NULL) {
2587 wtap_close(cf->wth);
2590 cf->state = FILE_CLOSED;
2593 g_free(capture_opts->save_file);
2594 is_tempfile = FALSE;
2596 epan_free(cf->epan);
2597 cf->epan = tshark_epan_new(cf);
2599 /* we didn't had a save_file before, must be a tempfile */
2603 /* save the new filename */
2604 capture_opts->save_file = g_strdup(new_file);
2606 /* if we are in real-time mode, open the new file now */
2607 if (do_dissection) {
2608 /* this is probably unecessary, but better safe than sorry */
2609 ((capture_file *)cap_session->cf)->open_type = WTAP_TYPE_AUTO;
2610 /* Attempt to open the capture file and set up to read from it. */
2611 switch(cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2615 /* Don't unlink (delete) the save file - leave it around,
2616 for debugging purposes. */
2617 g_free(capture_opts->save_file);
2618 capture_opts->save_file = NULL;
2623 cap_session->state = CAPTURE_RUNNING;
2629 /* capture child tells us we have new packets to read */
2631 capture_input_new_packets(capture_session *cap_session, int to_read)
2637 capture_file *cf = (capture_file *)cap_session->cf;
2638 gboolean filtering_tap_listeners;
2643 * Prevent a SIGINFO handler from writing to the standard error while
2644 * we're doing so or writing to the standard output; instead, have it
2645 * just set a flag telling us to print that information when we're done.
2648 #endif /* SIGINFO */
2650 /* Do we have any tap listeners with filters? */
2651 filtering_tap_listeners = have_filtering_tap_listeners();
2653 /* Get the union of the flags for all tap listeners. */
2654 tap_flags = union_of_tap_listener_flags();
2656 if (do_dissection) {
2657 gboolean create_proto_tree;
2658 epan_dissect_t *edt;
2661 * Determine whether we need to create a protocol tree.
2664 * we're going to apply a read filter;
2666 * we're going to apply a display filter;
2668 * we're going to print the protocol tree;
2670 * one of the tap listeners is going to apply a filter;
2672 * one of the tap listeners requires a protocol tree;
2674 * a postdissector wants field values or protocols
2675 * on the first pass;
2677 * we have custom columns (which require field values, which
2678 * currently requires that we build a protocol tree).
2681 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2682 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
2683 have_custom_cols(&cf->cinfo) || dissect_color);
2685 /* The protocol tree will be "visible", i.e., printed, only if we're
2686 printing packet details, which is true if we're printing stuff
2687 ("print_packet_info" is true) and we're in verbose mode
2688 ("packet_details" is true). */
2689 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2691 while (to_read-- && cf->wth) {
2692 wtap_cleareof(cf->wth);
2693 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2694 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
2696 /* read from file failed, tell the capture child to stop */
2697 sync_pipe_stop(cap_session);
2698 wtap_close(cf->wth);
2701 ret = process_packet_single_pass(cf, edt, data_offset,
2703 wtap_buf_ptr(cf->wth), tap_flags);
2706 /* packet successfully read and gone through the "Read Filter" */
2711 epan_dissect_free(edt);
2715 * Dumpcap's doing all the work; we're not doing any dissection.
2716 * Count all the packets it wrote.
2718 packet_count += to_read;
2721 if (print_packet_counts) {
2722 /* We're printing packet counts. */
2723 if (packet_count != 0) {
2724 fprintf(stderr, "\r%u ", packet_count);
2725 /* stderr could be line buffered */
2732 * Allow SIGINFO handlers to write.
2737 * If a SIGINFO handler asked us to write out capture counts, do so.
2741 #endif /* SIGINFO */
2747 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2748 /* Report the count only if we aren't printing a packet count
2749 as packets arrive. */
2750 fprintf(stderr, "%u packet%s captured\n", packet_count,
2751 plurality(packet_count, "", "s"));
2754 infoprint = FALSE; /* we just reported it */
2755 #endif /* SIGINFO */
2760 report_counts_siginfo(int signum _U_)
2762 int sav_errno = errno;
2763 /* If we've been told to delay printing, just set a flag asking
2764 that we print counts (if we're supposed to), otherwise print
2765 the count of packets captured (if we're supposed to). */
2772 #endif /* SIGINFO */
2775 /* capture child detected any packet drops? */
2777 capture_input_drops(capture_session *cap_session _U_, guint32 dropped)
2779 if (print_packet_counts) {
2780 /* We're printing packet counts to stderr.
2781 Send a newline so that we move to the line after the packet count. */
2782 fprintf(stderr, "\n");
2786 /* We're printing packet counts to stderr.
2787 Send a newline so that we move to the line after the packet count. */
2788 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2794 * Capture child closed its side of the pipe, report any error and
2795 * do the required cleanup.
2798 capture_input_closed(capture_session *cap_session, gchar *msg)
2800 capture_file *cf = (capture_file *) cap_session->cf;
2803 fprintf(stderr, "tshark: %s\n", msg);
2807 if (cf != NULL && cf->wth != NULL) {
2808 wtap_close(cf->wth);
2809 if (cf->is_tempfile) {
2810 ws_unlink(cf->filename);
2813 #ifdef USE_BROKEN_G_MAIN_LOOP
2814 /*g_main_loop_quit(loop);*/
2815 g_main_loop_quit(loop);
2817 loop_running = FALSE;
2826 capture_cleanup(DWORD ctrltype _U_)
2828 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2829 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2830 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2831 like SIGTERM at least when the machine's shutting down.
2833 For now, we handle them all as indications that we should clean up
2834 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2837 We must return TRUE so that no other handler - such as one that would
2838 terminate the process - gets called.
2840 XXX - for some reason, typing ^C to TShark, if you run this in
2841 a Cygwin console window in at least some versions of Cygwin,
2842 causes TShark to terminate immediately; this routine gets
2843 called, but the main loop doesn't get a chance to run and
2844 exit cleanly, at least if this is compiled with Microsoft Visual
2845 C++ (i.e., it's a property of the Cygwin console window or Bash;
2846 it happens if TShark is not built with Cygwin - for all I know,
2847 building it with Cygwin may make the problem go away). */
2849 /* tell the capture child to stop */
2850 sync_pipe_stop(&global_capture_session);
2852 /* don't stop our own loop already here, otherwise status messages and
2853 * cleanup wouldn't be done properly. The child will indicate the stop of
2854 * everything by calling capture_input_closed() later */
2860 capture_cleanup(int signum _U_)
2862 /* tell the capture child to stop */
2863 sync_pipe_stop(&global_capture_session);
2865 /* don't stop our own loop already here, otherwise status messages and
2866 * cleanup wouldn't be done properly. The child will indicate the stop of
2867 * everything by calling capture_input_closed() later */
2870 #endif /* HAVE_LIBPCAP */
2873 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2874 gint64 offset, struct wtap_pkthdr *whdr,
2881 /* The frame number of this packet is one more than the count of
2882 frames in this packet. */
2883 framenum = cf->count + 1;
2885 /* If we're not running a display filter and we're not printing any
2886 packet information, we don't need to do a dissection. This means
2887 that all packets can be marked as 'passed'. */
2890 frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
2892 /* If we're going to run a read filter or a display filter, set up to
2893 do a dissection and do so. (This is the first pass of two passes
2894 over the packets, so we will not be printing any information
2895 from the dissection or running taps on the packet; if we're doing
2896 any of that, we'll do it in the second pass.) */
2898 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2899 gbl_resolv_flags.transport_name)
2900 /* Grab any resolved addresses */
2901 host_name_lookup_process();
2903 /* If we're running a read filter, prime the epan_dissect_t with that
2906 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
2909 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2911 /* This is the first pass, so prime the epan_dissect_t with the
2912 hfids postdissectors want on the first pass. */
2913 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
2915 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2917 if (ref == &fdlocal) {
2918 ref_frame = fdlocal;
2922 epan_dissect_run(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdlocal, pd), &fdlocal, NULL);
2924 /* Run the read filter if we have one. */
2926 passed = dfilter_apply_edt(cf->rfcode, edt);
2930 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2931 prev_cap = prev_dis = frame_data_sequence_add(cf->frames, &fdlocal);
2933 /* If we're not doing dissection then there won't be any dependent frames.
2934 * More importantly, edt.pi.dependent_frames won't be initialized because
2935 * epan hasn't been initialized.
2936 * if we *are* doing dissection, then mark the dependent frames, but only
2937 * if a display filter was given and it matches this packet.
2939 if (edt && cf->dfcode) {
2940 if (dfilter_apply_edt(cf->dfcode, edt)) {
2941 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
2947 /* if we don't add it to the frame_data_sequence, clean it up right now
2949 frame_data_destroy(&fdlocal);
2953 epan_dissect_reset(edt);
2959 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
2960 frame_data *fdata, struct wtap_pkthdr *phdr,
2961 Buffer *buf, guint tap_flags)
2966 /* If we're not running a display filter and we're not printing any
2967 packet information, we don't need to do a dissection. This means
2968 that all packets can be marked as 'passed'. */
2971 /* If we're going to print packet information, or we're going to
2972 run a read filter, or we're going to process taps, set up to
2973 do a dissection and do so. (This is the second pass of two
2974 passes over the packets; that's the pass where we print
2975 packet information or run taps.) */
2977 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2978 gbl_resolv_flags.transport_name)
2979 /* Grab any resolved addresses */
2980 host_name_lookup_process();
2982 /* If we're running a display filter, prime the epan_dissect_t with that
2985 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2987 col_custom_prime_edt(edt, &cf->cinfo);
2989 /* We only need the columns if either
2990 1) some tap needs the columns
2992 2) we're printing packet info but we're *not* verbose; in verbose
2993 mode, we print the protocol tree, not the protocol summary.
2995 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3000 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
3007 if (dissect_color) {
3008 color_filters_prime_edt(edt);
3009 fdata->flags.need_colorize = 1;
3012 epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new_buffer(fdata, buf), fdata, cinfo);
3014 /* Run the read/display filter if we have one. */
3016 passed = dfilter_apply_edt(cf->dfcode, edt);
3020 frame_data_set_after_dissect(fdata, &cum_bytes);
3021 /* Process this packet. */
3022 if (print_packet_info) {
3023 /* We're printing packet information; print the information for
3025 print_packet(cf, edt);
3027 /* If we're doing "line-buffering", flush the standard output
3028 after every packet. See the comment above, for the "-l"
3029 option, for an explanation of why we do that. */
3033 if (ferror(stdout)) {
3034 show_print_file_io_error(errno);
3043 epan_dissect_reset(edt);
3045 return passed || fdata->flags.dependent_of_displayed;
3049 process_cap_file(capture_file *cf, char *save_file, int out_file_type,
3050 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
3052 gboolean success = TRUE;
3054 int snapshot_length;
3057 int err = 0, err_pass1 = 0;
3058 gchar *err_info = NULL, *err_info_pass1 = NULL;
3060 gboolean filtering_tap_listeners;
3062 GArray *shb_hdrs = NULL;
3063 wtapng_iface_descriptions_t *idb_inf = NULL;
3064 GArray *nrb_hdrs = NULL;
3065 struct wtap_pkthdr phdr;
3067 epan_dissect_t *edt = NULL;
3068 char *shb_user_appl;
3070 wtap_phdr_init(&phdr);
3072 idb_inf = wtap_file_get_idb_info(cf->wth);
3073 #ifdef PCAP_NG_DEFAULT
3074 if (idb_inf->interface_data->len > 1) {
3075 linktype = WTAP_ENCAP_PER_PACKET;
3077 linktype = wtap_file_encap(cf->wth);
3080 linktype = wtap_file_encap(cf->wth);
3082 if (save_file != NULL) {
3083 /* Set up to write to the capture file. */
3084 snapshot_length = wtap_snapshot_length(cf->wth);
3085 if (snapshot_length == 0) {
3086 /* Snapshot length of input file not known. */
3087 snapshot_length = WTAP_MAX_PACKET_SIZE_STANDARD;
3089 tshark_debug("tshark: snapshot_length = %d", snapshot_length);
3091 shb_hdrs = wtap_file_get_shb_for_new_file(cf->wth);
3092 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->wth);
3094 /* If we don't have an application name add Tshark */
3095 if (wtap_block_get_string_option_value(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
3096 /* this is free'd by wtap_block_free() later */
3097 wtap_block_add_string_option_format(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "TShark (Wireshark) %s", get_ws_vcs_version_info());
3100 if (linktype != WTAP_ENCAP_PER_PACKET &&
3101 out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAP) {
3102 tshark_debug("tshark: writing PCAP format to %s", save_file);
3103 if (strcmp(save_file, "-") == 0) {
3104 /* Write to the standard output. */
3105 pdh = wtap_dump_open_stdout(out_file_type, linktype,
3106 snapshot_length, FALSE /* compressed */, &err);
3108 pdh = wtap_dump_open(save_file, out_file_type, linktype,
3109 snapshot_length, FALSE /* compressed */, &err);
3113 tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
3114 if (strcmp(save_file, "-") == 0) {
3115 /* Write to the standard output. */
3116 pdh = wtap_dump_open_stdout_ng(out_file_type, linktype,
3117 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
3119 pdh = wtap_dump_open_ng(save_file, out_file_type, linktype,
3120 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
3128 /* We couldn't set up to write to the capture file. */
3129 cfile_dump_open_failure_message("TShark", save_file, err, out_file_type);
3134 /* Set up to print packet information. */
3135 if (print_packet_info) {
3136 if (!write_preamble(cf)) {
3137 show_print_file_io_error(errno);
3147 /* Do we have any tap listeners with filters? */
3148 filtering_tap_listeners = have_filtering_tap_listeners();
3150 /* Get the union of the flags for all tap listeners. */
3151 tap_flags = union_of_tap_listener_flags();
3153 if (perform_two_pass_analysis) {
3156 tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3158 /* Allocate a frame_data_sequence for all the frames. */
3159 cf->frames = new_frame_data_sequence();
3161 if (do_dissection) {
3162 gboolean create_proto_tree;
3165 * Determine whether we need to create a protocol tree.
3168 * we're going to apply a read filter;
3170 * we're going to apply a display filter;
3172 * a postdissector wants field values or protocols
3173 * on the first pass.
3176 (cf->rfcode != NULL || cf->dfcode != NULL || postdissectors_want_hfids() || dissect_color);
3178 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3180 /* We're not going to display the protocol tree on this pass,
3181 so it's not going to be "visible". */
3182 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
3185 tshark_debug("tshark: reading records for first pass");
3186 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
3187 if (process_packet_first_pass(cf, edt, data_offset, wtap_phdr(cf->wth),
3188 wtap_buf_ptr(cf->wth))) {
3189 /* Stop reading if we have the maximum number of packets;
3190 * When the -c option has not been used, max_packet_count
3191 * starts at 0, which practically means, never stop reading.
3192 * (unless we roll over max_packet_count ?)
3194 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3195 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3196 max_packet_count, data_offset, max_byte_count);
3197 err = 0; /* This is not an error */
3204 * If we got a read error on the first pass, remember the error, so
3205 * but do the second pass, so we can at least process the packets we
3206 * read, and then report the first-pass error after the second pass
3207 * (and before we report any second-pass errors), so all the the
3208 * errors show up at the end.
3212 err_info_pass1 = err_info;
3218 epan_dissect_free(edt);
3222 /* Close the sequential I/O side, to free up memory it requires. */
3223 wtap_sequential_close(cf->wth);
3225 /* Allow the protocol dissectors to free up memory that they
3226 * don't need after the sequential run-through of the packets. */
3227 postseq_cleanup_all_protocols();
3231 ws_buffer_init(&buf, 1500);
3233 tshark_debug("tshark: done with first pass");
3235 if (do_dissection) {
3236 gboolean create_proto_tree;
3239 * Determine whether we need to create a protocol tree.
3242 * we're going to apply a display filter;
3244 * we're going to print the protocol tree;
3246 * one of the tap listeners requires a protocol tree;
3248 * we have custom columns (which require field values, which
3249 * currently requires that we build a protocol tree).
3252 (cf->dfcode || print_details || filtering_tap_listeners ||
3253 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo) || dissect_color);
3255 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3257 /* The protocol tree will be "visible", i.e., printed, only if we're
3258 printing packet details, which is true if we're printing stuff
3259 ("print_packet_info" is true) and we're in verbose mode
3260 ("packet_details" is true). */
3261 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3264 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
3265 fdata = frame_data_sequence_find(cf->frames, framenum);
3266 if (wtap_seek_read(cf->wth, fdata->file_off, &phdr, &buf, &err,
3268 tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3269 if (process_packet_second_pass(cf, edt, fdata, &phdr, &buf,
3271 /* Either there's no read filtering or this packet passed the
3272 filter, so, if we're writing to a capture file, write
3275 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3276 if (!wtap_dump(pdh, &phdr, ws_buffer_start_ptr(&buf), &err, &err_info)) {
3277 /* Error writing to a capture file */
3278 tshark_debug("tshark: error writing to a capture file (%d)", err);
3280 /* Report the error.
3281 XXX - framenum is not necessarily the frame number in
3282 the input file if there was a read filter. */
3283 cfile_write_failure_message("TShark", cf->filename, save_file,
3284 err, err_info, framenum,
3286 wtap_dump_close(pdh, &err);
3287 wtap_block_array_free(shb_hdrs);
3288 wtap_block_array_free(nrb_hdrs);
3297 epan_dissect_free(edt);
3301 ws_buffer_free(&buf);
3303 tshark_debug("tshark: done with second pass");
3306 /* !perform_two_pass_analysis */
3308 gboolean create_proto_tree = FALSE;
3309 tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3311 if (do_dissection) {
3313 * Determine whether we need to create a protocol tree.
3316 * we're going to apply a read filter;
3318 * we're going to apply a display filter;
3320 * we're going to print the protocol tree;
3322 * one of the tap listeners is going to apply a filter;
3324 * one of the tap listeners requires a protocol tree;
3326 * a postdissector wants field values or protocols
3327 * on the first pass;
3329 * we have custom columns (which require field values, which
3330 * currently requires that we build a protocol tree).
3333 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3334 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3335 have_custom_cols(&cf->cinfo) || dissect_color);
3337 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3339 /* The protocol tree will be "visible", i.e., printed, only if we're
3340 printing packet details, which is true if we're printing stuff
3341 ("print_packet_info" is true) and we're in verbose mode
3342 ("packet_details" is true). */
3343 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3346 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
3349 tshark_debug("tshark: processing packet #%d", framenum);
3351 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3353 if (process_packet_single_pass(cf, edt, data_offset, wtap_phdr(cf->wth),
3354 wtap_buf_ptr(cf->wth), tap_flags)) {
3355 /* Either there's no read filtering or this packet passed the
3356 filter, so, if we're writing to a capture file, write
3359 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3360 if (!wtap_dump(pdh, wtap_phdr(cf->wth), wtap_buf_ptr(cf->wth), &err, &err_info)) {
3361 /* Error writing to a capture file */
3362 tshark_debug("tshark: error writing to a capture file (%d)", err);
3363 cfile_write_failure_message("TShark", cf->filename, save_file,
3364 err, err_info, framenum, out_file_type);
3365 wtap_dump_close(pdh, &err);
3366 wtap_block_array_free(shb_hdrs);
3367 wtap_block_array_free(nrb_hdrs);
3372 /* Stop reading if we have the maximum number of packets;
3373 * When the -c option has not been used, max_packet_count
3374 * starts at 0, which practically means, never stop reading.
3375 * (unless we roll over max_packet_count ?)
3377 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3378 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3379 max_packet_count, data_offset, max_byte_count);
3380 err = 0; /* This is not an error */
3386 epan_dissect_free(edt);
3391 wtap_phdr_cleanup(&phdr);
3393 if (err != 0 || err_pass1 != 0) {
3394 tshark_debug("tshark: something failed along the line (%d)", err);
3396 * Print a message noting that the read failed somewhere along the line.
3398 * If we're printing packet data, and the standard output and error are
3399 * going to the same place, flush the standard output, so everything
3400 * buffered up is written, and then print a newline to the standard error
3401 * before printing the error message, to separate it from the packet
3402 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
3403 * the _fstat() documentation at Microsoft doesn't indicate whether
3404 * st_ino is even supported.)
3407 if (print_packet_info) {
3408 ws_statb64 stat_stdout, stat_stderr;
3410 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3411 if (stat_stdout.st_dev == stat_stderr.st_dev &&
3412 stat_stdout.st_ino == stat_stderr.st_ino) {
3414 fprintf(stderr, "\n");
3419 if (err_pass1 != 0) {
3420 /* Error on pass 1 of two-pass processing. */
3421 cfile_read_failure_message("TShark", cf->filename, err_pass1,
3425 /* Error on pass 2 of two-pass processing or on the only pass of
3426 one-pass processing. */
3427 cfile_read_failure_message("TShark", cf->filename, err, err_info);
3431 if (save_file != NULL) {
3432 if (pdh && out_file_name_res) {
3433 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3434 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3435 wtap_file_type_subtype_short_string(out_file_type));
3438 /* Now close the capture file. */
3439 if (!wtap_dump_close(pdh, &err)) {
3440 cfile_close_failure_message(save_file, err);
3444 if (print_packet_info) {
3445 if (!write_finale()) {
3446 show_print_file_io_error(errno);
3453 wtap_close(cf->wth);
3456 wtap_block_array_free(shb_hdrs);
3457 wtap_block_array_free(nrb_hdrs);
3463 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, gint64 offset,
3464 struct wtap_pkthdr *whdr, const guchar *pd,
3471 /* Count this packet. */
3474 /* If we're not running a display filter and we're not printing any
3475 packet information, we don't need to do a dissection. This means
3476 that all packets can be marked as 'passed'. */
3479 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
3481 /* If we're going to print packet information, or we're going to
3482 run a read filter, or we're going to process taps, set up to
3483 do a dissection and do so. (This is the one and only pass
3484 over the packets, so, if we'll be printing packet information
3485 or running taps, we'll be doing it here.) */
3487 if (print_packet_info && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
3488 gbl_resolv_flags.transport_name))
3489 /* Grab any resolved addresses */
3490 host_name_lookup_process();
3492 /* If we're running a filter, prime the epan_dissect_t with that
3495 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3497 /* This is the first and only pass, so prime the epan_dissect_t
3498 with the hfids postdissectors want on the first pass. */
3499 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
3501 col_custom_prime_edt(edt, &cf->cinfo);
3503 /* We only need the columns if either
3504 1) some tap needs the columns
3506 2) we're printing packet info but we're *not* verbose; in verbose
3507 mode, we print the protocol tree, not the protocol summary.
3509 3) there is a column mapped as an individual field */
3510 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3515 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3517 if (ref == &fdata) {
3522 if (dissect_color) {
3523 color_filters_prime_edt(edt);
3524 fdata.flags.need_colorize = 1;
3527 epan_dissect_run_with_taps(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdata, pd), &fdata, cinfo);
3529 /* Run the filter if we have it. */
3531 passed = dfilter_apply_edt(cf->dfcode, edt);
3535 frame_data_set_after_dissect(&fdata, &cum_bytes);
3537 /* Process this packet. */
3538 if (print_packet_info) {
3539 /* We're printing packet information; print the information for
3542 print_packet(cf, edt);
3544 /* If we're doing "line-buffering", flush the standard output
3545 after every packet. See the comment above, for the "-l"
3546 option, for an explanation of why we do that. */
3550 if (ferror(stdout)) {
3551 show_print_file_io_error(errno);
3556 /* this must be set after print_packet() [bug #8160] */
3557 prev_dis_frame = fdata;
3558 prev_dis = &prev_dis_frame;
3561 prev_cap_frame = fdata;
3562 prev_cap = &prev_cap_frame;
3565 epan_dissect_reset(edt);
3566 frame_data_destroy(&fdata);
3572 write_preamble(capture_file *cf)
3574 switch (output_action) {
3577 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3581 write_pdml_preamble(stdout, cf->filename);
3583 write_psml_preamble(&cf->cinfo, stdout);
3584 return !ferror(stdout);
3587 write_fields_preamble(output_fields, stdout);
3588 return !ferror(stdout);
3591 case WRITE_JSON_RAW:
3592 write_json_preamble(stdout);
3593 return !ferror(stdout);
3596 return !ferror(stdout);
3599 g_assert_not_reached();
3605 get_line_buf(size_t len)
3607 static char *line_bufp = NULL;
3608 static size_t line_buf_len = 256;
3609 size_t new_line_buf_len;
3611 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3612 new_line_buf_len *= 2)
3614 if (line_bufp == NULL) {
3615 line_buf_len = new_line_buf_len;
3616 line_bufp = (char *)g_malloc(line_buf_len + 1);
3618 if (new_line_buf_len > line_buf_len) {
3619 line_buf_len = new_line_buf_len;
3620 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3627 put_string(char *dest, const char *str, size_t str_len)
3629 memcpy(dest, str, str_len);
3630 dest[str_len] = '\0';
3634 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3638 for (i = str_len; i < str_with_spaces; i++)
3641 put_string(dest, str, str_len);
3645 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3649 memcpy(dest, str, str_len);
3650 for (i = str_len; i < str_with_spaces; i++)
3653 dest[str_with_spaces] = '\0';
3657 print_columns(capture_file *cf, const epan_dissect_t *edt)
3664 col_item_t* col_item;
3665 gchar str_format[11];
3666 const color_filter_t *color_filter = NULL;
3668 line_bufp = get_line_buf(256);
3673 color_filter = edt->pi.fd->color_filter;
3675 for (i = 0; i < cf->cinfo.num_cols; i++) {
3676 col_item = &cf->cinfo.columns[i];
3677 /* Skip columns not marked as visible. */
3678 if (!get_column_visible(i))
3680 switch (col_item->col_fmt) {
3682 column_len = col_len = strlen(col_item->col_data);
3685 line_bufp = get_line_buf(buf_offset + column_len);
3686 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3692 case COL_ABS_YMD_TIME: /* XXX - wider */
3693 case COL_ABS_YDOY_TIME: /* XXX - wider */
3695 case COL_UTC_YMD_TIME: /* XXX - wider */
3696 case COL_UTC_YDOY_TIME: /* XXX - wider */
3697 column_len = col_len = strlen(col_item->col_data);
3698 if (column_len < 10)
3700 line_bufp = get_line_buf(buf_offset + column_len);
3701 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3707 case COL_DEF_DL_SRC:
3708 case COL_RES_DL_SRC:
3709 case COL_UNRES_DL_SRC:
3710 case COL_DEF_NET_SRC:
3711 case COL_RES_NET_SRC:
3712 case COL_UNRES_NET_SRC:
3713 column_len = col_len = strlen(col_item->col_data);
3714 if (column_len < 12)
3716 line_bufp = get_line_buf(buf_offset + column_len);
3717 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3723 case COL_DEF_DL_DST:
3724 case COL_RES_DL_DST:
3725 case COL_UNRES_DL_DST:
3726 case COL_DEF_NET_DST:
3727 case COL_RES_NET_DST:
3728 case COL_UNRES_NET_DST:
3729 column_len = col_len = strlen(col_item->col_data);
3730 if (column_len < 12)
3732 line_bufp = get_line_buf(buf_offset + column_len);
3733 put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3737 column_len = strlen(col_item->col_data);
3738 line_bufp = get_line_buf(buf_offset + column_len);
3739 put_string(line_bufp + buf_offset, col_item->col_data, column_len);
3742 buf_offset += column_len;
3743 if (i != cf->cinfo.num_cols - 1) {
3745 * This isn't the last column, so we need to print a
3746 * separator between this column and the next.
3748 * If we printed a network source and are printing a
3749 * network destination of the same type next, separate
3750 * them with a UTF-8 right arrow; if we printed a network
3751 * destination and are printing a network source of the same
3752 * type next, separate them with a UTF-8 left arrow;
3753 * otherwise separate them with a space.
3755 * We add enough space to the buffer for " \xe2\x86\x90 "
3756 * or " \xe2\x86\x92 ", even if we're only adding " ".
3758 line_bufp = get_line_buf(buf_offset + 5);
3759 switch (col_item->col_fmt) {
3764 switch (cf->cinfo.columns[i+1].col_fmt) {
3769 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3770 put_string(line_bufp + buf_offset, str_format, 5);
3775 put_string(line_bufp + buf_offset, delimiter_char, 1);
3781 case COL_DEF_DL_SRC:
3782 case COL_RES_DL_SRC:
3783 case COL_UNRES_DL_SRC:
3784 switch (cf->cinfo.columns[i+1].col_fmt) {
3786 case COL_DEF_DL_DST:
3787 case COL_RES_DL_DST:
3788 case COL_UNRES_DL_DST:
3789 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3790 put_string(line_bufp + buf_offset, str_format, 5);
3795 put_string(line_bufp + buf_offset, delimiter_char, 1);
3801 case COL_DEF_NET_SRC:
3802 case COL_RES_NET_SRC:
3803 case COL_UNRES_NET_SRC:
3804 switch (cf->cinfo.columns[i+1].col_fmt) {
3806 case COL_DEF_NET_DST:
3807 case COL_RES_NET_DST:
3808 case COL_UNRES_NET_DST:
3809 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3810 put_string(line_bufp + buf_offset, str_format, 5);
3815 put_string(line_bufp + buf_offset, delimiter_char, 1);
3824 switch (cf->cinfo.columns[i+1].col_fmt) {
3829 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3830 put_string(line_bufp + buf_offset, str_format, 5);
3835 put_string(line_bufp + buf_offset, delimiter_char, 1);
3841 case COL_DEF_DL_DST:
3842 case COL_RES_DL_DST:
3843 case COL_UNRES_DL_DST:
3844 switch (cf->cinfo.columns[i+1].col_fmt) {
3846 case COL_DEF_DL_SRC:
3847 case COL_RES_DL_SRC:
3848 case COL_UNRES_DL_SRC:
3849 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3850 put_string(line_bufp + buf_offset, str_format, 5);
3855 put_string(line_bufp + buf_offset, delimiter_char, 1);
3861 case COL_DEF_NET_DST:
3862 case COL_RES_NET_DST:
3863 case COL_UNRES_NET_DST:
3864 switch (cf->cinfo.columns[i+1].col_fmt) {
3866 case COL_DEF_NET_SRC:
3867 case COL_RES_NET_SRC:
3868 case COL_UNRES_NET_SRC:
3869 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3870 put_string(line_bufp + buf_offset, str_format, 5);
3875 put_string(line_bufp + buf_offset, delimiter_char, 1);
3882 put_string(line_bufp + buf_offset, delimiter_char, 1);
3889 if (dissect_color && color_filter != NULL)
3890 return print_line_color(print_stream, 0, line_bufp, &color_filter->fg_color, &color_filter->bg_color);
3892 return print_line(print_stream, 0, line_bufp);
3896 print_packet(capture_file *cf, epan_dissect_t *edt)
3898 if (print_summary || output_fields_has_cols(output_fields))
3899 /* Just fill in the columns. */
3900 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3902 /* Print summary columns and/or protocol tree */
3903 switch (output_action) {
3906 if (print_summary && !print_columns(cf, edt))
3908 if (print_details) {
3909 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
3910 print_hex, edt, output_only_tables, print_stream))
3913 if (!print_line(print_stream, 0, separator))
3920 if (print_summary) {
3921 write_psml_columns(edt, stdout, dissect_color);
3922 return !ferror(stdout);
3924 if (print_details) {
3925 write_pdml_proto_tree(output_fields, protocolfilter, protocolfilter_flags, edt, stdout, dissect_color);
3927 return !ferror(stdout);
3932 if (print_summary) {
3933 /*No non-verbose "fields" format */
3934 g_assert_not_reached();
3936 if (print_details) {
3937 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
3939 return !ferror(stdout);
3945 g_assert_not_reached();
3946 if (print_details) {
3947 write_json_proto_tree(output_fields, print_dissections_expanded,
3948 print_hex, protocolfilter, protocolfilter_flags,
3949 edt, node_children_grouper, stdout);
3950 return !ferror(stdout);
3954 case WRITE_JSON_RAW:
3956 g_assert_not_reached();
3957 if (print_details) {
3958 write_json_proto_tree(output_fields, print_dissections_none, TRUE,
3959 protocolfilter, protocolfilter_flags,
3960 edt, node_children_grouper, stdout);
3961 return !ferror(stdout);
3966 write_ek_proto_tree(output_fields, print_summary, print_hex, protocolfilter,
3967 protocolfilter_flags, edt, stdout);
3968 return !ferror(stdout);
3972 if (print_summary || print_details) {
3973 if (!print_line(print_stream, 0, ""))
3976 if (!print_hex_data(print_stream, edt))
3978 if (!print_line(print_stream, 0, separator))
3987 switch (output_action) {
3990 return print_finale(print_stream);
3994 write_pdml_finale(stdout);
3996 write_psml_finale(stdout);
3997 return !ferror(stdout);
4000 write_fields_finale(output_fields, stdout);
4001 return !ferror(stdout);
4004 case WRITE_JSON_RAW:
4005 write_json_finale(stdout);
4006 return !ferror(stdout);
4009 return !ferror(stdout);
4012 g_assert_not_reached();
4018 cf_close(capture_file *cf)
4020 g_free(cf->filename);
4024 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
4029 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
4033 /* The open succeeded. Fill in the information for this file. */
4035 /* Create new epan session for dissection. */
4036 epan_free(cf->epan);
4037 cf->epan = tshark_epan_new(cf);
4040 cf->f_datalen = 0; /* not used, but set it anyway */
4042 /* Set the file name because we need it to set the follow stream filter.
4043 XXX - is that still true? We need it for other reasons, though,
4045 cf->filename = g_strdup(fname);
4047 /* Indicate whether it's a permanent or temporary file. */
4048 cf->is_tempfile = is_tempfile;
4050 /* No user changes yet. */
4051 cf->unsaved_changes = FALSE;
4053 cf->cd_t = wtap_file_type_subtype(cf->wth);
4054 cf->open_type = type;
4056 cf->drops_known = FALSE;
4058 cf->snap = wtap_snapshot_length(cf->wth);
4059 nstime_set_zero(&cf->elapsed_time);
4064 cf->state = FILE_READ_IN_PROGRESS;
4066 wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
4067 wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
4072 cfile_open_failure_message("TShark", fname, *err, err_info);
4077 show_print_file_io_error(int err)
4082 cmdarg_err("Not all the packets could be printed because there is "
4083 "no space left on the file system.");
4088 cmdarg_err("Not all the packets could be printed because you are "
4089 "too close to, or over your disk quota.");
4094 cmdarg_err("An error occurred while printing packets: %s.",
4101 * General errors and warnings are reported with an console message
4105 failure_warning_message(const char *msg_format, va_list ap)
4107 fprintf(stderr, "tshark: ");
4108 vfprintf(stderr, msg_format, ap);
4109 fprintf(stderr, "\n");
4113 * Open/create errors are reported with an console message in TShark.
4116 open_failure_message(const char *filename, int err, gboolean for_writing)
4118 fprintf(stderr, "tshark: ");
4119 fprintf(stderr, file_open_error_message(err, for_writing), filename);
4120 fprintf(stderr, "\n");
4124 * Read errors are reported with an console message in TShark.
4127 read_failure_message(const char *filename, int err)
4129 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4130 filename, g_strerror(err));
4134 * Write errors are reported with an console message in TShark.
4137 write_failure_message(const char *filename, int err)
4139 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4140 filename, g_strerror(err));
4143 static void reset_epan_mem(capture_file *cf,epan_dissect_t *edt, gboolean tree, gboolean visual)
4145 if (!epan_auto_reset || (cf->count < epan_auto_reset_count))
4148 fprintf(stderr, "resetting session.\n");
4150 epan_dissect_cleanup(edt);
4151 epan_free(cf->epan);
4153 cf->epan = tshark_epan_new(cf);
4154 epan_dissect_init(edt, cf->epan, tree, visual);
4159 * Report additional information for an error in command-line arguments.
4162 failure_message_cont(const char *msg_format, va_list ap)
4164 vfprintf(stderr, msg_format, ap);
4165 fprintf(stderr, "\n");
4169 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4174 * indent-tabs-mode: nil
4177 * vi: set shiftwidth=2 tabstop=8 expandtab:
4178 * :indentSize=2:tabSize=8:noTabs=true: