3 * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4 * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * SPDX-License-Identifier: GPL-2.0-or-later
28 # include <winsock2.h>
36 # include <sys/capability.h>
39 #ifndef HAVE_GETOPT_LONG
40 #include "wsutil/wsgetopt.h"
45 #include <epan/exceptions.h>
46 #include <epan/epan.h>
48 #include <ui/clopts_common.h>
49 #include <ui/cmdarg_err.h>
50 #include <wsutil/filesystem.h>
51 #include <wsutil/file_util.h>
52 #include <wsutil/privileges.h>
53 #include <wsutil/report_message.h>
55 #include <version_info.h>
56 #include <wiretap/wtap_opttypes.h>
57 #include <wiretap/pcapng.h>
60 #include <epan/timestamp.h>
61 #include <epan/packet.h>
63 #include <epan/wslua/init_wslua.h>
65 #include "frame_tvbuff.h"
66 #include <epan/disabled_protos.h>
67 #include <epan/prefs.h>
68 #include <epan/column.h>
69 #include <epan/decode_as.h>
70 #include <epan/print.h>
71 #include <epan/addr_resolv.h>
73 #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 #include "epan/maxmind_db.h"
89 #include <epan/epan_dissect.h>
91 #include <epan/stat_tap_ui.h>
92 #include <epan/conversation_table.h>
93 #include <epan/srt_table.h>
94 #include <epan/rtd_table.h>
95 #include <epan/ex-opt.h>
96 #include <epan/exported_pdu.h>
97 #include <epan/secrets.h>
99 #include "capture_opts.h"
101 #include "caputils/capture-pcap-util.h"
104 #include "caputils/capture_ifinfo.h"
106 #include "caputils/capture-wpcap.h"
108 #include <capchild/capture_session.h>
109 #include <capchild/capture_sync.h>
110 #include <capture_info.h>
111 #endif /* HAVE_LIBPCAP */
113 #include <epan/funnel.h>
115 #include <wsutil/str_util.h>
116 #include <wsutil/utf8_entities.h>
117 #include <wsutil/json_dumper.h>
122 #include <wsutil/plugins.h>
126 #define INVALID_OPTION 1
127 #define INVALID_INTERFACE 2
128 #define INVALID_FILE 2
129 #define INVALID_FILTER 2
130 #define INVALID_EXPORT 2
131 #define INVALID_CAPABILITY 2
132 #define INVALID_TAP 2
133 #define INVALID_DATA_LINK 2
134 #define INVALID_TIMESTAMP_TYPE 2
135 #define INVALID_CAPTURE 2
136 #define INIT_FAILED 2
139 * values 128..65535 are capture+dissect options, 65536 is used by
140 * ui/commandline.c, so start tshark-specific options 1000 after this
142 #define LONGOPT_COLOR (65536+1000)
143 #define LONGOPT_NO_DUPLICATE_KEYS (65536+1001)
144 #define LONGOPT_ELASTIC_MAPPING_FILTER (65536+1002)
147 #define tshark_debug(...) g_warning(__VA_ARGS__)
149 #define tshark_debug(...)
154 static guint32 cum_bytes;
155 static frame_data ref_frame;
156 static frame_data prev_dis_frame;
157 static frame_data prev_cap_frame;
159 static gboolean perform_two_pass_analysis;
160 static guint32 epan_auto_reset_count = 0;
161 static gboolean epan_auto_reset = FALSE;
164 * The way the packet decode is to be written.
167 WRITE_TEXT, /* summary or detail text */
168 WRITE_XML, /* PDML or PSML */
169 WRITE_FIELDS, /* User defined list of fields */
170 WRITE_JSON, /* JSON */
171 WRITE_JSON_RAW, /* JSON only raw hex */
172 WRITE_EK /* JSON bulk insert to Elasticsearch */
173 /* Add CSV and the like here */
176 static output_action_e output_action;
177 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
178 static gboolean print_packet_info; /* TRUE if we're to print packet information */
179 static gboolean print_summary; /* TRUE if we're to print packet summary information */
180 static gboolean print_details; /* TRUE if we're to print packet details information */
181 static gboolean print_hex; /* TRUE if we're to print hex/ascci information */
182 static gboolean line_buffered;
183 static gboolean really_quiet = FALSE;
184 static gchar* delimiter_char = " ";
185 static gboolean dissect_color = FALSE;
187 static print_format_e print_format = PR_FMT_TEXT;
188 static print_stream_t *print_stream = NULL;
190 static output_fields_t* output_fields = NULL;
191 static gchar **protocolfilter = NULL;
192 static pf_flags protocolfilter_flags = PF_NONE;
194 static gboolean no_duplicate_keys = FALSE;
195 static proto_node_children_grouper_func node_children_grouper = proto_node_group_children_by_unique;
197 static json_dumper jdumper;
199 /* The line separator used between packets, changeable via the -S option */
200 static const char *separator = "";
202 static gboolean prefs_loaded = FALSE;
206 * TRUE if we're to print packet counts to keep track of captured packets.
208 static gboolean print_packet_counts;
210 static capture_options global_capture_opts;
211 static capture_session global_capture_session;
212 static info_data_t global_info_data;
215 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
216 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
219 static gboolean capture(void);
220 static void report_counts(void);
222 static BOOL WINAPI capture_cleanup(DWORD);
224 static void capture_cleanup(int);
226 static void report_counts_siginfo(int);
230 #else /* HAVE_LIBPCAP */
232 static char *output_file_name;
234 #endif /* HAVE_LIBPCAP */
236 static void reset_epan_mem(capture_file *cf, epan_dissect_t *edt, gboolean tree, gboolean visual);
237 static gboolean process_cap_file(capture_file *, char *, int, gboolean, int, gint64);
238 static gboolean process_packet_single_pass(capture_file *cf,
239 epan_dissect_t *edt, gint64 offset, wtap_rec *rec,
240 const guchar *pd, guint tap_flags);
241 static void show_print_file_io_error(int err);
242 static gboolean write_preamble(capture_file *cf);
243 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
244 static gboolean write_finale(void);
246 static void failure_warning_message(const char *msg_format, va_list ap);
247 static void open_failure_message(const char *filename, int err,
248 gboolean for_writing);
249 static void read_failure_message(const char *filename, int err);
250 static void write_failure_message(const char *filename, int err);
251 static void failure_message_cont(const char *msg_format, va_list ap);
253 static GHashTable *output_only_tables = NULL;
256 const char *sstr; /* The short string */
257 const char *lstr; /* The long string */
261 string_compare(gconstpointer a, gconstpointer b)
263 return strcmp(((const struct string_elem *)a)->sstr,
264 ((const struct string_elem *)b)->sstr);
268 string_elem_print(gpointer data)
270 fprintf(stderr, " %s - %s\n",
271 ((struct string_elem *)data)->sstr,
272 ((struct string_elem *)data)->lstr);
276 list_capture_types(void) {
278 struct string_elem *captypes;
281 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
283 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
284 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
285 if (wtap_dump_can_open(i)) {
286 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
287 captypes[i].lstr = wtap_file_type_subtype_string(i);
288 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
291 g_slist_free_full(list, string_elem_print);
296 list_read_capture_types(void) {
298 struct string_elem *captypes;
300 const char *magic = "Magic-value-based";
301 const char *heuristic = "Heuristics-based";
303 /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
304 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
306 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
307 for (i = 0; open_routines[i].name != NULL; i++) {
308 captypes[i].sstr = open_routines[i].name;
309 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
310 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
312 g_slist_free_full(list, string_elem_print);
317 print_usage(FILE *output)
319 fprintf(output, "\n");
320 fprintf(output, "Usage: tshark [options] ...\n");
321 fprintf(output, "\n");
324 fprintf(output, "Capture interface:\n");
325 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
326 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
327 #ifdef HAVE_PCAP_CREATE
328 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
330 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
332 fprintf(output, " -p don't capture in promiscuous mode\n");
333 #ifdef HAVE_PCAP_CREATE
334 fprintf(output, " -I capture in monitor mode, if available\n");
336 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
337 fprintf(output, " -B <buffer size> size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
339 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
340 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
341 fprintf(output, " -D print list of interfaces and exit\n");
342 fprintf(output, " -L print list of link-layer types of iface and exit\n");
343 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
344 fprintf(output, "\n");
345 fprintf(output, "Capture stop conditions:\n");
346 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
347 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
348 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
349 fprintf(output, " files:NUM - stop after NUM files\n");
350 /*fprintf(output, "\n");*/
351 fprintf(output, "Capture output:\n");
352 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
353 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
354 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
355 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
356 #endif /* HAVE_LIBPCAP */
357 #ifdef HAVE_PCAP_REMOTE
358 fprintf(output, "RPCAP options:\n");
359 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
361 /*fprintf(output, "\n");*/
362 fprintf(output, "Input file:\n");
363 fprintf(output, " -r <infile> set the filename to read from (- to read from stdin)\n");
365 fprintf(output, "\n");
366 fprintf(output, "Processing:\n");
367 fprintf(output, " -2 perform a two-pass analysis\n");
368 fprintf(output, " -M <packet count> perform session auto reset\n");
369 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
370 fprintf(output, " (requires -2)\n");
371 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
372 fprintf(output, " syntax\n");
373 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
374 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtdv\"\n");
375 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
376 fprintf(output, " \"Decode As\", see the man page for details\n");
377 fprintf(output, " Example: tcp.port==8888,http\n");
378 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
379 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
380 fprintf(output, " --enable-protocol <proto_name>\n");
381 fprintf(output, " enable dissection of proto_name\n");
382 fprintf(output, " --disable-protocol <proto_name>\n");
383 fprintf(output, " disable dissection of proto_name\n");
384 fprintf(output, " --enable-heuristic <short_name>\n");
385 fprintf(output, " enable dissection of heuristic protocol\n");
386 fprintf(output, " --disable-heuristic <short_name>\n");
387 fprintf(output, " disable dissection of heuristic protocol\n");
389 /*fprintf(output, "\n");*/
390 fprintf(output, "Output:\n");
391 #ifdef PCAP_NG_DEFAULT
392 fprintf(output, " -w <outfile|-> write packets to a pcapng-format file named \"outfile\"\n");
394 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 #ifdef PCAP_NG_DEFAULT
399 fprintf(output, " -F <output file type> set the output file type, default is pcapng\n");
401 fprintf(output, " -F <output file type> set the output file type, default is pcap\n");
403 fprintf(output, " an empty \"-F\" option will list the file types\n");
404 fprintf(output, " -V add output of packet tree (Packet Details)\n");
405 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
406 fprintf(output, " separated\n");
407 fprintf(output, " -P print packet summary even when writing to a file\n");
408 fprintf(output, " -S <separator> the line separator to print between packets\n");
409 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
410 fprintf(output, " -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?\n");
411 fprintf(output, " format of text output (def: text)\n");
412 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected\n");
413 fprintf(output, " (e.g. \"ip ip.flags text\", filter does not expand child\n");
414 fprintf(output, " nodes, unless child is specified also in the filter)\n");
415 fprintf(output, " -J <protocolfilter> top level protocol filter if -T ek|pdml|json selected\n");
416 fprintf(output, " (e.g. \"http tcp\", filter which expands all child nodes)\n");
417 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
418 fprintf(output, " _ws.col.Info)\n");
419 fprintf(output, " this option can be repeated to print multiple fields\n");
420 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
421 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
422 fprintf(output, " header=y|n switch headers on and off\n");
423 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
424 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
425 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
426 fprintf(output, " aggregator\n");
427 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
428 fprintf(output, " -t a|ad|d|dd|e|r|u|ud|? output format of time stamps (def: r: rel. to first)\n");
429 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
430 fprintf(output, " -l flush standard output after each packet\n");
431 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
432 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
433 fprintf(output, " -g enable group read access on the output file(s)\n");
434 fprintf(output, " -W n Save extra information in the file, if supported.\n");
435 fprintf(output, " n = write network address resolution information\n");
436 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
437 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
438 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
439 fprintf(output, " --capture-comment <comment>\n");
440 fprintf(output, " add a capture comment to the newly created\n");
441 fprintf(output, " output file (only for pcapng)\n");
442 fprintf(output, " --export-objects <protocol>,<destdir> save exported objects for a protocol to\n");
443 fprintf(output, " a directory named \"destdir\"\n");
444 fprintf(output, " --color color output text similarly to the Wireshark GUI,\n");
445 fprintf(output, " requires a terminal with 24-bit color support\n");
446 fprintf(output, " Also supplies color attributes to pdml and psml formats\n");
447 fprintf(output, " (Note that attributes are nonstandard)\n");
448 fprintf(output, " --no-duplicate-keys If -T json is specified, merge duplicate keys in an object\n");
449 fprintf(output, " into a single key with as value a json array containing all\n");
450 fprintf(output, " values\n");
451 fprintf(output, " --elastic-mapping-filter <protocols> If -G elastic-mapping is specified, put only the\n");
452 fprintf(output, " specified protocols within the mapping file\n");
454 fprintf(output, "\n");
455 fprintf(output, "Miscellaneous:\n");
456 fprintf(output, " -h display this help and exit\n");
457 fprintf(output, " -v display version info and exit\n");
458 fprintf(output, " -o <name>:<value> ... override preference setting\n");
459 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
460 fprintf(output, " -G [report] dump one of several available reports and exit\n");
461 fprintf(output, " default report=\"fields\"\n");
462 fprintf(output, " use \"-G help\" for more help\n");
464 fprintf(output, "\n");
465 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
466 fprintf(output, "You might want to enable it by executing:\n");
467 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
468 fprintf(output, "Note that this can make your system less secure!\n");
474 glossary_option_help(void)
480 fprintf(output, "%s\n", get_appname_and_version());
482 fprintf(output, "\n");
483 fprintf(output, "Usage: tshark -G [report]\n");
484 fprintf(output, "\n");
485 fprintf(output, "Glossary table reports:\n");
486 fprintf(output, " -G column-formats dump column format codes and exit\n");
487 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
488 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
489 fprintf(output, " -G elastic-mapping dump ElasticSearch mapping file\n");
490 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
491 fprintf(output, " -G fields dump fields glossary and exit\n");
492 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
493 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
494 fprintf(output, " -G plugins dump installed plugins and exit\n");
495 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
496 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
497 fprintf(output, "\n");
498 fprintf(output, "Preference reports:\n");
499 fprintf(output, " -G currentprefs dump current preferences and exit\n");
500 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
501 fprintf(output, " -G folders dump about:folders\n");
502 fprintf(output, "\n");
506 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
507 const gchar *message, gpointer user_data)
509 /* ignore log message, if log_level isn't interesting based
510 upon the console log preferences.
511 If the preferences haven't been loaded yet, display the
514 The default console_log_level preference value is such that only
515 ERROR, CRITICAL and WARNING level messages are processed;
516 MESSAGE, INFO and DEBUG level messages are ignored.
518 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
519 ERROR and CRITICAL level messages so the current code is a behavioral
520 change. The current behavior is the same as in Wireshark.
522 if (prefs_loaded && (log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0) {
526 g_log_default_handler(log_domain, log_level, message, user_data);
531 print_current_user(void) {
532 gchar *cur_user, *cur_group;
534 if (started_with_special_privs()) {
535 cur_user = get_cur_username();
536 cur_group = get_cur_groupname();
537 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
538 cur_user, cur_group);
541 if (running_with_special_privs()) {
542 fprintf(stderr, " This could be dangerous.");
544 fprintf(stderr, "\n");
549 get_tshark_compiled_version_info(GString *str)
551 /* Capture libraries */
552 get_compiled_caplibs_version(str);
556 get_tshark_runtime_version_info(GString *str)
559 /* Capture libraries */
560 g_string_append(str, ", ");
561 get_runtime_caplibs_version(str);
564 /* stuff used by libwireshark */
565 epan_get_runtime_version_info(str);
571 const char *constpath;
579 * Fetching the "File" dialogs folder not implemented.
580 * This is arguably just a pwd for a ui/cli .
584 printf("%-21s\t%s\n", "Temp:", g_get_tmp_dir());
587 path = get_persconffile_path("", FALSE);
588 printf("%-21s\t%s\n", "Personal configuration:", path);
592 constpath = get_datafile_dir();
593 if (constpath != NULL) {
594 printf("%-21s\t%s\n", "Global configuration:", constpath);
598 constpath = get_systemfile_dir();
599 printf("%-21s\t%s\n", "System:", constpath);
602 constpath = get_progfile_dir();
603 printf("%-21s\t%s\n", "Program:", constpath);
607 printf("%-21s\t%s\n", "Personal Plugins:", get_plugins_pers_dir_with_version());
610 printf("%-21s\t%s\n", "Global Plugins:", get_plugins_dir_with_version());
614 /* pers lua plugins */
615 printf("%-21s\t%s\n", "Personal Lua Plugins:", get_plugins_pers_dir());
617 /* global lua plugins */
618 printf("%-21s\t%s\n", "Global Lua Plugins:", get_plugins_dir());
622 constpath = get_extcap_dir();
624 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
625 for(i = 0; resultArray[i]; i++)
626 printf("%-21s\t%s\n", "Extcap path:", g_strstrip(resultArray[i]));
628 g_strfreev(resultArray);
631 path = maxmind_db_get_paths();
633 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
635 for(i = 0; resultArray[i]; i++)
636 printf("%-21s\t%s\n", "MaxMind database path:", g_strstrip(resultArray[i]));
638 g_strfreev(resultArray);
643 path = oid_get_default_mib_path();
645 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 20);
647 for(i = 0; resultArray[i]; i++)
648 printf("%-21s\t%s\n", "MIB/PIB path:", g_strstrip(resultArray[i]));
650 g_strfreev(resultArray);
657 must_do_dissection(dfilter_t *rfcode, dfilter_t *dfcode,
658 gchar *volatile pdu_export_arg)
660 /* We have to dissect each packet if:
662 we're printing information about each packet;
664 we're using a read filter on the packets;
666 we're using a display filter on the packets;
668 we're exporting PDUs;
670 we're using any taps that need dissection. */
671 return print_packet_info || rfcode || dfcode || pdu_export_arg ||
672 tap_listeners_require_dissection() || dissect_color;
676 main(int argc, char *argv[])
678 char *init_progfile_dir_error;
680 static const struct option long_options[] = {
681 {"help", no_argument, NULL, 'h'},
682 {"version", no_argument, NULL, 'v'},
683 LONGOPT_CAPTURE_COMMON
684 LONGOPT_DISSECT_COMMON
685 {"print", no_argument, NULL, 'P'},
686 {"export-objects", required_argument, NULL, LONGOPT_EXPORT_OBJECTS},
687 {"color", no_argument, NULL, LONGOPT_COLOR},
688 {"no-duplicate-keys", no_argument, NULL, LONGOPT_NO_DUPLICATE_KEYS},
689 {"elastic-mapping-filter", required_argument, NULL, LONGOPT_ELASTIC_MAPPING_FILTER},
692 gboolean arg_error = FALSE;
700 volatile gboolean success;
701 volatile int exit_status = EXIT_SUCCESS;
703 int caps_queries = 0;
704 gboolean start_capture = FALSE;
708 gboolean capture_option_specified = FALSE;
709 volatile int max_packet_count = 0;
711 gboolean quiet = FALSE;
712 #ifdef PCAP_NG_DEFAULT
713 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
715 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAP;
717 volatile gboolean out_file_name_res = FALSE;
718 volatile int in_file_type = WTAP_TYPE_AUTO;
719 gchar *volatile cf_name = NULL;
720 gchar *rfilter = NULL;
721 gchar *dfilter = NULL;
722 #ifdef HAVE_PCAP_OPEN_DEAD
723 struct bpf_program fcode;
725 dfilter_t *rfcode = NULL;
726 dfilter_t *dfcode = NULL;
730 gchar *output_only = NULL;
731 gchar *volatile pdu_export_arg = NULL;
732 char *volatile exp_pdu_filename = NULL;
733 exp_pdu_t exp_pdu_tap_data;
734 const gchar* elastic_mapping_filter = NULL;
737 * The leading + ensures that getopt_long() does not permute the argv[]
740 * We have to make sure that the first getopt_long() preserves the content
741 * of argv[] for the subsequent getopt_long() call.
743 * We use getopt_long() in both cases to ensure that we're using a routine
744 * whose permutation behavior we can control in the same fashion on all
745 * platforms, and so that, if we ever need to process a long argument before
746 * doing further initialization, we can do so.
748 * Glibc and Solaris libc document that a leading + disables permutation
749 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
750 * and macOS don't document it, but do so anyway.
752 * We do *not* use a leading - because the behavior of a leading - is
753 * platform-dependent.
755 #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:"
757 static const char optstring[] = OPTSTRING;
759 tshark_debug("tshark started with %d args", argc);
761 /* Set the C-language locale to the native environment. */
762 setlocale(LC_ALL, "");
764 cmdarg_err_init(failure_warning_message, failure_message_cont);
767 create_app_running_mutex();
771 * Get credential information for later use, and drop privileges
772 * before doing anything else.
773 * Let the user know if anything happened.
775 init_process_policies();
776 relinquish_special_privs_perm();
777 print_current_user();
780 * Attempt to get the pathname of the directory containing the
783 init_progfile_dir_error = init_progfile_dir(argv[0]);
784 if (init_progfile_dir_error != NULL) {
786 "tshark: Can't get pathname of directory containing the tshark program: %s.\n"
787 "It won't be possible to capture traffic.\n"
788 "Report this to the Wireshark developers.",
789 init_progfile_dir_error);
790 g_free(init_progfile_dir_error);
793 initialize_funnel_ops();
796 ws_init_dll_search_path();
798 /* Load wpcap if possible. Do this before collecting the run-time version information */
800 #endif /* HAVE_LIBPCAP */
803 /* Initialize the version information. */
804 ws_init_version_info("TShark (Wireshark)", get_tshark_compiled_version_info,
805 epan_get_compiled_version_info,
806 get_tshark_runtime_version_info);
808 /* Fail sometimes. Useful for testing fuzz scripts. */
809 /* if (g_random_int_range(0, 100) < 5) abort(); */
812 * In order to have the -X opts assigned before the wslua machine starts
813 * we need to call getopt_long before epan_init() gets called.
815 * In order to handle, for example, -o options, we also need to call it
816 * *after* epan_init() gets called, so that the dissectors have had a
817 * chance to register their preferences.
819 * XXX - can we do this all with one getopt_long() call, saving the
820 * arguments we can't handle until after initializing libwireshark,
821 * and then process them after initializing libwireshark?
825 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
827 case 'C': /* Configuration Profile */
828 if (profile_exists (optarg, FALSE)) {
829 set_profile_name (optarg);
831 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
832 exit_status = INVALID_OPTION;
836 case 'P': /* Print packet summary info even when writing to a file */
837 print_packet_info = TRUE;
838 print_summary = TRUE;
840 case 'O': /* Only output these protocols */
841 output_only = g_strdup(optarg);
843 case 'V': /* Verbose */
844 print_details = TRUE;
845 print_packet_info = TRUE;
847 case 'x': /* Print packet data in hex (and ASCII) */
849 /* The user asked for hex output, so let's ensure they get it,
850 * even if they're writing to a file.
852 print_packet_info = TRUE;
857 case LONGOPT_ELASTIC_MAPPING_FILTER:
858 elastic_mapping_filter = optarg;
865 /** Send All g_log messages to our own handler **/
869 G_LOG_LEVEL_CRITICAL|
874 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
876 g_log_set_handler(NULL,
877 (GLogLevelFlags)log_flags,
878 tshark_log_handler, NULL /* user_data */);
879 g_log_set_handler(LOG_DOMAIN_MAIN,
880 (GLogLevelFlags)log_flags,
881 tshark_log_handler, NULL /* user_data */);
884 g_log_set_handler(LOG_DOMAIN_CAPTURE,
885 (GLogLevelFlags)log_flags,
886 tshark_log_handler, NULL /* user_data */);
887 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
888 (GLogLevelFlags)log_flags,
889 tshark_log_handler, NULL /* user_data */);
892 init_report_message(failure_warning_message, failure_warning_message,
893 open_failure_message, read_failure_message,
894 write_failure_message);
897 capture_opts_init(&global_capture_opts);
898 capture_session_init(&global_capture_session, &cfile);
901 timestamp_set_type(TS_RELATIVE);
902 timestamp_set_precision(TS_PREC_AUTO);
903 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
907 /* Register all dissectors; we must do this before checking for the
908 "-G" flag, as the "-G" flag dumps information registered by the
909 dissectors, and we must do it before we read the preferences, in
910 case any dissectors register preferences. */
911 if (!epan_init(NULL, NULL, TRUE)) {
912 exit_status = INIT_FAILED;
916 /* Register all tap listeners; we do this before we parse the arguments,
917 as the "-z" argument can specify a registered tap. */
919 /* we register the plugin taps before the other taps because
920 stats_tree taps plugins will be registered as tap listeners
921 by stats_tree_stat.c and need to registered before that */
923 register_all_plugin_tap_listeners();
925 extcap_register_preferences();
926 /* Register all tap listeners. */
927 for (tap_reg_t *t = tap_reg_listener; t->cb_func != NULL; t++) {
930 conversation_table_set_gui_info(init_iousers);
931 hostlist_table_set_gui_info(init_hostlists);
932 srt_table_iterate_tables(register_srt_tables, NULL);
933 rtd_table_iterate_tables(register_rtd_tables, NULL);
934 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
936 /* If invoked with the "-G" flag, we dump out information based on
937 the argument to the "-G" flag; if no argument is specified,
938 for backwards compatibility we dump out a glossary of display
941 XXX - we do this here, for now, to support "-G" with no arguments.
942 If none of our build or other processes uses "-G" with no arguments,
943 we can just process it with the other arguments. */
944 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
945 proto_initialize_all_prefixes();
948 proto_registrar_dump_fields();
950 if (strcmp(argv[2], "column-formats") == 0)
951 column_dump_column_formats();
952 else if (strcmp(argv[2], "currentprefs") == 0) {
953 epan_load_settings();
956 else if (strcmp(argv[2], "decodes") == 0)
957 dissector_dump_decodes();
958 else if (strcmp(argv[2], "defaultprefs") == 0)
960 else if (strcmp(argv[2], "dissector-tables") == 0)
961 dissector_dump_dissector_tables();
962 else if (strcmp(argv[2], "elastic-mapping") == 0)
963 proto_registrar_dump_elastic(elastic_mapping_filter);
964 else if (strcmp(argv[2], "fieldcount") == 0) {
965 /* return value for the test suite */
966 exit_status = proto_registrar_dump_fieldcount();
968 } else if (strcmp(argv[2], "fields") == 0)
969 proto_registrar_dump_fields();
970 else if (strcmp(argv[2], "folders") == 0) {
971 epan_load_settings();
973 } else if (strcmp(argv[2], "ftypes") == 0)
974 proto_registrar_dump_ftypes();
975 else if (strcmp(argv[2], "heuristic-decodes") == 0)
976 dissector_dump_heur_decodes();
977 else if (strcmp(argv[2], "plugins") == 0) {
982 wslua_plugins_dump_all();
985 else if (strcmp(argv[2], "protocols") == 0)
986 proto_registrar_dump_protocols();
987 else if (strcmp(argv[2], "values") == 0)
988 proto_registrar_dump_values();
989 else if (strcmp(argv[2], "help") == 0)
990 glossary_option_help();
991 /* These are supported only for backwards compatibility and may or may not work
992 * for a given user in a given directory on a given operating system with a given
993 * command-line interpreter.
995 else if (strcmp(argv[2], "?") == 0)
996 glossary_option_help();
997 else if (strcmp(argv[2], "-?") == 0)
998 glossary_option_help();
1000 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G help for more help.", argv[2]);
1001 exit_status = INVALID_OPTION;
1005 exit_status = EXIT_SUCCESS;
1009 tshark_debug("tshark reading settings");
1011 /* Load libwireshark settings from the current profile. */
1012 prefs_p = epan_load_settings();
1013 prefs_loaded = TRUE;
1015 read_filter_list(CFILTER_LIST);
1017 cap_file_init(&cfile);
1019 /* Print format defaults to this. */
1020 print_format = PR_FMT_TEXT;
1021 delimiter_char = " ";
1023 output_fields = output_fields_new();
1026 * To reset the options parser, set optreset to 1 on platforms that
1027 * have optreset (documented in *BSD and macOS, apparently present but
1028 * not documented in Solaris - the Illumos repository seems to
1029 * suggest that the first Solaris getopt_long(), at least as of 2004,
1030 * was based on the NetBSD one, it had optreset) and set optind to 1,
1031 * and set optind to 0 otherwise (documented as working in the GNU
1032 * getopt_long(). Setting optind to 0 didn't originally work in the
1033 * NetBSD one, but that was added later - we don't want to depend on
1034 * it if we have optreset).
1036 * Also reset opterr to 1, so that error messages are printed by
1039 #ifdef HAVE_OPTRESET
1047 /* Now get our args */
1048 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1050 case '2': /* Perform two pass analysis */
1051 if(epan_auto_reset){
1052 cmdarg_err("-2 does not support auto session reset.");
1055 perform_two_pass_analysis = TRUE;
1058 if(perform_two_pass_analysis){
1059 cmdarg_err("-M does not support two pass analysis.");
1062 epan_auto_reset_count = get_positive_int(optarg, "epan reset count");
1063 epan_auto_reset = TRUE;
1065 case 'a': /* autostop criteria */
1066 case 'b': /* Ringbuffer option */
1067 case 'c': /* Capture x packets */
1068 case 'f': /* capture filter */
1069 case 'g': /* enable group read access on file(s) */
1070 case 'i': /* Use interface x */
1071 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
1072 case 'p': /* Don't capture in promiscuous mode */
1073 #ifdef HAVE_PCAP_REMOTE
1074 case 'A': /* Authentication */
1076 #ifdef HAVE_PCAP_CREATE
1077 case 'I': /* Capture in monitor mode, if available */
1079 case 's': /* Set the snapshot (capture) length */
1080 case 'w': /* Write to capture file x */
1081 case 'y': /* Set the pcap data link type */
1082 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
1083 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1084 case 'B': /* Buffer size */
1087 exit_status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1088 if (exit_status != 0) {
1094 * Output file name, if we're reading a file and writing to another
1097 output_file_name = g_strdup(optarg);
1098 } else if (opt == 'c') {
1099 max_packet_count = get_positive_int(optarg, "packet count");
1101 capture_option_specified = TRUE;
1107 /* already processed; just ignore it now */
1109 case 'D': /* Print a list of capture devices and exit */
1111 if_list = capture_interface_list(&err, &err_str,NULL);
1112 if (if_list == NULL) {
1114 cmdarg_err("There are no interfaces on which a capture can be done");
1116 cmdarg_err("%s", err_str);
1119 exit_status = INVALID_INTERFACE;
1122 capture_opts_print_interfaces(if_list);
1123 free_interface_list(if_list);
1124 exit_status = EXIT_SUCCESS;
1127 capture_option_specified = TRUE;
1133 output_fields_add(output_fields, optarg);
1137 if (!output_fields_set_option(output_fields, optarg)) {
1138 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1139 output_fields_list_options(stderr);
1140 exit_status = INVALID_OPTION;
1145 out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1146 if (out_file_type < 0) {
1147 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1148 list_capture_types();
1149 exit_status = INVALID_OPTION;
1154 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1157 protocolfilter_flags = PF_INCLUDE_CHILDREN;
1158 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1160 case 'W': /* Select extra information to save in our capture file */
1161 /* This is patterned after the -N flag which may not be the best idea. */
1162 if (strchr(optarg, 'n')) {
1163 out_file_name_res = TRUE;
1165 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1166 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1167 exit_status = INVALID_OPTION;
1171 case 'H': /* Read address to name mappings from a hosts file */
1172 if (! add_hosts_file(optarg))
1174 cmdarg_err("Can't read host entries from \"%s\"", optarg);
1175 exit_status = INVALID_OPTION;
1178 out_file_name_res = TRUE;
1181 case 'h': /* Print help and exit */
1182 show_help_header("Dump and analyze network traffic.");
1183 print_usage(stdout);
1184 exit_status = EXIT_SUCCESS;
1187 case 'l': /* "Line-buffer" standard output */
1188 /* The ANSI C standard does not appear to *require* that a line-buffered
1189 stream be flushed to the host environment whenever a newline is
1190 written, it just says that, on such a stream, characters "are
1191 intended to be transmitted to or from the host environment as a
1192 block when a new-line character is encountered".
1194 The Visual C++ 6.0 C implementation doesn't do what is intended;
1195 even if you set a stream to be line-buffered, it still doesn't
1196 flush the buffer at the end of every line.
1198 The whole reason for the "-l" flag in either tcpdump or TShark
1199 is to allow the output of a live capture to be piped to a program
1200 or script and to have that script see the information for the
1201 packet as soon as it's printed, rather than having to wait until
1202 a standard I/O buffer fills up.
1204 So, if the "-l" flag is specified, we flush the standard output
1205 at the end of a packet. This will do the right thing if we're
1206 printing packet summary lines, and, as we print the entire protocol
1207 tree for a single packet without waiting for anything to happen,
1208 it should be as good as line-buffered mode if we're printing
1209 protocol trees - arguably even better, as it may do fewer
1211 line_buffered = TRUE;
1213 case 'L': /* Print list of link-layer types and exit */
1215 caps_queries |= CAPS_QUERY_LINK_TYPES;
1217 capture_option_specified = TRUE;
1221 case LONGOPT_LIST_TSTAMP_TYPES: /* List possible timestamp types */
1223 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
1225 capture_option_specified = TRUE;
1229 case 'o': /* Override preference from command line */
1231 char *errmsg = NULL;
1233 switch (prefs_set_pref(optarg, &errmsg)) {
1238 case PREFS_SET_SYNTAX_ERR:
1239 cmdarg_err("Invalid -o flag \"%s\"%s%s", optarg,
1240 errmsg ? ": " : "", errmsg ? errmsg : "");
1242 exit_status = INVALID_OPTION;
1246 case PREFS_SET_NO_SUCH_PREF:
1247 case PREFS_SET_OBSOLETE:
1248 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1249 exit_status = INVALID_OPTION;
1255 case 'q': /* Quiet */
1258 case 'Q': /* Really quiet */
1260 really_quiet = TRUE;
1262 case 'r': /* Read capture file x */
1263 cf_name = g_strdup(optarg);
1265 case 'R': /* Read file filter */
1269 /* already processed; just ignore it now */
1271 case 'S': /* Set the line Separator to be printed between packets */
1274 case 'T': /* printing Type */
1275 print_packet_info = TRUE;
1276 if (strcmp(optarg, "text") == 0) {
1277 output_action = WRITE_TEXT;
1278 print_format = PR_FMT_TEXT;
1279 } else if (strcmp(optarg, "tabs") == 0) {
1280 output_action = WRITE_TEXT;
1281 print_format = PR_FMT_TEXT;
1282 delimiter_char = "\t";
1283 } else if (strcmp(optarg, "ps") == 0) {
1284 output_action = WRITE_TEXT;
1285 print_format = PR_FMT_PS;
1286 } else if (strcmp(optarg, "pdml") == 0) {
1287 output_action = WRITE_XML;
1288 print_details = TRUE; /* Need details */
1289 print_summary = FALSE; /* Don't allow summary */
1290 } else if (strcmp(optarg, "psml") == 0) {
1291 output_action = WRITE_XML;
1292 print_details = FALSE; /* Don't allow details */
1293 print_summary = TRUE; /* Need summary */
1294 } else if (strcmp(optarg, "fields") == 0) {
1295 output_action = WRITE_FIELDS;
1296 print_details = TRUE; /* Need full tree info */
1297 print_summary = FALSE; /* Don't allow summary */
1298 } else if (strcmp(optarg, "json") == 0) {
1299 output_action = WRITE_JSON;
1300 print_details = TRUE; /* Need details */
1301 print_summary = FALSE; /* Don't allow summary */
1302 } else if (strcmp(optarg, "ek") == 0) {
1303 output_action = WRITE_EK;
1305 print_details = TRUE;
1306 } else if (strcmp(optarg, "jsonraw") == 0) {
1307 output_action = WRITE_JSON_RAW;
1308 print_details = TRUE; /* Need details */
1309 print_summary = FALSE; /* Don't allow summary */
1312 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg); /* x */
1313 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1314 "\t specified by the -E option.\n"
1315 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1316 "\t details of a decoded packet. This information is equivalent to\n"
1317 "\t the packet details printed with the -V flag.\n"
1318 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1319 "\t the packets, or a multi-line view of the details of each of\n"
1320 "\t the packets, depending on whether the -V flag was specified.\n"
1321 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1322 "\t summary information of a decoded packet. This information is\n"
1323 "\t equivalent to the information shown in the one-line summary\n"
1324 "\t printed by default.\n"
1325 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1326 "\t summary information of a decoded packet. This information is \n"
1327 "\t equivalent to the packet details printed with the -V flag.\n"
1328 "\t\"jsonraw\" Packet Details, a JSON-based format for machine parsing\n"
1329 "\t including only raw hex decoded fields (same as -T json -x but\n"
1330 "\t without text decoding, only raw fields included). \n"
1331 "\t\"ek\" Packet Details, an EK JSON-based format for the bulk insert \n"
1332 "\t into elastic search cluster. This information is \n"
1333 "\t equivalent to the packet details printed with the -V flag.\n"
1334 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1335 "\t packets, or a multi-line view of the details of each of the\n"
1336 "\t packets, depending on whether the -V flag was specified.\n"
1337 "\t This is the default.\n"
1338 "\t\"tabs\" Similar to the text report except that each column of the\n"
1339 "\t human-readable one-line summary is delimited with an ASCII\n"
1340 "\t horizontal tab character.");
1341 exit_status = INVALID_OPTION;
1345 case 'U': /* Export PDUs to file */
1347 GSList *export_pdu_tap_name_list = NULL;
1350 cmdarg_err("A tap name is required. Valid names are:");
1351 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)) {
1352 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1354 exit_status = INVALID_OPTION;
1357 pdu_export_arg = g_strdup(optarg);
1360 case 'v': /* Show version and exit */
1362 /* We don't really have to cleanup here, but it's a convenient way to test
1363 * start-up and shut-down of the epan library without any UI-specific
1364 * cruft getting in the way. Makes the results of running
1365 * $ ./tools/valgrind-wireshark -n
1366 * much more useful. */
1369 exit_status = EXIT_SUCCESS;
1371 case 'O': /* Only output these protocols */
1372 /* already processed; just ignore it now */
1374 case 'V': /* Verbose */
1375 /* already processed; just ignore it now */
1377 case 'x': /* Print packet data in hex (and ASCII) */
1378 /* already processed; just ignore it now */
1381 /* already processed; just ignore it now */
1387 /* We won't call the init function for the stat this soon
1388 as it would disallow MATE's fields (which are registered
1389 by the preferences set callback) from being used as
1390 part of a tap filter. Instead, we just add the argument
1391 to a list of stat arguments. */
1392 if (strcmp("help", optarg) == 0) {
1393 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1394 list_stat_cmd_args();
1395 exit_status = EXIT_SUCCESS;
1398 if (!process_stat_cmd_arg(optarg)) {
1399 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1400 list_stat_cmd_args();
1401 exit_status = INVALID_OPTION;
1405 case 'd': /* Decode as rule */
1406 case 'K': /* Kerberos keytab file */
1407 case 'n': /* No name resolution */
1408 case 'N': /* Select what types of addresses/port #s to resolve */
1409 case 't': /* Time stamp type */
1410 case 'u': /* Seconds type */
1411 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1412 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1413 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1414 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
1415 if (!dissect_opts_handle_opt(opt, optarg)) {
1416 exit_status = INVALID_OPTION;
1420 case LONGOPT_EXPORT_OBJECTS: /* --export-objects */
1421 if (strcmp("help", optarg) == 0) {
1422 fprintf(stderr, "tshark: The available export object types for the \"--export-objects\" option are:\n");
1423 eo_list_object_types();
1424 exit_status = EXIT_SUCCESS;
1427 if (!eo_tap_opt_add(optarg)) {
1428 exit_status = INVALID_OPTION;
1432 case LONGOPT_COLOR: /* print in color where appropriate */
1433 dissect_color = TRUE;
1435 case LONGOPT_NO_DUPLICATE_KEYS:
1436 no_duplicate_keys = TRUE;
1437 node_children_grouper = proto_node_group_children_by_json_key;
1440 case '?': /* Bad flag - print usage message */
1443 list_capture_types();
1446 print_usage(stderr);
1448 exit_status = INVALID_OPTION;
1455 * Print packet summary information is the default if neither -V or -x
1456 * were specified. Note that this is new behavior, which allows for the
1457 * possibility of printing only hex/ascii output without necessarily
1458 * requiring that either the summary or details be printed too.
1460 if (!print_summary && !print_details && !print_hex)
1461 print_summary = TRUE;
1463 if (no_duplicate_keys && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW) {
1464 cmdarg_err("--no-duplicate-keys can only be used with \"-T json\" and \"-T jsonraw\"");
1465 exit_status = INVALID_OPTION;
1469 /* If we specified output fields, but not the output field type... */
1470 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1471 cmdarg_err("Output fields were specified with \"-e\", "
1472 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1473 exit_status = INVALID_OPTION;
1475 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1476 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1477 "specified with \"-e\".");
1479 exit_status = INVALID_OPTION;
1483 if (dissect_color) {
1484 if (!color_filters_init(&err_msg, NULL)) {
1485 fprintf(stderr, "%s\n", err_msg);
1490 /* If no capture filter or display filter has been specified, and there are
1491 still command-line arguments, treat them as the tokens of a capture
1492 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1493 flag was specified. */
1494 if (optind < argc) {
1495 if (cf_name != NULL) {
1496 if (dfilter != NULL) {
1497 cmdarg_err("Display filters were specified both with \"-d\" "
1498 "and with additional command-line arguments.");
1499 exit_status = INVALID_OPTION;
1502 dfilter = get_args_as_string(argc, argv, optind);
1507 if (global_capture_opts.default_options.cfilter) {
1508 cmdarg_err("A default capture filter was specified both with \"-f\""
1509 " and with additional command-line arguments.");
1510 exit_status = INVALID_OPTION;
1513 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1514 interface_options *interface_opts;
1515 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
1516 if (interface_opts->cfilter == NULL) {
1517 interface_opts->cfilter = get_args_as_string(argc, argv, optind);
1519 cmdarg_err("A capture filter was specified both with \"-f\""
1520 " and with additional command-line arguments.");
1521 exit_status = INVALID_OPTION;
1525 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1527 capture_option_specified = TRUE;
1533 if (!global_capture_opts.saving_to_file) {
1535 if (!output_file_name) {
1537 /* We're not saving the capture to a file; if "-q" wasn't specified,
1538 we should print packet information */
1540 print_packet_info = TRUE;
1543 const char *save_file = global_capture_opts.save_file;
1545 const char *save_file = output_file_name;
1547 /* We're saving to a file; if we're writing to the standard output.
1548 and we'll also be writing dissected packets to the standard
1549 output, reject the request. At best, we could redirect that
1550 to the standard error; we *can't* write both to the standard
1551 output and have either of them be useful. */
1552 if (strcmp(save_file, "-") == 0 && print_packet_info) {
1553 cmdarg_err("You can't write both raw packet data and dissected packets"
1554 " to the standard output.");
1555 exit_status = INVALID_OPTION;
1560 #ifndef HAVE_LIBPCAP
1561 if (capture_option_specified)
1562 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1565 print_usage(stderr);
1566 exit_status = INVALID_OPTION;
1571 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW && output_action != WRITE_EK) {
1572 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON, JSONRAW or EK JSON");
1573 exit_status = INVALID_OPTION;
1578 if (output_only != NULL) {
1581 if (!print_details) {
1582 cmdarg_err("-O requires -V");
1583 exit_status = INVALID_OPTION;
1587 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1588 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1589 g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1593 if (rfilter != NULL && !perform_two_pass_analysis) {
1594 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1595 exit_status = INVALID_OPTION;
1601 /* We're supposed to list the link-layer/timestamp types for an interface;
1602 did the user also specify a capture file to be read? */
1604 /* Yes - that's bogus. */
1605 cmdarg_err("You can't specify %s and a capture file to be read.",
1606 caps_queries & CAPS_QUERY_LINK_TYPES ? "-L" : "--list-time-stamp-types");
1607 exit_status = INVALID_OPTION;
1610 /* No - did they specify a ring buffer option? */
1611 if (global_capture_opts.multi_files_on) {
1612 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1613 exit_status = INVALID_OPTION;
1619 * "-r" was specified, so we're reading a capture file.
1620 * Capture options don't apply here.
1623 /* We don't support capture filters when reading from a capture file
1624 (the BPF compiler doesn't support all link-layer types that we
1625 support in capture files we read). */
1626 if (global_capture_opts.default_options.cfilter) {
1627 cmdarg_err("Only read filters, not capture filters, "
1628 "can be specified when reading a capture file.");
1629 exit_status = INVALID_OPTION;
1632 if (global_capture_opts.multi_files_on) {
1633 cmdarg_err("Multiple capture files requested, but "
1634 "a capture isn't being done.");
1635 exit_status = INVALID_OPTION;
1638 if (global_capture_opts.has_file_duration) {
1639 cmdarg_err("Switching capture files after a time period was specified, but "
1640 "a capture isn't being done.");
1641 exit_status = INVALID_OPTION;
1644 if (global_capture_opts.has_file_interval) {
1645 cmdarg_err("Switching capture files after a time interval was specified, but "
1646 "a capture isn't being done.");
1647 exit_status = INVALID_OPTION;
1650 if (global_capture_opts.has_ring_num_files) {
1651 cmdarg_err("A ring buffer of capture files was specified, but "
1652 "a capture isn't being done.");
1653 exit_status = INVALID_OPTION;
1656 if (global_capture_opts.has_autostop_files) {
1657 cmdarg_err("A maximum number of capture files was specified, but "
1658 "a capture isn't being done.");
1659 exit_status = INVALID_OPTION;
1662 if (global_capture_opts.capture_comment) {
1663 cmdarg_err("A capture comment was specified, but "
1664 "a capture isn't being done.\nThere's no support for adding "
1665 "a capture comment to an existing capture file.");
1666 exit_status = INVALID_OPTION;
1670 /* Note: TShark now allows the restriction of a _read_ file by packet count
1671 * and byte count as well as a write file. Other autostop options remain valid
1672 * only for a write file.
1674 if (global_capture_opts.has_autostop_duration) {
1675 cmdarg_err("A maximum capture time was specified, but "
1676 "a capture isn't being done.");
1677 exit_status = INVALID_OPTION;
1682 * "-r" wasn't specified, so we're doing a live capture.
1684 if (perform_two_pass_analysis) {
1685 /* Two-pass analysis doesn't work with live capture since it requires us
1686 * to buffer packets until we've read all of them, but a live capture
1687 * has no useful/meaningful definition of "all" */
1688 cmdarg_err("Live captures do not support two-pass analysis.");
1689 exit_status = INVALID_OPTION;
1693 if (global_capture_opts.saving_to_file) {
1694 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1696 /* When capturing, we only support writing pcap or pcapng format. */
1697 if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1698 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1699 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1700 exit_status = INVALID_OPTION;
1703 if (global_capture_opts.capture_comment &&
1704 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1705 cmdarg_err("A capture comment can only be written to a pcapng file.");
1706 exit_status = INVALID_OPTION;
1709 if (global_capture_opts.multi_files_on) {
1710 /* Multiple-file mode doesn't work under certain conditions:
1711 a) it doesn't work if you're writing to the standard output;
1712 b) it doesn't work if you're writing to a pipe;
1714 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1715 cmdarg_err("Multiple capture files requested, but "
1716 "the capture is being written to the standard output.");
1717 exit_status = INVALID_OPTION;
1720 if (global_capture_opts.output_to_pipe) {
1721 cmdarg_err("Multiple capture files requested, but "
1722 "the capture file is a pipe.");
1723 exit_status = INVALID_OPTION;
1726 if (!global_capture_opts.has_autostop_filesize &&
1727 !global_capture_opts.has_file_duration &&
1728 !global_capture_opts.has_file_interval) {
1729 cmdarg_err("Multiple capture files requested, but "
1730 "no maximum capture file size, duration or interval was specified.");
1731 exit_status = INVALID_OPTION;
1735 /* Currently, we don't support read or display filters when capturing
1736 and saving the packets. */
1737 if (rfilter != NULL) {
1738 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1739 exit_status = INVALID_OPTION;
1742 if (dfilter != NULL) {
1743 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1744 exit_status = INVALID_OPTION;
1747 global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1749 /* They didn't specify a "-w" flag, so we won't be saving to a
1750 capture file. Check for options that only make sense if
1751 we're saving to a file. */
1752 if (global_capture_opts.has_autostop_filesize) {
1753 cmdarg_err("Maximum capture file size specified, but "
1754 "capture isn't being saved to a file.");
1755 exit_status = INVALID_OPTION;
1758 if (global_capture_opts.multi_files_on) {
1759 cmdarg_err("Multiple capture files requested, but "
1760 "the capture isn't being saved to a file.");
1761 exit_status = INVALID_OPTION;
1764 if (global_capture_opts.capture_comment) {
1765 cmdarg_err("A capture comment was specified, but "
1766 "the capture isn't being saved to a file.");
1767 exit_status = INVALID_OPTION;
1776 /* Start windows sockets */
1777 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1780 exit_status = INIT_FAILED;
1785 /* Notify all registered modules that have had any of their preferences
1786 changed either from one of the preferences file or from the command
1787 line that their preferences have changed. */
1790 /* We can also enable specified taps for export object */
1791 start_exportobjects();
1793 /* At this point MATE will have registered its field array so we can
1794 check if the fields specified by the user are all good.
1798 GSList *invalid_fields = output_fields_valid(output_fields);
1799 if (invalid_fields != NULL) {
1801 cmdarg_err("Some fields aren't valid:");
1802 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1803 cmdarg_err_cont("\t%s", (gchar *)it->data);
1805 g_slist_free(invalid_fields);
1806 exit_status = INVALID_OPTION;
1811 /* We currently don't support taps, or printing dissected packets,
1812 if we're writing to a pipe. */
1813 if (global_capture_opts.saving_to_file &&
1814 global_capture_opts.output_to_pipe) {
1815 if (tap_listeners_require_dissection()) {
1816 cmdarg_err("Taps aren't supported when saving to a pipe.");
1817 exit_status = INVALID_OPTION;
1820 if (print_packet_info) {
1821 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1822 exit_status = INVALID_OPTION;
1828 if (ex_opt_count("read_format") > 0) {
1829 const gchar* name = ex_opt_get_next("read_format");
1830 in_file_type = open_info_name_to_type(name);
1831 if (in_file_type == WTAP_TYPE_AUTO) {
1832 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1833 list_read_capture_types();
1834 exit_status = INVALID_OPTION;
1839 timestamp_set_type(global_dissect_options.time_format);
1842 * Enabled and disabled protocols and heuristic dissectors as per
1843 * command-line options.
1845 if (!setup_enabled_and_disabled_protocols()) {
1846 exit_status = INVALID_OPTION;
1850 /* Build the column format array */
1851 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1854 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1855 capture_opts_trim_ring_num_files(&global_capture_opts);
1858 if (rfilter != NULL) {
1859 tshark_debug("Compiling read filter: '%s'", rfilter);
1860 if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1861 cmdarg_err("%s", err_msg);
1865 #ifdef HAVE_PCAP_OPEN_DEAD
1869 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1871 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1873 " Note: That read filter code looks like a valid capture filter;\n"
1874 " maybe you mixed them up?");
1880 exit_status = INVALID_INTERFACE;
1884 cfile.rfcode = rfcode;
1886 if (dfilter != NULL) {
1887 tshark_debug("Compiling display filter: '%s'", dfilter);
1888 if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1889 cmdarg_err("%s", err_msg);
1893 #ifdef HAVE_PCAP_OPEN_DEAD
1897 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1899 if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1901 " Note: That display filter code looks like a valid capture filter;\n"
1902 " maybe you mixed them up?");
1908 exit_status = INVALID_FILTER;
1912 cfile.dfcode = dfcode;
1914 if (print_packet_info) {
1915 /* If we're printing as text or PostScript, we have
1916 to create a print stream. */
1917 if (output_action == WRITE_TEXT) {
1918 switch (print_format) {
1921 print_stream = print_stream_text_stdio_new(stdout);
1925 print_stream = print_stream_ps_stdio_new(stdout);
1929 g_assert_not_reached();
1934 /* PDU export requested. Take the ownership of the '-w' file, apply tap
1935 * filters and start tapping. */
1936 if (pdu_export_arg) {
1937 const char *exp_pdu_tap_name = pdu_export_arg;
1938 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1939 char *exp_pdu_error;
1944 cmdarg_err("PDUs export requires a capture file (specify with -r).");
1945 exit_status = INVALID_OPTION;
1948 /* Take ownership of the '-w' output file. */
1950 exp_pdu_filename = global_capture_opts.save_file;
1951 global_capture_opts.save_file = NULL;
1953 exp_pdu_filename = output_file_name;
1954 output_file_name = NULL;
1956 if (exp_pdu_filename == NULL) {
1957 cmdarg_err("PDUs export requires an output file (-w).");
1958 exit_status = INVALID_OPTION;
1962 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1964 if (exp_pdu_error) {
1965 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1966 g_free(exp_pdu_error);
1967 exit_status = INVALID_TAP;
1971 if (strcmp(exp_pdu_filename, "-") == 0) {
1972 /* Write to the standard output. */
1975 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1977 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
1978 exit_status = INVALID_FILE;
1983 /* Activate the export PDU tap */
1984 comment = g_strdup_printf("Dump of PDUs from %s", cf_name);
1985 err = exp_pdu_open(&exp_pdu_tap_data, exp_fd, comment);
1988 cfile_dump_open_failure_message("TShark", exp_pdu_filename, err,
1989 WTAP_FILE_TYPE_SUBTYPE_PCAPNG);
1990 exit_status = INVALID_EXPORT;
1995 tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
1998 tshark_debug("tshark: Opening capture file: %s", cf_name);
2000 * We're reading a capture file.
2002 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
2005 exit_status = INVALID_FILE;
2009 /* Start statistics taps; we do so after successfully opening the
2010 capture file, so we know we have something to compute stats
2011 on, and after registering all dissectors, so that MATE will
2012 have registered its field array so we can have a tap filter
2013 with one of MATE's late-registered fields as part of the
2015 start_requested_stats();
2017 /* Do we need to do dissection of packets? That depends on, among
2018 other things, what taps are listening, so determine that after
2019 starting the statistics taps. */
2020 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2022 /* Process the packets in the file */
2023 tshark_debug("tshark: invoking process_cap_file() to process the packets");
2026 success = process_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
2027 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
2028 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
2030 success = process_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, max_packet_count, 0);
2033 CATCH(OutOfMemoryError) {
2037 "Sorry, but TShark has to terminate now.\n"
2039 "More information and workarounds can be found at\n"
2040 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2046 /* We still dump out the results of taps, etc., as we might have
2047 read some packets; however, we exit with an error status. */
2051 if (pdu_export_arg) {
2052 err = exp_pdu_close(&exp_pdu_tap_data);
2054 cfile_close_failure_message(exp_pdu_filename, err);
2057 g_free(pdu_export_arg);
2058 g_free(exp_pdu_filename);
2061 tshark_debug("tshark: no capture file specified");
2062 /* No capture file specified, so we're supposed to do a live capture
2063 or get a list of link-layer types for a live capture device;
2064 do we have support for live captures? */
2067 /* Warn the user if npf.sys isn't loaded. */
2068 if (!npf_sys_is_running()) {
2069 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
2070 "capturing or\nlisting interfaces.\n");
2074 /* if no interface was specified, pick a default */
2075 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
2076 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
2077 if (exit_status != 0) {
2081 /* if requested, list the link layer types and exit */
2085 /* Get the list of link-layer types for the capture devices. */
2086 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2087 interface_options *interface_opts;
2088 if_capabilities_t *caps;
2089 char *auth_str = NULL;
2090 int if_caps_queries = caps_queries;
2092 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2093 #ifdef HAVE_PCAP_REMOTE
2094 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
2095 auth_str = g_strdup_printf("%s:%s", interface_opts->auth_username, interface_opts->auth_password);
2098 caps = capture_get_if_capabilities(interface_opts->name, interface_opts->monitor_mode, auth_str, &err_str, NULL);
2101 cmdarg_err("%s", err_str);
2103 exit_status = INVALID_CAPABILITY;
2106 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
2107 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
2108 exit_status = INVALID_DATA_LINK;
2111 if ((if_caps_queries & CAPS_QUERY_TIMESTAMP_TYPES) && caps->timestamp_types == NULL) {
2112 cmdarg_err("The capture device \"%s\" has no timestamp types.", interface_opts->name);
2113 exit_status = INVALID_TIMESTAMP_TYPE;
2116 if (interface_opts->monitor_mode)
2117 if_caps_queries |= CAPS_MONITOR_MODE;
2118 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
2119 free_if_capabilities(caps);
2121 exit_status = EXIT_SUCCESS;
2126 * If the standard error isn't a terminal, don't print packet counts,
2127 * as they won't show up on the user's terminal and they'll get in
2128 * the way of error messages in the file (to which we assume the
2129 * standard error was redirected; if it's redirected to the null
2130 * device, there's no point in printing packet counts anyway).
2132 * Otherwise, if we're printing packet information and the standard
2133 * output is a terminal (which we assume means the standard output and
2134 * error are going to the same terminal), don't print packet counts,
2135 * as they'll get in the way of the packet information.
2137 * Otherwise, if the user specified -q, don't print packet counts.
2139 * Otherwise, print packet counts.
2141 * XXX - what if the user wants to do a live capture, doesn't want
2142 * to save it to a file, doesn't want information printed for each
2143 * packet, does want some "-z" statistic, and wants packet counts
2144 * so they know whether they're seeing any packets? -q will
2145 * suppress the information printed for each packet, but it'll
2146 * also suppress the packet counts.
2148 if (!ws_isatty(ws_fileno(stderr)))
2149 print_packet_counts = FALSE;
2150 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
2151 print_packet_counts = FALSE;
2153 print_packet_counts = FALSE;
2155 print_packet_counts = TRUE;
2157 if (print_packet_info) {
2158 if (!write_preamble(&cfile)) {
2159 show_print_file_io_error(errno);
2160 exit_status = INVALID_FILE;
2165 tshark_debug("tshark: performing live capture");
2167 /* Start statistics taps; we should only do so after the capture
2168 started successfully, so we know we have something to compute
2169 stats, but we currently don't check for that - see below.
2171 We do so after registering all dissectors, so that MATE will
2172 have registered its field array so we can have a tap filter
2173 with one of MATE's late-registered fields as part of the
2175 start_requested_stats();
2177 /* Do we need to do dissection of packets? That depends on, among
2178 other things, what taps are listening, so determine that after
2179 starting the statistics taps. */
2180 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2183 * XXX - this returns FALSE if an error occurred, but it also
2184 * returns FALSE if the capture stops because a time limit
2185 * was reached (and possibly other limits), so we can't assume
2186 * it means an error.
2188 * The capture code is a bit twisty, so it doesn't appear to
2189 * be an easy fix. We just ignore the return value for now.
2190 * Instead, pass on the exit status from the capture child.
2193 exit_status = global_capture_session.fork_child_status;
2195 if (print_packet_info) {
2196 if (!write_finale()) {
2197 show_print_file_io_error(errno);
2201 /* No - complain. */
2202 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2203 exit_status = INVALID_CAPTURE;
2208 if (cfile.provider.frames != NULL) {
2209 free_frame_data_sequence(cfile.provider.frames);
2210 cfile.provider.frames = NULL;
2213 draw_tap_listeners(TRUE);
2214 /* Memory cleanup */
2215 reset_tap_listeners();
2216 funnel_dump_all_text_windows();
2217 epan_free(cfile.epan);
2221 output_fields_free(output_fields);
2222 output_fields = NULL;
2226 destroy_print_stream(print_stream);
2228 capture_opts_cleanup(&global_capture_opts);
2230 g_free(output_file_name);
2232 col_cleanup(&cfile.cinfo);
2233 free_filter_lists();
2237 dfilter_free(dfcode);
2241 /*#define USE_BROKEN_G_MAIN_LOOP*/
2243 #ifdef USE_BROKEN_G_MAIN_LOOP
2246 gboolean loop_running = FALSE;
2248 guint32 packet_count = 0;
2251 typedef struct pipe_input_tag {
2254 ws_process_id *child_process;
2255 pipe_input_cb_t input_cb;
2256 guint pipe_input_id;
2258 GMutex *callback_running;
2262 static pipe_input_t pipe_input;
2265 /* The timer has expired, see if there's stuff to read from the pipe,
2266 if so, do the callback */
2268 pipe_timer_cb(gpointer data)
2274 pipe_input_t *pipe_input_p = data;
2275 gint iterations = 0;
2277 g_mutex_lock (pipe_input_p->callback_running);
2279 /* try to read data from the pipe only 5 times, to avoid blocking */
2280 while(iterations < 5) {
2281 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2283 /* Oddly enough although Named pipes don't work on win9x,
2284 PeekNamedPipe does !!! */
2285 handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2286 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2288 /* Get the child process exit status */
2289 GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2292 /* If the Peek returned an error, or there are bytes to be read
2293 or the childwatcher thread has terminated then call the normal
2295 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2297 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2299 /* And call the real handler */
2300 if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2301 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2302 /* pipe closed, return false so that the timer is stopped */
2303 g_mutex_unlock (pipe_input_p->callback_running);
2308 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2309 /* No data, stop now */
2316 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2318 g_mutex_unlock (pipe_input_p->callback_running);
2320 /* we didn't stopped the timer, so let it run */
2327 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2330 pipe_input.source = source;
2331 pipe_input.child_process = child_process;
2332 pipe_input.user_data = user_data;
2333 pipe_input.input_cb = input_cb;
2336 pipe_input.callback_running = g_malloc(sizeof(GMutex));
2337 g_mutex_init(pipe_input.callback_running);
2338 /* Tricky to use pipes in win9x, as no concept of wait. NT can
2339 do this but that doesn't cover all win32 platforms. GTK can do
2340 this but doesn't seem to work over processes. Attempt to do
2341 something similar here, start a timer and check for data on every
2343 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2344 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2348 static const nstime_t *
2349 tshark_get_frame_ts(struct packet_provider_data *prov, guint32 frame_num)
2351 if (prov->ref && prov->ref->num == frame_num)
2352 return &prov->ref->abs_ts;
2354 if (prov->prev_dis && prov->prev_dis->num == frame_num)
2355 return &prov->prev_dis->abs_ts;
2357 if (prov->prev_cap && prov->prev_cap->num == frame_num)
2358 return &prov->prev_cap->abs_ts;
2361 frame_data *fd = frame_data_sequence_find(prov->frames, frame_num);
2363 return (fd) ? &fd->abs_ts : NULL;
2370 tshark_epan_new(capture_file *cf)
2372 static const struct packet_provider_funcs funcs = {
2373 tshark_get_frame_ts,
2374 cap_file_provider_get_interface_name,
2375 cap_file_provider_get_interface_description,
2379 return epan_new(&cf->provider, &funcs);
2386 volatile gboolean ret = TRUE;
2389 #ifdef USE_TSHARK_SELECT
2393 struct sigaction action, oldaction;
2396 /* Create new dissection section. */
2397 epan_free(cfile.epan);
2398 cfile.epan = tshark_epan_new(&cfile);
2401 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2402 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2404 /* Catch SIGINT and SIGTERM and, if we get either of them,
2405 clean up and exit. If SIGHUP isn't being ignored, catch
2406 it too and, if we get it, clean up and exit.
2408 We restart any read that was in progress, so that it doesn't
2409 disrupt reading from the sync pipe. The signal handler tells
2410 the capture child to finish; it will report that it finished,
2411 or will exit abnormally, so we'll stop reading from the sync
2412 pipe, pick up the exit status, and quit. */
2413 memset(&action, 0, sizeof(action));
2414 action.sa_handler = capture_cleanup;
2415 action.sa_flags = SA_RESTART;
2416 sigemptyset(&action.sa_mask);
2417 sigaction(SIGTERM, &action, NULL);
2418 sigaction(SIGINT, &action, NULL);
2419 sigaction(SIGHUP, NULL, &oldaction);
2420 if (oldaction.sa_handler == SIG_DFL)
2421 sigaction(SIGHUP, &action, NULL);
2424 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2425 quiet mode, report the number of packets we've captured.
2427 Again, restart any read that was in progress, so that it doesn't
2428 disrupt reading from the sync pipe. */
2429 action.sa_handler = report_counts_siginfo;
2430 action.sa_flags = SA_RESTART;
2431 sigemptyset(&action.sa_mask);
2432 sigaction(SIGINFO, &action, NULL);
2433 #endif /* SIGINFO */
2436 global_capture_session.state = CAPTURE_PREPARING;
2438 /* Let the user know which interfaces were chosen. */
2439 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2440 interface_options *interface_opts;
2442 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2443 interface_opts->descr = get_interface_descriptive_name(interface_opts->name);
2445 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2446 if (really_quiet == FALSE)
2447 fprintf(stderr, "Capturing on %s\n", str->str);
2449 g_string_free(str, TRUE);
2451 ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2457 * Force synchronous resolution of IP addresses; we're doing only
2458 * one pass, so we can't do it in the background and fix up past
2461 set_resolution_synchrony(TRUE);
2463 /* the actual capture loop
2465 * XXX - glib doesn't seem to provide any event based loop handling.
2467 * XXX - for whatever reason,
2468 * calling g_main_loop_new() ends up in 100% cpu load.
2470 * But that doesn't matter: in UNIX we can use select() to find an input
2471 * source with something to do.
2473 * But that doesn't matter because we're in a CLI (that doesn't need to
2474 * update a GUI or something at the same time) so it's OK if we block
2475 * trying to read from the pipe.
2477 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2478 * wrong (but I leave it there in case I am...).
2481 #ifdef USE_TSHARK_SELECT
2483 FD_SET(pipe_input.source, &readfds);
2486 loop_running = TRUE;
2490 while (loop_running)
2492 #ifdef USE_TSHARK_SELECT
2493 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2497 fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2499 loop_running = FALSE;
2500 } else if (ret == 1) {
2502 /* Call the real handler */
2503 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2504 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2506 loop_running = FALSE;
2508 #ifdef USE_TSHARK_SELECT
2513 CATCH(OutOfMemoryError) {
2517 "Sorry, but TShark has to terminate now.\n"
2519 "More information and workarounds can be found at\n"
2520 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2527 /* capture child detected an error */
2529 capture_input_error_message(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2531 cmdarg_err("%s", error_msg);
2532 cmdarg_err_cont("%s", secondary_error_msg);
2536 /* capture child detected an capture filter related error */
2538 capture_input_cfilter_error_message(capture_session *cap_session, guint i, char *error_message)
2540 capture_options *capture_opts = cap_session->capture_opts;
2541 dfilter_t *rfcode = NULL;
2542 interface_options *interface_opts;
2544 g_assert(i < capture_opts->ifaces->len);
2545 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2547 if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
2549 "Invalid capture filter \"%s\" for interface '%s'.\n"
2551 "That string looks like a valid display filter; however, it isn't a valid\n"
2552 "capture filter (%s).\n"
2554 "Note that display filters and capture filters don't have the same syntax,\n"
2555 "so you can't use most display filter expressions as capture filters.\n"
2557 "See the User's Guide for a description of the capture filter syntax.",
2558 interface_opts->cfilter, interface_opts->descr, error_message);
2559 dfilter_free(rfcode);
2562 "Invalid capture filter \"%s\" for interface '%s'.\n"
2564 "That string isn't a valid capture filter (%s).\n"
2565 "See the User's Guide for a description of the capture filter syntax.",
2566 interface_opts->cfilter, interface_opts->descr, error_message);
2571 /* capture child tells us we have a new (or the first) capture file */
2573 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2575 capture_options *capture_opts = cap_session->capture_opts;
2576 capture_file *cf = cap_session->cf;
2577 gboolean is_tempfile;
2580 if (cap_session->state == CAPTURE_PREPARING) {
2581 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2583 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2585 g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2587 /* free the old filename */
2588 if (capture_opts->save_file != NULL) {
2590 /* we start a new capture file, close the old one (if we had one before) */
2591 if (cf->state != FILE_CLOSED) {
2592 if (cf->provider.wth != NULL) {
2593 wtap_close(cf->provider.wth);
2594 cf->provider.wth = NULL;
2596 cf->state = FILE_CLOSED;
2599 g_free(capture_opts->save_file);
2600 is_tempfile = FALSE;
2602 epan_free(cf->epan);
2603 cf->epan = tshark_epan_new(cf);
2605 /* we didn't had a save_file before, must be a tempfile */
2609 /* save the new filename */
2610 capture_opts->save_file = g_strdup(new_file);
2612 /* if we are in real-time mode, open the new file now */
2613 if (do_dissection) {
2614 /* this is probably unecessary, but better safe than sorry */
2615 cap_session->cf->open_type = WTAP_TYPE_AUTO;
2616 /* Attempt to open the capture file and set up to read from it. */
2617 switch(cf_open(cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2621 /* Don't unlink (delete) the save file - leave it around,
2622 for debugging purposes. */
2623 g_free(capture_opts->save_file);
2624 capture_opts->save_file = NULL;
2629 cap_session->state = CAPTURE_RUNNING;
2635 /* capture child tells us we have new packets to read */
2637 capture_input_new_packets(capture_session *cap_session, int to_read)
2643 capture_file *cf = cap_session->cf;
2644 gboolean filtering_tap_listeners;
2649 * Prevent a SIGINFO handler from writing to the standard error while
2650 * we're doing so or writing to the standard output; instead, have it
2651 * just set a flag telling us to print that information when we're done.
2654 #endif /* SIGINFO */
2656 /* Do we have any tap listeners with filters? */
2657 filtering_tap_listeners = have_filtering_tap_listeners();
2659 /* Get the union of the flags for all tap listeners. */
2660 tap_flags = union_of_tap_listener_flags();
2662 if (do_dissection) {
2663 gboolean create_proto_tree;
2664 epan_dissect_t *edt;
2667 * Determine whether we need to create a protocol tree.
2670 * we're going to apply a read filter;
2672 * we're going to apply a display filter;
2674 * we're going to print the protocol tree;
2676 * one of the tap listeners is going to apply a filter;
2678 * one of the tap listeners requires a protocol tree;
2680 * a postdissector wants field values or protocols
2681 * on the first pass;
2683 * we have custom columns (which require field values, which
2684 * currently requires that we build a protocol tree).
2687 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2688 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
2689 have_custom_cols(&cf->cinfo) || dissect_color);
2691 /* The protocol tree will be "visible", i.e., printed, only if we're
2692 printing packet details, which is true if we're printing stuff
2693 ("print_packet_info" is true) and we're in verbose mode
2694 ("packet_details" is true). */
2695 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2697 while (to_read-- && cf->provider.wth) {
2698 wtap_cleareof(cf->provider.wth);
2699 ret = wtap_read(cf->provider.wth, &err, &err_info, &data_offset);
2700 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
2702 /* read from file failed, tell the capture child to stop */
2703 sync_pipe_stop(cap_session);
2704 wtap_close(cf->provider.wth);
2705 cf->provider.wth = NULL;
2707 ret = process_packet_single_pass(cf, edt, data_offset,
2708 wtap_get_rec(cf->provider.wth),
2709 wtap_get_buf_ptr(cf->provider.wth), tap_flags);
2712 /* packet successfully read and gone through the "Read Filter" */
2717 epan_dissect_free(edt);
2721 * Dumpcap's doing all the work; we're not doing any dissection.
2722 * Count all the packets it wrote.
2724 packet_count += to_read;
2727 if (print_packet_counts) {
2728 /* We're printing packet counts. */
2729 if (packet_count != 0) {
2730 fprintf(stderr, "\r%u ", packet_count);
2731 /* stderr could be line buffered */
2738 * Allow SIGINFO handlers to write.
2743 * If a SIGINFO handler asked us to write out capture counts, do so.
2747 #endif /* SIGINFO */
2753 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2754 /* Report the count only if we aren't printing a packet count
2755 as packets arrive. */
2756 fprintf(stderr, "%u packet%s captured\n", packet_count,
2757 plurality(packet_count, "", "s"));
2760 infoprint = FALSE; /* we just reported it */
2761 #endif /* SIGINFO */
2766 report_counts_siginfo(int signum _U_)
2768 int sav_errno = errno;
2769 /* If we've been told to delay printing, just set a flag asking
2770 that we print counts (if we're supposed to), otherwise print
2771 the count of packets captured (if we're supposed to). */
2778 #endif /* SIGINFO */
2781 /* capture child detected any packet drops? */
2783 capture_input_drops(capture_session *cap_session _U_, guint32 dropped, char* interface_name)
2785 if (print_packet_counts) {
2786 /* We're printing packet counts to stderr.
2787 Send a newline so that we move to the line after the packet count. */
2788 fprintf(stderr, "\n");
2792 /* We're printing packet counts to stderr.
2793 Send a newline so that we move to the line after the packet count. */
2794 if (interface_name != NULL) {
2795 fprintf(stderr, "%u packet%s dropped from %s\n", dropped, plurality(dropped, "", "s"), interface_name);
2797 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2804 * Capture child closed its side of the pipe, report any error and
2805 * do the required cleanup.
2808 capture_input_closed(capture_session *cap_session, gchar *msg)
2810 capture_file *cf = cap_session->cf;
2813 fprintf(stderr, "tshark: %s\n", msg);
2817 if (cf != NULL && cf->provider.wth != NULL) {
2818 wtap_close(cf->provider.wth);
2819 if (cf->is_tempfile) {
2820 ws_unlink(cf->filename);
2823 #ifdef USE_BROKEN_G_MAIN_LOOP
2824 /*g_main_loop_quit(loop);*/
2825 g_main_loop_quit(loop);
2827 loop_running = FALSE;
2836 capture_cleanup(DWORD ctrltype _U_)
2838 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2839 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2840 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2841 like SIGTERM at least when the machine's shutting down.
2843 For now, we handle them all as indications that we should clean up
2844 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2847 We must return TRUE so that no other handler - such as one that would
2848 terminate the process - gets called.
2850 XXX - for some reason, typing ^C to TShark, if you run this in
2851 a Cygwin console window in at least some versions of Cygwin,
2852 causes TShark to terminate immediately; this routine gets
2853 called, but the main loop doesn't get a chance to run and
2854 exit cleanly, at least if this is compiled with Microsoft Visual
2855 C++ (i.e., it's a property of the Cygwin console window or Bash;
2856 it happens if TShark is not built with Cygwin - for all I know,
2857 building it with Cygwin may make the problem go away). */
2859 /* tell the capture child to stop */
2860 sync_pipe_stop(&global_capture_session);
2862 /* don't stop our own loop already here, otherwise status messages and
2863 * cleanup wouldn't be done properly. The child will indicate the stop of
2864 * everything by calling capture_input_closed() later */
2870 capture_cleanup(int signum _U_)
2872 /* tell the capture child to stop */
2873 sync_pipe_stop(&global_capture_session);
2875 /* don't stop our own loop already here, otherwise status messages and
2876 * cleanup wouldn't be done properly. The child will indicate the stop of
2877 * everything by calling capture_input_closed() later */
2880 #endif /* HAVE_LIBPCAP */
2883 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2884 gint64 offset, wtap_rec *rec,
2891 /* The frame number of this packet is one more than the count of
2892 frames in this packet. */
2893 framenum = cf->count + 1;
2895 /* If we're not running a display filter and we're not printing any
2896 packet information, we don't need to do a dissection. This means
2897 that all packets can be marked as 'passed'. */
2900 frame_data_init(&fdlocal, framenum, rec, offset, cum_bytes);
2902 /* If we're going to run a read filter or a display filter, set up to
2903 do a dissection and do so. (This is the first pass of two passes
2904 over the packets, so we will not be printing any information
2905 from the dissection or running taps on the packet; if we're doing
2906 any of that, we'll do it in the second pass.) */
2908 /* If we're running a read filter, prime the epan_dissect_t with that
2911 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
2914 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2916 /* This is the first pass, so prime the epan_dissect_t with the
2917 hfids postdissectors want on the first pass. */
2918 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
2920 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2921 &cf->provider.ref, cf->provider.prev_dis);
2922 if (cf->provider.ref == &fdlocal) {
2923 ref_frame = fdlocal;
2924 cf->provider.ref = &ref_frame;
2927 epan_dissect_run(edt, cf->cd_t, rec,
2928 frame_tvbuff_new(&cf->provider, &fdlocal, pd),
2931 /* Run the read filter if we have one. */
2933 passed = dfilter_apply_edt(cf->rfcode, edt);
2937 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2938 cf->provider.prev_cap = cf->provider.prev_dis = frame_data_sequence_add(cf->provider.frames, &fdlocal);
2940 /* If we're not doing dissection then there won't be any dependent frames.
2941 * More importantly, edt.pi.dependent_frames won't be initialized because
2942 * epan hasn't been initialized.
2943 * if we *are* doing dissection, then mark the dependent frames, but only
2944 * if a display filter was given and it matches this packet.
2946 if (edt && cf->dfcode) {
2947 if (dfilter_apply_edt(cf->dfcode, edt)) {
2948 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
2954 /* if we don't add it to the frame_data_sequence, clean it up right now
2956 frame_data_destroy(&fdlocal);
2960 epan_dissect_reset(edt);
2966 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
2967 frame_data *fdata, wtap_rec *rec,
2968 Buffer *buf, guint tap_flags)
2973 /* If we're not running a display filter and we're not printing any
2974 packet information, we don't need to do a dissection. This means
2975 that all packets can be marked as 'passed'. */
2978 /* If we're going to print packet information, or we're going to
2979 run a read filter, or we're going to process taps, set up to
2980 do a dissection and do so. (This is the second pass of two
2981 passes over the packets; that's the pass where we print
2982 packet information or run taps.) */
2984 /* If we're running a display filter, prime the epan_dissect_t with that
2987 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
2989 col_custom_prime_edt(edt, &cf->cinfo);
2991 /* We only need the columns if either
2992 1) some tap needs the columns
2994 2) we're printing packet info but we're *not* verbose; in verbose
2995 mode, we print the protocol tree, not the protocol summary.
2997 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3002 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
3003 &cf->provider.ref, cf->provider.prev_dis);
3004 if (cf->provider.ref == fdata) {
3006 cf->provider.ref = &ref_frame;
3009 if (dissect_color) {
3010 color_filters_prime_edt(edt);
3011 fdata->need_colorize = 1;
3014 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
3015 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3018 /* Run the read/display filter if we have one. */
3020 passed = dfilter_apply_edt(cf->dfcode, edt);
3024 frame_data_set_after_dissect(fdata, &cum_bytes);
3025 /* Process this packet. */
3026 if (print_packet_info) {
3027 /* We're printing packet information; print the information for
3029 print_packet(cf, edt);
3031 /* If we're doing "line-buffering", flush the standard output
3032 after every packet. See the comment above, for the "-l"
3033 option, for an explanation of why we do that. */
3037 if (ferror(stdout)) {
3038 show_print_file_io_error(errno);
3042 cf->provider.prev_dis = fdata;
3044 cf->provider.prev_cap = fdata;
3047 epan_dissect_reset(edt);
3049 return passed || fdata->dependent_of_displayed;
3053 process_cap_file(capture_file *cf, char *save_file, int out_file_type,
3054 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
3056 gboolean success = TRUE;
3059 int err = 0, err_pass1 = 0;
3060 gchar *err_info = NULL, *err_info_pass1 = NULL;
3062 gboolean filtering_tap_listeners;
3064 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
3067 epan_dissect_t *edt = NULL;
3068 char *shb_user_appl;
3070 wtap_rec_init(&rec);
3072 if (save_file != NULL) {
3073 /* Set up to write to the capture file. */
3074 wtap_dump_params_init(¶ms, cf->provider.wth);
3076 /* If we don't have an application name add Tshark */
3077 if (wtap_block_get_string_option_value(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
3078 /* this is free'd by wtap_block_free() later */
3079 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
3082 tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
3083 if (strcmp(save_file, "-") == 0) {
3084 /* Write to the standard output. */
3085 pdh = wtap_dump_open_stdout(out_file_type, WTAP_UNCOMPRESSED, ¶ms,
3088 pdh = wtap_dump_open(save_file, out_file_type, WTAP_UNCOMPRESSED, ¶ms,
3092 g_free(params.idb_inf);
3093 params.idb_inf = NULL;
3096 /* We couldn't set up to write to the capture file. */
3097 cfile_dump_open_failure_message("TShark", save_file, err, out_file_type);
3102 /* Set up to print packet information. */
3103 if (print_packet_info) {
3104 if (!write_preamble(cf)) {
3105 show_print_file_io_error(errno);
3113 /* Do we have any tap listeners with filters? */
3114 filtering_tap_listeners = have_filtering_tap_listeners();
3116 /* Get the union of the flags for all tap listeners. */
3117 tap_flags = union_of_tap_listener_flags();
3119 if (perform_two_pass_analysis) {
3122 tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3124 /* Allocate a frame_data_sequence for all the frames. */
3125 cf->provider.frames = new_frame_data_sequence();
3127 if (do_dissection) {
3128 gboolean create_proto_tree;
3131 * Determine whether we need to create a protocol tree.
3134 * we're going to apply a read filter;
3136 * we're going to apply a display filter;
3138 * a postdissector wants field values or protocols
3139 * on the first pass.
3142 (cf->rfcode != NULL || cf->dfcode != NULL || postdissectors_want_hfids() || dissect_color);
3144 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3146 /* We're not going to display the protocol tree on this pass,
3147 so it's not going to be "visible". */
3148 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
3151 tshark_debug("tshark: reading records for first pass");
3152 while (wtap_read(cf->provider.wth, &err, &err_info, &data_offset)) {
3153 if (process_packet_first_pass(cf, edt, data_offset, wtap_get_rec(cf->provider.wth),
3154 wtap_get_buf_ptr(cf->provider.wth))) {
3155 /* Stop reading if we have the maximum number of packets;
3156 * When the -c option has not been used, max_packet_count
3157 * starts at 0, which practically means, never stop reading.
3158 * (unless we roll over max_packet_count ?)
3160 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3161 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3162 max_packet_count, data_offset, max_byte_count);
3163 err = 0; /* This is not an error */
3170 * If we got a read error on the first pass, remember the error, so
3171 * but do the second pass, so we can at least process the packets we
3172 * read, and then report the first-pass error after the second pass
3173 * (and before we report any second-pass errors), so all the the
3174 * errors show up at the end.
3178 err_info_pass1 = err_info;
3184 epan_dissect_free(edt);
3188 /* Close the sequential I/O side, to free up memory it requires. */
3189 wtap_sequential_close(cf->provider.wth);
3191 /* Allow the protocol dissectors to free up memory that they
3192 * don't need after the sequential run-through of the packets. */
3193 postseq_cleanup_all_protocols();
3195 cf->provider.prev_dis = NULL;
3196 cf->provider.prev_cap = NULL;
3197 ws_buffer_init(&buf, 1500);
3199 tshark_debug("tshark: done with first pass");
3201 if (do_dissection) {
3202 gboolean create_proto_tree;
3205 * Determine whether we need to create a protocol tree.
3208 * we're going to apply a display filter;
3210 * we're going to print the protocol tree;
3212 * one of the tap listeners requires a protocol tree;
3214 * we have custom columns (which require field values, which
3215 * currently requires that we build a protocol tree).
3218 (cf->dfcode || print_details || filtering_tap_listeners ||
3219 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo) || dissect_color);
3221 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3223 /* The protocol tree will be "visible", i.e., printed, only if we're
3224 printing packet details, which is true if we're printing stuff
3225 ("print_packet_info" is true) and we're in verbose mode
3226 ("packet_details" is true). */
3227 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3231 * Force synchronous resolution of IP addresses; in this pass, we
3232 * can't do it in the background and fix up past dissections.
3234 set_resolution_synchrony(TRUE);
3236 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
3237 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3238 if (wtap_seek_read(cf->provider.wth, fdata->file_off, &rec, &buf, &err,
3240 tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3241 if (process_packet_second_pass(cf, edt, fdata, &rec, &buf,
3243 /* Either there's no read filtering or this packet passed the
3244 filter, so, if we're writing to a capture file, write
3247 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3248 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&buf), &err, &err_info)) {
3249 /* Error writing to a capture file */
3250 tshark_debug("tshark: error writing to a capture file (%d)", err);
3252 /* Report the error.
3253 XXX - framenum is not necessarily the frame number in
3254 the input file if there was a read filter. */
3255 cfile_write_failure_message("TShark", cf->filename, save_file,
3256 err, err_info, framenum,
3258 wtap_dump_close(pdh, &err);
3259 wtap_dump_params_cleanup(¶ms);
3268 epan_dissect_free(edt);
3272 ws_buffer_free(&buf);
3274 tshark_debug("tshark: done with second pass");
3277 /* !perform_two_pass_analysis */
3279 gboolean create_proto_tree = FALSE;
3280 tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3282 if (do_dissection) {
3284 * Determine whether we need to create a protocol tree.
3287 * we're going to apply a read filter;
3289 * we're going to apply a display filter;
3291 * we're going to print the protocol tree;
3293 * one of the tap listeners is going to apply a filter;
3295 * one of the tap listeners requires a protocol tree;
3297 * a postdissector wants field values or protocols
3298 * on the first pass;
3300 * we have custom columns (which require field values, which
3301 * currently requires that we build a protocol tree).
3304 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3305 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3306 have_custom_cols(&cf->cinfo) || dissect_color);
3308 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3310 /* The protocol tree will be "visible", i.e., printed, only if we're
3311 printing packet details, which is true if we're printing stuff
3312 ("print_packet_info" is true) and we're in verbose mode
3313 ("packet_details" is true). */
3314 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3318 * Force synchronous resolution of IP addresses; we're doing only
3319 * one pass, so we can't do it in the background and fix up past
3322 set_resolution_synchrony(TRUE);
3324 while (wtap_read(cf->provider.wth, &err, &err_info, &data_offset)) {
3327 tshark_debug("tshark: processing packet #%d", framenum);
3329 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3331 if (process_packet_single_pass(cf, edt, data_offset, wtap_get_rec(cf->provider.wth),
3332 wtap_get_buf_ptr(cf->provider.wth), tap_flags)) {
3333 /* Either there's no read filtering or this packet passed the
3334 filter, so, if we're writing to a capture file, write
3337 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3338 if (!wtap_dump(pdh, wtap_get_rec(cf->provider.wth), wtap_get_buf_ptr(cf->provider.wth), &err, &err_info)) {
3339 /* Error writing to a capture file */
3340 tshark_debug("tshark: error writing to a capture file (%d)", err);
3341 cfile_write_failure_message("TShark", cf->filename, save_file,
3342 err, err_info, framenum, out_file_type);
3343 wtap_dump_close(pdh, &err);
3344 wtap_dump_params_cleanup(¶ms);
3349 /* Stop reading if we have the maximum number of packets;
3350 * When the -c option has not been used, max_packet_count
3351 * starts at 0, which practically means, never stop reading.
3352 * (unless we roll over max_packet_count ?)
3354 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3355 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3356 max_packet_count, data_offset, max_byte_count);
3357 err = 0; /* This is not an error */
3363 epan_dissect_free(edt);
3368 wtap_rec_cleanup(&rec);
3370 if (err != 0 || err_pass1 != 0) {
3371 tshark_debug("tshark: something failed along the line (%d)", err);
3373 * Print a message noting that the read failed somewhere along the line.
3375 * If we're printing packet data, and the standard output and error are
3376 * going to the same place, flush the standard output, so everything
3377 * buffered up is written, and then print a newline to the standard error
3378 * before printing the error message, to separate it from the packet
3379 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
3380 * the _fstat() documentation at Microsoft doesn't indicate whether
3381 * st_ino is even supported.)
3384 if (print_packet_info) {
3385 ws_statb64 stat_stdout, stat_stderr;
3387 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3388 if (stat_stdout.st_dev == stat_stderr.st_dev &&
3389 stat_stdout.st_ino == stat_stderr.st_ino) {
3391 fprintf(stderr, "\n");
3396 if (err_pass1 != 0) {
3397 /* Error on pass 1 of two-pass processing. */
3398 cfile_read_failure_message("TShark", cf->filename, err_pass1,
3402 /* Error on pass 2 of two-pass processing or on the only pass of
3403 one-pass processing. */
3404 cfile_read_failure_message("TShark", cf->filename, err, err_info);
3408 if (save_file != NULL) {
3409 if (pdh && out_file_name_res) {
3410 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3411 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3412 wtap_file_type_subtype_short_string(out_file_type));
3415 /* Now close the capture file. */
3416 if (!wtap_dump_close(pdh, &err)) {
3417 cfile_close_failure_message(save_file, err);
3421 if (print_packet_info) {
3422 if (!write_finale()) {
3423 show_print_file_io_error(errno);
3430 wtap_close(cf->provider.wth);
3431 cf->provider.wth = NULL;
3433 wtap_dump_params_cleanup(¶ms);
3439 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, gint64 offset,
3440 wtap_rec *rec, const guchar *pd,
3447 /* Count this packet. */
3450 /* If we're not running a display filter and we're not printing any
3451 packet information, we don't need to do a dissection. This means
3452 that all packets can be marked as 'passed'. */
3455 frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
3457 /* If we're going to print packet information, or we're going to
3458 run a read filter, or we're going to process taps, set up to
3459 do a dissection and do so. (This is the one and only pass
3460 over the packets, so, if we'll be printing packet information
3461 or running taps, we'll be doing it here.) */
3463 /* If we're running a filter, prime the epan_dissect_t with that
3466 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3468 /* This is the first and only pass, so prime the epan_dissect_t
3469 with the hfids postdissectors want on the first pass. */
3470 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
3472 col_custom_prime_edt(edt, &cf->cinfo);
3474 /* We only need the columns if either
3475 1) some tap needs the columns
3477 2) we're printing packet info but we're *not* verbose; in verbose
3478 mode, we print the protocol tree, not the protocol summary.
3480 3) there is a column mapped as an individual field */
3481 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3486 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3487 &cf->provider.ref, cf->provider.prev_dis);
3488 if (cf->provider.ref == &fdata) {
3490 cf->provider.ref = &ref_frame;
3493 if (dissect_color) {
3494 color_filters_prime_edt(edt);
3495 fdata.need_colorize = 1;
3498 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
3499 frame_tvbuff_new(&cf->provider, &fdata, pd),
3502 /* Run the filter if we have it. */
3504 passed = dfilter_apply_edt(cf->dfcode, edt);
3508 frame_data_set_after_dissect(&fdata, &cum_bytes);
3510 /* Process this packet. */
3511 if (print_packet_info) {
3512 /* We're printing packet information; print the information for
3515 print_packet(cf, edt);
3517 /* If we're doing "line-buffering", flush the standard output
3518 after every packet. See the comment above, for the "-l"
3519 option, for an explanation of why we do that. */
3523 if (ferror(stdout)) {
3524 show_print_file_io_error(errno);
3529 /* this must be set after print_packet() [bug #8160] */
3530 prev_dis_frame = fdata;
3531 cf->provider.prev_dis = &prev_dis_frame;
3534 prev_cap_frame = fdata;
3535 cf->provider.prev_cap = &prev_cap_frame;
3538 epan_dissect_reset(edt);
3539 frame_data_destroy(&fdata);
3545 write_preamble(capture_file *cf)
3547 switch (output_action) {
3550 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3554 write_pdml_preamble(stdout, cf->filename);
3556 write_psml_preamble(&cf->cinfo, stdout);
3557 return !ferror(stdout);
3560 write_fields_preamble(output_fields, stdout);
3561 return !ferror(stdout);
3564 case WRITE_JSON_RAW:
3565 jdumper = write_json_preamble(stdout);
3566 return !ferror(stdout);
3572 g_assert_not_reached();
3578 get_line_buf(size_t len)
3580 static char *line_bufp = NULL;
3581 static size_t line_buf_len = 256;
3582 size_t new_line_buf_len;
3584 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3585 new_line_buf_len *= 2)
3587 if (line_bufp == NULL) {
3588 line_buf_len = new_line_buf_len;
3589 line_bufp = (char *)g_malloc(line_buf_len + 1);
3591 if (new_line_buf_len > line_buf_len) {
3592 line_buf_len = new_line_buf_len;
3593 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3600 put_string(char *dest, const char *str, size_t str_len)
3602 memcpy(dest, str, str_len);
3603 dest[str_len] = '\0';
3607 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3611 for (i = str_len; i < str_with_spaces; i++)
3614 put_string(dest, str, str_len);
3618 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3622 memcpy(dest, str, str_len);
3623 for (i = str_len; i < str_with_spaces; i++)
3626 dest[str_with_spaces] = '\0';
3630 print_columns(capture_file *cf, const epan_dissect_t *edt)
3637 col_item_t* col_item;
3638 gchar str_format[11];
3639 const color_filter_t *color_filter = NULL;
3641 line_bufp = get_line_buf(256);
3646 color_filter = edt->pi.fd->color_filter;
3648 for (i = 0; i < cf->cinfo.num_cols; i++) {
3649 col_item = &cf->cinfo.columns[i];
3650 /* Skip columns not marked as visible. */
3651 if (!get_column_visible(i))
3653 switch (col_item->col_fmt) {
3655 column_len = col_len = strlen(col_item->col_data);
3658 line_bufp = get_line_buf(buf_offset + column_len);
3659 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3665 case COL_ABS_YMD_TIME: /* XXX - wider */
3666 case COL_ABS_YDOY_TIME: /* XXX - wider */
3668 case COL_UTC_YMD_TIME: /* XXX - wider */
3669 case COL_UTC_YDOY_TIME: /* XXX - wider */
3670 column_len = col_len = strlen(col_item->col_data);
3671 if (column_len < 10)
3673 line_bufp = get_line_buf(buf_offset + column_len);
3674 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3680 case COL_DEF_DL_SRC:
3681 case COL_RES_DL_SRC:
3682 case COL_UNRES_DL_SRC:
3683 case COL_DEF_NET_SRC:
3684 case COL_RES_NET_SRC:
3685 case COL_UNRES_NET_SRC:
3686 column_len = col_len = strlen(col_item->col_data);
3687 if (column_len < 12)
3689 line_bufp = get_line_buf(buf_offset + column_len);
3690 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3696 case COL_DEF_DL_DST:
3697 case COL_RES_DL_DST:
3698 case COL_UNRES_DL_DST:
3699 case COL_DEF_NET_DST:
3700 case COL_RES_NET_DST:
3701 case COL_UNRES_NET_DST:
3702 column_len = col_len = strlen(col_item->col_data);
3703 if (column_len < 12)
3705 line_bufp = get_line_buf(buf_offset + column_len);
3706 put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3710 column_len = strlen(col_item->col_data);
3711 line_bufp = get_line_buf(buf_offset + column_len);
3712 put_string(line_bufp + buf_offset, col_item->col_data, column_len);
3715 buf_offset += column_len;
3716 if (i != cf->cinfo.num_cols - 1) {
3718 * This isn't the last column, so we need to print a
3719 * separator between this column and the next.
3721 * If we printed a network source and are printing a
3722 * network destination of the same type next, separate
3723 * them with a UTF-8 right arrow; if we printed a network
3724 * destination and are printing a network source of the same
3725 * type next, separate them with a UTF-8 left arrow;
3726 * otherwise separate them with a space.
3728 * We add enough space to the buffer for " \xe2\x86\x90 "
3729 * or " \xe2\x86\x92 ", even if we're only adding " ".
3731 line_bufp = get_line_buf(buf_offset + 5);
3732 switch (col_item->col_fmt) {
3737 switch (cf->cinfo.columns[i+1].col_fmt) {
3742 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3743 put_string(line_bufp + buf_offset, str_format, 5);
3748 put_string(line_bufp + buf_offset, delimiter_char, 1);
3754 case COL_DEF_DL_SRC:
3755 case COL_RES_DL_SRC:
3756 case COL_UNRES_DL_SRC:
3757 switch (cf->cinfo.columns[i+1].col_fmt) {
3759 case COL_DEF_DL_DST:
3760 case COL_RES_DL_DST:
3761 case COL_UNRES_DL_DST:
3762 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3763 put_string(line_bufp + buf_offset, str_format, 5);
3768 put_string(line_bufp + buf_offset, delimiter_char, 1);
3774 case COL_DEF_NET_SRC:
3775 case COL_RES_NET_SRC:
3776 case COL_UNRES_NET_SRC:
3777 switch (cf->cinfo.columns[i+1].col_fmt) {
3779 case COL_DEF_NET_DST:
3780 case COL_RES_NET_DST:
3781 case COL_UNRES_NET_DST:
3782 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
3783 put_string(line_bufp + buf_offset, str_format, 5);
3788 put_string(line_bufp + buf_offset, delimiter_char, 1);
3797 switch (cf->cinfo.columns[i+1].col_fmt) {
3802 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3803 put_string(line_bufp + buf_offset, str_format, 5);
3808 put_string(line_bufp + buf_offset, delimiter_char, 1);
3814 case COL_DEF_DL_DST:
3815 case COL_RES_DL_DST:
3816 case COL_UNRES_DL_DST:
3817 switch (cf->cinfo.columns[i+1].col_fmt) {
3819 case COL_DEF_DL_SRC:
3820 case COL_RES_DL_SRC:
3821 case COL_UNRES_DL_SRC:
3822 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3823 put_string(line_bufp + buf_offset, str_format, 5);
3828 put_string(line_bufp + buf_offset, delimiter_char, 1);
3834 case COL_DEF_NET_DST:
3835 case COL_RES_NET_DST:
3836 case COL_UNRES_NET_DST:
3837 switch (cf->cinfo.columns[i+1].col_fmt) {
3839 case COL_DEF_NET_SRC:
3840 case COL_RES_NET_SRC:
3841 case COL_UNRES_NET_SRC:
3842 g_snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
3843 put_string(line_bufp + buf_offset, str_format, 5);
3848 put_string(line_bufp + buf_offset, delimiter_char, 1);
3855 put_string(line_bufp + buf_offset, delimiter_char, 1);
3862 if (dissect_color && color_filter != NULL)
3863 return print_line_color(print_stream, 0, line_bufp, &color_filter->fg_color, &color_filter->bg_color);
3865 return print_line(print_stream, 0, line_bufp);
3869 print_packet(capture_file *cf, epan_dissect_t *edt)
3871 if (print_summary || output_fields_has_cols(output_fields))
3872 /* Just fill in the columns. */
3873 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3875 /* Print summary columns and/or protocol tree */
3876 switch (output_action) {
3879 if (print_summary && !print_columns(cf, edt))
3881 if (print_details) {
3882 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
3883 print_hex, edt, output_only_tables, print_stream))
3886 if (!print_line(print_stream, 0, separator))
3893 if (print_summary) {
3894 write_psml_columns(edt, stdout, dissect_color);
3895 return !ferror(stdout);
3897 if (print_details) {
3898 write_pdml_proto_tree(output_fields, protocolfilter, protocolfilter_flags, edt, &cf->cinfo, stdout, dissect_color);
3900 return !ferror(stdout);
3905 if (print_summary) {
3906 /*No non-verbose "fields" format */
3907 g_assert_not_reached();
3909 if (print_details) {
3910 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
3912 return !ferror(stdout);
3918 g_assert_not_reached();
3919 if (print_details) {
3920 write_json_proto_tree(output_fields, print_dissections_expanded,
3921 print_hex, protocolfilter, protocolfilter_flags,
3922 edt, &cf->cinfo, node_children_grouper, &jdumper);
3923 return !ferror(stdout);
3927 case WRITE_JSON_RAW:
3929 g_assert_not_reached();
3930 if (print_details) {
3931 write_json_proto_tree(output_fields, print_dissections_none, TRUE,
3932 protocolfilter, protocolfilter_flags,
3933 edt, &cf->cinfo, node_children_grouper, &jdumper);
3934 return !ferror(stdout);
3939 write_ek_proto_tree(output_fields, print_summary, print_hex, protocolfilter,
3940 protocolfilter_flags, edt, &cf->cinfo, stdout);
3941 return !ferror(stdout);
3945 if (print_summary || print_details) {
3946 if (!print_line(print_stream, 0, ""))
3949 if (!print_hex_data(print_stream, edt))
3951 if (!print_line(print_stream, 0, separator))
3960 switch (output_action) {
3963 return print_finale(print_stream);
3967 write_pdml_finale(stdout);
3969 write_psml_finale(stdout);
3970 return !ferror(stdout);
3973 write_fields_finale(output_fields, stdout);
3974 return !ferror(stdout);
3977 case WRITE_JSON_RAW:
3978 write_json_finale(&jdumper);
3979 return !ferror(stdout);
3985 g_assert_not_reached();
3991 cf_close(capture_file *cf)
3993 g_free(cf->filename);
3997 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
4002 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
4006 /* The open succeeded. Fill in the information for this file. */
4008 cf->provider.wth = wth;
4009 cf->f_datalen = 0; /* not used, but set it anyway */
4011 /* Set the file name because we need it to set the follow stream filter.
4012 XXX - is that still true? We need it for other reasons, though,
4014 cf->filename = g_strdup(fname);
4016 /* Indicate whether it's a permanent or temporary file. */
4017 cf->is_tempfile = is_tempfile;
4019 /* No user changes yet. */
4020 cf->unsaved_changes = FALSE;
4022 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
4023 cf->open_type = type;
4025 cf->drops_known = FALSE;
4027 cf->snap = wtap_snapshot_length(cf->provider.wth);
4028 nstime_set_zero(&cf->elapsed_time);
4029 cf->provider.ref = NULL;
4030 cf->provider.prev_dis = NULL;
4031 cf->provider.prev_cap = NULL;
4033 /* Create new epan session for dissection. */
4034 epan_free(cf->epan);
4035 cf->epan = tshark_epan_new(cf);
4037 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
4038 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
4039 wtap_set_cb_new_secrets(cf->provider.wth, secrets_wtap_callback);
4044 cfile_open_failure_message("TShark", fname, *err, err_info);
4049 show_print_file_io_error(int err)
4054 cmdarg_err("Not all the packets could be printed because there is "
4055 "no space left on the file system.");
4060 cmdarg_err("Not all the packets could be printed because you are "
4061 "too close to, or over your disk quota.");
4066 cmdarg_err("An error occurred while printing packets: %s.",
4073 * General errors and warnings are reported with an console message
4077 failure_warning_message(const char *msg_format, va_list ap)
4079 fprintf(stderr, "tshark: ");
4080 vfprintf(stderr, msg_format, ap);
4081 fprintf(stderr, "\n");
4085 * Open/create errors are reported with an console message in TShark.
4088 open_failure_message(const char *filename, int err, gboolean for_writing)
4090 fprintf(stderr, "tshark: ");
4091 fprintf(stderr, file_open_error_message(err, for_writing), filename);
4092 fprintf(stderr, "\n");
4096 * Read errors are reported with an console message in TShark.
4099 read_failure_message(const char *filename, int err)
4101 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4102 filename, g_strerror(err));
4106 * Write errors are reported with an console message in TShark.
4109 write_failure_message(const char *filename, int err)
4111 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4112 filename, g_strerror(err));
4115 static void reset_epan_mem(capture_file *cf,epan_dissect_t *edt, gboolean tree, gboolean visual)
4117 if (!epan_auto_reset || (cf->count < epan_auto_reset_count))
4120 fprintf(stderr, "resetting session.\n");
4122 epan_dissect_cleanup(edt);
4123 epan_free(cf->epan);
4125 cf->epan = tshark_epan_new(cf);
4126 epan_dissect_init(edt, cf->epan, tree, visual);
4131 * Report additional information for an error in command-line arguments.
4134 failure_message_cont(const char *msg_format, va_list ap)
4136 vfprintf(stderr, msg_format, ap);
4137 fprintf(stderr, "\n");
4141 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4146 * indent-tabs-mode: nil
4149 * vi: set shiftwidth=2 tabstop=8 expandtab:
4150 * :indentSize=2:tabSize=8:noTabs=true: