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 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
44 # include <sys/capability.h>
47 #ifndef HAVE_GETOPT_LONG
48 #include "wsutil/wsgetopt.h"
53 #include <epan/exceptions.h>
54 #include <epan/epan-int.h>
55 #include <epan/epan.h>
57 #include <wsutil/clopts_common.h>
58 #include <wsutil/cmdarg_err.h>
59 #include <wsutil/crash_info.h>
60 #include <wsutil/filesystem.h>
61 #include <wsutil/file_util.h>
62 #include <wsutil/privileges.h>
63 #include <wsutil/report_err.h>
64 #include <ws_version_info.h>
65 #include <wiretap/wtap_opttypes.h>
66 #include <wiretap/pcapng.h>
69 #include <epan/timestamp.h>
70 #include <epan/packet.h>
72 #include <epan/wslua/init_wslua.h>
74 #include "frame_tvbuff.h"
75 #include <epan/disabled_protos.h>
76 #include <epan/prefs.h>
77 #include <epan/column.h>
78 #include <epan/print.h>
79 #include <epan/addr_resolv.h>
81 #include "ui/capture_ui_utils.h"
84 #include "ui/ui_util.h"
85 #include "ui/decode_as_utils.h"
86 #include "ui/cli/tshark-tap.h"
87 #include "ui/tap_export_pdu.h"
89 #include "filter_files.h"
90 #include <epan/epan_dissect.h>
92 #include <epan/stat_tap_ui.h>
93 #include <epan/conversation_table.h>
94 #include <epan/srt_table.h>
95 #include <epan/rtd_table.h>
96 #include <epan/ex-opt.h>
97 #include <epan/exported_pdu.h>
99 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
100 #include <epan/asn1.h>
101 #include <epan/dissectors/packet-kerberos.h>
104 #include "capture_opts.h"
106 #include "caputils/capture-pcap-util.h"
109 #include "caputils/capture_ifinfo.h"
111 #include "caputils/capture-wpcap.h"
112 #include <wsutil/os_version_info.h>
113 #include <wsutil/unicode-utils.h>
115 #include <capchild/capture_session.h>
116 #include <capchild/capture_sync.h>
117 #include <capture_info.h>
118 #endif /* HAVE_LIBPCAP */
120 #include <epan/funnel.h>
122 #include <wsutil/str_util.h>
123 #include <wsutil/utf8_entities.h>
126 #include <wsutil/plugins.h>
131 #define tshark_debug(...) g_warning(__VA_ARGS__)
133 #define tshark_debug(...)
136 static guint32 cum_bytes;
137 static const frame_data *ref;
138 static frame_data ref_frame;
139 static frame_data *prev_dis;
140 static frame_data prev_dis_frame;
141 static frame_data *prev_cap;
142 static frame_data prev_cap_frame;
144 static gboolean perform_two_pass_analysis;
147 * The way the packet decode is to be written.
150 WRITE_TEXT, /* summary or detail text */
151 WRITE_XML, /* PDML or PSML */
152 WRITE_FIELDS, /* User defined list of fields */
153 WRITE_JSON, /* JSON */
154 WRITE_EK /* JSON bulk insert to Elasticsearch */
155 /* Add CSV and the like here */
158 static output_action_e output_action;
159 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
160 static gboolean print_packet_info; /* TRUE if we're to print packet information */
161 static gint print_summary = -1; /* TRUE if we're to print packet summary information */
162 static gboolean print_details; /* TRUE if we're to print packet details information */
163 static gboolean print_hex; /* TRUE if we're to print hex/ascci information */
164 static gboolean line_buffered;
165 static gboolean really_quiet = FALSE;
167 static print_format_e print_format = PR_FMT_TEXT;
168 static print_stream_t *print_stream;
170 static output_fields_t* output_fields = NULL;
171 static gchar **protocolfilter = NULL;
173 /* The line separator used between packets, changeable via the -S option */
174 static const char *separator = "";
178 * TRUE if we're to print packet counts to keep track of captured packets.
180 static gboolean print_packet_counts;
182 static capture_options global_capture_opts;
183 static capture_session global_capture_session;
184 static info_data_t global_info_data;
187 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
188 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
191 static gboolean capture(void);
192 static void report_counts(void);
194 static BOOL WINAPI capture_cleanup(DWORD);
196 static void capture_cleanup(int);
198 static void report_counts_siginfo(int);
202 #else /* HAVE_LIBPCAP */
204 static char *output_file_name;
206 #endif /* HAVE_LIBPCAP */
208 static int load_cap_file(capture_file *, char *, int, gboolean, int, gint64);
209 static gboolean process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset,
210 struct wtap_pkthdr *whdr, const guchar *pd,
212 static void show_capture_file_io_error(const char *, int, gboolean);
213 static void show_print_file_io_error(int err);
214 static gboolean write_preamble(capture_file *cf);
215 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
216 static gboolean write_finale(void);
217 static const char *cf_open_error_message(int err, gchar *err_info,
218 gboolean for_writing, int file_type);
220 static void open_failure_message(const char *filename, int err,
221 gboolean for_writing);
222 static void failure_message(const char *msg_format, va_list ap);
223 static void read_failure_message(const char *filename, int err);
224 static void write_failure_message(const char *filename, int err);
225 static void failure_message_cont(const char *msg_format, va_list ap);
229 static GHashTable *output_only_tables = NULL;
232 const char *sstr; /* The short string */
233 const char *lstr; /* The long string */
237 string_compare(gconstpointer a, gconstpointer b)
239 return strcmp(((const struct string_elem *)a)->sstr,
240 ((const struct string_elem *)b)->sstr);
244 string_elem_print(gpointer data, gpointer not_used _U_)
246 fprintf(stderr, " %s - %s\n",
247 ((struct string_elem *)data)->sstr,
248 ((struct string_elem *)data)->lstr);
252 list_capture_types(void) {
254 struct string_elem *captypes;
257 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
259 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
260 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
261 if (wtap_dump_can_open(i)) {
262 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
263 captypes[i].lstr = wtap_file_type_subtype_string(i);
264 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
267 g_slist_foreach(list, string_elem_print, NULL);
273 list_read_capture_types(void) {
275 struct string_elem *captypes;
277 const char *magic = "Magic-value-based";
278 const char *heuristic = "Heuristics-based";
280 /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
281 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
283 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
284 for (i = 0; open_routines[i].name != NULL; i++) {
285 captypes[i].sstr = open_routines[i].name;
286 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
287 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
289 g_slist_foreach(list, string_elem_print, NULL);
295 print_usage(FILE *output)
297 fprintf(output, "\n");
298 fprintf(output, "Usage: tshark [options] ...\n");
299 fprintf(output, "\n");
302 fprintf(output, "Capture interface:\n");
303 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
304 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
305 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
306 fprintf(output, " -p don't capture in promiscuous mode\n");
307 #ifdef HAVE_PCAP_CREATE
308 fprintf(output, " -I capture in monitor mode, if available\n");
310 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
311 fprintf(output, " -B <buffer size> size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
313 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
314 fprintf(output, " -D print list of interfaces and exit\n");
315 fprintf(output, " -L print list of link-layer types of iface and exit\n");
316 fprintf(output, "\n");
317 fprintf(output, "Capture stop conditions:\n");
318 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
319 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
320 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
321 fprintf(output, " files:NUM - stop after NUM files\n");
322 /*fprintf(output, "\n");*/
323 fprintf(output, "Capture output:\n");
324 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
325 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
326 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
327 #endif /* HAVE_LIBPCAP */
328 #ifdef HAVE_PCAP_REMOTE
329 fprintf(output, "RPCAP options:\n");
330 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
332 /*fprintf(output, "\n");*/
333 fprintf(output, "Input file:\n");
334 fprintf(output, " -r <infile> set the filename to read from (- to read from stdin)\n");
336 fprintf(output, "\n");
337 fprintf(output, "Processing:\n");
338 fprintf(output, " -2 perform a two-pass analysis\n");
339 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
340 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
341 fprintf(output, " syntax\n");
342 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
343 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtCd\"\n");
344 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
345 fprintf(output, " \"Decode As\", see the man page for details\n");
346 fprintf(output, " Example: tcp.port==8888,http\n");
347 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
348 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
349 fprintf(output, " --disable-protocol <proto_name>\n");
350 fprintf(output, " disable dissection of proto_name\n");
351 fprintf(output, " --enable-heuristic <short_name>\n");
352 fprintf(output, " enable dissection of heuristic protocol\n");
353 fprintf(output, " --disable-heuristic <short_name>\n");
354 fprintf(output, " disable dissection of heuristic protocol\n");
356 /*fprintf(output, "\n");*/
357 fprintf(output, "Output:\n");
358 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
359 fprintf(output, " (or to the standard output for \"-\")\n");
360 fprintf(output, " -C <config profile> start with specified configuration profile\n");
361 fprintf(output, " -F <output file type> set the output file type, default is pcapng\n");
362 fprintf(output, " an empty \"-F\" option will list the file types\n");
363 fprintf(output, " -V add output of packet tree (Packet Details)\n");
364 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
365 fprintf(output, " separated\n");
366 fprintf(output, " -P print packet summary even when writing to a file\n");
367 fprintf(output, " -S <separator> the line separator to print between packets\n");
368 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
369 fprintf(output, " -T pdml|ps|psml|json|ek|text|fields\n");
370 fprintf(output, " format of text output (def: text)\n");
371 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected,\n");
372 fprintf(output, " (e.g. \"http tcp ip\",\n");
373 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
374 fprintf(output, " _ws.col.Info)\n");
375 fprintf(output, " this option can be repeated to print multiple fields\n");
376 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
377 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
378 fprintf(output, " header=y|n switch headers on and off\n");
379 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
380 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
381 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
382 fprintf(output, " aggregator\n");
383 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
384 fprintf(output, " -t a|ad|d|dd|e|r|u|ud output format of time stamps (def: r: rel. to first)\n");
385 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
386 fprintf(output, " -l flush standard output after each packet\n");
387 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
388 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
389 fprintf(output, " -g enable group read access on the output file(s)\n");
390 fprintf(output, " -W n Save extra information in the file, if supported.\n");
391 fprintf(output, " n = write network address resolution information\n");
392 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
393 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
394 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
395 fprintf(output, " --capture-comment <comment>\n");
396 fprintf(output, " add a capture comment to the newly created\n");
397 fprintf(output, " output file (only for pcapng)\n");
399 fprintf(output, "\n");
400 fprintf(output, "Miscellaneous:\n");
401 fprintf(output, " -h display this help and exit\n");
402 fprintf(output, " -v display version info and exit\n");
403 fprintf(output, " -o <name>:<value> ... override preference setting\n");
404 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
405 fprintf(output, " -G [report] dump one of several available reports and exit\n");
406 fprintf(output, " default report=\"fields\"\n");
407 fprintf(output, " use \"-G ?\" for more help\n");
409 fprintf(output, "\n");
410 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
411 fprintf(output, "You might want to reset it\n");
412 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
413 fprintf(output, "\n");
419 glossary_option_help(void)
425 fprintf(output, "TShark (Wireshark) %s\n", get_ws_vcs_version_info());
427 fprintf(output, "\n");
428 fprintf(output, "Usage: tshark -G [report]\n");
429 fprintf(output, "\n");
430 fprintf(output, "Glossary table reports:\n");
431 fprintf(output, " -G column-formats dump column format codes and exit\n");
432 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
433 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
434 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
435 fprintf(output, " -G fields dump fields glossary and exit\n");
436 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
437 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
438 fprintf(output, " -G plugins dump installed plugins and exit\n");
439 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
440 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
441 fprintf(output, "\n");
442 fprintf(output, "Preference reports:\n");
443 fprintf(output, " -G currentprefs dump current preferences and exit\n");
444 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
445 fprintf(output, "\n");
449 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
450 const gchar *message, gpointer user_data)
452 /* ignore log message, if log_level isn't interesting based
453 upon the console log preferences.
454 If the preferences haven't been loaded loaded yet, display the
457 The default console_log_level preference value is such that only
458 ERROR, CRITICAL and WARNING level messages are processed;
459 MESSAGE, INFO and DEBUG level messages are ignored.
461 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
462 ERROR and CRITICAL level messages so the current code is a behavioral
463 change. The current behavior is the same as in Wireshark.
465 if ((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
466 prefs.console_log_level != 0) {
470 g_log_default_handler(log_domain, log_level, message, user_data);
475 output_file_description(const char *fname)
477 char *save_file_string;
479 /* Get a string that describes what we're writing to */
480 if (strcmp(fname, "-") == 0) {
481 /* We're writing to the standard output */
482 save_file_string = g_strdup("standard output");
484 /* We're writing to a file with the name in save_file */
485 save_file_string = g_strdup_printf("file \"%s\"", fname);
487 return save_file_string;
491 print_current_user(void) {
492 gchar *cur_user, *cur_group;
494 if (started_with_special_privs()) {
495 cur_user = get_cur_username();
496 cur_group = get_cur_groupname();
497 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
498 cur_user, cur_group);
501 if (running_with_special_privs()) {
502 fprintf(stderr, " This could be dangerous.");
504 fprintf(stderr, "\n");
509 get_tshark_compiled_version_info(GString *str)
511 /* Capture libraries */
512 get_compiled_caplibs_version(str);
516 get_tshark_runtime_version_info(GString *str)
519 /* Capture libraries */
520 g_string_append(str, ", ");
521 get_runtime_caplibs_version(str);
524 /* stuff used by libwireshark */
525 epan_get_runtime_version_info(str);
529 main(int argc, char *argv[])
531 GString *comp_info_str;
532 GString *runtime_info_str;
533 char *init_progfile_dir_error;
535 static const struct option long_options[] = {
536 {"help", no_argument, NULL, 'h'},
537 {"version", no_argument, NULL, 'v'},
538 LONGOPT_CAPTURE_COMMON
541 gboolean arg_error = FALSE;
547 char *gpf_path, *pf_path;
548 char *gdp_path, *dp_path;
550 int gpf_open_errno, gpf_read_errno;
551 int pf_open_errno, pf_read_errno;
552 int gdp_open_errno, gdp_read_errno;
553 int dp_open_errno, dp_read_errno;
556 volatile int exit_status = 0;
558 gboolean list_link_layer_types = FALSE;
559 gboolean start_capture = FALSE;
564 gboolean capture_option_specified = FALSE;
566 gboolean quiet = FALSE;
567 #ifdef PCAP_NG_DEFAULT
568 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
570 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAP;
572 volatile gboolean out_file_name_res = FALSE;
573 volatile int in_file_type = WTAP_TYPE_AUTO;
574 gchar *volatile cf_name = NULL;
575 gchar *rfilter = NULL;
576 gchar *dfilter = NULL;
577 #ifdef HAVE_PCAP_OPEN_DEAD
578 struct bpf_program fcode;
580 dfilter_t *rfcode = NULL;
581 dfilter_t *dfcode = NULL;
586 gchar *output_only = NULL;
587 GSList *disable_protocol_slist = NULL;
588 GSList *enable_heur_slist = NULL;
589 GSList *disable_heur_slist = NULL;
590 gchar *volatile pdu_export_arg = NULL;
591 exp_pdu_t exp_pdu_tap_data;
594 * The leading + ensures that getopt_long() does not permute the argv[]
597 * We have to make sure that the first getopt_long() preserves the content
598 * of argv[] for the subsequent getopt_long() call.
600 * We use getopt_long() in both cases to ensure that we're using a routine
601 * whose permutation behavior we can control in the same fashion on all
602 * platforms, and so that, if we ever need to process a long argument before
603 * doing further initialization, we can do so.
605 * Glibc and Solaris libc document that a leading + disables permutation
606 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
607 * and OS X don't document it, but do so anyway.
609 * We do *not* use a leading - because the behavior of a leading - is
610 * platform-dependent.
612 #define OPTSTRING "+2" OPTSTRING_CAPTURE_COMMON "C:d:e:E:F:gG:hH:j:" "K:lnN:o:O:PqQr:R:S:t:T:u:U:vVw:W:xX:Y:z:"
614 static const char optstring[] = OPTSTRING;
616 tshark_debug("tshark started with %d args", argc);
618 /* Set the C-language locale to the native environment. */
619 setlocale(LC_ALL, "");
621 cmdarg_err_init(failure_message, failure_message_cont);
624 arg_list_utf_16to8(argc, argv);
625 create_app_running_mutex();
626 #if !GLIB_CHECK_VERSION(2,31,0)
632 * Get credential information for later use, and drop privileges
633 * before doing anything else.
634 * Let the user know if anything happened.
636 init_process_policies();
637 relinquish_special_privs_perm();
638 print_current_user();
641 * Attempt to get the pathname of the executable file.
643 init_progfile_dir_error = init_progfile_dir(argv[0], main);
644 if (init_progfile_dir_error != NULL) {
645 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
646 init_progfile_dir_error);
649 initialize_funnel_ops();
652 ws_init_dll_search_path();
653 /* Load wpcap if possible. Do this before collecting the run-time version information */
656 /* Warn the user if npf.sys isn't loaded. */
657 if (!npf_sys_is_running() && get_windows_major_version() >= 6) {
658 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
659 "capturing or\nlisting interfaces.\n");
663 /* Get the compile-time version information string */
664 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
665 epan_get_compiled_version_info);
667 /* Get the run-time version information string */
668 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
670 /* Add it to the information to be reported on a crash. */
671 ws_add_crash_info("TShark (Wireshark) %s\n"
676 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
677 g_string_free(comp_info_str, TRUE);
678 g_string_free(runtime_info_str, TRUE);
680 /* Fail sometimes. Useful for testing fuzz scripts. */
681 /* if (g_random_int_range(0, 100) < 5) abort(); */
684 * In order to have the -X opts assigned before the wslua machine starts
685 * we need to call getopt_long before epan_init() gets called.
687 * In order to handle, for example, -o options, we also need to call it
688 * *after* epan_init() gets called, so that the dissectors have had a
689 * chance to register their preferences.
691 * XXX - can we do this all with one getopt_long() call, saving the
692 * arguments we can't handle until after initializing libwireshark,
693 * and then process them after initializing libwireshark?
697 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
699 case 'C': /* Configuration Profile */
700 if (profile_exists (optarg, FALSE)) {
701 set_profile_name (optarg);
703 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
707 case 'P': /* Print packet summary info even when writing to a file */
708 print_packet_info = TRUE;
709 print_summary = TRUE;
711 case 'O': /* Only output these protocols */
712 output_only = g_strdup(optarg);
714 case 'V': /* Verbose */
715 print_details = TRUE;
716 print_packet_info = TRUE;
718 case 'x': /* Print packet data in hex (and ASCII) */
720 /* The user asked for hex output, so let's ensure they get it,
721 * even if they're writing to a file.
723 print_packet_info = TRUE;
734 * Print packet summary information is the default, unless either -V or -x
735 * were specified and -P was not. Note that this is new behavior, which
736 * allows for the possibility of printing only hex/ascii output without
737 * necessarily requiring that either the summary or details be printed too.
739 if (print_summary == -1)
740 print_summary = (print_details || print_hex) ? FALSE : TRUE;
742 /** Send All g_log messages to our own handler **/
746 G_LOG_LEVEL_CRITICAL|
751 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
753 g_log_set_handler(NULL,
754 (GLogLevelFlags)log_flags,
755 tshark_log_handler, NULL /* user_data */);
756 g_log_set_handler(LOG_DOMAIN_MAIN,
757 (GLogLevelFlags)log_flags,
758 tshark_log_handler, NULL /* user_data */);
761 g_log_set_handler(LOG_DOMAIN_CAPTURE,
762 (GLogLevelFlags)log_flags,
763 tshark_log_handler, NULL /* user_data */);
764 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
765 (GLogLevelFlags)log_flags,
766 tshark_log_handler, NULL /* user_data */);
769 init_report_err(failure_message, open_failure_message, read_failure_message,
770 write_failure_message);
773 capture_opts_init(&global_capture_opts);
774 capture_session_init(&global_capture_session, &cfile);
777 timestamp_set_type(TS_RELATIVE);
778 timestamp_set_precision(TS_PREC_AUTO);
779 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
781 init_open_routines();
784 /* Register all the plugin types we have. */
785 epan_register_plugin_types(); /* Types known to libwireshark */
786 wtap_register_plugin_types(); /* Types known to libwiretap */
788 /* Scan for plugins. This does *not* call their registration routines;
789 that's done later. */
792 /* Register all libwiretap plugin modules. */
793 register_all_wiretap_modules();
796 /* Register all dissectors; we must do this before checking for the
797 "-G" flag, as the "-G" flag dumps information registered by the
798 dissectors, and we must do it before we read the preferences, in
799 case any dissectors register preferences. */
800 if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
804 /* Register all tap listeners; we do this before we parse the arguments,
805 as the "-z" argument can specify a registered tap. */
807 /* we register the plugin taps before the other taps because
808 stats_tree taps plugins will be registered as tap listeners
809 by stats_tree_stat.c and need to registered before that */
811 register_all_plugin_tap_listeners();
813 register_all_tap_listeners();
814 conversation_table_set_gui_info(init_iousers);
815 hostlist_table_set_gui_info(init_hostlists);
816 srt_table_iterate_tables(register_srt_tables, NULL);
817 rtd_table_iterate_tables(register_rtd_tables, NULL);
818 new_stat_tap_iterate_tables(register_simple_stat_tables, NULL);
820 /* If invoked with the "-G" flag, we dump out information based on
821 the argument to the "-G" flag; if no argument is specified,
822 for backwards compatibility we dump out a glossary of display
825 XXX - we do this here, for now, to support "-G" with no arguments.
826 If none of our build or other processes uses "-G" with no arguments,
827 we can just process it with the other arguments. */
828 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
829 proto_initialize_all_prefixes();
832 proto_registrar_dump_fields();
834 if (strcmp(argv[2], "column-formats") == 0)
835 column_dump_column_formats();
836 else if (strcmp(argv[2], "currentprefs") == 0) {
837 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
838 &pf_open_errno, &pf_read_errno, &pf_path);
841 else if (strcmp(argv[2], "decodes") == 0)
842 dissector_dump_decodes();
843 else if (strcmp(argv[2], "defaultprefs") == 0)
845 else if (strcmp(argv[2], "dissector-tables") == 0)
846 dissector_dump_dissector_tables();
847 else if (strcmp(argv[2], "fieldcount") == 0) {
848 /* return value for the test suite */
849 return proto_registrar_dump_fieldcount();
850 } else if (strcmp(argv[2], "fields") == 0)
851 proto_registrar_dump_fields();
852 else if (strcmp(argv[2], "ftypes") == 0)
853 proto_registrar_dump_ftypes();
854 else if (strcmp(argv[2], "heuristic-decodes") == 0)
855 dissector_dump_heur_decodes();
856 else if (strcmp(argv[2], "plugins") == 0) {
861 wslua_plugins_dump_all();
864 else if (strcmp(argv[2], "protocols") == 0)
865 proto_registrar_dump_protocols();
866 else if (strcmp(argv[2], "values") == 0)
867 proto_registrar_dump_values();
868 else if (strcmp(argv[2], "?") == 0)
869 glossary_option_help();
870 else if (strcmp(argv[2], "-?") == 0)
871 glossary_option_help();
873 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
880 /* load the decode as entries of this profile */
881 load_decode_as_entries();
883 tshark_debug("tshark reading preferences");
885 prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
886 &pf_open_errno, &pf_read_errno, &pf_path);
887 if (gpf_path != NULL) {
888 if (gpf_open_errno != 0) {
889 cmdarg_err("Can't open global preferences file \"%s\": %s.",
890 pf_path, g_strerror(gpf_open_errno));
892 if (gpf_read_errno != 0) {
893 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
894 pf_path, g_strerror(gpf_read_errno));
897 if (pf_path != NULL) {
898 if (pf_open_errno != 0) {
899 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
900 g_strerror(pf_open_errno));
902 if (pf_read_errno != 0) {
903 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
904 pf_path, g_strerror(pf_read_errno));
910 read_filter_list(CFILTER_LIST, &cf_path, &cf_open_errno);
911 if (cf_path != NULL) {
912 cmdarg_err("Could not open your capture filter file\n\"%s\": %s.",
913 cf_path, g_strerror(cf_open_errno));
917 /* Read the disabled protocols file. */
918 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
919 &dp_path, &dp_open_errno, &dp_read_errno);
920 read_disabled_heur_dissector_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
921 &dp_path, &dp_open_errno, &dp_read_errno);
922 if (gdp_path != NULL) {
923 if (gdp_open_errno != 0) {
924 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
925 gdp_path, g_strerror(gdp_open_errno));
927 if (gdp_read_errno != 0) {
928 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
929 gdp_path, g_strerror(gdp_read_errno));
933 if (dp_path != NULL) {
934 if (dp_open_errno != 0) {
936 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
937 g_strerror(dp_open_errno));
939 if (dp_read_errno != 0) {
941 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
942 g_strerror(dp_read_errno));
947 cap_file_init(&cfile);
949 /* Print format defaults to this. */
950 print_format = PR_FMT_TEXT;
952 output_fields = output_fields_new();
955 * To reset the options parser, set optreset to 1 on platforms that
956 * have optreset (documented in *BSD and OS X, apparently present but
957 * not documented in Solaris - the Illumos repository seems to
958 * suggest that the first Solaris getopt_long(), at least as of 2004,
959 * was based on the NetBSD one, it had optreset) and set optind to 1,
960 * and set optind to 0 otherwise (documented as working in the GNU
961 * getopt_long(). Setting optind to 0 didn't originally work in the
962 * NetBSD one, but that was added later - we don't want to depend on
963 * it if we have optreset).
965 * Also reset opterr to 1, so that error messages are printed by
976 /* Now get our args */
977 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
979 case '2': /* Perform two pass analysis */
980 perform_two_pass_analysis = TRUE;
982 case 'a': /* autostop criteria */
983 case 'b': /* Ringbuffer option */
984 case 'c': /* Capture x packets */
985 case 'f': /* capture filter */
986 case 'g': /* enable group read access on file(s) */
987 case 'i': /* Use interface x */
988 case 'p': /* Don't capture in promiscuous mode */
989 #ifdef HAVE_PCAP_REMOTE
990 case 'A': /* Authentication */
992 #ifdef HAVE_PCAP_CREATE
993 case 'I': /* Capture in monitor mode, if available */
995 case 's': /* Set the snapshot (capture) length */
996 case 'w': /* Write to capture file x */
997 case 'y': /* Set the pcap data link type */
998 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
999 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1000 case 'B': /* Buffer size */
1003 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1010 * Output file name, if we're reading a file and writing to another
1013 output_file_name = optarg;
1015 capture_option_specified = TRUE;
1021 /* already processed; just ignore it now */
1023 case 'd': /* Decode as rule */
1024 if (!decode_as_command_option(optarg))
1027 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1028 case 'K': /* Kerberos keytab file */
1029 read_keytab_file(optarg);
1032 case 'D': /* Print a list of capture devices and exit */
1034 if_list = capture_interface_list(&err, &err_str,NULL);
1035 if (if_list == NULL) {
1037 cmdarg_err("There are no interfaces on which a capture can be done");
1039 cmdarg_err("%s", err_str);
1044 capture_opts_print_interfaces(if_list);
1045 free_interface_list(if_list);
1048 capture_option_specified = TRUE;
1054 output_fields_add(output_fields, optarg);
1058 if (!output_fields_set_option(output_fields, optarg)) {
1059 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1060 output_fields_list_options(stderr);
1065 out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1066 if (out_file_type < 0) {
1067 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1068 list_capture_types();
1073 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1075 case 'W': /* Select extra information to save in our capture file */
1076 /* This is patterned after the -N flag which may not be the best idea. */
1077 if (strchr(optarg, 'n')) {
1078 out_file_name_res = TRUE;
1080 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1081 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1085 case 'H': /* Read address to name mappings from a hosts file */
1086 if (! add_hosts_file(optarg))
1088 cmdarg_err("Can't read host entries from \"%s\"", optarg);
1091 out_file_name_res = TRUE;
1094 case 'h': /* Print help and exit */
1095 printf("TShark (Wireshark) %s\n"
1096 "Dump and analyze network traffic.\n"
1097 "See https://www.wireshark.org for more information.\n",
1098 get_ws_vcs_version_info());
1099 print_usage(stdout);
1102 case 'l': /* "Line-buffer" standard output */
1103 /* This isn't line-buffering, strictly speaking, it's just
1104 flushing the standard output after the information for
1105 each packet is printed; however, that should be good
1106 enough for all the purposes to which "-l" is put (and
1107 is probably actually better for "-V", as it does fewer
1110 See the comment in "process_packet()" for an explanation of
1111 why we do that, and why we don't just use "setvbuf()" to
1112 make the standard output line-buffered (short version: in
1113 Windows, "line-buffered" is the same as "fully-buffered",
1114 and the output buffer is only flushed when it fills up). */
1115 line_buffered = TRUE;
1117 case 'L': /* Print list of link-layer types and exit */
1119 list_link_layer_types = TRUE;
1121 capture_option_specified = TRUE;
1125 case 'n': /* No name resolution */
1126 disable_name_resolution();
1128 case 'N': /* Select what types of addresses/port #s to resolve */
1129 badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1130 if (badopt != '\0') {
1131 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are:",
1133 cmdarg_err_cont("\t'd' to enable address resolution from captured DNS packets\n"
1134 "\t'm' to enable MAC address resolution\n"
1135 "\t'n' to enable network address resolution\n"
1136 "\t'N' to enable using external resolvers (e.g., DNS)\n"
1137 "\t for network address resolution\n"
1138 "\t't' to enable transport-layer port number resolution");
1142 case 'o': /* Override preference from command line */
1143 switch (prefs_set_pref(optarg)) {
1148 case PREFS_SET_SYNTAX_ERR:
1149 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1153 case PREFS_SET_NO_SUCH_PREF:
1154 case PREFS_SET_OBSOLETE:
1155 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1160 case 'q': /* Quiet */
1163 case 'Q': /* Really quiet */
1165 really_quiet = TRUE;
1167 case 'r': /* Read capture file x */
1168 cf_name = g_strdup(optarg);
1170 case 'R': /* Read file filter */
1174 /* already processed; just ignore it now */
1176 case 'S': /* Set the line Separator to be printed between packets */
1179 case 't': /* Time stamp type */
1180 if (strcmp(optarg, "r") == 0)
1181 timestamp_set_type(TS_RELATIVE);
1182 else if (strcmp(optarg, "a") == 0)
1183 timestamp_set_type(TS_ABSOLUTE);
1184 else if (strcmp(optarg, "ad") == 0)
1185 timestamp_set_type(TS_ABSOLUTE_WITH_YMD);
1186 else if (strcmp(optarg, "adoy") == 0)
1187 timestamp_set_type(TS_ABSOLUTE_WITH_YDOY);
1188 else if (strcmp(optarg, "d") == 0)
1189 timestamp_set_type(TS_DELTA);
1190 else if (strcmp(optarg, "dd") == 0)
1191 timestamp_set_type(TS_DELTA_DIS);
1192 else if (strcmp(optarg, "e") == 0)
1193 timestamp_set_type(TS_EPOCH);
1194 else if (strcmp(optarg, "u") == 0)
1195 timestamp_set_type(TS_UTC);
1196 else if (strcmp(optarg, "ud") == 0)
1197 timestamp_set_type(TS_UTC_WITH_YMD);
1198 else if (strcmp(optarg, "udoy") == 0)
1199 timestamp_set_type(TS_UTC_WITH_YDOY);
1201 cmdarg_err("Invalid time stamp type \"%s\"; it must be one of:", optarg);
1202 cmdarg_err_cont("\t\"a\" for absolute\n"
1203 "\t\"ad\" for absolute with YYYY-MM-DD date\n"
1204 "\t\"adoy\" for absolute with YYYY/DOY date\n"
1205 "\t\"d\" for delta\n"
1206 "\t\"dd\" for delta displayed\n"
1207 "\t\"e\" for epoch\n"
1208 "\t\"r\" for relative\n"
1209 "\t\"u\" for absolute UTC\n"
1210 "\t\"ud\" for absolute UTC with YYYY-MM-DD date\n"
1211 "\t\"udoy\" for absolute UTC with YYYY/DOY date");
1215 case 'T': /* printing Type */
1216 print_packet_info = TRUE;
1217 if (strcmp(optarg, "text") == 0) {
1218 output_action = WRITE_TEXT;
1219 print_format = PR_FMT_TEXT;
1220 } else if (strcmp(optarg, "ps") == 0) {
1221 output_action = WRITE_TEXT;
1222 print_format = PR_FMT_PS;
1223 } else if (strcmp(optarg, "pdml") == 0) {
1224 output_action = WRITE_XML;
1225 print_details = TRUE; /* Need details */
1226 print_summary = FALSE; /* Don't allow summary */
1227 } else if (strcmp(optarg, "psml") == 0) {
1228 output_action = WRITE_XML;
1229 print_details = FALSE; /* Don't allow details */
1230 print_summary = TRUE; /* Need summary */
1231 } else if (strcmp(optarg, "fields") == 0) {
1232 output_action = WRITE_FIELDS;
1233 print_details = TRUE; /* Need full tree info */
1234 print_summary = FALSE; /* Don't allow summary */
1235 } else if (strcmp(optarg, "json") == 0) {
1236 output_action = WRITE_JSON;
1237 print_details = TRUE; /* Need details */
1238 print_summary = FALSE; /* Don't allow summary */
1239 } else if (strcmp(optarg, "ek") == 0) {
1240 output_action = WRITE_EK;
1241 print_details = TRUE; /* Need details */
1242 print_summary = FALSE; /* Don't allow summary */
1245 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg); /* x */
1246 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1247 "\t specified by the -E option.\n"
1248 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1249 "\t details of a decoded packet. This information is equivalent to\n"
1250 "\t the packet details printed with the -V flag.\n"
1251 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1252 "\t the packets, or a multi-line view of the details of each of\n"
1253 "\t the packets, depending on whether the -V flag was specified.\n"
1254 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1255 "\t summary information of a decoded packet. This information is\n"
1256 "\t equivalent to the information shown in the one-line summary\n"
1257 "\t printed by default.\n"
1258 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1259 "\t summary information of a decoded packet. This information is \n"
1260 "\t equivalent to the packet details printed with the -V flag.\n"
1261 "\t\"ek\" Packet Summary, an EK JSON-based format for the bulk insert \n"
1262 "\t into elastic search cluster. This information is \n"
1263 "\t equivalent to the packet details printed with the -V flag.\n"
1264 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1265 "\t packets, or a multi-line view of the details of each of the\n"
1266 "\t packets, depending on whether the -V flag was specified.\n"
1267 "\t This is the default.");
1271 case 'u': /* Seconds type */
1272 if (strcmp(optarg, "s") == 0)
1273 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1274 else if (strcmp(optarg, "hms") == 0)
1275 timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1277 cmdarg_err("Invalid seconds type \"%s\"; it must be one of:", optarg);
1278 cmdarg_err_cont("\t\"s\" for seconds\n"
1279 "\t\"hms\" for hours, minutes and seconds");
1283 case 'U': /* Export PDUs to file */
1285 GSList *export_pdu_tap_name_list = NULL;
1288 cmdarg_err("Tap name is required! Valid names are:");
1289 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)) {
1290 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1294 pdu_export_arg = g_strdup(optarg);
1297 case 'v': /* Show version and exit */
1298 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
1299 epan_get_compiled_version_info);
1300 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
1301 show_version("TShark (Wireshark)", comp_info_str, runtime_info_str);
1302 g_string_free(comp_info_str, TRUE);
1303 g_string_free(runtime_info_str, TRUE);
1304 /* We don't really have to cleanup here, but it's a convenient way to test
1305 * start-up and shut-down of the epan library without any UI-specific
1306 * cruft getting in the way. Makes the results of running
1307 * $ ./tools/valgrind-wireshark -n
1308 * much more useful. */
1311 case 'O': /* Only output these protocols */
1312 /* already processed; just ignore it now */
1314 case 'V': /* Verbose */
1315 /* already processed; just ignore it now */
1317 case 'x': /* Print packet data in hex (and ASCII) */
1318 /* already processed; just ignore it now */
1321 /* already processed; just ignore it now */
1327 /* We won't call the init function for the stat this soon
1328 as it would disallow MATE's fields (which are registered
1329 by the preferences set callback) from being used as
1330 part of a tap filter. Instead, we just add the argument
1331 to a list of stat arguments. */
1332 if (strcmp("help", optarg) == 0) {
1333 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1334 list_stat_cmd_args();
1337 if (!process_stat_cmd_arg(optarg)) {
1338 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1339 list_stat_cmd_args();
1343 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1344 disable_protocol_slist = g_slist_append(disable_protocol_slist, optarg);
1346 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1347 enable_heur_slist = g_slist_append(enable_heur_slist, optarg);
1349 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1350 disable_heur_slist = g_slist_append(disable_heur_slist, optarg);
1354 case '?': /* Bad flag - print usage message */
1357 list_capture_types();
1360 print_usage(stderr);
1367 /* If we specified output fields, but not the output field type... */
1368 if (WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1369 cmdarg_err("Output fields were specified with \"-e\", "
1370 "but \"-Tfields\" was not specified.");
1372 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1373 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1374 "specified with \"-e\".");
1379 /* If no capture filter or display filter has been specified, and there are
1380 still command-line arguments, treat them as the tokens of a capture
1381 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1382 flag was specified. */
1383 if (optind < argc) {
1384 if (cf_name != NULL) {
1385 if (dfilter != NULL) {
1386 cmdarg_err("Display filters were specified both with \"-d\" "
1387 "and with additional command-line arguments.");
1390 dfilter = get_args_as_string(argc, argv, optind);
1395 if (global_capture_opts.default_options.cfilter) {
1396 cmdarg_err("A default capture filter was specified both with \"-f\""
1397 " and with additional command-line arguments.");
1400 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1401 interface_options interface_opts;
1402 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1403 if (interface_opts.cfilter == NULL) {
1404 interface_opts.cfilter = get_args_as_string(argc, argv, optind);
1405 global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
1406 g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
1408 cmdarg_err("A capture filter was specified both with \"-f\""
1409 " and with additional command-line arguments.");
1413 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1415 capture_option_specified = TRUE;
1421 if (!global_capture_opts.saving_to_file) {
1422 /* We're not saving the capture to a file; if "-q" wasn't specified,
1423 we should print packet information */
1425 print_packet_info = TRUE;
1427 /* We're saving to a file; if we're writing to the standard output.
1428 and we'll also be writing dissected packets to the standard
1429 output, reject the request. At best, we could redirect that
1430 to the standard error; we *can't* write both to the standard
1431 output and have either of them be useful. */
1432 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1433 cmdarg_err("You can't write both raw packet data and dissected packets"
1434 " to the standard output.");
1439 /* We're not saving the capture to a file; if "-q" wasn't specified,
1440 we should print packet information */
1442 print_packet_info = TRUE;
1445 #ifndef HAVE_LIBPCAP
1446 if (capture_option_specified)
1447 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1450 print_usage(stderr);
1455 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_EK) {
1456 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON or EK JSON");
1461 if (output_only != NULL) {
1464 if (!print_details) {
1465 cmdarg_err("-O requires -V");
1469 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1470 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1471 g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1475 if (rfilter != NULL && !perform_two_pass_analysis) {
1476 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1481 if (list_link_layer_types) {
1482 /* We're supposed to list the link-layer types for an interface;
1483 did the user also specify a capture file to be read? */
1485 /* Yes - that's bogus. */
1486 cmdarg_err("You can't specify -L and a capture file to be read.");
1489 /* No - did they specify a ring buffer option? */
1490 if (global_capture_opts.multi_files_on) {
1491 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1497 * "-r" was specified, so we're reading a capture file.
1498 * Capture options don't apply here.
1501 /* We don't support capture filters when reading from a capture file
1502 (the BPF compiler doesn't support all link-layer types that we
1503 support in capture files we read). */
1504 if (global_capture_opts.default_options.cfilter) {
1505 cmdarg_err("Only read filters, not capture filters, "
1506 "can be specified when reading a capture file.");
1509 if (global_capture_opts.multi_files_on) {
1510 cmdarg_err("Multiple capture files requested, but "
1511 "a capture isn't being done.");
1514 if (global_capture_opts.has_file_duration) {
1515 cmdarg_err("Switching capture files after a time interval was specified, but "
1516 "a capture isn't being done.");
1519 if (global_capture_opts.has_ring_num_files) {
1520 cmdarg_err("A ring buffer of capture files was specified, but "
1521 "a capture isn't being done.");
1524 if (global_capture_opts.has_autostop_files) {
1525 cmdarg_err("A maximum number of capture files was specified, but "
1526 "a capture isn't being done.");
1529 if (global_capture_opts.capture_comment) {
1530 cmdarg_err("A capture comment was specified, but "
1531 "a capture isn't being done.\nThere's no support for adding "
1532 "a capture comment to an existing capture file.");
1536 /* Note: TShark now allows the restriction of a _read_ file by packet count
1537 * and byte count as well as a write file. Other autostop options remain valid
1538 * only for a write file.
1540 if (global_capture_opts.has_autostop_duration) {
1541 cmdarg_err("A maximum capture time was specified, but "
1542 "a capture isn't being done.");
1547 * "-r" wasn't specified, so we're doing a live capture.
1549 if (perform_two_pass_analysis) {
1550 /* Two-pass analysis doesn't work with live capture since it requires us
1551 * to buffer packets until we've read all of them, but a live capture
1552 * has no useful/meaningful definition of "all" */
1553 cmdarg_err("Live captures do not support two-pass analysis.");
1557 if (global_capture_opts.saving_to_file) {
1558 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1560 /* When capturing, we only support writing pcap or pcap-ng format. */
1561 if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1562 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1563 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1566 if (global_capture_opts.capture_comment &&
1567 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1568 cmdarg_err("A capture comment can only be written to a pcapng file.");
1571 if (global_capture_opts.multi_files_on) {
1572 /* Multiple-file mode doesn't work under certain conditions:
1573 a) it doesn't work if you're writing to the standard output;
1574 b) it doesn't work if you're writing to a pipe;
1576 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1577 cmdarg_err("Multiple capture files requested, but "
1578 "the capture is being written to the standard output.");
1581 if (global_capture_opts.output_to_pipe) {
1582 cmdarg_err("Multiple capture files requested, but "
1583 "the capture file is a pipe.");
1586 if (!global_capture_opts.has_autostop_filesize &&
1587 !global_capture_opts.has_file_duration) {
1588 cmdarg_err("Multiple capture files requested, but "
1589 "no maximum capture file size or duration was specified.");
1593 /* Currently, we don't support read or display filters when capturing
1594 and saving the packets. */
1595 if (rfilter != NULL) {
1596 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1599 if (dfilter != NULL) {
1600 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1603 global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1605 /* They didn't specify a "-w" flag, so we won't be saving to a
1606 capture file. Check for options that only make sense if
1607 we're saving to a file. */
1608 if (global_capture_opts.has_autostop_filesize) {
1609 cmdarg_err("Maximum capture file size specified, but "
1610 "capture isn't being saved to a file.");
1613 if (global_capture_opts.multi_files_on) {
1614 cmdarg_err("Multiple capture files requested, but "
1615 "the capture isn't being saved to a file.");
1618 if (global_capture_opts.capture_comment) {
1619 cmdarg_err("A capture comment was specified, but "
1620 "the capture isn't being saved to a file.");
1629 /* Start windows sockets */
1630 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1633 /* Notify all registered modules that have had any of their preferences
1634 changed either from one of the preferences file or from the command
1635 line that their preferences have changed. */
1638 /* At this point MATE will have registered its field array so we can
1639 have a tap filter with one of MATE's late-registered fields as part
1640 of the filter. We can now process all the "-z" arguments. */
1641 start_requested_stats();
1643 /* At this point MATE will have registered its field array so we can
1644 check if the fields specified by the user are all good.
1648 GSList *invalid_fields = output_fields_valid(output_fields);
1649 if (invalid_fields != NULL) {
1651 cmdarg_err("Some fields aren't valid:");
1652 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1653 cmdarg_err_cont("\t%s", (gchar *)it->data);
1655 g_slist_free(invalid_fields);
1660 /* We currently don't support taps, or printing dissected packets,
1661 if we're writing to a pipe. */
1662 if (global_capture_opts.saving_to_file &&
1663 global_capture_opts.output_to_pipe) {
1664 if (tap_listeners_require_dissection()) {
1665 cmdarg_err("Taps aren't supported when saving to a pipe.");
1668 if (print_packet_info) {
1669 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1675 if (ex_opt_count("read_format") > 0) {
1676 const gchar* name = ex_opt_get_next("read_format");
1677 in_file_type = open_info_name_to_type(name);
1678 if (in_file_type == WTAP_TYPE_AUTO) {
1679 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1680 list_read_capture_types();
1685 /* disabled protocols as per configuration file */
1686 if (gdp_path == NULL && dp_path == NULL) {
1687 set_disabled_protos_list();
1688 set_disabled_heur_dissector_list();
1691 if(disable_protocol_slist) {
1692 GSList *proto_disable;
1693 for (proto_disable = disable_protocol_slist; proto_disable != NULL; proto_disable = g_slist_next(proto_disable))
1695 proto_disable_proto_by_name((char*)proto_disable->data);
1699 if(enable_heur_slist) {
1700 GSList *heur_enable;
1701 for (heur_enable = enable_heur_slist; heur_enable != NULL; heur_enable = g_slist_next(heur_enable))
1703 proto_enable_heuristic_by_name((char*)heur_enable->data, TRUE);
1707 if(disable_heur_slist) {
1708 GSList *heur_disable;
1709 for (heur_disable = disable_heur_slist; heur_disable != NULL; heur_disable = g_slist_next(heur_disable))
1711 proto_enable_heuristic_by_name((char*)heur_disable->data, FALSE);
1715 /* Build the column format array */
1716 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1719 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1720 capture_opts_trim_ring_num_files(&global_capture_opts);
1723 if (rfilter != NULL) {
1724 tshark_debug("Compiling read filter: '%s'", rfilter);
1725 if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1726 cmdarg_err("%s", err_msg);
1729 #ifdef HAVE_PCAP_OPEN_DEAD
1733 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1735 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1737 " Note: That read filter code looks like a valid capture filter;\n"
1738 " maybe you mixed them up?");
1747 cfile.rfcode = rfcode;
1749 if (dfilter != NULL) {
1750 tshark_debug("Compiling display filter: '%s'", dfilter);
1751 if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1752 cmdarg_err("%s", err_msg);
1755 #ifdef HAVE_PCAP_OPEN_DEAD
1759 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1761 if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1763 " Note: That display filter code looks like a valid capture filter;\n"
1764 " maybe you mixed them up?");
1773 cfile.dfcode = dfcode;
1775 if (print_packet_info) {
1776 /* If we're printing as text or PostScript, we have
1777 to create a print stream. */
1778 if (output_action == WRITE_TEXT) {
1779 switch (print_format) {
1782 print_stream = print_stream_text_stdio_new(stdout);
1786 print_stream = print_stream_ps_stdio_new(stdout);
1790 g_assert_not_reached();
1795 /* PDU export requested. Take the ownership of the '-w' file, apply tap
1796 * filters and start tapping. */
1797 if (pdu_export_arg) {
1798 const char *exp_pdu_filename;
1799 const char *exp_pdu_tap_name = pdu_export_arg;
1800 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1801 char *exp_pdu_error;
1805 cmdarg_err("PDUs export requires a capture file (specify with -r).");
1808 /* Take ownership of the '-w' output file. */
1810 exp_pdu_filename = global_capture_opts.save_file;
1811 global_capture_opts.save_file = NULL;
1813 exp_pdu_filename = output_file_name;
1814 output_file_name = NULL;
1816 if (exp_pdu_filename == NULL) {
1817 cmdarg_err("PDUs export requires an output file (-w).");
1821 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1823 if (exp_pdu_error) {
1824 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1825 g_free(exp_pdu_error);
1829 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1831 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
1835 /* Activate the export PDU tap */
1836 err = exp_pdu_open(&exp_pdu_tap_data, exp_fd,
1837 g_strdup_printf("Dump of PDUs from %s", cf_name));
1839 cmdarg_err("Failed to start the PDU export: %s", g_strerror(err));
1844 /* We have to dissect each packet if:
1846 we're printing information about each packet;
1848 we're using a read filter on the packets;
1850 we're using a display filter on the packets;
1852 we're exporting PDUs;
1854 we're using any taps that need dissection. */
1855 do_dissection = print_packet_info || rfcode || dfcode || pdu_export_arg ||
1856 tap_listeners_require_dissection();
1857 tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
1860 tshark_debug("tshark: Opening capture file: %s", cf_name);
1862 * We're reading a capture file.
1864 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
1869 /* Process the packets in the file */
1870 tshark_debug("tshark: invoking load_cap_file() to process the packets");
1873 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
1874 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1875 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1877 err = load_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, 0, 0);
1880 CATCH(OutOfMemoryError) {
1884 "Sorry, but TShark has to terminate now.\n"
1886 "More information and workarounds can be found at\n"
1887 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
1892 /* We still dump out the results of taps, etc., as we might have
1893 read some packets; however, we exit with an error status. */
1897 if (pdu_export_arg) {
1898 err = exp_pdu_close(&exp_pdu_tap_data);
1900 cmdarg_err("%s", wtap_strerror(err));
1903 g_free(pdu_export_arg);
1906 tshark_debug("tshark: no capture file specified");
1907 /* No capture file specified, so we're supposed to do a live capture
1908 or get a list of link-layer types for a live capture device;
1909 do we have support for live captures? */
1911 /* if no interface was specified, pick a default */
1912 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
1913 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
1914 if (exit_status != 0)
1917 /* if requested, list the link layer types and exit */
1918 if (list_link_layer_types) {
1921 /* Get the list of link-layer types for the capture devices. */
1922 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1923 interface_options interface_opts;
1924 if_capabilities_t *caps;
1925 char *auth_str = NULL;
1927 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1928 #ifdef HAVE_PCAP_REMOTE
1929 if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
1930 auth_str = g_strdup_printf("%s:%s", interface_opts.auth_username, interface_opts.auth_password);
1933 caps = capture_get_if_capabilities(interface_opts.name, interface_opts.monitor_mode, auth_str, &err_str, NULL);
1936 cmdarg_err("%s", err_str);
1940 if (caps->data_link_types == NULL) {
1941 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
1944 capture_opts_print_if_capabilities(caps, interface_opts.name, interface_opts.monitor_mode);
1945 free_if_capabilities(caps);
1951 * If the standard error isn't a terminal, don't print packet counts,
1952 * as they won't show up on the user's terminal and they'll get in
1953 * the way of error messages in the file (to which we assume the
1954 * standard error was redirected; if it's redirected to the null
1955 * device, there's no point in printing packet counts anyway).
1957 * Otherwise, if we're printing packet information and the standard
1958 * output is a terminal (which we assume means the standard output and
1959 * error are going to the same terminal), don't print packet counts,
1960 * as they'll get in the way of the packet information.
1962 * Otherwise, if the user specified -q, don't print packet counts.
1964 * Otherwise, print packet counts.
1966 * XXX - what if the user wants to do a live capture, doesn't want
1967 * to save it to a file, doesn't want information printed for each
1968 * packet, does want some "-z" statistic, and wants packet counts
1969 * so they know whether they're seeing any packets? -q will
1970 * suppress the information printed for each packet, but it'll
1971 * also suppress the packet counts.
1973 if (!ws_isatty(ws_fileno(stderr)))
1974 print_packet_counts = FALSE;
1975 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
1976 print_packet_counts = FALSE;
1978 print_packet_counts = FALSE;
1980 print_packet_counts = TRUE;
1982 if (print_packet_info) {
1983 if (!write_preamble(&cfile)) {
1984 show_print_file_io_error(errno);
1989 tshark_debug("tshark: performing live capture");
1991 * XXX - this returns FALSE if an error occurred, but it also
1992 * returns FALSE if the capture stops because a time limit
1993 * was reached (and possibly other limits), so we can't assume
1994 * it means an error.
1996 * The capture code is a bit twisty, so it doesn't appear to
1997 * be an easy fix. We just ignore the return value for now.
1998 * Instead, pass on the exit status from the capture child.
2001 exit_status = global_capture_session.fork_child_status;
2003 if (print_packet_info) {
2004 if (!write_finale()) {
2006 show_print_file_io_error(err);
2010 /* No - complain. */
2011 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2018 if (cfile.frames != NULL) {
2019 free_frame_data_sequence(cfile.frames);
2020 cfile.frames = NULL;
2023 draw_tap_listeners(TRUE);
2024 funnel_dump_all_text_windows();
2025 epan_free(cfile.epan);
2028 output_fields_free(output_fields);
2029 output_fields = NULL;
2034 /*#define USE_BROKEN_G_MAIN_LOOP*/
2036 #ifdef USE_BROKEN_G_MAIN_LOOP
2039 gboolean loop_running = FALSE;
2041 guint32 packet_count = 0;
2044 typedef struct pipe_input_tag {
2047 ws_process_id *child_process;
2048 pipe_input_cb_t input_cb;
2049 guint pipe_input_id;
2051 GMutex *callback_running;
2055 static pipe_input_t pipe_input;
2058 /* The timer has expired, see if there's stuff to read from the pipe,
2059 if so, do the callback */
2061 pipe_timer_cb(gpointer data)
2067 pipe_input_t *pipe_input_p = data;
2068 gint iterations = 0;
2070 g_mutex_lock (pipe_input_p->callback_running);
2072 /* try to read data from the pipe only 5 times, to avoid blocking */
2073 while(iterations < 5) {
2074 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2076 /* Oddly enough although Named pipes don't work on win9x,
2077 PeekNamedPipe does !!! */
2078 handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2079 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2081 /* Get the child process exit status */
2082 GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2085 /* If the Peek returned an error, or there are bytes to be read
2086 or the childwatcher thread has terminated then call the normal
2088 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2090 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2092 /* And call the real handler */
2093 if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2094 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2095 /* pipe closed, return false so that the timer is stopped */
2096 g_mutex_unlock (pipe_input_p->callback_running);
2101 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2102 /* No data, stop now */
2109 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2111 g_mutex_unlock (pipe_input_p->callback_running);
2113 /* we didn't stopped the timer, so let it run */
2120 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2123 pipe_input.source = source;
2124 pipe_input.child_process = child_process;
2125 pipe_input.user_data = user_data;
2126 pipe_input.input_cb = input_cb;
2129 #if GLIB_CHECK_VERSION(2,31,0)
2130 pipe_input.callback_running = g_malloc(sizeof(GMutex));
2131 g_mutex_init(pipe_input.callback_running);
2133 pipe_input.callback_running = g_mutex_new();
2135 /* Tricky to use pipes in win9x, as no concept of wait. NT can
2136 do this but that doesn't cover all win32 platforms. GTK can do
2137 this but doesn't seem to work over processes. Attempt to do
2138 something similar here, start a timer and check for data on every
2140 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2141 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2145 static const nstime_t *
2146 tshark_get_frame_ts(void *data, guint32 frame_num)
2148 capture_file *cf = (capture_file *) data;
2150 if (ref && ref->num == frame_num)
2151 return &ref->abs_ts;
2153 if (prev_dis && prev_dis->num == frame_num)
2154 return &prev_dis->abs_ts;
2156 if (prev_cap && prev_cap->num == frame_num)
2157 return &prev_cap->abs_ts;
2160 frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);
2162 return (fd) ? &fd->abs_ts : NULL;
2169 tshark_epan_new(capture_file *cf)
2171 epan_t *epan = epan_new();
2174 epan->get_frame_ts = tshark_get_frame_ts;
2175 epan->get_interface_name = cap_file_get_interface_name;
2176 epan->get_user_comment = NULL;
2188 #ifdef USE_TSHARK_SELECT
2192 struct sigaction action, oldaction;
2195 /* Create new dissection section. */
2196 epan_free(cfile.epan);
2197 cfile.epan = tshark_epan_new(&cfile);
2200 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2201 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2203 /* Catch SIGINT and SIGTERM and, if we get either of them,
2204 clean up and exit. If SIGHUP isn't being ignored, catch
2205 it too and, if we get it, clean up and exit.
2207 We restart any read that was in progress, so that it doesn't
2208 disrupt reading from the sync pipe. The signal handler tells
2209 the capture child to finish; it will report that it finished,
2210 or will exit abnormally, so we'll stop reading from the sync
2211 pipe, pick up the exit status, and quit. */
2212 memset(&action, 0, sizeof(action));
2213 action.sa_handler = capture_cleanup;
2214 action.sa_flags = SA_RESTART;
2215 sigemptyset(&action.sa_mask);
2216 sigaction(SIGTERM, &action, NULL);
2217 sigaction(SIGINT, &action, NULL);
2218 sigaction(SIGHUP, NULL, &oldaction);
2219 if (oldaction.sa_handler == SIG_DFL)
2220 sigaction(SIGHUP, &action, NULL);
2223 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2224 quiet mode, report the number of packets we've captured.
2226 Again, restart any read that was in progress, so that it doesn't
2227 disrupt reading from the sync pipe. */
2228 action.sa_handler = report_counts_siginfo;
2229 action.sa_flags = SA_RESTART;
2230 sigemptyset(&action.sa_mask);
2231 sigaction(SIGINFO, &action, NULL);
2232 #endif /* SIGINFO */
2235 global_capture_session.state = CAPTURE_PREPARING;
2237 /* Let the user know which interfaces were chosen. */
2238 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2239 interface_options interface_opts;
2241 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
2242 interface_opts.descr = get_interface_descriptive_name(interface_opts.name);
2243 global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
2244 g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
2246 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2247 if (really_quiet == FALSE)
2248 fprintf(stderr, "Capturing on %s\n", str->str);
2250 g_string_free(str, TRUE);
2252 ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2257 /* the actual capture loop
2259 * XXX - glib doesn't seem to provide any event based loop handling.
2261 * XXX - for whatever reason,
2262 * calling g_main_loop_new() ends up in 100% cpu load.
2264 * But that doesn't matter: in UNIX we can use select() to find an input
2265 * source with something to do.
2267 * But that doesn't matter because we're in a CLI (that doesn't need to
2268 * update a GUI or something at the same time) so it's OK if we block
2269 * trying to read from the pipe.
2271 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2272 * wrong (but I leave it there in case I am...).
2275 #ifdef USE_TSHARK_SELECT
2277 FD_SET(pipe_input.source, &readfds);
2280 loop_running = TRUE;
2284 while (loop_running)
2286 #ifdef USE_TSHARK_SELECT
2287 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2291 fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2293 } else if (ret == 1) {
2295 /* Call the real handler */
2296 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2297 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2300 #ifdef USE_TSHARK_SELECT
2305 CATCH(OutOfMemoryError) {
2309 "Sorry, but TShark has to terminate now.\n"
2311 "More information and workarounds can be found at\n"
2312 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2319 /* capture child detected an error */
2321 capture_input_error_message(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2323 cmdarg_err("%s", error_msg);
2324 cmdarg_err_cont("%s", secondary_error_msg);
2328 /* capture child detected an capture filter related error */
2330 capture_input_cfilter_error_message(capture_session *cap_session, guint i, char *error_message)
2332 capture_options *capture_opts = cap_session->capture_opts;
2333 dfilter_t *rfcode = NULL;
2334 interface_options interface_opts;
2336 g_assert(i < capture_opts->ifaces->len);
2337 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2339 if (dfilter_compile(interface_opts.cfilter, &rfcode, NULL) && rfcode != NULL) {
2341 "Invalid capture filter \"%s\" for interface '%s'.\n"
2343 "That string looks like a valid display filter; however, it isn't a valid\n"
2344 "capture filter (%s).\n"
2346 "Note that display filters and capture filters don't have the same syntax,\n"
2347 "so you can't use most display filter expressions as capture filters.\n"
2349 "See the User's Guide for a description of the capture filter syntax.",
2350 interface_opts.cfilter, interface_opts.descr, error_message);
2351 dfilter_free(rfcode);
2354 "Invalid capture filter \"%s\" for interface '%s'.\n"
2356 "That string isn't a valid capture filter (%s).\n"
2357 "See the User's Guide for a description of the capture filter syntax.",
2358 interface_opts.cfilter, interface_opts.descr, error_message);
2363 /* capture child tells us we have a new (or the first) capture file */
2365 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2367 capture_options *capture_opts = cap_session->capture_opts;
2368 capture_file *cf = (capture_file *) cap_session->cf;
2369 gboolean is_tempfile;
2372 if (cap_session->state == CAPTURE_PREPARING) {
2373 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2375 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2377 g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2379 /* free the old filename */
2380 if (capture_opts->save_file != NULL) {
2382 /* we start a new capture file, close the old one (if we had one before) */
2383 if (cf->state != FILE_CLOSED) {
2384 if (cf->wth != NULL) {
2385 wtap_close(cf->wth);
2388 cf->state = FILE_CLOSED;
2391 g_free(capture_opts->save_file);
2392 is_tempfile = FALSE;
2394 epan_free(cf->epan);
2395 cf->epan = tshark_epan_new(cf);
2397 /* we didn't had a save_file before, must be a tempfile */
2401 /* save the new filename */
2402 capture_opts->save_file = g_strdup(new_file);
2404 /* if we are in real-time mode, open the new file now */
2405 if (do_dissection) {
2406 /* this is probably unecessary, but better safe than sorry */
2407 ((capture_file *)cap_session->cf)->open_type = WTAP_TYPE_AUTO;
2408 /* Attempt to open the capture file and set up to read from it. */
2409 switch(cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2413 /* Don't unlink (delete) the save file - leave it around,
2414 for debugging purposes. */
2415 g_free(capture_opts->save_file);
2416 capture_opts->save_file = NULL;
2421 cap_session->state = CAPTURE_RUNNING;
2427 /* capture child tells us we have new packets to read */
2429 capture_input_new_packets(capture_session *cap_session, int to_read)
2435 capture_file *cf = (capture_file *)cap_session->cf;
2436 gboolean filtering_tap_listeners;
2441 * Prevent a SIGINFO handler from writing to the standard error while
2442 * we're doing so or writing to the standard output; instead, have it
2443 * just set a flag telling us to print that information when we're done.
2446 #endif /* SIGINFO */
2448 /* Do we have any tap listeners with filters? */
2449 filtering_tap_listeners = have_filtering_tap_listeners();
2451 /* Get the union of the flags for all tap listeners. */
2452 tap_flags = union_of_tap_listener_flags();
2454 if (do_dissection) {
2455 gboolean create_proto_tree;
2456 epan_dissect_t *edt;
2458 if (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2459 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2460 create_proto_tree = TRUE;
2462 create_proto_tree = FALSE;
2464 /* The protocol tree will be "visible", i.e., printed, only if we're
2465 printing packet details, which is true if we're printing stuff
2466 ("print_packet_info" is true) and we're in verbose mode
2467 ("packet_details" is true). */
2468 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2470 while (to_read-- && cf->wth) {
2471 wtap_cleareof(cf->wth);
2472 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2474 /* read from file failed, tell the capture child to stop */
2475 sync_pipe_stop(cap_session);
2476 wtap_close(cf->wth);
2479 ret = process_packet(cf, edt, data_offset, wtap_phdr(cf->wth),
2480 wtap_buf_ptr(cf->wth),
2484 /* packet successfully read and gone through the "Read Filter" */
2489 epan_dissect_free(edt);
2493 * Dumpcap's doing all the work; we're not doing any dissection.
2494 * Count all the packets it wrote.
2496 packet_count += to_read;
2499 if (print_packet_counts) {
2500 /* We're printing packet counts. */
2501 if (packet_count != 0) {
2502 fprintf(stderr, "\r%u ", packet_count);
2503 /* stderr could be line buffered */
2510 * Allow SIGINFO handlers to write.
2515 * If a SIGINFO handler asked us to write out capture counts, do so.
2519 #endif /* SIGINFO */
2525 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2526 /* Report the count only if we aren't printing a packet count
2527 as packets arrive. */
2528 fprintf(stderr, "%u packet%s captured\n", packet_count,
2529 plurality(packet_count, "", "s"));
2532 infoprint = FALSE; /* we just reported it */
2533 #endif /* SIGINFO */
2538 report_counts_siginfo(int signum _U_)
2540 int sav_errno = errno;
2541 /* If we've been told to delay printing, just set a flag asking
2542 that we print counts (if we're supposed to), otherwise print
2543 the count of packets captured (if we're supposed to). */
2550 #endif /* SIGINFO */
2553 /* capture child detected any packet drops? */
2555 capture_input_drops(capture_session *cap_session _U_, guint32 dropped)
2557 if (print_packet_counts) {
2558 /* We're printing packet counts to stderr.
2559 Send a newline so that we move to the line after the packet count. */
2560 fprintf(stderr, "\n");
2564 /* We're printing packet counts to stderr.
2565 Send a newline so that we move to the line after the packet count. */
2566 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2572 * Capture child closed its side of the pipe, report any error and
2573 * do the required cleanup.
2576 capture_input_closed(capture_session *cap_session, gchar *msg)
2578 capture_file *cf = (capture_file *) cap_session->cf;
2581 fprintf(stderr, "tshark: %s\n", msg);
2585 if (cf != NULL && cf->wth != NULL) {
2586 wtap_close(cf->wth);
2587 if (cf->is_tempfile) {
2588 ws_unlink(cf->filename);
2591 #ifdef USE_BROKEN_G_MAIN_LOOP
2592 /*g_main_loop_quit(loop);*/
2593 g_main_loop_quit(loop);
2595 loop_running = FALSE;
2604 capture_cleanup(DWORD ctrltype _U_)
2606 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2607 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2608 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2609 like SIGTERM at least when the machine's shutting down.
2611 For now, we handle them all as indications that we should clean up
2612 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2615 We must return TRUE so that no other handler - such as one that would
2616 terminate the process - gets called.
2618 XXX - for some reason, typing ^C to TShark, if you run this in
2619 a Cygwin console window in at least some versions of Cygwin,
2620 causes TShark to terminate immediately; this routine gets
2621 called, but the main loop doesn't get a chance to run and
2622 exit cleanly, at least if this is compiled with Microsoft Visual
2623 C++ (i.e., it's a property of the Cygwin console window or Bash;
2624 it happens if TShark is not built with Cygwin - for all I know,
2625 building it with Cygwin may make the problem go away). */
2627 /* tell the capture child to stop */
2628 sync_pipe_stop(&global_capture_session);
2630 /* don't stop our own loop already here, otherwise status messages and
2631 * cleanup wouldn't be done properly. The child will indicate the stop of
2632 * everything by calling capture_input_closed() later */
2638 capture_cleanup(int signum _U_)
2640 /* tell the capture child to stop */
2641 sync_pipe_stop(&global_capture_session);
2643 /* don't stop our own loop already here, otherwise status messages and
2644 * cleanup wouldn't be done properly. The child will indicate the stop of
2645 * everything by calling capture_input_closed() later */
2648 #endif /* HAVE_LIBPCAP */
2651 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2652 gint64 offset, struct wtap_pkthdr *whdr,
2659 /* The frame number of this packet is one more than the count of
2660 frames in this packet. */
2661 framenum = cf->count + 1;
2663 /* If we're not running a display filter and we're not printing any
2664 packet information, we don't need to do a dissection. This means
2665 that all packets can be marked as 'passed'. */
2668 frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
2670 /* If we're going to print packet information, or we're going to
2671 run a read filter, or display filter, or we're going to process taps, set up to
2672 do a dissection and do so. */
2674 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2675 gbl_resolv_flags.transport_name)
2676 /* Grab any resolved addresses */
2677 host_name_lookup_process();
2679 /* If we're running a read filter, prime the epan_dissect_t with that
2682 epan_dissect_prime_dfilter(edt, cf->rfcode);
2685 epan_dissect_prime_dfilter(edt, cf->dfcode);
2687 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2689 if (ref == &fdlocal) {
2690 ref_frame = fdlocal;
2694 epan_dissect_run(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdlocal, pd), &fdlocal, NULL);
2696 /* Run the read filter if we have one. */
2698 passed = dfilter_apply_edt(cf->rfcode, edt);
2702 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2703 prev_cap = prev_dis = frame_data_sequence_add(cf->frames, &fdlocal);
2705 /* If we're not doing dissection then there won't be any dependent frames.
2706 * More importantly, edt.pi.dependent_frames won't be initialized because
2707 * epan hasn't been initialized.
2708 * if we *are* doing dissection, then mark the dependent frames, but only
2709 * if a display filter was given and it matches this packet.
2711 if (edt && cf->dfcode) {
2712 if (dfilter_apply_edt(cf->dfcode, edt)) {
2713 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
2719 /* if we don't add it to the frame_data_sequence, clean it up right now
2721 frame_data_destroy(&fdlocal);
2725 epan_dissect_reset(edt);
2731 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt, frame_data *fdata,
2732 struct wtap_pkthdr *phdr, Buffer *buf,
2738 /* If we're not running a display filter and we're not printing any
2739 packet information, we don't need to do a dissection. This means
2740 that all packets can be marked as 'passed'. */
2743 /* If we're going to print packet information, or we're going to
2744 run a read filter, or we're going to process taps, set up to
2745 do a dissection and do so. */
2747 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2748 gbl_resolv_flags.transport_name)
2749 /* Grab any resolved addresses */
2750 host_name_lookup_process();
2752 /* If we're running a display filter, prime the epan_dissect_t with that
2755 epan_dissect_prime_dfilter(edt, cf->dfcode);
2757 col_custom_prime_edt(edt, &cf->cinfo);
2759 /* We only need the columns if either
2760 1) some tap needs the columns
2762 2) we're printing packet info but we're *not* verbose; in verbose
2763 mode, we print the protocol tree, not the protocol summary.
2765 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
2770 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2777 epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new_buffer(fdata, buf), fdata, cinfo);
2779 /* Run the read/display filter if we have one. */
2781 passed = dfilter_apply_edt(cf->dfcode, edt);
2785 frame_data_set_after_dissect(fdata, &cum_bytes);
2786 /* Process this packet. */
2787 if (print_packet_info) {
2788 /* We're printing packet information; print the information for
2790 print_packet(cf, edt);
2792 /* The ANSI C standard does not appear to *require* that a line-buffered
2793 stream be flushed to the host environment whenever a newline is
2794 written, it just says that, on such a stream, characters "are
2795 intended to be transmitted to or from the host environment as a
2796 block when a new-line character is encountered".
2798 The Visual C++ 6.0 C implementation doesn't do what is intended;
2799 even if you set a stream to be line-buffered, it still doesn't
2800 flush the buffer at the end of every line.
2802 So, if the "-l" flag was specified, we flush the standard output
2803 at the end of a packet. This will do the right thing if we're
2804 printing packet summary lines, and, as we print the entire protocol
2805 tree for a single packet without waiting for anything to happen,
2806 it should be as good as line-buffered mode if we're printing
2807 protocol trees. (The whole reason for the "-l" flag in either
2808 tcpdump or TShark is to allow the output of a live capture to
2809 be piped to a program or script and to have that script see the
2810 information for the packet as soon as it's printed, rather than
2811 having to wait until a standard I/O buffer fills up. */
2815 if (ferror(stdout)) {
2816 show_print_file_io_error(errno);
2825 epan_dissect_reset(edt);
2827 return passed || fdata->flags.dependent_of_displayed;
2831 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2832 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
2835 int snapshot_length;
2839 gchar *err_info = NULL;
2841 char *save_file_string = NULL;
2842 gboolean filtering_tap_listeners;
2844 GArray *shb_hdrs = NULL;
2845 wtapng_iface_descriptions_t *idb_inf = NULL;
2846 GArray *nrb_hdrs = NULL;
2847 struct wtap_pkthdr phdr;
2849 epan_dissect_t *edt = NULL;
2850 char *shb_user_appl;
2852 wtap_phdr_init(&phdr);
2854 idb_inf = wtap_file_get_idb_info(cf->wth);
2855 #ifdef PCAP_NG_DEFAULT
2856 if (idb_inf->interface_data->len > 1) {
2857 linktype = WTAP_ENCAP_PER_PACKET;
2859 linktype = wtap_file_encap(cf->wth);
2862 linktype = wtap_file_encap(cf->wth);
2864 if (save_file != NULL) {
2865 /* Get a string that describes what we're writing to */
2866 save_file_string = output_file_description(save_file);
2868 /* Set up to write to the capture file. */
2869 snapshot_length = wtap_snapshot_length(cf->wth);
2870 if (snapshot_length == 0) {
2871 /* Snapshot length of input file not known. */
2872 snapshot_length = WTAP_MAX_PACKET_SIZE;
2874 tshark_debug("tshark: snapshot_length = %d", snapshot_length);
2876 shb_hdrs = wtap_file_get_shb_for_new_file(cf->wth);
2877 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->wth);
2879 /* If we don't have an application name add Tshark */
2880 wtap_optionblock_get_option_string(g_array_index(shb_hdrs, wtap_optionblock_t, 0), OPT_SHB_USERAPPL, &shb_user_appl);
2881 if (shb_user_appl == NULL) {
2882 /* this is free'd by wtap_optionblock_free() later */
2883 wtap_optionblock_set_option_string_format(g_array_index(shb_hdrs, wtap_optionblock_t, 0), OPT_SHB_USERAPPL, "TShark (Wireshark) %s", get_ws_vcs_version_info());
2886 if (linktype != WTAP_ENCAP_PER_PACKET &&
2887 out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAP) {
2888 tshark_debug("tshark: writing PCAP format to %s", save_file);
2889 if (strcmp(save_file, "-") == 0) {
2890 /* Write to the standard output. */
2891 pdh = wtap_dump_open_stdout(out_file_type, linktype,
2892 snapshot_length, FALSE /* compressed */, &err);
2894 pdh = wtap_dump_open(save_file, out_file_type, linktype,
2895 snapshot_length, FALSE /* compressed */, &err);
2899 tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
2900 if (strcmp(save_file, "-") == 0) {
2901 /* Write to the standard output. */
2902 pdh = wtap_dump_open_stdout_ng(out_file_type, linktype,
2903 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
2905 pdh = wtap_dump_open_ng(save_file, out_file_type, linktype,
2906 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
2914 /* We couldn't set up to write to the capture file. */
2917 case WTAP_ERR_UNWRITABLE_FILE_TYPE:
2918 cmdarg_err("Capture files can't be written in that format.");
2921 case WTAP_ERR_UNWRITABLE_ENCAP:
2922 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2923 cmdarg_err("The capture file being read can't be written as a "
2924 "\"%s\" file.", wtap_file_type_subtype_short_string(out_file_type));
2927 case WTAP_ERR_CANT_OPEN:
2928 cmdarg_err("The %s couldn't be created for some "
2929 "unknown reason.", save_file_string);
2932 case WTAP_ERR_SHORT_WRITE:
2933 cmdarg_err("A full header couldn't be written to the %s.",
2938 cmdarg_err("The %s could not be created: %s.", save_file_string,
2939 wtap_strerror(err));
2945 if (print_packet_info) {
2946 if (!write_preamble(cf)) {
2948 show_print_file_io_error(err);
2957 /* Do we have any tap listeners with filters? */
2958 filtering_tap_listeners = have_filtering_tap_listeners();
2960 /* Get the union of the flags for all tap listeners. */
2961 tap_flags = union_of_tap_listener_flags();
2963 if (perform_two_pass_analysis) {
2966 tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
2968 /* Allocate a frame_data_sequence for all the frames. */
2969 cf->frames = new_frame_data_sequence();
2971 if (do_dissection) {
2972 gboolean create_proto_tree = FALSE;
2974 /* If we're going to be applying a filter, we'll need to
2975 create a protocol tree against which to apply the filter. */
2976 if (cf->rfcode || cf->dfcode)
2977 create_proto_tree = TRUE;
2979 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
2981 /* We're not going to display the protocol tree on this pass,
2982 so it's not going to be "visible". */
2983 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
2986 tshark_debug("tshark: reading records for first pass");
2987 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2988 if (process_packet_first_pass(cf, edt, data_offset, wtap_phdr(cf->wth),
2989 wtap_buf_ptr(cf->wth))) {
2990 /* Stop reading if we have the maximum number of packets;
2991 * When the -c option has not been used, max_packet_count
2992 * starts at 0, which practically means, never stop reading.
2993 * (unless we roll over max_packet_count ?)
2995 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2996 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
2997 max_packet_count, data_offset, max_byte_count);
2998 err = 0; /* This is not an error */
3005 epan_dissect_free(edt);
3009 /* Close the sequential I/O side, to free up memory it requires. */
3010 wtap_sequential_close(cf->wth);
3012 /* Allow the protocol dissectors to free up memory that they
3013 * don't need after the sequential run-through of the packets. */
3014 postseq_cleanup_all_protocols();
3018 ws_buffer_init(&buf, 1500);
3020 tshark_debug("tshark: done with first pass");
3022 if (do_dissection) {
3023 gboolean create_proto_tree;
3025 if (cf->dfcode || print_details || filtering_tap_listeners ||
3026 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3027 create_proto_tree = TRUE;
3029 create_proto_tree = FALSE;
3031 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3033 /* The protocol tree will be "visible", i.e., printed, only if we're
3034 printing packet details, which is true if we're printing stuff
3035 ("print_packet_info" is true) and we're in verbose mode
3036 ("packet_details" is true). */
3037 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3040 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
3041 fdata = frame_data_sequence_find(cf->frames, framenum);
3042 if (wtap_seek_read(cf->wth, fdata->file_off, &phdr, &buf, &err,
3044 tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3045 if (process_packet_second_pass(cf, edt, fdata, &phdr, &buf,
3047 /* Either there's no read filtering or this packet passed the
3048 filter, so, if we're writing to a capture file, write
3051 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3052 if (!wtap_dump(pdh, &phdr, ws_buffer_start_ptr(&buf), &err, &err_info)) {
3053 /* Error writing to a capture file */
3054 tshark_debug("tshark: error writing to a capture file (%d)", err);
3057 case WTAP_ERR_UNWRITABLE_ENCAP:
3059 * This is a problem with the particular frame we're writing
3060 * and the file type and subtype we're writing; note that,
3061 * and report the frame number and file type/subtype.
3063 * XXX - framenum is not necessarily the frame number in
3064 * the input file if there was a read filter.
3067 "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
3068 framenum, cf->filename,
3069 wtap_file_type_subtype_short_string(out_file_type));
3072 case WTAP_ERR_PACKET_TOO_LARGE:
3074 * This is a problem with the particular frame we're writing
3075 * and the file type and subtype we're writing; note that,
3076 * and report the frame number and file type/subtype.
3078 * XXX - framenum is not necessarily the frame number in
3079 * the input file if there was a read filter.
3082 "Frame %u of \"%s\" is too large for a \"%s\" file.\n",
3083 framenum, cf->filename,
3084 wtap_file_type_subtype_short_string(out_file_type));
3087 case WTAP_ERR_UNWRITABLE_REC_TYPE:
3089 * This is a problem with the particular record we're writing
3090 * and the file type and subtype we're writing; note that,
3091 * and report the record number and file type/subtype.
3093 * XXX - framenum is not necessarily the record number in
3094 * the input file if there was a read filter.
3097 "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
3098 framenum, cf->filename,
3099 wtap_file_type_subtype_short_string(out_file_type));
3102 case WTAP_ERR_UNWRITABLE_REC_DATA:
3104 * This is a problem with the particular record we're writing
3105 * and the file type and subtype we're writing; note that,
3106 * and report the record number and file type/subtype.
3108 * XXX - framenum is not necessarily the record number in
3109 * the input file if there was a read filter.
3112 "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
3113 framenum, cf->filename,
3114 wtap_file_type_subtype_short_string(out_file_type),
3115 err_info != NULL ? err_info : "no information supplied");
3120 show_capture_file_io_error(save_file, err, FALSE);
3123 wtap_dump_close(pdh, &err);
3124 wtap_optionblock_array_free(shb_hdrs);
3125 wtap_optionblock_array_free(nrb_hdrs);
3134 epan_dissect_free(edt);
3138 ws_buffer_free(&buf);
3140 tshark_debug("tshark: done with second pass");
3143 /* !perform_two_pass_analysis */
3146 tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3148 if (do_dissection) {
3149 gboolean create_proto_tree;
3151 if (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3152 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3153 create_proto_tree = TRUE;
3155 create_proto_tree = FALSE;
3157 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3159 /* The protocol tree will be "visible", i.e., printed, only if we're
3160 printing packet details, which is true if we're printing stuff
3161 ("print_packet_info" is true) and we're in verbose mode
3162 ("packet_details" is true). */
3163 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3166 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
3169 tshark_debug("tshark: processing packet #%d", framenum);
3171 if (process_packet(cf, edt, data_offset, wtap_phdr(cf->wth),
3172 wtap_buf_ptr(cf->wth),
3174 /* Either there's no read filtering or this packet passed the
3175 filter, so, if we're writing to a capture file, write
3178 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3179 if (!wtap_dump(pdh, wtap_phdr(cf->wth), wtap_buf_ptr(cf->wth), &err, &err_info)) {
3180 /* Error writing to a capture file */
3181 tshark_debug("tshark: error writing to a capture file (%d)", err);
3184 case WTAP_ERR_UNWRITABLE_ENCAP:
3186 * This is a problem with the particular frame we're writing
3187 * and the file type and subtype we're writing; note that,
3188 * and report the frame number and file type/subtype.
3191 "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
3192 framenum, cf->filename,
3193 wtap_file_type_subtype_short_string(out_file_type));
3196 case WTAP_ERR_PACKET_TOO_LARGE:
3198 * This is a problem with the particular frame we're writing
3199 * and the file type and subtype we're writing; note that,
3200 * and report the frame number and file type/subtype.
3203 "Frame %u of \"%s\" is too large for a \"%s\" file.\n",
3204 framenum, cf->filename,
3205 wtap_file_type_subtype_short_string(out_file_type));
3208 case WTAP_ERR_UNWRITABLE_REC_TYPE:
3210 * This is a problem with the particular record we're writing
3211 * and the file type and subtype we're writing; note that,
3212 * and report the record number and file type/subtype.
3215 "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
3216 framenum, cf->filename,
3217 wtap_file_type_subtype_short_string(out_file_type));
3220 case WTAP_ERR_UNWRITABLE_REC_DATA:
3222 * This is a problem with the particular record we're writing
3223 * and the file type and subtype we're writing; note that,
3224 * and report the record number and file type/subtype.
3227 "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
3228 framenum, cf->filename,
3229 wtap_file_type_subtype_short_string(out_file_type),
3230 err_info != NULL ? err_info : "no information supplied");
3235 show_capture_file_io_error(save_file, err, FALSE);
3238 wtap_dump_close(pdh, &err);
3239 wtap_optionblock_array_free(shb_hdrs);
3240 wtap_optionblock_array_free(nrb_hdrs);
3245 /* Stop reading if we have the maximum number of packets;
3246 * When the -c option has not been used, max_packet_count
3247 * starts at 0, which practically means, never stop reading.
3248 * (unless we roll over max_packet_count ?)
3250 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3251 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3252 max_packet_count, data_offset, max_byte_count);
3253 err = 0; /* This is not an error */
3259 epan_dissect_free(edt);
3264 wtap_phdr_cleanup(&phdr);
3267 tshark_debug("tshark: something failed along the line (%d)", err);
3269 * Print a message noting that the read failed somewhere along the line.
3271 * If we're printing packet data, and the standard output and error are
3272 * going to the same place, flush the standard output, so everything
3273 * buffered up is written, and then print a newline to the standard error
3274 * before printing the error message, to separate it from the packet
3275 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
3276 * the _fstat() documentation at Microsoft doesn't indicate whether
3277 * st_ino is even supported.)
3280 if (print_packet_info) {
3281 ws_statb64 stat_stdout, stat_stderr;
3283 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3284 if (stat_stdout.st_dev == stat_stderr.st_dev &&
3285 stat_stdout.st_ino == stat_stderr.st_ino) {
3287 fprintf(stderr, "\n");
3294 case WTAP_ERR_UNSUPPORTED:
3295 cmdarg_err("The file \"%s\" contains record data that TShark doesn't support.\n(%s)",
3297 err_info != NULL ? err_info : "no information supplied");
3301 case WTAP_ERR_SHORT_READ:
3302 cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
3306 case WTAP_ERR_BAD_FILE:
3307 cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
3309 err_info != NULL ? err_info : "no information supplied");
3313 case WTAP_ERR_DECOMPRESS:
3314 cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
3315 "(%s)", cf->filename,
3316 err_info != NULL ? err_info : "no information supplied");
3321 cmdarg_err("An error occurred while reading the file \"%s\": %s.",
3322 cf->filename, wtap_strerror(err));
3325 if (save_file != NULL) {
3326 /* Now close the capture file. */
3327 if (!wtap_dump_close(pdh, &err))
3328 show_capture_file_io_error(save_file, err, TRUE);
3331 if (save_file != NULL) {
3332 if (pdh && out_file_name_res) {
3333 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3334 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3335 wtap_file_type_subtype_short_string(out_file_type));
3338 /* Now close the capture file. */
3339 if (!wtap_dump_close(pdh, &err))
3340 show_capture_file_io_error(save_file, err, TRUE);
3342 if (print_packet_info) {
3343 if (!write_finale()) {
3345 show_print_file_io_error(err);
3352 wtap_close(cf->wth);
3355 g_free(save_file_string);
3356 wtap_optionblock_array_free(shb_hdrs);
3357 wtap_optionblock_array_free(nrb_hdrs);
3363 process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset, struct wtap_pkthdr *whdr,
3364 const guchar *pd, guint tap_flags)
3370 /* Count this packet. */
3373 /* If we're not running a display filter and we're not printing any
3374 packet information, we don't need to do a dissection. This means
3375 that all packets can be marked as 'passed'. */
3378 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
3380 /* If we're going to print packet information, or we're going to
3381 run a read filter, or we're going to process taps, set up to
3382 do a dissection and do so. */
3384 if (print_packet_info && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
3385 gbl_resolv_flags.transport_name))
3386 /* Grab any resolved addresses */
3387 host_name_lookup_process();
3389 /* If we're running a filter, prime the epan_dissect_t with that
3392 epan_dissect_prime_dfilter(edt, cf->dfcode);
3394 col_custom_prime_edt(edt, &cf->cinfo);
3396 /* We only need the columns if either
3397 1) some tap needs the columns
3399 2) we're printing packet info but we're *not* verbose; in verbose
3400 mode, we print the protocol tree, not the protocol summary.
3402 3) there is a column mapped as an individual field */
3403 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3408 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3410 if (ref == &fdata) {
3415 epan_dissect_run_with_taps(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdata, pd), &fdata, cinfo);
3417 /* Run the filter if we have it. */
3419 passed = dfilter_apply_edt(cf->dfcode, edt);
3423 frame_data_set_after_dissect(&fdata, &cum_bytes);
3425 /* Process this packet. */
3426 if (print_packet_info) {
3427 /* We're printing packet information; print the information for
3429 print_packet(cf, edt);
3431 /* The ANSI C standard does not appear to *require* that a line-buffered
3432 stream be flushed to the host environment whenever a newline is
3433 written, it just says that, on such a stream, characters "are
3434 intended to be transmitted to or from the host environment as a
3435 block when a new-line character is encountered".
3437 The Visual C++ 6.0 C implementation doesn't do what is intended;
3438 even if you set a stream to be line-buffered, it still doesn't
3439 flush the buffer at the end of every line.
3441 So, if the "-l" flag was specified, we flush the standard output
3442 at the end of a packet. This will do the right thing if we're
3443 printing packet summary lines, and, as we print the entire protocol
3444 tree for a single packet without waiting for anything to happen,
3445 it should be as good as line-buffered mode if we're printing
3446 protocol trees. (The whole reason for the "-l" flag in either
3447 tcpdump or TShark is to allow the output of a live capture to
3448 be piped to a program or script and to have that script see the
3449 information for the packet as soon as it's printed, rather than
3450 having to wait until a standard I/O buffer fills up. */
3454 if (ferror(stdout)) {
3455 show_print_file_io_error(errno);
3460 /* this must be set after print_packet() [bug #8160] */
3461 prev_dis_frame = fdata;
3462 prev_dis = &prev_dis_frame;
3465 prev_cap_frame = fdata;
3466 prev_cap = &prev_cap_frame;
3469 epan_dissect_reset(edt);
3470 frame_data_destroy(&fdata);
3476 write_preamble(capture_file *cf)
3478 switch (output_action) {
3481 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3485 write_pdml_preamble(stdout, cf->filename);
3487 write_psml_preamble(&cf->cinfo, stdout);
3488 return !ferror(stdout);
3491 write_fields_preamble(output_fields, stdout);
3492 return !ferror(stdout);
3495 write_json_preamble(stdout);
3496 return !ferror(stdout);
3499 return !ferror(stdout);
3502 g_assert_not_reached();
3508 get_line_buf(size_t len)
3510 static char *line_bufp = NULL;
3511 static size_t line_buf_len = 256;
3512 size_t new_line_buf_len;
3514 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3515 new_line_buf_len *= 2)
3517 if (line_bufp == NULL) {
3518 line_buf_len = new_line_buf_len;
3519 line_bufp = (char *)g_malloc(line_buf_len + 1);
3521 if (new_line_buf_len > line_buf_len) {
3522 line_buf_len = new_line_buf_len;
3523 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3530 put_string(char *dest, const char *str, size_t str_len)
3532 memcpy(dest, str, str_len);
3533 dest[str_len] = '\0';
3537 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3541 for (i = str_len; i < str_with_spaces; i++)
3544 put_string(dest, str, str_len);
3548 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3552 memcpy(dest, str, str_len);
3553 for (i = str_len; i < str_with_spaces; i++)
3556 dest[str_with_spaces] = '\0';
3560 print_columns(capture_file *cf)
3567 col_item_t* col_item;
3569 line_bufp = get_line_buf(256);
3572 for (i = 0; i < cf->cinfo.num_cols; i++) {
3573 col_item = &cf->cinfo.columns[i];
3574 /* Skip columns not marked as visible. */
3575 if (!get_column_visible(i))
3577 switch (col_item->col_fmt) {
3579 column_len = col_len = strlen(col_item->col_data);
3582 line_bufp = get_line_buf(buf_offset + column_len);
3583 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3589 case COL_ABS_YMD_TIME: /* XXX - wider */
3590 case COL_ABS_YDOY_TIME: /* XXX - wider */
3592 case COL_UTC_YMD_TIME: /* XXX - wider */
3593 case COL_UTC_YDOY_TIME: /* XXX - wider */
3594 column_len = col_len = strlen(col_item->col_data);
3595 if (column_len < 10)
3597 line_bufp = get_line_buf(buf_offset + column_len);
3598 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3604 case COL_DEF_DL_SRC:
3605 case COL_RES_DL_SRC:
3606 case COL_UNRES_DL_SRC:
3607 case COL_DEF_NET_SRC:
3608 case COL_RES_NET_SRC:
3609 case COL_UNRES_NET_SRC:
3610 column_len = col_len = strlen(col_item->col_data);
3611 if (column_len < 12)
3613 line_bufp = get_line_buf(buf_offset + column_len);
3614 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3620 case COL_DEF_DL_DST:
3621 case COL_RES_DL_DST:
3622 case COL_UNRES_DL_DST:
3623 case COL_DEF_NET_DST:
3624 case COL_RES_NET_DST:
3625 case COL_UNRES_NET_DST:
3626 column_len = col_len = strlen(col_item->col_data);
3627 if (column_len < 12)
3629 line_bufp = get_line_buf(buf_offset + column_len);
3630 put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3634 column_len = strlen(col_item->col_data);
3635 line_bufp = get_line_buf(buf_offset + column_len);
3636 put_string(line_bufp + buf_offset, col_item->col_data, column_len);
3639 buf_offset += column_len;
3640 if (i != cf->cinfo.num_cols - 1) {
3642 * This isn't the last column, so we need to print a
3643 * separator between this column and the next.
3645 * If we printed a network source and are printing a
3646 * network destination of the same type next, separate
3647 * them with a UTF-8 right arrow; if we printed a network
3648 * destination and are printing a network source of the same
3649 * type next, separate them with a UTF-8 left arrow;
3650 * otherwise separate them with a space.
3652 * We add enough space to the buffer for " \xe2\x86\x90 "
3653 * or " \xe2\x86\x92 ", even if we're only adding " ".
3655 line_bufp = get_line_buf(buf_offset + 5);
3656 switch (col_item->col_fmt) {
3661 switch (cf->cinfo.columns[i+1].col_fmt) {
3666 put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3671 put_string(line_bufp + buf_offset, " ", 1);
3677 case COL_DEF_DL_SRC:
3678 case COL_RES_DL_SRC:
3679 case COL_UNRES_DL_SRC:
3680 switch (cf->cinfo.columns[i+1].col_fmt) {
3682 case COL_DEF_DL_DST:
3683 case COL_RES_DL_DST:
3684 case COL_UNRES_DL_DST:
3685 put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3690 put_string(line_bufp + buf_offset, " ", 1);
3696 case COL_DEF_NET_SRC:
3697 case COL_RES_NET_SRC:
3698 case COL_UNRES_NET_SRC:
3699 switch (cf->cinfo.columns[i+1].col_fmt) {
3701 case COL_DEF_NET_DST:
3702 case COL_RES_NET_DST:
3703 case COL_UNRES_NET_DST:
3704 put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3709 put_string(line_bufp + buf_offset, " ", 1);
3718 switch (cf->cinfo.columns[i+1].col_fmt) {
3723 put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3728 put_string(line_bufp + buf_offset, " ", 1);
3734 case COL_DEF_DL_DST:
3735 case COL_RES_DL_DST:
3736 case COL_UNRES_DL_DST:
3737 switch (cf->cinfo.columns[i+1].col_fmt) {
3739 case COL_DEF_DL_SRC:
3740 case COL_RES_DL_SRC:
3741 case COL_UNRES_DL_SRC:
3742 put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3747 put_string(line_bufp + buf_offset, " ", 1);
3753 case COL_DEF_NET_DST:
3754 case COL_RES_NET_DST:
3755 case COL_UNRES_NET_DST:
3756 switch (cf->cinfo.columns[i+1].col_fmt) {
3758 case COL_DEF_NET_SRC:
3759 case COL_RES_NET_SRC:
3760 case COL_UNRES_NET_SRC:
3761 put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3766 put_string(line_bufp + buf_offset, " ", 1);
3773 put_string(line_bufp + buf_offset, " ", 1);
3779 return print_line(print_stream, 0, line_bufp);
3783 print_packet(capture_file *cf, epan_dissect_t *edt)
3785 print_args_t print_args;
3787 if (print_summary || output_fields_has_cols(output_fields)) {
3788 /* Just fill in the columns. */
3789 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3791 if (print_summary) {
3792 /* Now print them. */
3793 switch (output_action) {
3796 if (!print_columns(cf))
3801 write_psml_columns(edt, stdout);
3802 return !ferror(stdout);
3803 case WRITE_FIELDS: /*No non-verbose "fields" format */
3806 g_assert_not_reached();
3811 if (print_details) {
3812 /* Print the information in the protocol tree. */
3813 switch (output_action) {
3816 /* Only initialize the fields that are actually used in proto_tree_print.
3817 * This is particularly important for .range, as that's heap memory which
3818 * we would otherwise have to g_free().
3819 print_args.to_file = TRUE;
3820 print_args.format = print_format;
3821 print_args.print_summary = print_summary;
3822 print_args.print_formfeed = FALSE;
3823 packet_range_init(&print_args.range, &cfile);
3825 print_args.print_hex = print_hex;
3826 print_args.print_dissections = print_details ? print_dissections_expanded : print_dissections_none;
3828 if (!proto_tree_print(&print_args, edt, output_only_tables, print_stream))
3831 if (!print_line(print_stream, 0, separator))
3837 write_pdml_proto_tree(protocolfilter, edt, stdout);
3839 return !ferror(stdout);
3841 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
3843 return !ferror(stdout);
3845 print_args.print_hex = print_hex;
3846 write_json_proto_tree(&print_args, protocolfilter, edt, stdout);
3848 return !ferror(stdout);
3850 print_args.print_hex = print_hex;
3851 write_ek_proto_tree(&print_args, protocolfilter, edt, stdout);
3853 return !ferror(stdout);
3857 if (print_summary || print_details) {
3858 if (!print_line(print_stream, 0, ""))
3861 if (!print_hex_data(print_stream, edt))
3863 if (!print_line(print_stream, 0, separator))
3872 switch (output_action) {
3875 return print_finale(print_stream);
3879 write_pdml_finale(stdout);
3881 write_psml_finale(stdout);
3882 return !ferror(stdout);
3885 write_fields_finale(output_fields, stdout);
3886 return !ferror(stdout);
3889 write_json_finale(stdout);
3890 return !ferror(stdout);
3893 return !ferror(stdout);
3896 g_assert_not_reached();
3902 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
3906 char err_msg[2048+1];
3908 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
3912 /* The open succeeded. Fill in the information for this file. */
3914 /* Create new epan session for dissection. */
3915 epan_free(cf->epan);
3916 cf->epan = tshark_epan_new(cf);
3919 cf->f_datalen = 0; /* not used, but set it anyway */
3921 /* Set the file name because we need it to set the follow stream filter.
3922 XXX - is that still true? We need it for other reasons, though,
3924 cf->filename = g_strdup(fname);
3926 /* Indicate whether it's a permanent or temporary file. */
3927 cf->is_tempfile = is_tempfile;
3929 /* No user changes yet. */
3930 cf->unsaved_changes = FALSE;
3932 cf->cd_t = wtap_file_type_subtype(cf->wth);
3933 cf->open_type = type;
3935 cf->drops_known = FALSE;
3937 cf->snap = wtap_snapshot_length(cf->wth);
3938 if (cf->snap == 0) {
3939 /* Snapshot length not known. */
3940 cf->has_snap = FALSE;
3941 cf->snap = WTAP_MAX_PACKET_SIZE;
3943 cf->has_snap = TRUE;
3944 nstime_set_zero(&cf->elapsed_time);
3949 cf->state = FILE_READ_IN_PROGRESS;
3951 wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
3952 wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
3957 g_snprintf(err_msg, sizeof err_msg,
3958 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3959 cmdarg_err("%s", err_msg);
3964 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3966 char *save_file_string;
3968 save_file_string = output_file_description(fname);
3973 cmdarg_err("Not all the packets could be written to the %s because there is "
3974 "no space left on the file system.",
3980 cmdarg_err("Not all the packets could be written to the %s because you are "
3981 "too close to, or over your disk quota.",
3986 case WTAP_ERR_CANT_CLOSE:
3987 cmdarg_err("The %s couldn't be closed for some unknown reason.",
3991 case WTAP_ERR_SHORT_WRITE:
3992 cmdarg_err("Not all the packets could be written to the %s.",
3998 cmdarg_err("The %s could not be closed: %s.", save_file_string,
3999 wtap_strerror(err));
4001 cmdarg_err("An error occurred while writing to the %s: %s.",
4002 save_file_string, wtap_strerror(err));
4006 g_free(save_file_string);
4010 show_print_file_io_error(int err)
4015 cmdarg_err("Not all the packets could be printed because there is "
4016 "no space left on the file system.");
4021 cmdarg_err("Not all the packets could be printed because you are "
4022 "too close to, or over your disk quota.");
4027 cmdarg_err("An error occurred while printing packets: %s.",
4034 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
4038 static char errmsg_errno[1024+1];
4041 /* Wiretap error. */
4044 case WTAP_ERR_NOT_REGULAR_FILE:
4045 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
4048 case WTAP_ERR_RANDOM_OPEN_PIPE:
4049 /* Seen only when opening a capture file for reading. */
4050 errmsg = "The file \"%s\" is a pipe or FIFO; TShark can't read pipe or FIFO files in two-pass mode.";
4053 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4054 /* Seen only when opening a capture file for reading. */
4055 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
4058 case WTAP_ERR_UNSUPPORTED:
4059 /* Seen only when opening a capture file for reading. */
4060 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4061 "The file \"%%s\" contains record data that TShark doesn't support.\n"
4063 err_info != NULL ? err_info : "no information supplied");
4065 errmsg = errmsg_errno;
4068 case WTAP_ERR_CANT_WRITE_TO_PIPE:
4069 /* Seen only when opening a capture file for writing. */
4070 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4071 "The file \"%%s\" is a pipe, and \"%s\" capture files can't be "
4072 "written to a pipe.", wtap_file_type_subtype_short_string(file_type));
4073 errmsg = errmsg_errno;
4076 case WTAP_ERR_UNWRITABLE_FILE_TYPE:
4077 /* Seen only when opening a capture file for writing. */
4078 errmsg = "TShark doesn't support writing capture files in that format.";
4081 case WTAP_ERR_UNWRITABLE_ENCAP:
4082 /* Seen only when opening a capture file for writing. */
4083 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4084 "TShark can't save this capture as a \"%s\" file.",
4085 wtap_file_type_subtype_short_string(file_type));
4086 errmsg = errmsg_errno;
4089 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4091 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4092 "TShark can't save this capture as a \"%s\" file.",
4093 wtap_file_type_subtype_short_string(file_type));
4094 errmsg = errmsg_errno;
4096 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
4099 case WTAP_ERR_BAD_FILE:
4100 /* Seen only when opening a capture file for reading. */
4101 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4102 "The file \"%%s\" appears to be damaged or corrupt.\n"
4104 err_info != NULL ? err_info : "no information supplied");
4106 errmsg = errmsg_errno;
4109 case WTAP_ERR_CANT_OPEN:
4111 errmsg = "The file \"%s\" could not be created for some unknown reason.";
4113 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
4116 case WTAP_ERR_SHORT_READ:
4117 errmsg = "The file \"%s\" appears to have been cut short"
4118 " in the middle of a packet or other data.";
4121 case WTAP_ERR_SHORT_WRITE:
4122 errmsg = "A full header couldn't be written to the file \"%s\".";
4125 case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4126 errmsg = "This file type cannot be written as a compressed file.";
4129 case WTAP_ERR_DECOMPRESS:
4130 /* Seen only when opening a capture file for reading. */
4131 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4132 "The compressed file \"%%s\" appears to be damaged or corrupt.\n"
4134 err_info != NULL ? err_info : "no information supplied");
4136 errmsg = errmsg_errno;
4140 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4141 "The file \"%%s\" could not be %s: %s.",
4142 for_writing ? "created" : "opened",
4143 wtap_strerror(err));
4144 errmsg = errmsg_errno;
4148 errmsg = file_open_error_message(err, for_writing);
4153 * Open/create errors are reported with an console message in TShark.
4156 open_failure_message(const char *filename, int err, gboolean for_writing)
4158 fprintf(stderr, "tshark: ");
4159 fprintf(stderr, file_open_error_message(err, for_writing), filename);
4160 fprintf(stderr, "\n");
4164 * General errors are reported with an console message in TShark.
4167 failure_message(const char *msg_format, va_list ap)
4169 fprintf(stderr, "tshark: ");
4170 vfprintf(stderr, msg_format, ap);
4171 fprintf(stderr, "\n");
4175 * Read errors are reported with an console message in TShark.
4178 read_failure_message(const char *filename, int err)
4180 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4181 filename, g_strerror(err));
4185 * Write errors are reported with an console message in TShark.
4188 write_failure_message(const char *filename, int err)
4190 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4191 filename, g_strerror(err));
4195 * Report additional information for an error in command-line arguments.
4198 failure_message_cont(const char *msg_format, va_list ap)
4200 vfprintf(stderr, msg_format, ap);
4201 fprintf(stderr, "\n");
4205 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4210 * indent-tabs-mode: nil
4213 * vi: set shiftwidth=2 tabstop=8 expandtab:
4214 * :indentSize=2:tabSize=8:noTabs=true: