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"
91 #include "epan/register.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(...)
158 static guint32 cum_bytes;
159 static frame_data ref_frame;
160 static frame_data prev_dis_frame;
161 static frame_data prev_cap_frame;
163 static gboolean perform_two_pass_analysis;
164 static guint32 epan_auto_reset_count = 0;
165 static gboolean epan_auto_reset = FALSE;
168 * The way the packet decode is to be written.
171 WRITE_TEXT, /* summary or detail text */
172 WRITE_XML, /* PDML or PSML */
173 WRITE_FIELDS, /* User defined list of fields */
174 WRITE_JSON, /* JSON */
175 WRITE_JSON_RAW, /* JSON only raw hex */
176 WRITE_EK /* JSON bulk insert to Elasticsearch */
177 /* Add CSV and the like here */
180 static output_action_e output_action;
181 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
182 static gboolean print_packet_info; /* TRUE if we're to print packet information */
183 static gboolean print_summary; /* TRUE if we're to print packet summary information */
184 static gboolean print_details; /* TRUE if we're to print packet details information */
185 static gboolean print_hex; /* TRUE if we're to print hex/ascci information */
186 static gboolean line_buffered;
187 static gboolean really_quiet = FALSE;
188 static gchar* delimiter_char = " ";
189 static gboolean dissect_color = FALSE;
191 static print_format_e print_format = PR_FMT_TEXT;
192 static print_stream_t *print_stream = NULL;
194 static output_fields_t* output_fields = NULL;
195 static gchar **protocolfilter = NULL;
196 static pf_flags protocolfilter_flags = PF_NONE;
198 static gboolean no_duplicate_keys = FALSE;
199 static proto_node_children_grouper_func node_children_grouper = proto_node_group_children_by_unique;
201 /* The line separator used between packets, changeable via the -S option */
202 static const char *separator = "";
204 static gboolean prefs_loaded = FALSE;
208 * TRUE if we're to print packet counts to keep track of captured packets.
210 static gboolean print_packet_counts;
212 static capture_options global_capture_opts;
213 static capture_session global_capture_session;
214 static info_data_t global_info_data;
217 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
218 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
221 static gboolean capture(void);
222 static void report_counts(void);
224 static BOOL WINAPI capture_cleanup(DWORD);
226 static void capture_cleanup(int);
228 static void report_counts_siginfo(int);
232 #else /* HAVE_LIBPCAP */
234 static char *output_file_name;
236 #endif /* HAVE_LIBPCAP */
238 static void reset_epan_mem(capture_file *cf, epan_dissect_t *edt, gboolean tree, gboolean visual);
239 static gboolean process_cap_file(capture_file *, char *, int, gboolean, int, gint64);
240 static gboolean process_packet_single_pass(capture_file *cf,
241 epan_dissect_t *edt, gint64 offset, struct wtap_pkthdr *whdr,
242 const guchar *pd, guint tap_flags);
243 static void show_print_file_io_error(int err);
244 static gboolean write_preamble(capture_file *cf);
245 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
246 static gboolean write_finale(void);
248 static void failure_warning_message(const char *msg_format, va_list ap);
249 static void open_failure_message(const char *filename, int err,
250 gboolean for_writing);
251 static void read_failure_message(const char *filename, int err);
252 static void write_failure_message(const char *filename, int err);
253 static void failure_message_cont(const char *msg_format, va_list ap);
255 static GHashTable *output_only_tables = NULL;
258 const char *sstr; /* The short string */
259 const char *lstr; /* The long string */
263 string_compare(gconstpointer a, gconstpointer b)
265 return strcmp(((const struct string_elem *)a)->sstr,
266 ((const struct string_elem *)b)->sstr);
270 string_elem_print(gpointer data, gpointer not_used _U_)
272 fprintf(stderr, " %s - %s\n",
273 ((struct string_elem *)data)->sstr,
274 ((struct string_elem *)data)->lstr);
278 list_capture_types(void) {
280 struct string_elem *captypes;
283 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
285 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
286 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
287 if (wtap_dump_can_open(i)) {
288 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
289 captypes[i].lstr = wtap_file_type_subtype_string(i);
290 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
293 g_slist_foreach(list, string_elem_print, NULL);
299 list_read_capture_types(void) {
301 struct string_elem *captypes;
303 const char *magic = "Magic-value-based";
304 const char *heuristic = "Heuristics-based";
306 /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
307 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
309 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
310 for (i = 0; open_routines[i].name != NULL; i++) {
311 captypes[i].sstr = open_routines[i].name;
312 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
313 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
315 g_slist_foreach(list, string_elem_print, NULL);
321 print_usage(FILE *output)
323 fprintf(output, "\n");
324 fprintf(output, "Usage: tshark [options] ...\n");
325 fprintf(output, "\n");
328 fprintf(output, "Capture interface:\n");
329 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
330 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
331 #ifdef HAVE_PCAP_CREATE
332 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
334 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
336 fprintf(output, " -p don't capture in promiscuous mode\n");
337 #ifdef HAVE_PCAP_CREATE
338 fprintf(output, " -I capture in monitor mode, if available\n");
340 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
341 fprintf(output, " -B <buffer size> size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
343 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
344 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
345 fprintf(output, " -D print list of interfaces and exit\n");
346 fprintf(output, " -L print list of link-layer types of iface and exit\n");
347 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
348 fprintf(output, "\n");
349 fprintf(output, "Capture stop conditions:\n");
350 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
351 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
352 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
353 fprintf(output, " files:NUM - stop after NUM files\n");
354 /*fprintf(output, "\n");*/
355 fprintf(output, "Capture output:\n");
356 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
357 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
358 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
359 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
360 #endif /* HAVE_LIBPCAP */
361 #ifdef HAVE_PCAP_REMOTE
362 fprintf(output, "RPCAP options:\n");
363 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
365 /*fprintf(output, "\n");*/
366 fprintf(output, "Input file:\n");
367 fprintf(output, " -r <infile> set the filename to read from (- to read from stdin)\n");
369 fprintf(output, "\n");
370 fprintf(output, "Processing:\n");
371 fprintf(output, " -2 perform a two-pass analysis\n");
372 fprintf(output, " -M <packet count> perform session auto reset\n");
373 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
374 fprintf(output, " (requires -2)\n");
375 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
376 fprintf(output, " syntax\n");
377 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
378 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtCd\"\n");
379 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
380 fprintf(output, " \"Decode As\", see the man page for details\n");
381 fprintf(output, " Example: tcp.port==8888,http\n");
382 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
383 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
384 fprintf(output, " --enable-protocol <proto_name>\n");
385 fprintf(output, " enable dissection of proto_name\n");
386 fprintf(output, " --disable-protocol <proto_name>\n");
387 fprintf(output, " disable dissection of proto_name\n");
388 fprintf(output, " --enable-heuristic <short_name>\n");
389 fprintf(output, " enable dissection of heuristic protocol\n");
390 fprintf(output, " --disable-heuristic <short_name>\n");
391 fprintf(output, " disable dissection of heuristic protocol\n");
393 /*fprintf(output, "\n");*/
394 fprintf(output, "Output:\n");
395 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
396 fprintf(output, " (or to the standard output for \"-\")\n");
397 fprintf(output, " -C <config profile> start with specified configuration profile\n");
398 fprintf(output, " -F <output file type> set the output file type, default is pcapng\n");
399 fprintf(output, " an empty \"-F\" option will list the file types\n");
400 fprintf(output, " -V add output of packet tree (Packet Details)\n");
401 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
402 fprintf(output, " separated\n");
403 fprintf(output, " -P print packet summary even when writing to a file\n");
404 fprintf(output, " -S <separator> the line separator to print between packets\n");
405 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
406 fprintf(output, " -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?\n");
407 fprintf(output, " format of text output (def: text)\n");
408 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected\n");
409 fprintf(output, " (e.g. \"ip ip.flags text\", filter does not expand child\n");
410 fprintf(output, " nodes, unless child is specified also in the filter)\n");
411 fprintf(output, " -J <protocolfilter> top level protocol filter if -T ek|pdml|json selected\n");
412 fprintf(output, " (e.g. \"http tcp\", filter which expands all child nodes)\n");
413 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
414 fprintf(output, " _ws.col.Info)\n");
415 fprintf(output, " this option can be repeated to print multiple fields\n");
416 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
417 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
418 fprintf(output, " header=y|n switch headers on and off\n");
419 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
420 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
421 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
422 fprintf(output, " aggregator\n");
423 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
424 fprintf(output, " -t a|ad|d|dd|e|r|u|ud|? output format of time stamps (def: r: rel. to first)\n");
425 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
426 fprintf(output, " -l flush standard output after each packet\n");
427 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
428 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
429 fprintf(output, " -g enable group read access on the output file(s)\n");
430 fprintf(output, " -W n Save extra information in the file, if supported.\n");
431 fprintf(output, " n = write network address resolution information\n");
432 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
433 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
434 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
435 fprintf(output, " --capture-comment <comment>\n");
436 fprintf(output, " add a capture comment to the newly created\n");
437 fprintf(output, " output file (only for pcapng)\n");
438 fprintf(output, " --export-objects <protocol>,<destdir> save exported objects for a protocol to\n");
439 fprintf(output, " a directory named \"destdir\"\n");
440 fprintf(output, " --color color output text similarly to the Wireshark GUI,\n");
441 fprintf(output, " requires a terminal with 24-bit color support\n");
442 fprintf(output, " Also supplies color attributes to pdml and psml formats\n");
443 fprintf(output, " (Note that attributes are nonstandard)\n");
444 fprintf(output, " --no-duplicate-keys If -T json is specified, merge duplicate keys in an object\n");
445 fprintf(output, " into a single key with as value a json array containing all\n");
446 fprintf(output, " values");
448 fprintf(output, "\n");
449 fprintf(output, "Miscellaneous:\n");
450 fprintf(output, " -h display this help and exit\n");
451 fprintf(output, " -v display version info and exit\n");
452 fprintf(output, " -o <name>:<value> ... override preference setting\n");
453 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
454 fprintf(output, " -G [report] dump one of several available reports and exit\n");
455 fprintf(output, " default report=\"fields\"\n");
456 fprintf(output, " use \"-G help\" for more help\n");
458 fprintf(output, "\n");
459 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
460 fprintf(output, "You might want to reset it\n");
461 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
467 glossary_option_help(void)
473 fprintf(output, "TShark (Wireshark) %s\n", get_ws_vcs_version_info());
475 fprintf(output, "\n");
476 fprintf(output, "Usage: tshark -G [report]\n");
477 fprintf(output, "\n");
478 fprintf(output, "Glossary table reports:\n");
479 fprintf(output, " -G column-formats dump column format codes and exit\n");
480 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
481 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
482 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
483 fprintf(output, " -G fields dump fields glossary and exit\n");
484 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
485 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
486 fprintf(output, " -G plugins dump installed plugins and exit\n");
487 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
488 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
489 fprintf(output, "\n");
490 fprintf(output, "Preference reports:\n");
491 fprintf(output, " -G currentprefs dump current preferences and exit\n");
492 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
493 fprintf(output, " -G folders dump about:folders\n");
494 fprintf(output, "\n");
498 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
499 const gchar *message, gpointer user_data)
501 /* ignore log message, if log_level isn't interesting based
502 upon the console log preferences.
503 If the preferences haven't been loaded yet, display the
506 The default console_log_level preference value is such that only
507 ERROR, CRITICAL and WARNING level messages are processed;
508 MESSAGE, INFO and DEBUG level messages are ignored.
510 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
511 ERROR and CRITICAL level messages so the current code is a behavioral
512 change. The current behavior is the same as in Wireshark.
514 if (prefs_loaded && (log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0) {
518 g_log_default_handler(log_domain, log_level, message, user_data);
523 print_current_user(void) {
524 gchar *cur_user, *cur_group;
526 if (started_with_special_privs()) {
527 cur_user = get_cur_username();
528 cur_group = get_cur_groupname();
529 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
530 cur_user, cur_group);
533 if (running_with_special_privs()) {
534 fprintf(stderr, " This could be dangerous.");
536 fprintf(stderr, "\n");
541 get_tshark_compiled_version_info(GString *str)
543 /* Capture libraries */
544 get_compiled_caplibs_version(str);
548 get_tshark_runtime_version_info(GString *str)
551 /* Capture libraries */
552 g_string_append(str, ", ");
553 get_runtime_caplibs_version(str);
556 /* stuff used by libwireshark */
557 epan_get_runtime_version_info(str);
563 const char *constpath;
565 #if defined(HAVE_LIBSMI) || defined(HAVE_GEOIP) || defined(HAVE_EXTCAP)
573 * Fetching the "File" dialogs folder not implemented.
574 * This is arguably just a pwd for a ui/cli .
578 printf("%-21s\t%s\n", "Temp:", g_get_tmp_dir());
581 path = get_persconffile_path("", FALSE);
582 printf("%-21s\t%s\n", "Personal configuration:", path);
586 constpath = get_datafile_dir();
587 if (constpath != NULL) {
588 printf("%-21s\t%s\n", "Global configuration:", constpath);
592 constpath = get_systemfile_dir();
593 printf("%-21s\t%s\n", "System:", constpath);
596 constpath = get_progfile_dir();
597 printf("%-21s\t%s\n", "Program:", constpath);
601 printf("%-21s\t%s\n", "Personal Plugins:", get_plugins_pers_dir_with_version());
604 printf("%-21s\t%s\n", "Global Plugins:", get_plugins_dir_with_version());
608 /* pers lua plugins */
609 printf("%-21s\t%s\n", "Personal Lua Plugins:", get_plugins_pers_dir());
611 /* global lua plugins */
612 printf("%-21s\t%s\n", "Global Lua Plugins:", get_plugins_dir());
617 constpath = get_extcap_dir();
619 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
620 for(i = 0; resultArray[i]; i++)
621 printf("%-21s\t%s\n", "Extcap path:", g_strstrip(resultArray[i]));
623 g_strfreev(resultArray);
628 path = geoip_db_get_paths();
630 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
632 for(i = 0; resultArray[i]; i++)
633 printf("%-21s\t%s\n", "GeoIP path:", g_strstrip(resultArray[i]));
635 g_strfreev(resultArray);
641 path = oid_get_default_mib_path();
642 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
644 for(i = 0; resultArray[i]; i++)
645 printf("%-21s\t%s\n", "MIB/PIB path:", g_strstrip(resultArray[i]));
647 g_strfreev(resultArray);
654 main(int argc, char *argv[])
656 GString *comp_info_str;
657 GString *runtime_info_str;
658 char *init_progfile_dir_error;
660 static const struct option long_options[] = {
661 {"help", no_argument, NULL, 'h'},
662 {"version", no_argument, NULL, 'v'},
663 LONGOPT_CAPTURE_COMMON
664 LONGOPT_DISSECT_COMMON
665 {"print", no_argument, NULL, 'P'},
666 {"export-objects", required_argument, NULL, LONGOPT_EXPORT_OBJECTS},
667 {"color", no_argument, NULL, LONGOPT_COLOR},
668 {"no-duplicate-keys", no_argument, NULL, LONGOPT_NO_DUPLICATE_KEYS},
671 gboolean arg_error = FALSE;
679 volatile gboolean success;
680 volatile int exit_status = EXIT_SUCCESS;
682 int caps_queries = 0;
683 gboolean start_capture = FALSE;
687 gboolean capture_option_specified = FALSE;
689 gboolean quiet = FALSE;
690 #ifdef PCAP_NG_DEFAULT
691 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
693 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAP;
695 volatile gboolean out_file_name_res = FALSE;
696 volatile int in_file_type = WTAP_TYPE_AUTO;
697 gchar *volatile cf_name = NULL;
698 gchar *rfilter = NULL;
699 gchar *dfilter = NULL;
700 #ifdef HAVE_PCAP_OPEN_DEAD
701 struct bpf_program fcode;
703 dfilter_t *rfcode = NULL;
704 dfilter_t *dfcode = NULL;
708 gchar *output_only = NULL;
709 gchar *volatile pdu_export_arg = NULL;
710 const char *volatile exp_pdu_filename = NULL;
711 exp_pdu_t exp_pdu_tap_data;
714 * The leading + ensures that getopt_long() does not permute the argv[]
717 * We have to make sure that the first getopt_long() preserves the content
718 * of argv[] for the subsequent getopt_long() call.
720 * We use getopt_long() in both cases to ensure that we're using a routine
721 * whose permutation behavior we can control in the same fashion on all
722 * platforms, and so that, if we ever need to process a long argument before
723 * doing further initialization, we can do so.
725 * Glibc and Solaris libc document that a leading + disables permutation
726 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
727 * and macOS don't document it, but do so anyway.
729 * We do *not* use a leading - because the behavior of a leading - is
730 * platform-dependent.
732 #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:"
734 static const char optstring[] = OPTSTRING;
736 tshark_debug("tshark started with %d args", argc);
738 /* Set the C-language locale to the native environment. */
739 setlocale(LC_ALL, "");
741 cmdarg_err_init(failure_warning_message, failure_message_cont);
744 arg_list_utf_16to8(argc, argv);
745 create_app_running_mutex();
746 #if !GLIB_CHECK_VERSION(2,31,0)
752 * Get credential information for later use, and drop privileges
753 * before doing anything else.
754 * Let the user know if anything happened.
756 init_process_policies();
757 relinquish_special_privs_perm();
758 print_current_user();
761 * Attempt to get the pathname of the directory containing the
764 init_progfile_dir_error = init_progfile_dir(argv[0], main);
765 if (init_progfile_dir_error != NULL) {
767 "tshark: Can't get pathname of directory containing the tshark program: %s.\n"
768 "It won't be possible to capture traffic.\n"
769 "Report this to the Wireshark developers.",
770 init_progfile_dir_error);
771 g_free(init_progfile_dir_error);
774 initialize_funnel_ops();
777 ws_init_dll_search_path();
779 /* Load wpcap if possible. Do this before collecting the run-time version information */
782 /* Warn the user if npf.sys isn't loaded. */
783 if (!npf_sys_is_running() && get_windows_major_version() >= 6) {
784 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
785 "capturing or\nlisting interfaces.\n");
787 #endif /* HAVE_LIBPCAP */
790 /* Get the compile-time version information string */
791 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
792 epan_get_compiled_version_info);
794 /* Get the run-time version information string */
795 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
797 /* Add it to the information to be reported on a crash. */
798 ws_add_crash_info("TShark (Wireshark) %s\n"
803 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
804 g_string_free(comp_info_str, TRUE);
805 g_string_free(runtime_info_str, TRUE);
807 /* Fail sometimes. Useful for testing fuzz scripts. */
808 /* if (g_random_int_range(0, 100) < 5) abort(); */
811 * In order to have the -X opts assigned before the wslua machine starts
812 * we need to call getopt_long before epan_init() gets called.
814 * In order to handle, for example, -o options, we also need to call it
815 * *after* epan_init() gets called, so that the dissectors have had a
816 * chance to register their preferences.
818 * XXX - can we do this all with one getopt_long() call, saving the
819 * arguments we can't handle until after initializing libwireshark,
820 * and then process them after initializing libwireshark?
824 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
826 case 'C': /* Configuration Profile */
827 if (profile_exists (optarg, FALSE)) {
828 set_profile_name (optarg);
830 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
831 exit_status = INVALID_OPTION;
835 case 'P': /* Print packet summary info even when writing to a file */
836 print_packet_info = TRUE;
837 print_summary = TRUE;
839 case 'O': /* Only output these protocols */
840 output_only = g_strdup(optarg);
842 case 'V': /* Verbose */
843 print_details = TRUE;
844 print_packet_info = TRUE;
846 case 'x': /* Print packet data in hex (and ASCII) */
848 /* The user asked for hex output, so let's ensure they get it,
849 * even if they're writing to a file.
851 print_packet_info = TRUE;
861 /** Send All g_log messages to our own handler **/
865 G_LOG_LEVEL_CRITICAL|
870 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
872 g_log_set_handler(NULL,
873 (GLogLevelFlags)log_flags,
874 tshark_log_handler, NULL /* user_data */);
875 g_log_set_handler(LOG_DOMAIN_MAIN,
876 (GLogLevelFlags)log_flags,
877 tshark_log_handler, NULL /* user_data */);
880 g_log_set_handler(LOG_DOMAIN_CAPTURE,
881 (GLogLevelFlags)log_flags,
882 tshark_log_handler, NULL /* user_data */);
883 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
884 (GLogLevelFlags)log_flags,
885 tshark_log_handler, NULL /* user_data */);
888 init_report_message(failure_warning_message, failure_warning_message,
889 open_failure_message, read_failure_message,
890 write_failure_message);
893 capture_opts_init(&global_capture_opts);
894 capture_session_init(&global_capture_session, &cfile);
897 timestamp_set_type(TS_RELATIVE);
898 timestamp_set_precision(TS_PREC_AUTO);
899 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
904 /* Register all the plugin types we have. */
905 epan_register_plugin_types(); /* Types known to libwireshark */
907 /* Scan for plugins. This does *not* call their registration routines;
908 that's done later. */
909 scan_plugins(REPORT_LOAD_FAILURE);
911 /* Register all libwiretap plugin modules. */
912 register_all_wiretap_modules();
915 /* Register all dissectors; we must do this before checking for the
916 "-G" flag, as the "-G" flag dumps information registered by the
917 dissectors, and we must do it before we read the preferences, in
918 case any dissectors register preferences. */
919 if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
921 exit_status = INIT_FAILED;
925 /* Register all tap listeners; we do this before we parse the arguments,
926 as the "-z" argument can specify a registered tap. */
928 /* we register the plugin taps before the other taps because
929 stats_tree taps plugins will be registered as tap listeners
930 by stats_tree_stat.c and need to registered before that */
932 register_all_plugin_tap_listeners();
935 extcap_register_preferences();
937 register_all_tap_listeners();
938 conversation_table_set_gui_info(init_iousers);
939 hostlist_table_set_gui_info(init_hostlists);
940 srt_table_iterate_tables(register_srt_tables, NULL);
941 rtd_table_iterate_tables(register_rtd_tables, NULL);
942 new_stat_tap_iterate_tables(register_simple_stat_tables, NULL);
944 /* If invoked with the "-G" flag, we dump out information based on
945 the argument to the "-G" flag; if no argument is specified,
946 for backwards compatibility we dump out a glossary of display
949 XXX - we do this here, for now, to support "-G" with no arguments.
950 If none of our build or other processes uses "-G" with no arguments,
951 we can just process it with the other arguments. */
952 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
953 proto_initialize_all_prefixes();
956 proto_registrar_dump_fields();
958 if (strcmp(argv[2], "column-formats") == 0)
959 column_dump_column_formats();
960 else if (strcmp(argv[2], "currentprefs") == 0) {
961 epan_load_settings();
964 else if (strcmp(argv[2], "decodes") == 0)
965 dissector_dump_decodes();
966 else if (strcmp(argv[2], "defaultprefs") == 0)
968 else if (strcmp(argv[2], "dissector-tables") == 0)
969 dissector_dump_dissector_tables();
970 else if (strcmp(argv[2], "fieldcount") == 0) {
971 /* return value for the test suite */
972 exit_status = proto_registrar_dump_fieldcount();
974 } else if (strcmp(argv[2], "fields") == 0)
975 proto_registrar_dump_fields();
976 else if (strcmp(argv[2], "folders") == 0)
978 else if (strcmp(argv[2], "ftypes") == 0)
979 proto_registrar_dump_ftypes();
980 else if (strcmp(argv[2], "heuristic-decodes") == 0)
981 dissector_dump_heur_decodes();
982 else if (strcmp(argv[2], "plugins") == 0) {
987 wslua_plugins_dump_all();
990 else if (strcmp(argv[2], "protocols") == 0)
991 proto_registrar_dump_protocols();
992 else if (strcmp(argv[2], "values") == 0)
993 proto_registrar_dump_values();
994 else if (strcmp(argv[2], "help") == 0)
995 glossary_option_help();
996 /* These are supported only for backwards compatibility and may or may not work
997 * for a given user in a given directory on a given operating system with a given
998 * command-line interpreter.
1000 else if (strcmp(argv[2], "?") == 0)
1001 glossary_option_help();
1002 else if (strcmp(argv[2], "-?") == 0)
1003 glossary_option_help();
1005 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G help for more help.", argv[2]);
1006 exit_status = INVALID_OPTION;
1010 exit_status = EXIT_SUCCESS;
1014 tshark_debug("tshark reading settings");
1016 /* Load libwireshark settings from the current profile. */
1017 prefs_p = epan_load_settings();
1018 prefs_loaded = TRUE;
1020 read_filter_list(CFILTER_LIST);
1022 cap_file_init(&cfile);
1024 /* Print format defaults to this. */
1025 print_format = PR_FMT_TEXT;
1026 delimiter_char = " ";
1028 output_fields = output_fields_new();
1031 * To reset the options parser, set optreset to 1 on platforms that
1032 * have optreset (documented in *BSD and macOS, apparently present but
1033 * not documented in Solaris - the Illumos repository seems to
1034 * suggest that the first Solaris getopt_long(), at least as of 2004,
1035 * was based on the NetBSD one, it had optreset) and set optind to 1,
1036 * and set optind to 0 otherwise (documented as working in the GNU
1037 * getopt_long(). Setting optind to 0 didn't originally work in the
1038 * NetBSD one, but that was added later - we don't want to depend on
1039 * it if we have optreset).
1041 * Also reset opterr to 1, so that error messages are printed by
1044 #ifdef HAVE_OPTRESET
1052 /* Now get our args */
1053 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1055 case '2': /* Perform two pass analysis */
1056 if(epan_auto_reset){
1057 cmdarg_err("-2 does not support auto session reset.");
1060 perform_two_pass_analysis = TRUE;
1063 if(perform_two_pass_analysis){
1064 cmdarg_err("-M does not support two pass analysis.");
1067 epan_auto_reset_count = get_positive_int(optarg, "epan reset count");
1068 epan_auto_reset = TRUE;
1070 case 'a': /* autostop criteria */
1071 case 'b': /* Ringbuffer option */
1072 case 'c': /* Capture x packets */
1073 case 'f': /* capture filter */
1074 case 'g': /* enable group read access on file(s) */
1075 case 'i': /* Use interface x */
1076 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
1077 case 'p': /* Don't capture in promiscuous mode */
1078 #ifdef HAVE_PCAP_REMOTE
1079 case 'A': /* Authentication */
1081 #ifdef HAVE_PCAP_CREATE
1082 case 'I': /* Capture in monitor mode, if available */
1084 case 's': /* Set the snapshot (capture) length */
1085 case 'w': /* Write to capture file x */
1086 case 'y': /* Set the pcap data link type */
1087 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
1088 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1089 case 'B': /* Buffer size */
1092 exit_status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1093 if (exit_status != 0) {
1099 * Output file name, if we're reading a file and writing to another
1102 output_file_name = optarg;
1104 capture_option_specified = TRUE;
1110 /* already processed; just ignore it now */
1112 case 'D': /* Print a list of capture devices and exit */
1114 if_list = capture_interface_list(&err, &err_str,NULL);
1115 if (if_list == NULL) {
1117 cmdarg_err("There are no interfaces on which a capture can be done");
1119 cmdarg_err("%s", err_str);
1122 exit_status = INVALID_INTERFACE;
1125 capture_opts_print_interfaces(if_list);
1126 free_interface_list(if_list);
1127 exit_status = EXIT_SUCCESS;
1130 capture_option_specified = TRUE;
1136 output_fields_add(output_fields, optarg);
1140 if (!output_fields_set_option(output_fields, optarg)) {
1141 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1142 output_fields_list_options(stderr);
1143 exit_status = INVALID_OPTION;
1148 out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1149 if (out_file_type < 0) {
1150 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1151 list_capture_types();
1152 exit_status = INVALID_OPTION;
1157 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1160 protocolfilter_flags = PF_INCLUDE_CHILDREN;
1161 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1163 case 'W': /* Select extra information to save in our capture file */
1164 /* This is patterned after the -N flag which may not be the best idea. */
1165 if (strchr(optarg, 'n')) {
1166 out_file_name_res = TRUE;
1168 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1169 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1170 exit_status = INVALID_OPTION;
1174 case 'H': /* Read address to name mappings from a hosts file */
1175 if (! add_hosts_file(optarg))
1177 cmdarg_err("Can't read host entries from \"%s\"", optarg);
1178 exit_status = INVALID_OPTION;
1181 out_file_name_res = TRUE;
1184 case 'h': /* Print help and exit */
1185 printf("TShark (Wireshark) %s\n"
1186 "Dump and analyze network traffic.\n"
1187 "See https://www.wireshark.org for more information.\n",
1188 get_ws_vcs_version_info());
1189 print_usage(stdout);
1190 exit_status = EXIT_SUCCESS;
1193 case 'l': /* "Line-buffer" standard output */
1194 /* The ANSI C standard does not appear to *require* that a line-buffered
1195 stream be flushed to the host environment whenever a newline is
1196 written, it just says that, on such a stream, characters "are
1197 intended to be transmitted to or from the host environment as a
1198 block when a new-line character is encountered".
1200 The Visual C++ 6.0 C implementation doesn't do what is intended;
1201 even if you set a stream to be line-buffered, it still doesn't
1202 flush the buffer at the end of every line.
1204 The whole reason for the "-l" flag in either tcpdump or TShark
1205 is to allow the output of a live capture to be piped to a program
1206 or script and to have that script see the information for the
1207 packet as soon as it's printed, rather than having to wait until
1208 a standard I/O buffer fills up.
1210 So, if the "-l" flag is specified, we flush the standard output
1211 at the end of a packet. This will do the right thing if we're
1212 printing packet summary lines, and, as we print the entire protocol
1213 tree for a single packet without waiting for anything to happen,
1214 it should be as good as line-buffered mode if we're printing
1215 protocol trees - arguably even better, as it may do fewer
1217 line_buffered = TRUE;
1219 case 'L': /* Print list of link-layer types and exit */
1221 caps_queries |= CAPS_QUERY_LINK_TYPES;
1223 capture_option_specified = TRUE;
1227 case LONGOPT_LIST_TSTAMP_TYPES: /* List possible timestamp types */
1229 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
1231 capture_option_specified = TRUE;
1235 case 'o': /* Override preference from command line */
1237 char *errmsg = NULL;
1239 switch (prefs_set_pref(optarg, &errmsg)) {
1244 case PREFS_SET_SYNTAX_ERR:
1245 cmdarg_err("Invalid -o flag \"%s\"%s%s", optarg,
1246 errmsg ? ": " : "", errmsg ? errmsg : "");
1248 exit_status = INVALID_OPTION;
1252 case PREFS_SET_NO_SUCH_PREF:
1253 case PREFS_SET_OBSOLETE:
1254 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1255 exit_status = INVALID_OPTION;
1261 case 'q': /* Quiet */
1264 case 'Q': /* Really quiet */
1266 really_quiet = TRUE;
1268 case 'r': /* Read capture file x */
1269 cf_name = g_strdup(optarg);
1271 case 'R': /* Read file filter */
1275 /* already processed; just ignore it now */
1277 case 'S': /* Set the line Separator to be printed between packets */
1280 case 'T': /* printing Type */
1281 print_packet_info = TRUE;
1282 if (strcmp(optarg, "text") == 0) {
1283 output_action = WRITE_TEXT;
1284 print_format = PR_FMT_TEXT;
1285 } else if (strcmp(optarg, "tabs") == 0) {
1286 output_action = WRITE_TEXT;
1287 print_format = PR_FMT_TEXT;
1288 delimiter_char = "\t";
1289 } else if (strcmp(optarg, "ps") == 0) {
1290 output_action = WRITE_TEXT;
1291 print_format = PR_FMT_PS;
1292 } else if (strcmp(optarg, "pdml") == 0) {
1293 output_action = WRITE_XML;
1294 print_details = TRUE; /* Need details */
1295 print_summary = FALSE; /* Don't allow summary */
1296 } else if (strcmp(optarg, "psml") == 0) {
1297 output_action = WRITE_XML;
1298 print_details = FALSE; /* Don't allow details */
1299 print_summary = TRUE; /* Need summary */
1300 } else if (strcmp(optarg, "fields") == 0) {
1301 output_action = WRITE_FIELDS;
1302 print_details = TRUE; /* Need full tree info */
1303 print_summary = FALSE; /* Don't allow summary */
1304 } else if (strcmp(optarg, "json") == 0) {
1305 output_action = WRITE_JSON;
1306 print_details = TRUE; /* Need details */
1307 print_summary = FALSE; /* Don't allow summary */
1308 } else if (strcmp(optarg, "ek") == 0) {
1309 output_action = WRITE_EK;
1311 print_details = TRUE;
1312 } else if (strcmp(optarg, "jsonraw") == 0) {
1313 output_action = WRITE_JSON_RAW;
1314 print_details = TRUE; /* Need details */
1315 print_summary = FALSE; /* Don't allow summary */
1318 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg); /* x */
1319 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1320 "\t specified by the -E option.\n"
1321 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1322 "\t details of a decoded packet. This information is equivalent to\n"
1323 "\t the packet details printed with the -V flag.\n"
1324 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1325 "\t the packets, or a multi-line view of the details of each of\n"
1326 "\t the packets, depending on whether the -V flag was specified.\n"
1327 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1328 "\t summary information of a decoded packet. This information is\n"
1329 "\t equivalent to the information shown in the one-line summary\n"
1330 "\t printed by default.\n"
1331 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1332 "\t summary information of a decoded packet. This information is \n"
1333 "\t equivalent to the packet details printed with the -V flag.\n"
1334 "\t\"jsonraw\" Packet Details, a JSON-based format for machine parsing\n"
1335 "\t including only raw hex decoded fields (same as -T json -x but\n"
1336 "\t without text decoding, only raw fields included). \n"
1337 "\t\"ek\" Packet Details, an EK JSON-based format for the bulk insert \n"
1338 "\t into elastic search cluster. This information is \n"
1339 "\t equivalent to the packet details printed with the -V flag.\n"
1340 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1341 "\t packets, or a multi-line view of the details of each of the\n"
1342 "\t packets, depending on whether the -V flag was specified.\n"
1343 "\t This is the default.\n"
1344 "\t\"tabs\" Similar to the text report except that each column of the\n"
1345 "\t human-readable one-line summary is delimited with an ASCII\n"
1346 "\t horizontal tab character.");
1347 exit_status = INVALID_OPTION;
1351 case 'U': /* Export PDUs to file */
1353 GSList *export_pdu_tap_name_list = NULL;
1356 cmdarg_err("A tap name is required. Valid names are:");
1357 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)) {
1358 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1360 exit_status = INVALID_OPTION;
1363 pdu_export_arg = g_strdup(optarg);
1366 case 'v': /* Show version and exit */
1367 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
1368 epan_get_compiled_version_info);
1369 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
1370 show_version("TShark (Wireshark)", comp_info_str, runtime_info_str);
1371 g_string_free(comp_info_str, TRUE);
1372 g_string_free(runtime_info_str, TRUE);
1373 /* We don't really have to cleanup here, but it's a convenient way to test
1374 * start-up and shut-down of the epan library without any UI-specific
1375 * cruft getting in the way. Makes the results of running
1376 * $ ./tools/valgrind-wireshark -n
1377 * much more useful. */
1382 exit_status = EXIT_SUCCESS;
1384 case 'O': /* Only output these protocols */
1385 /* already processed; just ignore it now */
1387 case 'V': /* Verbose */
1388 /* already processed; just ignore it now */
1390 case 'x': /* Print packet data in hex (and ASCII) */
1391 /* already processed; just ignore it now */
1394 /* already processed; just ignore it now */
1400 /* We won't call the init function for the stat this soon
1401 as it would disallow MATE's fields (which are registered
1402 by the preferences set callback) from being used as
1403 part of a tap filter. Instead, we just add the argument
1404 to a list of stat arguments. */
1405 if (strcmp("help", optarg) == 0) {
1406 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1407 list_stat_cmd_args();
1408 exit_status = EXIT_SUCCESS;
1411 if (!process_stat_cmd_arg(optarg)) {
1412 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1413 list_stat_cmd_args();
1414 exit_status = INVALID_OPTION;
1418 case 'd': /* Decode as rule */
1419 case 'K': /* Kerberos keytab file */
1420 case 'n': /* No name resolution */
1421 case 'N': /* Select what types of addresses/port #s to resolve */
1422 case 't': /* Time stamp type */
1423 case 'u': /* Seconds type */
1424 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1425 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1426 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1427 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
1428 if (!dissect_opts_handle_opt(opt, optarg)) {
1429 exit_status = INVALID_OPTION;
1433 case LONGOPT_EXPORT_OBJECTS: /* --export-objects */
1434 if (strcmp("help", optarg) == 0) {
1435 fprintf(stderr, "tshark: The available export object types for the \"--export-objects\" option are:\n");
1436 eo_list_object_types();
1437 exit_status = EXIT_SUCCESS;
1440 if (!eo_tap_opt_add(optarg)) {
1441 exit_status = INVALID_OPTION;
1445 case LONGOPT_COLOR: /* print in color where appropriate */
1446 dissect_color = TRUE;
1448 case LONGOPT_NO_DUPLICATE_KEYS:
1449 no_duplicate_keys = TRUE;
1450 node_children_grouper = proto_node_group_children_by_json_key;
1453 case '?': /* Bad flag - print usage message */
1456 list_capture_types();
1459 print_usage(stderr);
1461 exit_status = INVALID_OPTION;
1468 * Print packet summary information is the default if neither -V or -x
1469 * were specified. Note that this is new behavior, which allows for the
1470 * possibility of printing only hex/ascii output without necessarily
1471 * requiring that either the summary or details be printed too.
1473 if (!print_summary && !print_details && !print_hex)
1474 print_summary = TRUE;
1476 if (no_duplicate_keys && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW) {
1477 cmdarg_err("--no-duplicate-keys can only be used with \"-T json\" and \"-T jsonraw\"");
1478 exit_status = INVALID_OPTION;
1482 /* If we specified output fields, but not the output field type... */
1483 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1484 cmdarg_err("Output fields were specified with \"-e\", "
1485 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1486 exit_status = INVALID_OPTION;
1488 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1489 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1490 "specified with \"-e\".");
1492 exit_status = INVALID_OPTION;
1496 if (dissect_color) {
1497 if (!color_filters_init(&err_msg, NULL)) {
1498 fprintf(stderr, "%s\n", err_msg);
1503 /* If no capture filter or display filter has been specified, and there are
1504 still command-line arguments, treat them as the tokens of a capture
1505 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1506 flag was specified. */
1507 if (optind < argc) {
1508 if (cf_name != NULL) {
1509 if (dfilter != NULL) {
1510 cmdarg_err("Display filters were specified both with \"-d\" "
1511 "and with additional command-line arguments.");
1512 exit_status = INVALID_OPTION;
1515 dfilter = get_args_as_string(argc, argv, optind);
1520 if (global_capture_opts.default_options.cfilter) {
1521 cmdarg_err("A default capture filter was specified both with \"-f\""
1522 " and with additional command-line arguments.");
1523 exit_status = INVALID_OPTION;
1526 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1527 interface_options *interface_opts;
1528 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
1529 if (interface_opts->cfilter == NULL) {
1530 interface_opts->cfilter = get_args_as_string(argc, argv, optind);
1532 cmdarg_err("A capture filter was specified both with \"-f\""
1533 " and with additional command-line arguments.");
1534 exit_status = INVALID_OPTION;
1538 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1540 capture_option_specified = TRUE;
1546 if (!global_capture_opts.saving_to_file) {
1547 /* We're not saving the capture to a file; if "-q" wasn't specified,
1548 we should print packet information */
1550 print_packet_info = TRUE;
1552 /* We're saving to a file; if we're writing to the standard output.
1553 and we'll also be writing dissected packets to the standard
1554 output, reject the request. At best, we could redirect that
1555 to the standard error; we *can't* write both to the standard
1556 output and have either of them be useful. */
1557 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1558 cmdarg_err("You can't write both raw packet data and dissected packets"
1559 " to the standard output.");
1560 exit_status = INVALID_OPTION;
1565 /* We're not saving the capture to a file; if "-q" wasn't specified,
1566 we should print packet information */
1568 print_packet_info = TRUE;
1571 #ifndef HAVE_LIBPCAP
1572 if (capture_option_specified)
1573 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1576 print_usage(stderr);
1577 exit_status = INVALID_OPTION;
1582 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW && output_action != WRITE_EK) {
1583 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON, JSONRAW or EK JSON");
1584 exit_status = INVALID_OPTION;
1589 if (output_only != NULL) {
1592 if (!print_details) {
1593 cmdarg_err("-O requires -V");
1594 exit_status = INVALID_OPTION;
1598 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1599 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1600 g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1604 if (rfilter != NULL && !perform_two_pass_analysis) {
1605 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1606 exit_status = INVALID_OPTION;
1612 /* We're supposed to list the link-layer/timestamp types for an interface;
1613 did the user also specify a capture file to be read? */
1615 /* Yes - that's bogus. */
1616 cmdarg_err("You can't specify %s and a capture file to be read.",
1617 caps_queries & CAPS_QUERY_LINK_TYPES ? "-L" : "--list-time-stamp-types");
1618 exit_status = INVALID_OPTION;
1621 /* No - did they specify a ring buffer option? */
1622 if (global_capture_opts.multi_files_on) {
1623 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1624 exit_status = INVALID_OPTION;
1630 * "-r" was specified, so we're reading a capture file.
1631 * Capture options don't apply here.
1634 /* We don't support capture filters when reading from a capture file
1635 (the BPF compiler doesn't support all link-layer types that we
1636 support in capture files we read). */
1637 if (global_capture_opts.default_options.cfilter) {
1638 cmdarg_err("Only read filters, not capture filters, "
1639 "can be specified when reading a capture file.");
1640 exit_status = INVALID_OPTION;
1643 if (global_capture_opts.multi_files_on) {
1644 cmdarg_err("Multiple capture files requested, but "
1645 "a capture isn't being done.");
1646 exit_status = INVALID_OPTION;
1649 if (global_capture_opts.has_file_duration) {
1650 cmdarg_err("Switching capture files after a time period was specified, but "
1651 "a capture isn't being done.");
1652 exit_status = INVALID_OPTION;
1655 if (global_capture_opts.has_file_interval) {
1656 cmdarg_err("Switching capture files after a time interval was specified, but "
1657 "a capture isn't being done.");
1658 exit_status = INVALID_OPTION;
1661 if (global_capture_opts.has_ring_num_files) {
1662 cmdarg_err("A ring buffer of capture files was specified, but "
1663 "a capture isn't being done.");
1664 exit_status = INVALID_OPTION;
1667 if (global_capture_opts.has_autostop_files) {
1668 cmdarg_err("A maximum number of capture files was specified, but "
1669 "a capture isn't being done.");
1670 exit_status = INVALID_OPTION;
1673 if (global_capture_opts.capture_comment) {
1674 cmdarg_err("A capture comment was specified, but "
1675 "a capture isn't being done.\nThere's no support for adding "
1676 "a capture comment to an existing capture file.");
1677 exit_status = INVALID_OPTION;
1681 /* Note: TShark now allows the restriction of a _read_ file by packet count
1682 * and byte count as well as a write file. Other autostop options remain valid
1683 * only for a write file.
1685 if (global_capture_opts.has_autostop_duration) {
1686 cmdarg_err("A maximum capture time was specified, but "
1687 "a capture isn't being done.");
1688 exit_status = INVALID_OPTION;
1693 * "-r" wasn't specified, so we're doing a live capture.
1695 if (perform_two_pass_analysis) {
1696 /* Two-pass analysis doesn't work with live capture since it requires us
1697 * to buffer packets until we've read all of them, but a live capture
1698 * has no useful/meaningful definition of "all" */
1699 cmdarg_err("Live captures do not support two-pass analysis.");
1700 exit_status = INVALID_OPTION;
1704 if (global_capture_opts.saving_to_file) {
1705 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1707 /* When capturing, we only support writing pcap or pcap-ng format. */
1708 if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1709 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1710 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1711 exit_status = INVALID_OPTION;
1714 if (global_capture_opts.capture_comment &&
1715 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1716 cmdarg_err("A capture comment can only be written to a pcapng file.");
1717 exit_status = INVALID_OPTION;
1720 if (global_capture_opts.multi_files_on) {
1721 /* Multiple-file mode doesn't work under certain conditions:
1722 a) it doesn't work if you're writing to the standard output;
1723 b) it doesn't work if you're writing to a pipe;
1725 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1726 cmdarg_err("Multiple capture files requested, but "
1727 "the capture is being written to the standard output.");
1728 exit_status = INVALID_OPTION;
1731 if (global_capture_opts.output_to_pipe) {
1732 cmdarg_err("Multiple capture files requested, but "
1733 "the capture file is a pipe.");
1734 exit_status = INVALID_OPTION;
1737 if (!global_capture_opts.has_autostop_filesize &&
1738 !global_capture_opts.has_file_duration &&
1739 !global_capture_opts.has_file_interval) {
1740 cmdarg_err("Multiple capture files requested, but "
1741 "no maximum capture file size, duration or interval was specified.");
1742 exit_status = INVALID_OPTION;
1746 /* Currently, we don't support read or display filters when capturing
1747 and saving the packets. */
1748 if (rfilter != NULL) {
1749 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1750 exit_status = INVALID_OPTION;
1753 if (dfilter != NULL) {
1754 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1755 exit_status = INVALID_OPTION;
1758 global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1760 /* They didn't specify a "-w" flag, so we won't be saving to a
1761 capture file. Check for options that only make sense if
1762 we're saving to a file. */
1763 if (global_capture_opts.has_autostop_filesize) {
1764 cmdarg_err("Maximum capture file size specified, but "
1765 "capture isn't being saved to a file.");
1766 exit_status = INVALID_OPTION;
1769 if (global_capture_opts.multi_files_on) {
1770 cmdarg_err("Multiple capture files requested, but "
1771 "the capture isn't being saved to a file.");
1772 exit_status = INVALID_OPTION;
1775 if (global_capture_opts.capture_comment) {
1776 cmdarg_err("A capture comment was specified, but "
1777 "the capture isn't being saved to a file.");
1778 exit_status = INVALID_OPTION;
1787 /* Start windows sockets */
1788 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1791 exit_status = INIT_FAILED;
1796 /* Notify all registered modules that have had any of their preferences
1797 changed either from one of the preferences file or from the command
1798 line that their preferences have changed. */
1801 /* At this point MATE will have registered its field array so we can
1802 have a tap filter with one of MATE's late-registered fields as part
1803 of the filter. We can now process all the "-z" arguments. */
1804 start_requested_stats();
1806 /* We can also enable specified taps for export object */
1807 start_exportobjects();
1809 /* At this point MATE will have registered its field array so we can
1810 check if the fields specified by the user are all good.
1814 GSList *invalid_fields = output_fields_valid(output_fields);
1815 if (invalid_fields != NULL) {
1817 cmdarg_err("Some fields aren't valid:");
1818 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1819 cmdarg_err_cont("\t%s", (gchar *)it->data);
1821 g_slist_free(invalid_fields);
1822 exit_status = INVALID_OPTION;
1827 /* We currently don't support taps, or printing dissected packets,
1828 if we're writing to a pipe. */
1829 if (global_capture_opts.saving_to_file &&
1830 global_capture_opts.output_to_pipe) {
1831 if (tap_listeners_require_dissection()) {
1832 cmdarg_err("Taps aren't supported when saving to a pipe.");
1833 exit_status = INVALID_OPTION;
1836 if (print_packet_info) {
1837 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1838 exit_status = INVALID_OPTION;
1844 if (ex_opt_count("read_format") > 0) {
1845 const gchar* name = ex_opt_get_next("read_format");
1846 in_file_type = open_info_name_to_type(name);
1847 if (in_file_type == WTAP_TYPE_AUTO) {
1848 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1849 list_read_capture_types();
1850 exit_status = INVALID_OPTION;
1855 timestamp_set_type(global_dissect_options.time_format);
1858 * Enabled and disabled protocols and heuristic dissectors as per
1859 * command-line options.
1861 if (!setup_enabled_and_disabled_protocols()) {
1862 exit_status = INVALID_OPTION;
1866 /* Build the column format array */
1867 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1870 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1871 capture_opts_trim_ring_num_files(&global_capture_opts);
1874 if (rfilter != NULL) {
1875 tshark_debug("Compiling read filter: '%s'", rfilter);
1876 if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1877 cmdarg_err("%s", err_msg);
1883 #ifdef HAVE_PCAP_OPEN_DEAD
1887 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1889 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1891 " Note: That read filter code looks like a valid capture filter;\n"
1892 " maybe you mixed them up?");
1898 exit_status = INVALID_INTERFACE;
1902 cfile.rfcode = rfcode;
1904 if (dfilter != NULL) {
1905 tshark_debug("Compiling display filter: '%s'", dfilter);
1906 if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1907 cmdarg_err("%s", err_msg);
1913 #ifdef HAVE_PCAP_OPEN_DEAD
1917 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1919 if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1921 " Note: That display filter code looks like a valid capture filter;\n"
1922 " maybe you mixed them up?");
1928 exit_status = INVALID_FILTER;
1932 cfile.dfcode = dfcode;
1934 if (print_packet_info) {
1935 /* If we're printing as text or PostScript, we have
1936 to create a print stream. */
1937 if (output_action == WRITE_TEXT) {
1938 switch (print_format) {
1941 print_stream = print_stream_text_stdio_new(stdout);
1945 print_stream = print_stream_ps_stdio_new(stdout);
1949 g_assert_not_reached();
1954 /* PDU export requested. Take the ownership of the '-w' file, apply tap
1955 * filters and start tapping. */
1956 if (pdu_export_arg) {
1957 const char *exp_pdu_tap_name = pdu_export_arg;
1958 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1959 char *exp_pdu_error;
1964 cmdarg_err("PDUs export requires a capture file (specify with -r).");
1965 exit_status = INVALID_OPTION;
1968 /* Take ownership of the '-w' output file. */
1970 exp_pdu_filename = global_capture_opts.save_file;
1971 global_capture_opts.save_file = NULL;
1973 exp_pdu_filename = output_file_name;
1974 output_file_name = NULL;
1976 if (exp_pdu_filename == NULL) {
1977 cmdarg_err("PDUs export requires an output file (-w).");
1978 exit_status = INVALID_OPTION;
1982 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1984 if (exp_pdu_error) {
1985 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1986 g_free(exp_pdu_error);
1987 exit_status = INVALID_TAP;
1991 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1993 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
1994 exit_status = INVALID_FILE;
1998 /* Activate the export PDU tap */
1999 comment = g_strdup_printf("Dump of PDUs from %s", cf_name);
2000 err = exp_pdu_open(&exp_pdu_tap_data, exp_fd, comment);
2002 cfile_dump_open_failure_message("TShark", exp_pdu_filename, err,
2003 WTAP_FILE_TYPE_SUBTYPE_PCAPNG);
2005 exit_status = INVALID_EXPORT;
2010 /* We have to dissect each packet if:
2012 we're printing information about each packet;
2014 we're using a read filter on the packets;
2016 we're using a display filter on the packets;
2018 we're exporting PDUs;
2020 we're using any taps that need dissection. */
2021 do_dissection = print_packet_info || rfcode || dfcode || pdu_export_arg ||
2022 tap_listeners_require_dissection() || dissect_color;
2023 tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2026 tshark_debug("tshark: Opening capture file: %s", cf_name);
2028 * We're reading a capture file.
2030 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
2035 exit_status = INVALID_FILE;
2039 /* Process the packets in the file */
2040 tshark_debug("tshark: invoking process_cap_file() to process the packets");
2043 success = process_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
2044 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
2045 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
2047 success = process_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, 0, 0);
2050 CATCH(OutOfMemoryError) {
2054 "Sorry, but TShark has to terminate now.\n"
2056 "More information and workarounds can be found at\n"
2057 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2063 /* We still dump out the results of taps, etc., as we might have
2064 read some packets; however, we exit with an error status. */
2068 if (pdu_export_arg) {
2069 err = exp_pdu_close(&exp_pdu_tap_data);
2071 cfile_close_failure_message(exp_pdu_filename, err);
2074 g_free(pdu_export_arg);
2077 tshark_debug("tshark: no capture file specified");
2078 /* No capture file specified, so we're supposed to do a live capture
2079 or get a list of link-layer types for a live capture device;
2080 do we have support for live captures? */
2082 /* if no interface was specified, pick a default */
2083 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
2084 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
2085 if (exit_status != 0) {
2089 /* if requested, list the link layer types and exit */
2093 /* Get the list of link-layer types for the capture devices. */
2094 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2095 interface_options *interface_opts;
2096 if_capabilities_t *caps;
2097 char *auth_str = NULL;
2098 int if_caps_queries = caps_queries;
2100 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2101 #ifdef HAVE_PCAP_REMOTE
2102 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
2103 auth_str = g_strdup_printf("%s:%s", interface_opts->auth_username, interface_opts->auth_password);
2106 caps = capture_get_if_capabilities(interface_opts->name, interface_opts->monitor_mode, auth_str, &err_str, NULL);
2109 cmdarg_err("%s", err_str);
2111 exit_status = INVALID_CAPABILITY;
2114 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
2115 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
2116 exit_status = INVALID_DATA_LINK;
2119 if ((if_caps_queries & CAPS_QUERY_TIMESTAMP_TYPES) && caps->timestamp_types == NULL) {
2120 cmdarg_err("The capture device \"%s\" has no timestamp types.", interface_opts->name);
2121 exit_status = INVALID_TIMESTAMP_TYPE;
2124 if (interface_opts->monitor_mode)
2125 if_caps_queries |= CAPS_MONITOR_MODE;
2126 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
2127 free_if_capabilities(caps);
2129 exit_status = EXIT_SUCCESS;
2134 * If the standard error isn't a terminal, don't print packet counts,
2135 * as they won't show up on the user's terminal and they'll get in
2136 * the way of error messages in the file (to which we assume the
2137 * standard error was redirected; if it's redirected to the null
2138 * device, there's no point in printing packet counts anyway).
2140 * Otherwise, if we're printing packet information and the standard
2141 * output is a terminal (which we assume means the standard output and
2142 * error are going to the same terminal), don't print packet counts,
2143 * as they'll get in the way of the packet information.
2145 * Otherwise, if the user specified -q, don't print packet counts.
2147 * Otherwise, print packet counts.
2149 * XXX - what if the user wants to do a live capture, doesn't want
2150 * to save it to a file, doesn't want information printed for each
2151 * packet, does want some "-z" statistic, and wants packet counts
2152 * so they know whether they're seeing any packets? -q will
2153 * suppress the information printed for each packet, but it'll
2154 * also suppress the packet counts.
2156 if (!ws_isatty(ws_fileno(stderr)))
2157 print_packet_counts = FALSE;
2158 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
2159 print_packet_counts = FALSE;
2161 print_packet_counts = FALSE;
2163 print_packet_counts = TRUE;
2165 if (print_packet_info) {
2166 if (!write_preamble(&cfile)) {
2167 show_print_file_io_error(errno);
2168 exit_status = INVALID_FILE;
2173 tshark_debug("tshark: performing live capture");
2175 * XXX - this returns FALSE if an error occurred, but it also
2176 * returns FALSE if the capture stops because a time limit
2177 * was reached (and possibly other limits), so we can't assume
2178 * it means an error.
2180 * The capture code is a bit twisty, so it doesn't appear to
2181 * be an easy fix. We just ignore the return value for now.
2182 * Instead, pass on the exit status from the capture child.
2185 exit_status = global_capture_session.fork_child_status;
2187 if (print_packet_info) {
2188 if (!write_finale()) {
2189 show_print_file_io_error(errno);
2193 /* No - complain. */
2194 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2195 exit_status = INVALID_CAPTURE;
2202 if (cfile.frame_set_info.frames != NULL) {
2203 free_frame_data_sequence(cfile.frame_set_info.frames);
2204 cfile.frame_set_info.frames = NULL;
2207 draw_tap_listeners(TRUE);
2208 funnel_dump_all_text_windows();
2209 epan_free(cfile.epan);
2215 output_fields_free(output_fields);
2216 output_fields = NULL;
2219 destroy_print_stream(print_stream);
2221 capture_opts_cleanup(&global_capture_opts);
2223 col_cleanup(&cfile.cinfo);
2224 free_filter_lists();
2234 /*#define USE_BROKEN_G_MAIN_LOOP*/
2236 #ifdef USE_BROKEN_G_MAIN_LOOP
2239 gboolean loop_running = FALSE;
2241 guint32 packet_count = 0;
2244 typedef struct pipe_input_tag {
2247 ws_process_id *child_process;
2248 pipe_input_cb_t input_cb;
2249 guint pipe_input_id;
2251 GMutex *callback_running;
2255 static pipe_input_t pipe_input;
2258 /* The timer has expired, see if there's stuff to read from the pipe,
2259 if so, do the callback */
2261 pipe_timer_cb(gpointer data)
2267 pipe_input_t *pipe_input_p = data;
2268 gint iterations = 0;
2270 g_mutex_lock (pipe_input_p->callback_running);
2272 /* try to read data from the pipe only 5 times, to avoid blocking */
2273 while(iterations < 5) {
2274 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2276 /* Oddly enough although Named pipes don't work on win9x,
2277 PeekNamedPipe does !!! */
2278 handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2279 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2281 /* Get the child process exit status */
2282 GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2285 /* If the Peek returned an error, or there are bytes to be read
2286 or the childwatcher thread has terminated then call the normal
2288 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2290 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2292 /* And call the real handler */
2293 if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2294 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2295 /* pipe closed, return false so that the timer is stopped */
2296 g_mutex_unlock (pipe_input_p->callback_running);
2301 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2302 /* No data, stop now */
2309 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2311 g_mutex_unlock (pipe_input_p->callback_running);
2313 /* we didn't stopped the timer, so let it run */
2320 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2323 pipe_input.source = source;
2324 pipe_input.child_process = child_process;
2325 pipe_input.user_data = user_data;
2326 pipe_input.input_cb = input_cb;
2329 #if GLIB_CHECK_VERSION(2,31,0)
2330 pipe_input.callback_running = g_malloc(sizeof(GMutex));
2331 g_mutex_init(pipe_input.callback_running);
2333 pipe_input.callback_running = g_mutex_new();
2335 /* Tricky to use pipes in win9x, as no concept of wait. NT can
2336 do this but that doesn't cover all win32 platforms. GTK can do
2337 this but doesn't seem to work over processes. Attempt to do
2338 something similar here, start a timer and check for data on every
2340 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2341 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2345 static const nstime_t *
2346 tshark_get_frame_ts(frame_set *fs, guint32 frame_num)
2348 if (fs->ref && fs->ref->num == frame_num)
2349 return &fs->ref->abs_ts;
2351 if (fs->prev_dis && fs->prev_dis->num == frame_num)
2352 return &fs->prev_dis->abs_ts;
2354 if (fs->prev_cap && fs->prev_cap->num == frame_num)
2355 return &fs->prev_cap->abs_ts;
2358 frame_data *fd = frame_data_sequence_find(fs->frames, frame_num);
2360 return (fd) ? &fd->abs_ts : NULL;
2367 tshark_epan_new(capture_file *cf)
2369 epan_t *epan = epan_new();
2371 epan->fs = &cf->frame_set_info;
2372 epan->get_frame_ts = tshark_get_frame_ts;
2373 epan->get_interface_name = frame_set_get_interface_name;
2374 epan->get_interface_description = frame_set_get_interface_description;
2375 epan->get_user_comment = NULL;
2387 #ifdef USE_TSHARK_SELECT
2391 struct sigaction action, oldaction;
2394 /* Create new dissection section. */
2395 epan_free(cfile.epan);
2396 cfile.epan = tshark_epan_new(&cfile);
2399 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2400 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2402 /* Catch SIGINT and SIGTERM and, if we get either of them,
2403 clean up and exit. If SIGHUP isn't being ignored, catch
2404 it too and, if we get it, clean up and exit.
2406 We restart any read that was in progress, so that it doesn't
2407 disrupt reading from the sync pipe. The signal handler tells
2408 the capture child to finish; it will report that it finished,
2409 or will exit abnormally, so we'll stop reading from the sync
2410 pipe, pick up the exit status, and quit. */
2411 memset(&action, 0, sizeof(action));
2412 action.sa_handler = capture_cleanup;
2413 action.sa_flags = SA_RESTART;
2414 sigemptyset(&action.sa_mask);
2415 sigaction(SIGTERM, &action, NULL);
2416 sigaction(SIGINT, &action, NULL);
2417 sigaction(SIGHUP, NULL, &oldaction);
2418 if (oldaction.sa_handler == SIG_DFL)
2419 sigaction(SIGHUP, &action, NULL);
2422 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2423 quiet mode, report the number of packets we've captured.
2425 Again, restart any read that was in progress, so that it doesn't
2426 disrupt reading from the sync pipe. */
2427 action.sa_handler = report_counts_siginfo;
2428 action.sa_flags = SA_RESTART;
2429 sigemptyset(&action.sa_mask);
2430 sigaction(SIGINFO, &action, NULL);
2431 #endif /* SIGINFO */
2434 global_capture_session.state = CAPTURE_PREPARING;
2436 /* Let the user know which interfaces were chosen. */
2437 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2438 interface_options *interface_opts;
2440 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2441 interface_opts->descr = get_interface_descriptive_name(interface_opts->name);
2443 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2444 if (really_quiet == FALSE)
2445 fprintf(stderr, "Capturing on %s\n", str->str);
2447 g_string_free(str, TRUE);
2449 ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2454 /* the actual capture loop
2456 * XXX - glib doesn't seem to provide any event based loop handling.
2458 * XXX - for whatever reason,
2459 * calling g_main_loop_new() ends up in 100% cpu load.
2461 * But that doesn't matter: in UNIX we can use select() to find an input
2462 * source with something to do.
2464 * But that doesn't matter because we're in a CLI (that doesn't need to
2465 * update a GUI or something at the same time) so it's OK if we block
2466 * trying to read from the pipe.
2468 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2469 * wrong (but I leave it there in case I am...).
2472 #ifdef USE_TSHARK_SELECT
2474 FD_SET(pipe_input.source, &readfds);
2477 loop_running = TRUE;
2481 while (loop_running)
2483 #ifdef USE_TSHARK_SELECT
2484 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2488 fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2490 } else if (ret == 1) {
2492 /* Call the real handler */
2493 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2494 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2497 #ifdef USE_TSHARK_SELECT
2502 CATCH(OutOfMemoryError) {
2506 "Sorry, but TShark has to terminate now.\n"
2508 "More information and workarounds can be found at\n"
2509 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2516 /* capture child detected an error */
2518 capture_input_error_message(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2520 cmdarg_err("%s", error_msg);
2521 cmdarg_err_cont("%s", secondary_error_msg);
2525 /* capture child detected an capture filter related error */
2527 capture_input_cfilter_error_message(capture_session *cap_session, guint i, char *error_message)
2529 capture_options *capture_opts = cap_session->capture_opts;
2530 dfilter_t *rfcode = NULL;
2531 interface_options *interface_opts;
2533 g_assert(i < capture_opts->ifaces->len);
2534 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2536 if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
2538 "Invalid capture filter \"%s\" for interface '%s'.\n"
2540 "That string looks like a valid display filter; however, it isn't a valid\n"
2541 "capture filter (%s).\n"
2543 "Note that display filters and capture filters don't have the same syntax,\n"
2544 "so you can't use most display filter expressions as capture filters.\n"
2546 "See the User's Guide for a description of the capture filter syntax.",
2547 interface_opts->cfilter, interface_opts->descr, error_message);
2548 dfilter_free(rfcode);
2551 "Invalid capture filter \"%s\" for interface '%s'.\n"
2553 "That string isn't a valid capture filter (%s).\n"
2554 "See the User's Guide for a description of the capture filter syntax.",
2555 interface_opts->cfilter, interface_opts->descr, error_message);
2560 /* capture child tells us we have a new (or the first) capture file */
2562 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2564 capture_options *capture_opts = cap_session->capture_opts;
2565 capture_file *cf = (capture_file *) cap_session->cf;
2566 gboolean is_tempfile;
2569 if (cap_session->state == CAPTURE_PREPARING) {
2570 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2572 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2574 g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2576 /* free the old filename */
2577 if (capture_opts->save_file != NULL) {
2579 /* we start a new capture file, close the old one (if we had one before) */
2580 if (cf->state != FILE_CLOSED) {
2581 if (cf->frame_set_info.wth != NULL) {
2582 wtap_close(cf->frame_set_info.wth);
2583 cf->frame_set_info.wth = NULL;
2585 cf->state = FILE_CLOSED;
2588 g_free(capture_opts->save_file);
2589 is_tempfile = FALSE;
2591 epan_free(cf->epan);
2592 cf->epan = tshark_epan_new(cf);
2594 /* we didn't had a save_file before, must be a tempfile */
2598 /* save the new filename */
2599 capture_opts->save_file = g_strdup(new_file);
2601 /* if we are in real-time mode, open the new file now */
2602 if (do_dissection) {
2603 /* this is probably unecessary, but better safe than sorry */
2604 ((capture_file *)cap_session->cf)->open_type = WTAP_TYPE_AUTO;
2605 /* Attempt to open the capture file and set up to read from it. */
2606 switch(cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2610 /* Don't unlink (delete) the save file - leave it around,
2611 for debugging purposes. */
2612 g_free(capture_opts->save_file);
2613 capture_opts->save_file = NULL;
2618 cap_session->state = CAPTURE_RUNNING;
2624 /* capture child tells us we have new packets to read */
2626 capture_input_new_packets(capture_session *cap_session, int to_read)
2632 capture_file *cf = (capture_file *)cap_session->cf;
2633 gboolean filtering_tap_listeners;
2638 * Prevent a SIGINFO handler from writing to the standard error while
2639 * we're doing so or writing to the standard output; instead, have it
2640 * just set a flag telling us to print that information when we're done.
2643 #endif /* SIGINFO */
2645 /* Do we have any tap listeners with filters? */
2646 filtering_tap_listeners = have_filtering_tap_listeners();
2648 /* Get the union of the flags for all tap listeners. */
2649 tap_flags = union_of_tap_listener_flags();
2651 if (do_dissection) {
2652 gboolean create_proto_tree;
2653 epan_dissect_t *edt;
2656 * Determine whether we need to create a protocol tree.
2659 * we're going to apply a read filter;
2661 * we're going to apply a display filter;
2663 * we're going to print the protocol tree;
2665 * one of the tap listeners is going to apply a filter;
2667 * one of the tap listeners requires a protocol tree;
2669 * a postdissector wants field values or protocols
2670 * on the first pass;
2672 * we have custom columns (which require field values, which
2673 * currently requires that we build a protocol tree).
2676 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2677 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
2678 have_custom_cols(&cf->cinfo) || dissect_color);
2680 /* The protocol tree will be "visible", i.e., printed, only if we're
2681 printing packet details, which is true if we're printing stuff
2682 ("print_packet_info" is true) and we're in verbose mode
2683 ("packet_details" is true). */
2684 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2686 while (to_read-- && cf->frame_set_info.wth) {
2687 wtap_cleareof(cf->frame_set_info.wth);
2688 ret = wtap_read(cf->frame_set_info.wth, &err, &err_info, &data_offset);
2689 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
2691 /* read from file failed, tell the capture child to stop */
2692 sync_pipe_stop(cap_session);
2693 wtap_close(cf->frame_set_info.wth);
2694 cf->frame_set_info.wth = NULL;
2696 ret = process_packet_single_pass(cf, edt, data_offset,
2697 wtap_phdr(cf->frame_set_info.wth),
2698 wtap_buf_ptr(cf->frame_set_info.wth), tap_flags);
2701 /* packet successfully read and gone through the "Read Filter" */
2706 epan_dissect_free(edt);
2710 * Dumpcap's doing all the work; we're not doing any dissection.
2711 * Count all the packets it wrote.
2713 packet_count += to_read;
2716 if (print_packet_counts) {
2717 /* We're printing packet counts. */
2718 if (packet_count != 0) {
2719 fprintf(stderr, "\r%u ", packet_count);
2720 /* stderr could be line buffered */
2727 * Allow SIGINFO handlers to write.
2732 * If a SIGINFO handler asked us to write out capture counts, do so.
2736 #endif /* SIGINFO */
2742 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2743 /* Report the count only if we aren't printing a packet count
2744 as packets arrive. */
2745 fprintf(stderr, "%u packet%s captured\n", packet_count,
2746 plurality(packet_count, "", "s"));
2749 infoprint = FALSE; /* we just reported it */
2750 #endif /* SIGINFO */
2755 report_counts_siginfo(int signum _U_)
2757 int sav_errno = errno;
2758 /* If we've been told to delay printing, just set a flag asking
2759 that we print counts (if we're supposed to), otherwise print
2760 the count of packets captured (if we're supposed to). */
2767 #endif /* SIGINFO */
2770 /* capture child detected any packet drops? */
2772 capture_input_drops(capture_session *cap_session _U_, guint32 dropped)
2774 if (print_packet_counts) {
2775 /* We're printing packet counts to stderr.
2776 Send a newline so that we move to the line after the packet count. */
2777 fprintf(stderr, "\n");
2781 /* We're printing packet counts to stderr.
2782 Send a newline so that we move to the line after the packet count. */
2783 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2789 * Capture child closed its side of the pipe, report any error and
2790 * do the required cleanup.
2793 capture_input_closed(capture_session *cap_session, gchar *msg)
2795 capture_file *cf = (capture_file *) cap_session->cf;
2798 fprintf(stderr, "tshark: %s\n", msg);
2802 if (cf != NULL && cf->frame_set_info.wth != NULL) {
2803 wtap_close(cf->frame_set_info.wth);
2804 if (cf->is_tempfile) {
2805 ws_unlink(cf->filename);
2808 #ifdef USE_BROKEN_G_MAIN_LOOP
2809 /*g_main_loop_quit(loop);*/
2810 g_main_loop_quit(loop);
2812 loop_running = FALSE;
2821 capture_cleanup(DWORD ctrltype _U_)
2823 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2824 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2825 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2826 like SIGTERM at least when the machine's shutting down.
2828 For now, we handle them all as indications that we should clean up
2829 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2832 We must return TRUE so that no other handler - such as one that would
2833 terminate the process - gets called.
2835 XXX - for some reason, typing ^C to TShark, if you run this in
2836 a Cygwin console window in at least some versions of Cygwin,
2837 causes TShark to terminate immediately; this routine gets
2838 called, but the main loop doesn't get a chance to run and
2839 exit cleanly, at least if this is compiled with Microsoft Visual
2840 C++ (i.e., it's a property of the Cygwin console window or Bash;
2841 it happens if TShark is not built with Cygwin - for all I know,
2842 building it with Cygwin may make the problem go away). */
2844 /* tell the capture child to stop */
2845 sync_pipe_stop(&global_capture_session);
2847 /* don't stop our own loop already here, otherwise status messages and
2848 * cleanup wouldn't be done properly. The child will indicate the stop of
2849 * everything by calling capture_input_closed() later */
2855 capture_cleanup(int signum _U_)
2857 /* tell the capture child to stop */
2858 sync_pipe_stop(&global_capture_session);
2860 /* don't stop our own loop already here, otherwise status messages and
2861 * cleanup wouldn't be done properly. The child will indicate the stop of
2862 * everything by calling capture_input_closed() later */
2865 #endif /* HAVE_LIBPCAP */
2868 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2869 gint64 offset, struct wtap_pkthdr *whdr,
2876 /* The frame number of this packet is one more than the count of
2877 frames in this packet. */
2878 framenum = cf->count + 1;
2880 /* If we're not running a display filter and we're not printing any
2881 packet information, we don't need to do a dissection. This means
2882 that all packets can be marked as 'passed'. */
2885 frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
2887 /* If we're going to run a read filter or a display filter, set up to
2888 do a dissection and do so. (This is the first pass of two passes
2889 over the packets, so we will not be printing any information
2890 from the dissection or running taps on the packet; if we're doing
2891 any of that, we'll do it in the second pass.) */
2893 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2894 gbl_resolv_flags.transport_name)
2895 /* Grab any resolved addresses */
2896 host_name_lookup_process();
2898 /* If we're running a read filter, prime the epan_dissect_t with that
2901 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
2904 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2906 /* This is the first pass, so prime the epan_dissect_t with the
2907 hfids postdissectors want on the first pass. */
2908 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
2910 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2911 &cf->frame_set_info.ref, cf->frame_set_info.prev_dis);
2912 if (cf->frame_set_info.ref == &fdlocal) {
2913 ref_frame = fdlocal;
2914 cf->frame_set_info.ref = &ref_frame;
2917 epan_dissect_run(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdlocal, pd), &fdlocal, NULL);
2919 /* Run the read filter if we have one. */
2921 passed = dfilter_apply_edt(cf->rfcode, edt);
2925 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2926 cf->frame_set_info.prev_cap = cf->frame_set_info.prev_dis = frame_data_sequence_add(cf->frame_set_info.frames, &fdlocal);
2928 /* If we're not doing dissection then there won't be any dependent frames.
2929 * More importantly, edt.pi.dependent_frames won't be initialized because
2930 * epan hasn't been initialized.
2931 * if we *are* doing dissection, then mark the dependent frames, but only
2932 * if a display filter was given and it matches this packet.
2934 if (edt && cf->dfcode) {
2935 if (dfilter_apply_edt(cf->dfcode, edt)) {
2936 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frame_set_info.frames);
2942 /* if we don't add it to the frame_data_sequence, clean it up right now
2944 frame_data_destroy(&fdlocal);
2948 epan_dissect_reset(edt);
2954 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
2955 frame_data *fdata, struct wtap_pkthdr *phdr,
2956 Buffer *buf, guint tap_flags)
2961 /* If we're not running a display filter and we're not printing any
2962 packet information, we don't need to do a dissection. This means
2963 that all packets can be marked as 'passed'. */
2966 /* If we're going to print packet information, or we're going to
2967 run a read filter, or we're going to process taps, set up to
2968 do a dissection and do so. (This is the second pass of two
2969 passes over the packets; that's the pass where we print
2970 packet information or run taps.) */
2972 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2973 gbl_resolv_flags.transport_name)
2974 /* Grab any resolved addresses */
2975 host_name_lookup_process();
2977 /* If we're running a display filter, prime the epan_dissect_t with that
2980 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2982 col_custom_prime_edt(edt, &cf->cinfo);
2984 /* We only need the columns if either
2985 1) some tap needs the columns
2987 2) we're printing packet info but we're *not* verbose; in verbose
2988 mode, we print the protocol tree, not the protocol summary.
2990 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
2995 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2996 &cf->frame_set_info.ref, cf->frame_set_info.prev_dis);
2997 if (cf->frame_set_info.ref == fdata) {
2999 cf->frame_set_info.ref = &ref_frame;
3002 if (dissect_color) {
3003 color_filters_prime_edt(edt);
3004 fdata->flags.need_colorize = 1;
3007 epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new_buffer(fdata, buf), fdata, cinfo);
3009 /* Run the read/display filter if we have one. */
3011 passed = dfilter_apply_edt(cf->dfcode, edt);
3015 frame_data_set_after_dissect(fdata, &cum_bytes);
3016 /* Process this packet. */
3017 if (print_packet_info) {
3018 /* We're printing packet information; print the information for
3020 print_packet(cf, edt);
3022 /* If we're doing "line-buffering", flush the standard output
3023 after every packet. See the comment above, for the "-l"
3024 option, for an explanation of why we do that. */
3028 if (ferror(stdout)) {
3029 show_print_file_io_error(errno);
3033 cf->frame_set_info.prev_dis = fdata;
3035 cf->frame_set_info.prev_cap = fdata;
3038 epan_dissect_reset(edt);
3040 return passed || fdata->flags.dependent_of_displayed;
3044 process_cap_file(capture_file *cf, char *save_file, int out_file_type,
3045 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
3047 gboolean success = TRUE;
3049 int snapshot_length;
3052 int err = 0, err_pass1 = 0;
3053 gchar *err_info = NULL, *err_info_pass1 = NULL;
3055 gboolean filtering_tap_listeners;
3057 GArray *shb_hdrs = NULL;
3058 wtapng_iface_descriptions_t *idb_inf = NULL;
3059 GArray *nrb_hdrs = NULL;
3060 struct wtap_pkthdr phdr;
3062 epan_dissect_t *edt = NULL;
3063 char *shb_user_appl;
3065 wtap_phdr_init(&phdr);
3067 idb_inf = wtap_file_get_idb_info(cf->frame_set_info.wth);
3068 #ifdef PCAP_NG_DEFAULT
3069 if (idb_inf->interface_data->len > 1) {
3070 linktype = WTAP_ENCAP_PER_PACKET;
3072 linktype = wtap_file_encap(cf->frame_set_info.wth);
3075 linktype = wtap_file_encap(cf->frame_set_info.wth);
3077 if (save_file != NULL) {
3078 /* Set up to write to the capture file. */
3079 snapshot_length = wtap_snapshot_length(cf->frame_set_info.wth);
3080 if (snapshot_length == 0) {
3081 /* Snapshot length of input file not known. */
3082 snapshot_length = WTAP_MAX_PACKET_SIZE_STANDARD;
3084 tshark_debug("tshark: snapshot_length = %d", snapshot_length);
3086 shb_hdrs = wtap_file_get_shb_for_new_file(cf->frame_set_info.wth);
3087 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->frame_set_info.wth);
3089 /* If we don't have an application name add Tshark */
3090 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) {
3091 /* this is free'd by wtap_block_free() later */
3092 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());
3095 if (linktype != WTAP_ENCAP_PER_PACKET &&
3096 out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAP) {
3097 tshark_debug("tshark: writing PCAP format to %s", save_file);
3098 if (strcmp(save_file, "-") == 0) {
3099 /* Write to the standard output. */
3100 pdh = wtap_dump_open_stdout(out_file_type, linktype,
3101 snapshot_length, FALSE /* compressed */, &err);
3103 pdh = wtap_dump_open(save_file, out_file_type, linktype,
3104 snapshot_length, FALSE /* compressed */, &err);
3108 tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
3109 if (strcmp(save_file, "-") == 0) {
3110 /* Write to the standard output. */
3111 pdh = wtap_dump_open_stdout_ng(out_file_type, linktype,
3112 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
3114 pdh = wtap_dump_open_ng(save_file, out_file_type, linktype,
3115 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
3123 /* We couldn't set up to write to the capture file. */
3124 cfile_dump_open_failure_message("TShark", save_file, err, out_file_type);
3129 /* Set up to print packet information. */
3130 if (print_packet_info) {
3131 if (!write_preamble(cf)) {
3132 show_print_file_io_error(errno);
3142 /* Do we have any tap listeners with filters? */
3143 filtering_tap_listeners = have_filtering_tap_listeners();
3145 /* Get the union of the flags for all tap listeners. */
3146 tap_flags = union_of_tap_listener_flags();
3148 if (perform_two_pass_analysis) {
3151 tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3153 /* Allocate a frame_data_sequence for all the frames. */
3154 cf->frame_set_info.frames = new_frame_data_sequence();
3156 if (do_dissection) {
3157 gboolean create_proto_tree;
3160 * Determine whether we need to create a protocol tree.
3163 * we're going to apply a read filter;
3165 * we're going to apply a display filter;
3167 * a postdissector wants field values or protocols
3168 * on the first pass.
3171 (cf->rfcode != NULL || cf->dfcode != NULL || postdissectors_want_hfids() || dissect_color);
3173 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3175 /* We're not going to display the protocol tree on this pass,
3176 so it's not going to be "visible". */
3177 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
3180 tshark_debug("tshark: reading records for first pass");
3181 while (wtap_read(cf->frame_set_info.wth, &err, &err_info, &data_offset)) {
3182 if (process_packet_first_pass(cf, edt, data_offset, wtap_phdr(cf->frame_set_info.wth),
3183 wtap_buf_ptr(cf->frame_set_info.wth))) {
3184 /* Stop reading if we have the maximum number of packets;
3185 * When the -c option has not been used, max_packet_count
3186 * starts at 0, which practically means, never stop reading.
3187 * (unless we roll over max_packet_count ?)
3189 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3190 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3191 max_packet_count, data_offset, max_byte_count);
3192 err = 0; /* This is not an error */
3199 * If we got a read error on the first pass, remember the error, so
3200 * but do the second pass, so we can at least process the packets we
3201 * read, and then report the first-pass error after the second pass
3202 * (and before we report any second-pass errors), so all the the
3203 * errors show up at the end.
3207 err_info_pass1 = err_info;
3213 epan_dissect_free(edt);
3217 /* Close the sequential I/O side, to free up memory it requires. */
3218 wtap_sequential_close(cf->frame_set_info.wth);
3220 /* Allow the protocol dissectors to free up memory that they
3221 * don't need after the sequential run-through of the packets. */
3222 postseq_cleanup_all_protocols();
3224 cf->frame_set_info.prev_dis = NULL;
3225 cf->frame_set_info.prev_cap = NULL;
3226 ws_buffer_init(&buf, 1500);
3228 tshark_debug("tshark: done with first pass");
3230 if (do_dissection) {
3231 gboolean create_proto_tree;
3234 * Determine whether we need to create a protocol tree.
3237 * we're going to apply a display filter;
3239 * we're going to print the protocol tree;
3241 * one of the tap listeners requires a protocol tree;
3243 * we have custom columns (which require field values, which
3244 * currently requires that we build a protocol tree).
3247 (cf->dfcode || print_details || filtering_tap_listeners ||
3248 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo) || dissect_color);
3250 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3252 /* The protocol tree will be "visible", i.e., printed, only if we're
3253 printing packet details, which is true if we're printing stuff
3254 ("print_packet_info" is true) and we're in verbose mode
3255 ("packet_details" is true). */
3256 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3259 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
3260 fdata = frame_data_sequence_find(cf->frame_set_info.frames, framenum);
3261 if (wtap_seek_read(cf->frame_set_info.wth, fdata->file_off, &phdr, &buf, &err,
3263 tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3264 if (process_packet_second_pass(cf, edt, fdata, &phdr, &buf,
3266 /* Either there's no read filtering or this packet passed the
3267 filter, so, if we're writing to a capture file, write
3270 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3271 if (!wtap_dump(pdh, &phdr, ws_buffer_start_ptr(&buf), &err, &err_info)) {
3272 /* Error writing to a capture file */
3273 tshark_debug("tshark: error writing to a capture file (%d)", err);
3275 /* Report the error.
3276 XXX - framenum is not necessarily the frame number in
3277 the input file if there was a read filter. */
3278 cfile_write_failure_message("TShark", cf->filename, save_file,
3279 err, err_info, framenum,
3281 wtap_dump_close(pdh, &err);
3282 wtap_block_array_free(shb_hdrs);
3283 wtap_block_array_free(nrb_hdrs);
3292 epan_dissect_free(edt);
3296 ws_buffer_free(&buf);
3298 tshark_debug("tshark: done with second pass");
3301 /* !perform_two_pass_analysis */
3303 gboolean create_proto_tree = FALSE;
3304 tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3306 if (do_dissection) {
3308 * Determine whether we need to create a protocol tree.
3311 * we're going to apply a read filter;
3313 * we're going to apply a display filter;
3315 * we're going to print the protocol tree;
3317 * one of the tap listeners is going to apply a filter;
3319 * one of the tap listeners requires a protocol tree;
3321 * a postdissector wants field values or protocols
3322 * on the first pass;
3324 * we have custom columns (which require field values, which
3325 * currently requires that we build a protocol tree).
3328 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3329 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3330 have_custom_cols(&cf->cinfo) || dissect_color);
3332 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3334 /* The protocol tree will be "visible", i.e., printed, only if we're
3335 printing packet details, which is true if we're printing stuff
3336 ("print_packet_info" is true) and we're in verbose mode
3337 ("packet_details" is true). */
3338 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3341 while (wtap_read(cf->frame_set_info.wth, &err, &err_info, &data_offset)) {
3344 tshark_debug("tshark: processing packet #%d", framenum);
3346 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3348 if (process_packet_single_pass(cf, edt, data_offset, wtap_phdr(cf->frame_set_info.wth),
3349 wtap_buf_ptr(cf->frame_set_info.wth), tap_flags)) {
3350 /* Either there's no read filtering or this packet passed the
3351 filter, so, if we're writing to a capture file, write
3354 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3355 if (!wtap_dump(pdh, wtap_phdr(cf->frame_set_info.wth), wtap_buf_ptr(cf->frame_set_info.wth), &err, &err_info)) {
3356 /* Error writing to a capture file */
3357 tshark_debug("tshark: error writing to a capture file (%d)", err);
3358 cfile_write_failure_message("TShark", cf->filename, save_file,
3359 err, err_info, framenum, out_file_type);
3360 wtap_dump_close(pdh, &err);
3361 wtap_block_array_free(shb_hdrs);
3362 wtap_block_array_free(nrb_hdrs);
3367 /* Stop reading if we have the maximum number of packets;
3368 * When the -c option has not been used, max_packet_count
3369 * starts at 0, which practically means, never stop reading.
3370 * (unless we roll over max_packet_count ?)
3372 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3373 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3374 max_packet_count, data_offset, max_byte_count);
3375 err = 0; /* This is not an error */
3381 epan_dissect_free(edt);
3386 wtap_phdr_cleanup(&phdr);
3388 if (err != 0 || err_pass1 != 0) {
3389 tshark_debug("tshark: something failed along the line (%d)", err);
3391 * Print a message noting that the read failed somewhere along the line.
3393 * If we're printing packet data, and the standard output and error are
3394 * going to the same place, flush the standard output, so everything
3395 * buffered up is written, and then print a newline to the standard error
3396 * before printing the error message, to separate it from the packet
3397 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
3398 * the _fstat() documentation at Microsoft doesn't indicate whether
3399 * st_ino is even supported.)
3402 if (print_packet_info) {
3403 ws_statb64 stat_stdout, stat_stderr;
3405 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3406 if (stat_stdout.st_dev == stat_stderr.st_dev &&
3407 stat_stdout.st_ino == stat_stderr.st_ino) {
3409 fprintf(stderr, "\n");
3414 if (err_pass1 != 0) {
3415 /* Error on pass 1 of two-pass processing. */
3416 cfile_read_failure_message("TShark", cf->filename, err_pass1,
3420 /* Error on pass 2 of two-pass processing or on the only pass of
3421 one-pass processing. */
3422 cfile_read_failure_message("TShark", cf->filename, err, err_info);
3426 if (save_file != NULL) {
3427 if (pdh && out_file_name_res) {
3428 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3429 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3430 wtap_file_type_subtype_short_string(out_file_type));
3433 /* Now close the capture file. */
3434 if (!wtap_dump_close(pdh, &err)) {
3435 cfile_close_failure_message(save_file, err);
3439 if (print_packet_info) {
3440 if (!write_finale()) {
3441 show_print_file_io_error(errno);
3448 wtap_close(cf->frame_set_info.wth);
3449 cf->frame_set_info.wth = NULL;
3451 wtap_block_array_free(shb_hdrs);
3452 wtap_block_array_free(nrb_hdrs);
3458 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, gint64 offset,
3459 struct wtap_pkthdr *whdr, const guchar *pd,
3466 /* Count this packet. */
3469 /* If we're not running a display filter and we're not printing any
3470 packet information, we don't need to do a dissection. This means
3471 that all packets can be marked as 'passed'. */
3474 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
3476 /* If we're going to print packet information, or we're going to
3477 run a read filter, or we're going to process taps, set up to
3478 do a dissection and do so. (This is the one and only pass
3479 over the packets, so, if we'll be printing packet information
3480 or running taps, we'll be doing it here.) */
3482 if (print_packet_info && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
3483 gbl_resolv_flags.transport_name))
3484 /* Grab any resolved addresses */
3485 host_name_lookup_process();
3487 /* If we're running a filter, prime the epan_dissect_t with that
3490 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3492 /* This is the first and only pass, so prime the epan_dissect_t
3493 with the hfids postdissectors want on the first pass. */
3494 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
3496 col_custom_prime_edt(edt, &cf->cinfo);
3498 /* We only need the columns if either
3499 1) some tap needs the columns
3501 2) we're printing packet info but we're *not* verbose; in verbose
3502 mode, we print the protocol tree, not the protocol summary.
3504 3) there is a column mapped as an individual field */
3505 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3510 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3511 &cf->frame_set_info.ref, cf->frame_set_info.prev_dis);
3512 if (cf->frame_set_info.ref == &fdata) {
3514 cf->frame_set_info.ref = &ref_frame;
3517 if (dissect_color) {
3518 color_filters_prime_edt(edt);
3519 fdata.flags.need_colorize = 1;
3522 epan_dissect_run_with_taps(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdata, pd), &fdata, cinfo);
3524 /* Run the filter if we have it. */
3526 passed = dfilter_apply_edt(cf->dfcode, edt);
3530 frame_data_set_after_dissect(&fdata, &cum_bytes);
3532 /* Process this packet. */
3533 if (print_packet_info) {
3534 /* We're printing packet information; print the information for
3537 print_packet(cf, edt);
3539 /* If we're doing "line-buffering", flush the standard output
3540 after every packet. See the comment above, for the "-l"
3541 option, for an explanation of why we do that. */
3545 if (ferror(stdout)) {
3546 show_print_file_io_error(errno);
3551 /* this must be set after print_packet() [bug #8160] */
3552 prev_dis_frame = fdata;
3553 cf->frame_set_info.prev_dis = &prev_dis_frame;
3556 prev_cap_frame = fdata;
3557 cf->frame_set_info.prev_cap = &prev_cap_frame;
3560 epan_dissect_reset(edt);
3561 frame_data_destroy(&fdata);
3567 write_preamble(capture_file *cf)
3569 switch (output_action) {
3572 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3576 write_pdml_preamble(stdout, cf->filename);
3578 write_psml_preamble(&cf->cinfo, stdout);
3579 return !ferror(stdout);
3582 write_fields_preamble(output_fields, stdout);
3583 return !ferror(stdout);
3586 case WRITE_JSON_RAW:
3587 write_json_preamble(stdout);
3588 return !ferror(stdout);
3591 return !ferror(stdout);
3594 g_assert_not_reached();
3600 get_line_buf(size_t len)
3602 static char *line_bufp = NULL;
3603 static size_t line_buf_len = 256;
3604 size_t new_line_buf_len;
3606 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3607 new_line_buf_len *= 2)
3609 if (line_bufp == NULL) {
3610 line_buf_len = new_line_buf_len;
3611 line_bufp = (char *)g_malloc(line_buf_len + 1);
3613 if (new_line_buf_len > line_buf_len) {
3614 line_buf_len = new_line_buf_len;
3615 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3622 put_string(char *dest, const char *str, size_t str_len)
3624 memcpy(dest, str, str_len);
3625 dest[str_len] = '\0';
3629 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3633 for (i = str_len; i < str_with_spaces; i++)
3636 put_string(dest, str, str_len);
3640 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3644 memcpy(dest, str, str_len);
3645 for (i = str_len; i < str_with_spaces; i++)
3648 dest[str_with_spaces] = '\0';
3652 print_columns(capture_file *cf, const epan_dissect_t *edt)
3659 col_item_t* col_item;
3660 gchar str_format[11];
3661 const color_filter_t *color_filter = NULL;
3663 line_bufp = get_line_buf(256);
3668 color_filter = edt->pi.fd->color_filter;
3670 for (i = 0; i < cf->cinfo.num_cols; i++) {
3671 col_item = &cf->cinfo.columns[i];
3672 /* Skip columns not marked as visible. */
3673 if (!get_column_visible(i))
3675 switch (col_item->col_fmt) {
3677 column_len = col_len = strlen(col_item->col_data);
3680 line_bufp = get_line_buf(buf_offset + column_len);
3681 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3687 case COL_ABS_YMD_TIME: /* XXX - wider */
3688 case COL_ABS_YDOY_TIME: /* XXX - wider */
3690 case COL_UTC_YMD_TIME: /* XXX - wider */
3691 case COL_UTC_YDOY_TIME: /* XXX - wider */
3692 column_len = col_len = strlen(col_item->col_data);
3693 if (column_len < 10)
3695 line_bufp = get_line_buf(buf_offset + column_len);
3696 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3702 case COL_DEF_DL_SRC:
3703 case COL_RES_DL_SRC:
3704 case COL_UNRES_DL_SRC:
3705 case COL_DEF_NET_SRC:
3706 case COL_RES_NET_SRC:
3707 case COL_UNRES_NET_SRC:
3708 column_len = col_len = strlen(col_item->col_data);
3709 if (column_len < 12)
3711 line_bufp = get_line_buf(buf_offset + column_len);
3712 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3718 case COL_DEF_DL_DST:
3719 case COL_RES_DL_DST:
3720 case COL_UNRES_DL_DST:
3721 case COL_DEF_NET_DST:
3722 case COL_RES_NET_DST:
3723 case COL_UNRES_NET_DST:
3724 column_len = col_len = strlen(col_item->col_data);
3725 if (column_len < 12)
3727 line_bufp = get_line_buf(buf_offset + column_len);
3728 put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3732 column_len = strlen(col_item->col_data);
3733 line_bufp = get_line_buf(buf_offset + column_len);
3734 put_string(line_bufp + buf_offset, col_item->col_data, column_len);
3737 buf_offset += column_len;
3738 if (i != cf->cinfo.num_cols - 1) {
3740 * This isn't the last column, so we need to print a
3741 * separator between this column and the next.
3743 * If we printed a network source and are printing a
3744 * network destination of the same type next, separate
3745 * them with a UTF-8 right arrow; if we printed a network
3746 * destination and are printing a network source of the same
3747 * type next, separate them with a UTF-8 left arrow;
3748 * otherwise separate them with a space.
3750 * We add enough space to the buffer for " \xe2\x86\x90 "
3751 * or " \xe2\x86\x92 ", even if we're only adding " ".
3753 line_bufp = get_line_buf(buf_offset + 5);
3754 switch (col_item->col_fmt) {
3759 switch (cf->cinfo.columns[i+1].col_fmt) {
3764 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3765 put_string(line_bufp + buf_offset, str_format, 5);
3770 put_string(line_bufp + buf_offset, delimiter_char, 1);
3776 case COL_DEF_DL_SRC:
3777 case COL_RES_DL_SRC:
3778 case COL_UNRES_DL_SRC:
3779 switch (cf->cinfo.columns[i+1].col_fmt) {
3781 case COL_DEF_DL_DST:
3782 case COL_RES_DL_DST:
3783 case COL_UNRES_DL_DST:
3784 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3785 put_string(line_bufp + buf_offset, str_format, 5);
3790 put_string(line_bufp + buf_offset, delimiter_char, 1);
3796 case COL_DEF_NET_SRC:
3797 case COL_RES_NET_SRC:
3798 case COL_UNRES_NET_SRC:
3799 switch (cf->cinfo.columns[i+1].col_fmt) {
3801 case COL_DEF_NET_DST:
3802 case COL_RES_NET_DST:
3803 case COL_UNRES_NET_DST:
3804 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3805 put_string(line_bufp + buf_offset, str_format, 5);
3810 put_string(line_bufp + buf_offset, delimiter_char, 1);
3819 switch (cf->cinfo.columns[i+1].col_fmt) {
3824 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3825 put_string(line_bufp + buf_offset, str_format, 5);
3830 put_string(line_bufp + buf_offset, delimiter_char, 1);
3836 case COL_DEF_DL_DST:
3837 case COL_RES_DL_DST:
3838 case COL_UNRES_DL_DST:
3839 switch (cf->cinfo.columns[i+1].col_fmt) {
3841 case COL_DEF_DL_SRC:
3842 case COL_RES_DL_SRC:
3843 case COL_UNRES_DL_SRC:
3844 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3845 put_string(line_bufp + buf_offset, str_format, 5);
3850 put_string(line_bufp + buf_offset, delimiter_char, 1);
3856 case COL_DEF_NET_DST:
3857 case COL_RES_NET_DST:
3858 case COL_UNRES_NET_DST:
3859 switch (cf->cinfo.columns[i+1].col_fmt) {
3861 case COL_DEF_NET_SRC:
3862 case COL_RES_NET_SRC:
3863 case COL_UNRES_NET_SRC:
3864 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3865 put_string(line_bufp + buf_offset, str_format, 5);
3870 put_string(line_bufp + buf_offset, delimiter_char, 1);
3877 put_string(line_bufp + buf_offset, delimiter_char, 1);
3884 if (dissect_color && color_filter != NULL)
3885 return print_line_color(print_stream, 0, line_bufp, &color_filter->fg_color, &color_filter->bg_color);
3887 return print_line(print_stream, 0, line_bufp);
3891 print_packet(capture_file *cf, epan_dissect_t *edt)
3893 if (print_summary || output_fields_has_cols(output_fields))
3894 /* Just fill in the columns. */
3895 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3897 /* Print summary columns and/or protocol tree */
3898 switch (output_action) {
3901 if (print_summary && !print_columns(cf, edt))
3903 if (print_details) {
3904 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
3905 print_hex, edt, output_only_tables, print_stream))
3908 if (!print_line(print_stream, 0, separator))
3915 if (print_summary) {
3916 write_psml_columns(edt, stdout, dissect_color);
3917 return !ferror(stdout);
3919 if (print_details) {
3920 write_pdml_proto_tree(output_fields, protocolfilter, protocolfilter_flags, edt, stdout, dissect_color);
3922 return !ferror(stdout);
3927 if (print_summary) {
3928 /*No non-verbose "fields" format */
3929 g_assert_not_reached();
3931 if (print_details) {
3932 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
3934 return !ferror(stdout);
3940 g_assert_not_reached();
3941 if (print_details) {
3942 write_json_proto_tree(output_fields, print_dissections_expanded,
3943 print_hex, protocolfilter, protocolfilter_flags,
3944 edt, node_children_grouper, stdout);
3945 return !ferror(stdout);
3949 case WRITE_JSON_RAW:
3951 g_assert_not_reached();
3952 if (print_details) {
3953 write_json_proto_tree(output_fields, print_dissections_none, TRUE,
3954 protocolfilter, protocolfilter_flags,
3955 edt, node_children_grouper, stdout);
3956 return !ferror(stdout);
3961 write_ek_proto_tree(output_fields, print_summary, print_hex, protocolfilter,
3962 protocolfilter_flags, edt, stdout);
3963 return !ferror(stdout);
3967 if (print_summary || print_details) {
3968 if (!print_line(print_stream, 0, ""))
3971 if (!print_hex_data(print_stream, edt))
3973 if (!print_line(print_stream, 0, separator))
3982 switch (output_action) {
3985 return print_finale(print_stream);
3989 write_pdml_finale(stdout);
3991 write_psml_finale(stdout);
3992 return !ferror(stdout);
3995 write_fields_finale(output_fields, stdout);
3996 return !ferror(stdout);
3999 case WRITE_JSON_RAW:
4000 write_json_finale(stdout);
4001 return !ferror(stdout);
4004 return !ferror(stdout);
4007 g_assert_not_reached();
4013 cf_close(capture_file *cf)
4015 g_free(cf->filename);
4019 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
4024 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
4028 /* The open succeeded. Fill in the information for this file. */
4030 /* Create new epan session for dissection. */
4031 epan_free(cf->epan);
4032 cf->epan = tshark_epan_new(cf);
4034 cf->frame_set_info.wth = wth;
4035 cf->f_datalen = 0; /* not used, but set it anyway */
4037 /* Set the file name because we need it to set the follow stream filter.
4038 XXX - is that still true? We need it for other reasons, though,
4040 cf->filename = g_strdup(fname);
4042 /* Indicate whether it's a permanent or temporary file. */
4043 cf->is_tempfile = is_tempfile;
4045 /* No user changes yet. */
4046 cf->unsaved_changes = FALSE;
4048 cf->cd_t = wtap_file_type_subtype(cf->frame_set_info.wth);
4049 cf->open_type = type;
4051 cf->drops_known = FALSE;
4053 cf->snap = wtap_snapshot_length(cf->frame_set_info.wth);
4054 nstime_set_zero(&cf->elapsed_time);
4055 cf->frame_set_info.ref = NULL;
4056 cf->frame_set_info.prev_dis = NULL;
4057 cf->frame_set_info.prev_cap = NULL;
4059 cf->state = FILE_READ_IN_PROGRESS;
4061 wtap_set_cb_new_ipv4(cf->frame_set_info.wth, add_ipv4_name);
4062 wtap_set_cb_new_ipv6(cf->frame_set_info.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
4067 cfile_open_failure_message("TShark", fname, *err, err_info);
4072 show_print_file_io_error(int err)
4077 cmdarg_err("Not all the packets could be printed because there is "
4078 "no space left on the file system.");
4083 cmdarg_err("Not all the packets could be printed because you are "
4084 "too close to, or over your disk quota.");
4089 cmdarg_err("An error occurred while printing packets: %s.",
4096 * General errors and warnings are reported with an console message
4100 failure_warning_message(const char *msg_format, va_list ap)
4102 fprintf(stderr, "tshark: ");
4103 vfprintf(stderr, msg_format, ap);
4104 fprintf(stderr, "\n");
4108 * Open/create errors are reported with an console message in TShark.
4111 open_failure_message(const char *filename, int err, gboolean for_writing)
4113 fprintf(stderr, "tshark: ");
4114 fprintf(stderr, file_open_error_message(err, for_writing), filename);
4115 fprintf(stderr, "\n");
4119 * Read errors are reported with an console message in TShark.
4122 read_failure_message(const char *filename, int err)
4124 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4125 filename, g_strerror(err));
4129 * Write errors are reported with an console message in TShark.
4132 write_failure_message(const char *filename, int err)
4134 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4135 filename, g_strerror(err));
4138 static void reset_epan_mem(capture_file *cf,epan_dissect_t *edt, gboolean tree, gboolean visual)
4140 if (!epan_auto_reset || (cf->count < epan_auto_reset_count))
4143 fprintf(stderr, "resetting session.\n");
4145 epan_dissect_cleanup(edt);
4146 epan_free(cf->epan);
4148 cf->epan = tshark_epan_new(cf);
4149 epan_dissect_init(edt, cf->epan, tree, visual);
4154 * Report additional information for an error in command-line arguments.
4157 failure_message_cont(const char *msg_format, va_list ap)
4159 vfprintf(stderr, msg_format, ap);
4160 fprintf(stderr, "\n");
4164 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4169 * indent-tabs-mode: nil
4172 * vi: set shiftwidth=2 tabstop=8 expandtab:
4173 * :indentSize=2:tabSize=8:noTabs=true: