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>
130 #include <wsutil/plugins.h>
135 #define tshark_debug(...) g_warning(__VA_ARGS__)
137 #define tshark_debug(...)
140 static guint32 cum_bytes;
141 static const frame_data *ref;
142 static frame_data ref_frame;
143 static frame_data *prev_dis;
144 static frame_data prev_dis_frame;
145 static frame_data *prev_cap;
146 static frame_data prev_cap_frame;
148 static gboolean perform_two_pass_analysis;
151 * The way the packet decode is to be written.
154 WRITE_TEXT, /* summary or detail text */
155 WRITE_XML, /* PDML or PSML */
156 WRITE_FIELDS, /* User defined list of fields */
157 WRITE_JSON, /* JSON */
158 WRITE_EK /* JSON bulk insert to Elasticsearch */
159 /* Add CSV and the like here */
162 static output_action_e output_action;
163 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
164 static gboolean print_packet_info; /* TRUE if we're to print packet information */
165 static gint print_summary = -1; /* TRUE if we're to print packet summary information */
166 static gboolean print_details; /* TRUE if we're to print packet details information */
167 static gboolean print_hex; /* TRUE if we're to print hex/ascci information */
168 static gboolean line_buffered;
169 static gboolean really_quiet = FALSE;
171 static print_format_e print_format = PR_FMT_TEXT;
172 static print_stream_t *print_stream;
174 static output_fields_t* output_fields = NULL;
175 static gchar **protocolfilter = NULL;
177 /* The line separator used between packets, changeable via the -S option */
178 static const char *separator = "";
182 * TRUE if we're to print packet counts to keep track of captured packets.
184 static gboolean print_packet_counts;
186 static capture_options global_capture_opts;
187 static capture_session global_capture_session;
188 static info_data_t global_info_data;
191 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
192 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
195 static gboolean capture(void);
196 static void report_counts(void);
198 static BOOL WINAPI capture_cleanup(DWORD);
200 static void capture_cleanup(int);
202 static void report_counts_siginfo(int);
206 #else /* HAVE_LIBPCAP */
208 static char *output_file_name;
210 #endif /* HAVE_LIBPCAP */
212 static int load_cap_file(capture_file *, char *, int, gboolean, int, gint64);
213 static gboolean process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset,
214 struct wtap_pkthdr *whdr, const guchar *pd,
216 static void show_capture_file_io_error(const char *, int, gboolean);
217 static void show_print_file_io_error(int err);
218 static gboolean write_preamble(capture_file *cf);
219 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
220 static gboolean write_finale(void);
221 static const char *cf_open_error_message(int err, gchar *err_info,
222 gboolean for_writing, int file_type);
224 static void open_failure_message(const char *filename, int err,
225 gboolean for_writing);
226 static void failure_message(const char *msg_format, va_list ap);
227 static void read_failure_message(const char *filename, int err);
228 static void write_failure_message(const char *filename, int err);
229 static void failure_message_cont(const char *msg_format, va_list ap);
233 static GHashTable *output_only_tables = NULL;
236 const char *sstr; /* The short string */
237 const char *lstr; /* The long string */
241 string_compare(gconstpointer a, gconstpointer b)
243 return strcmp(((const struct string_elem *)a)->sstr,
244 ((const struct string_elem *)b)->sstr);
248 string_elem_print(gpointer data, gpointer not_used _U_)
250 fprintf(stderr, " %s - %s\n",
251 ((struct string_elem *)data)->sstr,
252 ((struct string_elem *)data)->lstr);
256 list_capture_types(void) {
258 struct string_elem *captypes;
261 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
263 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
264 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
265 if (wtap_dump_can_open(i)) {
266 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
267 captypes[i].lstr = wtap_file_type_subtype_string(i);
268 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
271 g_slist_foreach(list, string_elem_print, NULL);
277 list_read_capture_types(void) {
279 struct string_elem *captypes;
281 const char *magic = "Magic-value-based";
282 const char *heuristic = "Heuristics-based";
284 /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
285 captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
287 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
288 for (i = 0; open_routines[i].name != NULL; i++) {
289 captypes[i].sstr = open_routines[i].name;
290 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
291 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
293 g_slist_foreach(list, string_elem_print, NULL);
299 print_usage(FILE *output)
301 fprintf(output, "\n");
302 fprintf(output, "Usage: tshark [options] ...\n");
303 fprintf(output, "\n");
306 fprintf(output, "Capture interface:\n");
307 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
308 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
309 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
310 fprintf(output, " -p don't capture in promiscuous mode\n");
311 #ifdef HAVE_PCAP_CREATE
312 fprintf(output, " -I capture in monitor mode, if available\n");
314 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
315 fprintf(output, " -B <buffer size> size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
317 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
318 fprintf(output, " -D print list of interfaces and exit\n");
319 fprintf(output, " -L print list of link-layer types of iface and exit\n");
320 fprintf(output, "\n");
321 fprintf(output, "Capture stop conditions:\n");
322 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
323 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
324 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
325 fprintf(output, " files:NUM - stop after NUM files\n");
326 /*fprintf(output, "\n");*/
327 fprintf(output, "Capture output:\n");
328 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
329 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
330 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
331 #endif /* HAVE_LIBPCAP */
332 #ifdef HAVE_PCAP_REMOTE
333 fprintf(output, "RPCAP options:\n");
334 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
336 /*fprintf(output, "\n");*/
337 fprintf(output, "Input file:\n");
338 fprintf(output, " -r <infile> set the filename to read from (- to read from stdin)\n");
340 fprintf(output, "\n");
341 fprintf(output, "Processing:\n");
342 fprintf(output, " -2 perform a two-pass analysis\n");
343 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
344 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
345 fprintf(output, " syntax\n");
346 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
347 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtCd\"\n");
348 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
349 fprintf(output, " \"Decode As\", see the man page for details\n");
350 fprintf(output, " Example: tcp.port==8888,http\n");
351 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
352 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
353 fprintf(output, " --disable-protocol <proto_name>\n");
354 fprintf(output, " disable dissection of proto_name\n");
355 fprintf(output, " --enable-heuristic <short_name>\n");
356 fprintf(output, " enable dissection of heuristic protocol\n");
357 fprintf(output, " --disable-heuristic <short_name>\n");
358 fprintf(output, " disable dissection of heuristic protocol\n");
360 /*fprintf(output, "\n");*/
361 fprintf(output, "Output:\n");
362 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
363 fprintf(output, " (or to the standard output for \"-\")\n");
364 fprintf(output, " -C <config profile> start with specified configuration profile\n");
365 fprintf(output, " -F <output file type> set the output file type, default is pcapng\n");
366 fprintf(output, " an empty \"-F\" option will list the file types\n");
367 fprintf(output, " -V add output of packet tree (Packet Details)\n");
368 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
369 fprintf(output, " separated\n");
370 fprintf(output, " -P print packet summary even when writing to a file\n");
371 fprintf(output, " -S <separator> the line separator to print between packets\n");
372 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
373 fprintf(output, " -T pdml|ps|psml|json|ek|text|fields\n");
374 fprintf(output, " format of text output (def: text)\n");
375 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected,\n");
376 fprintf(output, " (e.g. \"http tcp ip\",\n");
377 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
378 fprintf(output, " _ws.col.Info)\n");
379 fprintf(output, " this option can be repeated to print multiple fields\n");
380 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
381 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
382 fprintf(output, " header=y|n switch headers on and off\n");
383 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
384 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
385 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
386 fprintf(output, " aggregator\n");
387 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
388 fprintf(output, " -t a|ad|d|dd|e|r|u|ud output format of time stamps (def: r: rel. to first)\n");
389 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
390 fprintf(output, " -l flush standard output after each packet\n");
391 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
392 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
393 fprintf(output, " -g enable group read access on the output file(s)\n");
394 fprintf(output, " -W n Save extra information in the file, if supported.\n");
395 fprintf(output, " n = write network address resolution information\n");
396 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
397 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
398 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
399 fprintf(output, " --capture-comment <comment>\n");
400 fprintf(output, " add a capture comment to the newly created\n");
401 fprintf(output, " output file (only for pcapng)\n");
403 fprintf(output, "\n");
404 fprintf(output, "Miscellaneous:\n");
405 fprintf(output, " -h display this help and exit\n");
406 fprintf(output, " -v display version info and exit\n");
407 fprintf(output, " -o <name>:<value> ... override preference setting\n");
408 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
409 fprintf(output, " -G [report] dump one of several available reports and exit\n");
410 fprintf(output, " default report=\"fields\"\n");
411 fprintf(output, " use \"-G ?\" for more help\n");
413 fprintf(output, "\n");
414 fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
415 fprintf(output, "You might want to reset it\n");
416 fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
417 fprintf(output, "\n");
423 glossary_option_help(void)
429 fprintf(output, "TShark (Wireshark) %s\n", get_ws_vcs_version_info());
431 fprintf(output, "\n");
432 fprintf(output, "Usage: tshark -G [report]\n");
433 fprintf(output, "\n");
434 fprintf(output, "Glossary table reports:\n");
435 fprintf(output, " -G column-formats dump column format codes and exit\n");
436 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
437 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
438 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
439 fprintf(output, " -G fields dump fields glossary and exit\n");
440 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
441 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
442 fprintf(output, " -G plugins dump installed plugins and exit\n");
443 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
444 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
445 fprintf(output, "\n");
446 fprintf(output, "Preference reports:\n");
447 fprintf(output, " -G currentprefs dump current preferences and exit\n");
448 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
449 fprintf(output, "\n");
453 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
454 const gchar *message, gpointer user_data)
456 /* ignore log message, if log_level isn't interesting based
457 upon the console log preferences.
458 If the preferences haven't been loaded loaded yet, display the
461 The default console_log_level preference value is such that only
462 ERROR, CRITICAL and WARNING level messages are processed;
463 MESSAGE, INFO and DEBUG level messages are ignored.
465 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
466 ERROR and CRITICAL level messages so the current code is a behavioral
467 change. The current behavior is the same as in Wireshark.
469 if ((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
470 prefs.console_log_level != 0) {
474 g_log_default_handler(log_domain, log_level, message, user_data);
479 output_file_description(const char *fname)
481 char *save_file_string;
483 /* Get a string that describes what we're writing to */
484 if (strcmp(fname, "-") == 0) {
485 /* We're writing to the standard output */
486 save_file_string = g_strdup("standard output");
488 /* We're writing to a file with the name in save_file */
489 save_file_string = g_strdup_printf("file \"%s\"", fname);
491 return save_file_string;
495 print_current_user(void) {
496 gchar *cur_user, *cur_group;
498 if (started_with_special_privs()) {
499 cur_user = get_cur_username();
500 cur_group = get_cur_groupname();
501 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
502 cur_user, cur_group);
505 if (running_with_special_privs()) {
506 fprintf(stderr, " This could be dangerous.");
508 fprintf(stderr, "\n");
513 get_tshark_compiled_version_info(GString *str)
515 /* Capture libraries */
516 get_compiled_caplibs_version(str);
520 get_tshark_runtime_version_info(GString *str)
523 /* Capture libraries */
524 g_string_append(str, ", ");
525 get_runtime_caplibs_version(str);
528 /* stuff used by libwireshark */
529 epan_get_runtime_version_info(str);
533 main(int argc, char *argv[])
535 GString *comp_info_str;
536 GString *runtime_info_str;
537 char *init_progfile_dir_error;
539 static const struct option long_options[] = {
540 {"help", no_argument, NULL, 'h'},
541 {"version", no_argument, NULL, 'v'},
542 LONGOPT_CAPTURE_COMMON
545 gboolean arg_error = FALSE;
551 char *gpf_path, *pf_path;
552 char *gdp_path, *dp_path;
554 int gpf_open_errno, gpf_read_errno;
555 int pf_open_errno, pf_read_errno;
556 int gdp_open_errno, gdp_read_errno;
557 int dp_open_errno, dp_read_errno;
560 volatile int exit_status = 0;
562 gboolean list_link_layer_types = FALSE;
563 gboolean start_capture = FALSE;
568 gboolean capture_option_specified = FALSE;
570 gboolean quiet = FALSE;
571 #ifdef PCAP_NG_DEFAULT
572 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
574 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAP;
576 volatile gboolean out_file_name_res = FALSE;
577 volatile int in_file_type = WTAP_TYPE_AUTO;
578 gchar *volatile cf_name = NULL;
579 gchar *rfilter = NULL;
580 gchar *dfilter = NULL;
581 #ifdef HAVE_PCAP_OPEN_DEAD
582 struct bpf_program fcode;
584 dfilter_t *rfcode = NULL;
585 dfilter_t *dfcode = NULL;
590 gchar *output_only = NULL;
591 GSList *disable_protocol_slist = NULL;
592 GSList *enable_heur_slist = NULL;
593 GSList *disable_heur_slist = NULL;
594 gchar *volatile pdu_export_arg = NULL;
595 exp_pdu_t exp_pdu_tap_data;
598 * The leading + ensures that getopt_long() does not permute the argv[]
601 * We have to make sure that the first getopt_long() preserves the content
602 * of argv[] for the subsequent getopt_long() call.
604 * We use getopt_long() in both cases to ensure that we're using a routine
605 * whose permutation behavior we can control in the same fashion on all
606 * platforms, and so that, if we ever need to process a long argument before
607 * doing further initialization, we can do so.
609 * Glibc and Solaris libc document that a leading + disables permutation
610 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
611 * and OS X don't document it, but do so anyway.
613 * We do *not* use a leading - because the behavior of a leading - is
614 * platform-dependent.
616 #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:"
618 static const char optstring[] = OPTSTRING;
620 tshark_debug("tshark started with %d args", argc);
622 /* Set the C-language locale to the native environment. */
623 setlocale(LC_ALL, "");
625 cmdarg_err_init(failure_message, failure_message_cont);
628 arg_list_utf_16to8(argc, argv);
629 create_app_running_mutex();
630 #if !GLIB_CHECK_VERSION(2,31,0)
636 * Get credential information for later use, and drop privileges
637 * before doing anything else.
638 * Let the user know if anything happened.
640 init_process_policies();
641 relinquish_special_privs_perm();
642 print_current_user();
645 * Attempt to get the pathname of the executable file.
647 init_progfile_dir_error = init_progfile_dir(argv[0], main);
648 if (init_progfile_dir_error != NULL) {
649 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
650 init_progfile_dir_error);
653 initialize_funnel_ops();
656 ws_init_dll_search_path();
657 /* Load wpcap if possible. Do this before collecting the run-time version information */
660 /* Warn the user if npf.sys isn't loaded. */
661 if (!npf_sys_is_running() && get_windows_major_version() >= 6) {
662 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
663 "capturing or\nlisting interfaces.\n");
667 /* Get the compile-time version information string */
668 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
669 epan_get_compiled_version_info);
671 /* Get the run-time version information string */
672 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
674 /* Add it to the information to be reported on a crash. */
675 ws_add_crash_info("TShark (Wireshark) %s\n"
680 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
681 g_string_free(comp_info_str, TRUE);
682 g_string_free(runtime_info_str, TRUE);
684 /* Fail sometimes. Useful for testing fuzz scripts. */
685 /* if (g_random_int_range(0, 100) < 5) abort(); */
688 * In order to have the -X opts assigned before the wslua machine starts
689 * we need to call getopt_long before epan_init() gets called.
691 * In order to handle, for example, -o options, we also need to call it
692 * *after* epan_init() gets called, so that the dissectors have had a
693 * chance to register their preferences.
695 * XXX - can we do this all with one getopt_long() call, saving the
696 * arguments we can't handle until after initializing libwireshark,
697 * and then process them after initializing libwireshark?
701 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
703 case 'C': /* Configuration Profile */
704 if (profile_exists (optarg, FALSE)) {
705 set_profile_name (optarg);
707 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
711 case 'P': /* Print packet summary info even when writing to a file */
712 print_packet_info = TRUE;
713 print_summary = TRUE;
715 case 'O': /* Only output these protocols */
716 output_only = g_strdup(optarg);
718 case 'V': /* Verbose */
719 print_details = TRUE;
720 print_packet_info = TRUE;
722 case 'x': /* Print packet data in hex (and ASCII) */
724 /* The user asked for hex output, so let's ensure they get it,
725 * even if they're writing to a file.
727 print_packet_info = TRUE;
738 * Print packet summary information is the default, unless either -V or -x
739 * were specified and -P was not. Note that this is new behavior, which
740 * allows for the possibility of printing only hex/ascii output without
741 * necessarily requiring that either the summary or details be printed too.
743 if (print_summary == -1)
744 print_summary = (print_details || print_hex) ? FALSE : TRUE;
746 /** Send All g_log messages to our own handler **/
750 G_LOG_LEVEL_CRITICAL|
755 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
757 g_log_set_handler(NULL,
758 (GLogLevelFlags)log_flags,
759 tshark_log_handler, NULL /* user_data */);
760 g_log_set_handler(LOG_DOMAIN_MAIN,
761 (GLogLevelFlags)log_flags,
762 tshark_log_handler, NULL /* user_data */);
765 g_log_set_handler(LOG_DOMAIN_CAPTURE,
766 (GLogLevelFlags)log_flags,
767 tshark_log_handler, NULL /* user_data */);
768 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
769 (GLogLevelFlags)log_flags,
770 tshark_log_handler, NULL /* user_data */);
773 init_report_err(failure_message, open_failure_message, read_failure_message,
774 write_failure_message);
777 capture_opts_init(&global_capture_opts);
778 capture_session_init(&global_capture_session, &cfile);
781 timestamp_set_type(TS_RELATIVE);
782 timestamp_set_precision(TS_PREC_AUTO);
783 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
785 init_open_routines();
788 /* Register all the plugin types we have. */
789 epan_register_plugin_types(); /* Types known to libwireshark */
790 wtap_register_plugin_types(); /* Types known to libwiretap */
792 /* Scan for plugins. This does *not* call their registration routines;
793 that's done later. */
796 /* Register all libwiretap plugin modules. */
797 register_all_wiretap_modules();
800 /* Register all dissectors; we must do this before checking for the
801 "-G" flag, as the "-G" flag dumps information registered by the
802 dissectors, and we must do it before we read the preferences, in
803 case any dissectors register preferences. */
804 if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
808 /* Register all tap listeners; we do this before we parse the arguments,
809 as the "-z" argument can specify a registered tap. */
811 /* we register the plugin taps before the other taps because
812 stats_tree taps plugins will be registered as tap listeners
813 by stats_tree_stat.c and need to registered before that */
815 register_all_plugin_tap_listeners();
817 register_all_tap_listeners();
818 conversation_table_set_gui_info(init_iousers);
819 hostlist_table_set_gui_info(init_hostlists);
820 srt_table_iterate_tables(register_srt_tables, NULL);
821 rtd_table_iterate_tables(register_rtd_tables, NULL);
822 new_stat_tap_iterate_tables(register_simple_stat_tables, NULL);
824 /* If invoked with the "-G" flag, we dump out information based on
825 the argument to the "-G" flag; if no argument is specified,
826 for backwards compatibility we dump out a glossary of display
829 XXX - we do this here, for now, to support "-G" with no arguments.
830 If none of our build or other processes uses "-G" with no arguments,
831 we can just process it with the other arguments. */
832 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
833 proto_initialize_all_prefixes();
836 proto_registrar_dump_fields();
838 if (strcmp(argv[2], "column-formats") == 0)
839 column_dump_column_formats();
840 else if (strcmp(argv[2], "currentprefs") == 0) {
841 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
842 &pf_open_errno, &pf_read_errno, &pf_path);
845 else if (strcmp(argv[2], "decodes") == 0)
846 dissector_dump_decodes();
847 else if (strcmp(argv[2], "defaultprefs") == 0)
849 else if (strcmp(argv[2], "dissector-tables") == 0)
850 dissector_dump_dissector_tables();
851 else if (strcmp(argv[2], "fieldcount") == 0) {
852 /* return value for the test suite */
853 return proto_registrar_dump_fieldcount();
854 } else if (strcmp(argv[2], "fields") == 0)
855 proto_registrar_dump_fields();
856 else if (strcmp(argv[2], "ftypes") == 0)
857 proto_registrar_dump_ftypes();
858 else if (strcmp(argv[2], "heuristic-decodes") == 0)
859 dissector_dump_heur_decodes();
860 else if (strcmp(argv[2], "plugins") == 0) {
865 wslua_plugins_dump_all();
868 else if (strcmp(argv[2], "protocols") == 0)
869 proto_registrar_dump_protocols();
870 else if (strcmp(argv[2], "values") == 0)
871 proto_registrar_dump_values();
872 else if (strcmp(argv[2], "?") == 0)
873 glossary_option_help();
874 else if (strcmp(argv[2], "-?") == 0)
875 glossary_option_help();
877 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
884 /* load the decode as entries of this profile */
885 load_decode_as_entries();
887 tshark_debug("tshark reading preferences");
889 prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
890 &pf_open_errno, &pf_read_errno, &pf_path);
891 if (gpf_path != NULL) {
892 if (gpf_open_errno != 0) {
893 cmdarg_err("Can't open global preferences file \"%s\": %s.",
894 pf_path, g_strerror(gpf_open_errno));
896 if (gpf_read_errno != 0) {
897 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
898 pf_path, g_strerror(gpf_read_errno));
901 if (pf_path != NULL) {
902 if (pf_open_errno != 0) {
903 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
904 g_strerror(pf_open_errno));
906 if (pf_read_errno != 0) {
907 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
908 pf_path, g_strerror(pf_read_errno));
914 read_filter_list(CFILTER_LIST, &cf_path, &cf_open_errno);
915 if (cf_path != NULL) {
916 cmdarg_err("Could not open your capture filter file\n\"%s\": %s.",
917 cf_path, g_strerror(cf_open_errno));
921 /* Read the disabled protocols file. */
922 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
923 &dp_path, &dp_open_errno, &dp_read_errno);
924 read_disabled_heur_dissector_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
925 &dp_path, &dp_open_errno, &dp_read_errno);
926 if (gdp_path != NULL) {
927 if (gdp_open_errno != 0) {
928 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
929 gdp_path, g_strerror(gdp_open_errno));
931 if (gdp_read_errno != 0) {
932 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
933 gdp_path, g_strerror(gdp_read_errno));
937 if (dp_path != NULL) {
938 if (dp_open_errno != 0) {
940 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
941 g_strerror(dp_open_errno));
943 if (dp_read_errno != 0) {
945 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
946 g_strerror(dp_read_errno));
951 cap_file_init(&cfile);
953 /* Print format defaults to this. */
954 print_format = PR_FMT_TEXT;
956 output_fields = output_fields_new();
959 * To reset the options parser, set optreset to 1 on platforms that
960 * have optreset (documented in *BSD and OS X, apparently present but
961 * not documented in Solaris - the Illumos repository seems to
962 * suggest that the first Solaris getopt_long(), at least as of 2004,
963 * was based on the NetBSD one, it had optreset) and set optind to 1,
964 * and set optind to 0 otherwise (documented as working in the GNU
965 * getopt_long(). Setting optind to 0 didn't originally work in the
966 * NetBSD one, but that was added later - we don't want to depend on
967 * it if we have optreset).
969 * Also reset opterr to 1, so that error messages are printed by
980 /* Now get our args */
981 while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
983 case '2': /* Perform two pass analysis */
984 perform_two_pass_analysis = TRUE;
986 case 'a': /* autostop criteria */
987 case 'b': /* Ringbuffer option */
988 case 'c': /* Capture x packets */
989 case 'f': /* capture filter */
990 case 'g': /* enable group read access on file(s) */
991 case 'i': /* Use interface x */
992 case 'p': /* Don't capture in promiscuous mode */
993 #ifdef HAVE_PCAP_REMOTE
994 case 'A': /* Authentication */
996 #ifdef HAVE_PCAP_CREATE
997 case 'I': /* Capture in monitor mode, if available */
999 case 's': /* Set the snapshot (capture) length */
1000 case 'w': /* Write to capture file x */
1001 case 'y': /* Set the pcap data link type */
1002 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
1003 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1004 case 'B': /* Buffer size */
1007 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1014 * Output file name, if we're reading a file and writing to another
1017 output_file_name = optarg;
1019 capture_option_specified = TRUE;
1025 /* already processed; just ignore it now */
1027 case 'd': /* Decode as rule */
1028 if (!decode_as_command_option(optarg))
1031 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1032 case 'K': /* Kerberos keytab file */
1033 read_keytab_file(optarg);
1036 case 'D': /* Print a list of capture devices and exit */
1038 if_list = capture_interface_list(&err, &err_str,NULL);
1039 if (if_list == NULL) {
1041 cmdarg_err("There are no interfaces on which a capture can be done");
1043 cmdarg_err("%s", err_str);
1048 capture_opts_print_interfaces(if_list);
1049 free_interface_list(if_list);
1052 capture_option_specified = TRUE;
1058 output_fields_add(output_fields, optarg);
1062 if (!output_fields_set_option(output_fields, optarg)) {
1063 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1064 output_fields_list_options(stderr);
1069 out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1070 if (out_file_type < 0) {
1071 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1072 list_capture_types();
1077 protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1079 case 'W': /* Select extra information to save in our capture file */
1080 /* This is patterned after the -N flag which may not be the best idea. */
1081 if (strchr(optarg, 'n')) {
1082 out_file_name_res = TRUE;
1084 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1085 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1089 case 'H': /* Read address to name mappings from a hosts file */
1090 if (! add_hosts_file(optarg))
1092 cmdarg_err("Can't read host entries from \"%s\"", optarg);
1095 out_file_name_res = TRUE;
1098 case 'h': /* Print help and exit */
1099 printf("TShark (Wireshark) %s\n"
1100 "Dump and analyze network traffic.\n"
1101 "See https://www.wireshark.org for more information.\n",
1102 get_ws_vcs_version_info());
1103 print_usage(stdout);
1106 case 'l': /* "Line-buffer" standard output */
1107 /* This isn't line-buffering, strictly speaking, it's just
1108 flushing the standard output after the information for
1109 each packet is printed; however, that should be good
1110 enough for all the purposes to which "-l" is put (and
1111 is probably actually better for "-V", as it does fewer
1114 See the comment in "process_packet()" for an explanation of
1115 why we do that, and why we don't just use "setvbuf()" to
1116 make the standard output line-buffered (short version: in
1117 Windows, "line-buffered" is the same as "fully-buffered",
1118 and the output buffer is only flushed when it fills up). */
1119 line_buffered = TRUE;
1121 case 'L': /* Print list of link-layer types and exit */
1123 list_link_layer_types = TRUE;
1125 capture_option_specified = TRUE;
1129 case 'n': /* No name resolution */
1130 disable_name_resolution();
1132 case 'N': /* Select what types of addresses/port #s to resolve */
1133 badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1134 if (badopt != '\0') {
1135 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are:",
1137 cmdarg_err_cont("\t'd' to enable address resolution from captured DNS packets\n"
1138 "\t'm' to enable MAC address resolution\n"
1139 "\t'n' to enable network address resolution\n"
1140 "\t'N' to enable using external resolvers (e.g., DNS)\n"
1141 "\t for network address resolution\n"
1142 "\t't' to enable transport-layer port number resolution");
1146 case 'o': /* Override preference from command line */
1147 switch (prefs_set_pref(optarg)) {
1152 case PREFS_SET_SYNTAX_ERR:
1153 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1157 case PREFS_SET_NO_SUCH_PREF:
1158 case PREFS_SET_OBSOLETE:
1159 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1164 case 'q': /* Quiet */
1167 case 'Q': /* Really quiet */
1169 really_quiet = TRUE;
1171 case 'r': /* Read capture file x */
1172 cf_name = g_strdup(optarg);
1174 case 'R': /* Read file filter */
1178 /* already processed; just ignore it now */
1180 case 'S': /* Set the line Separator to be printed between packets */
1183 case 't': /* Time stamp type */
1184 if (strcmp(optarg, "r") == 0)
1185 timestamp_set_type(TS_RELATIVE);
1186 else if (strcmp(optarg, "a") == 0)
1187 timestamp_set_type(TS_ABSOLUTE);
1188 else if (strcmp(optarg, "ad") == 0)
1189 timestamp_set_type(TS_ABSOLUTE_WITH_YMD);
1190 else if (strcmp(optarg, "adoy") == 0)
1191 timestamp_set_type(TS_ABSOLUTE_WITH_YDOY);
1192 else if (strcmp(optarg, "d") == 0)
1193 timestamp_set_type(TS_DELTA);
1194 else if (strcmp(optarg, "dd") == 0)
1195 timestamp_set_type(TS_DELTA_DIS);
1196 else if (strcmp(optarg, "e") == 0)
1197 timestamp_set_type(TS_EPOCH);
1198 else if (strcmp(optarg, "u") == 0)
1199 timestamp_set_type(TS_UTC);
1200 else if (strcmp(optarg, "ud") == 0)
1201 timestamp_set_type(TS_UTC_WITH_YMD);
1202 else if (strcmp(optarg, "udoy") == 0)
1203 timestamp_set_type(TS_UTC_WITH_YDOY);
1205 cmdarg_err("Invalid time stamp type \"%s\"; it must be one of:", optarg);
1206 cmdarg_err_cont("\t\"a\" for absolute\n"
1207 "\t\"ad\" for absolute with YYYY-MM-DD date\n"
1208 "\t\"adoy\" for absolute with YYYY/DOY date\n"
1209 "\t\"d\" for delta\n"
1210 "\t\"dd\" for delta displayed\n"
1211 "\t\"e\" for epoch\n"
1212 "\t\"r\" for relative\n"
1213 "\t\"u\" for absolute UTC\n"
1214 "\t\"ud\" for absolute UTC with YYYY-MM-DD date\n"
1215 "\t\"udoy\" for absolute UTC with YYYY/DOY date");
1219 case 'T': /* printing Type */
1220 print_packet_info = TRUE;
1221 if (strcmp(optarg, "text") == 0) {
1222 output_action = WRITE_TEXT;
1223 print_format = PR_FMT_TEXT;
1224 } else if (strcmp(optarg, "ps") == 0) {
1225 output_action = WRITE_TEXT;
1226 print_format = PR_FMT_PS;
1227 } else if (strcmp(optarg, "pdml") == 0) {
1228 output_action = WRITE_XML;
1229 print_details = TRUE; /* Need details */
1230 print_summary = FALSE; /* Don't allow summary */
1231 } else if (strcmp(optarg, "psml") == 0) {
1232 output_action = WRITE_XML;
1233 print_details = FALSE; /* Don't allow details */
1234 print_summary = TRUE; /* Need summary */
1235 } else if (strcmp(optarg, "fields") == 0) {
1236 output_action = WRITE_FIELDS;
1237 print_details = TRUE; /* Need full tree info */
1238 print_summary = FALSE; /* Don't allow summary */
1239 } else if (strcmp(optarg, "json") == 0) {
1240 output_action = WRITE_JSON;
1241 print_details = TRUE; /* Need details */
1242 print_summary = FALSE; /* Don't allow summary */
1243 } else if (strcmp(optarg, "ek") == 0) {
1244 output_action = WRITE_EK;
1245 print_details = TRUE; /* Need details */
1246 print_summary = FALSE; /* Don't allow summary */
1249 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg); /* x */
1250 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1251 "\t specified by the -E option.\n"
1252 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1253 "\t details of a decoded packet. This information is equivalent to\n"
1254 "\t the packet details printed with the -V flag.\n"
1255 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1256 "\t the packets, or a multi-line view of the details of each of\n"
1257 "\t the packets, depending on whether the -V flag was specified.\n"
1258 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1259 "\t summary information of a decoded packet. This information is\n"
1260 "\t equivalent to the information shown in the one-line summary\n"
1261 "\t printed by default.\n"
1262 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1263 "\t summary information of a decoded packet. This information is \n"
1264 "\t equivalent to the packet details printed with the -V flag.\n"
1265 "\t\"ek\" Packet Summary, an EK JSON-based format for the bulk insert \n"
1266 "\t into elastic search cluster. This information is \n"
1267 "\t equivalent to the packet details printed with the -V flag.\n"
1268 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1269 "\t packets, or a multi-line view of the details of each of the\n"
1270 "\t packets, depending on whether the -V flag was specified.\n"
1271 "\t This is the default.");
1275 case 'u': /* Seconds type */
1276 if (strcmp(optarg, "s") == 0)
1277 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1278 else if (strcmp(optarg, "hms") == 0)
1279 timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1281 cmdarg_err("Invalid seconds type \"%s\"; it must be one of:", optarg);
1282 cmdarg_err_cont("\t\"s\" for seconds\n"
1283 "\t\"hms\" for hours, minutes and seconds");
1287 case 'U': /* Export PDUs to file */
1289 GSList *export_pdu_tap_name_list = NULL;
1292 cmdarg_err("Tap name is required! Valid names are:");
1293 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)) {
1294 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1298 pdu_export_arg = g_strdup(optarg);
1301 case 'v': /* Show version and exit */
1302 comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
1303 epan_get_compiled_version_info);
1304 runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
1305 show_version("TShark (Wireshark)", comp_info_str, runtime_info_str);
1306 g_string_free(comp_info_str, TRUE);
1307 g_string_free(runtime_info_str, TRUE);
1308 /* We don't really have to cleanup here, but it's a convenient way to test
1309 * start-up and shut-down of the epan library without any UI-specific
1310 * cruft getting in the way. Makes the results of running
1311 * $ ./tools/valgrind-wireshark -n
1312 * much more useful. */
1318 case 'O': /* Only output these protocols */
1319 /* already processed; just ignore it now */
1321 case 'V': /* Verbose */
1322 /* already processed; just ignore it now */
1324 case 'x': /* Print packet data in hex (and ASCII) */
1325 /* already processed; just ignore it now */
1328 /* already processed; just ignore it now */
1334 /* We won't call the init function for the stat this soon
1335 as it would disallow MATE's fields (which are registered
1336 by the preferences set callback) from being used as
1337 part of a tap filter. Instead, we just add the argument
1338 to a list of stat arguments. */
1339 if (strcmp("help", optarg) == 0) {
1340 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1341 list_stat_cmd_args();
1344 if (!process_stat_cmd_arg(optarg)) {
1345 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1346 list_stat_cmd_args();
1350 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1351 disable_protocol_slist = g_slist_append(disable_protocol_slist, optarg);
1353 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1354 enable_heur_slist = g_slist_append(enable_heur_slist, optarg);
1356 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1357 disable_heur_slist = g_slist_append(disable_heur_slist, optarg);
1361 case '?': /* Bad flag - print usage message */
1364 list_capture_types();
1367 print_usage(stderr);
1374 /* If we specified output fields, but not the output field type... */
1375 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1376 cmdarg_err("Output fields were specified with \"-e\", "
1377 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1379 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1380 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1381 "specified with \"-e\".");
1386 /* If no capture filter or display filter has been specified, and there are
1387 still command-line arguments, treat them as the tokens of a capture
1388 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1389 flag was specified. */
1390 if (optind < argc) {
1391 if (cf_name != NULL) {
1392 if (dfilter != NULL) {
1393 cmdarg_err("Display filters were specified both with \"-d\" "
1394 "and with additional command-line arguments.");
1397 dfilter = get_args_as_string(argc, argv, optind);
1402 if (global_capture_opts.default_options.cfilter) {
1403 cmdarg_err("A default capture filter was specified both with \"-f\""
1404 " and with additional command-line arguments.");
1407 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1408 interface_options interface_opts;
1409 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1410 if (interface_opts.cfilter == NULL) {
1411 interface_opts.cfilter = get_args_as_string(argc, argv, optind);
1412 global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
1413 g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
1415 cmdarg_err("A capture filter was specified both with \"-f\""
1416 " and with additional command-line arguments.");
1420 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1422 capture_option_specified = TRUE;
1428 if (!global_capture_opts.saving_to_file) {
1429 /* We're not saving the capture to a file; if "-q" wasn't specified,
1430 we should print packet information */
1432 print_packet_info = TRUE;
1434 /* We're saving to a file; if we're writing to the standard output.
1435 and we'll also be writing dissected packets to the standard
1436 output, reject the request. At best, we could redirect that
1437 to the standard error; we *can't* write both to the standard
1438 output and have either of them be useful. */
1439 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1440 cmdarg_err("You can't write both raw packet data and dissected packets"
1441 " to the standard output.");
1446 /* We're not saving the capture to a file; if "-q" wasn't specified,
1447 we should print packet information */
1449 print_packet_info = TRUE;
1452 #ifndef HAVE_LIBPCAP
1453 if (capture_option_specified)
1454 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1457 print_usage(stderr);
1462 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_EK) {
1463 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON or EK JSON");
1468 if (output_only != NULL) {
1471 if (!print_details) {
1472 cmdarg_err("-O requires -V");
1476 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1477 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1478 g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1482 if (rfilter != NULL && !perform_two_pass_analysis) {
1483 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1488 if (list_link_layer_types) {
1489 /* We're supposed to list the link-layer types for an interface;
1490 did the user also specify a capture file to be read? */
1492 /* Yes - that's bogus. */
1493 cmdarg_err("You can't specify -L and a capture file to be read.");
1496 /* No - did they specify a ring buffer option? */
1497 if (global_capture_opts.multi_files_on) {
1498 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1504 * "-r" was specified, so we're reading a capture file.
1505 * Capture options don't apply here.
1508 /* We don't support capture filters when reading from a capture file
1509 (the BPF compiler doesn't support all link-layer types that we
1510 support in capture files we read). */
1511 if (global_capture_opts.default_options.cfilter) {
1512 cmdarg_err("Only read filters, not capture filters, "
1513 "can be specified when reading a capture file.");
1516 if (global_capture_opts.multi_files_on) {
1517 cmdarg_err("Multiple capture files requested, but "
1518 "a capture isn't being done.");
1521 if (global_capture_opts.has_file_duration) {
1522 cmdarg_err("Switching capture files after a time interval was specified, but "
1523 "a capture isn't being done.");
1526 if (global_capture_opts.has_ring_num_files) {
1527 cmdarg_err("A ring buffer of capture files was specified, but "
1528 "a capture isn't being done.");
1531 if (global_capture_opts.has_autostop_files) {
1532 cmdarg_err("A maximum number of capture files was specified, but "
1533 "a capture isn't being done.");
1536 if (global_capture_opts.capture_comment) {
1537 cmdarg_err("A capture comment was specified, but "
1538 "a capture isn't being done.\nThere's no support for adding "
1539 "a capture comment to an existing capture file.");
1543 /* Note: TShark now allows the restriction of a _read_ file by packet count
1544 * and byte count as well as a write file. Other autostop options remain valid
1545 * only for a write file.
1547 if (global_capture_opts.has_autostop_duration) {
1548 cmdarg_err("A maximum capture time was specified, but "
1549 "a capture isn't being done.");
1554 * "-r" wasn't specified, so we're doing a live capture.
1556 if (perform_two_pass_analysis) {
1557 /* Two-pass analysis doesn't work with live capture since it requires us
1558 * to buffer packets until we've read all of them, but a live capture
1559 * has no useful/meaningful definition of "all" */
1560 cmdarg_err("Live captures do not support two-pass analysis.");
1564 if (global_capture_opts.saving_to_file) {
1565 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1567 /* When capturing, we only support writing pcap or pcap-ng format. */
1568 if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1569 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1570 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1573 if (global_capture_opts.capture_comment &&
1574 out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1575 cmdarg_err("A capture comment can only be written to a pcapng file.");
1578 if (global_capture_opts.multi_files_on) {
1579 /* Multiple-file mode doesn't work under certain conditions:
1580 a) it doesn't work if you're writing to the standard output;
1581 b) it doesn't work if you're writing to a pipe;
1583 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1584 cmdarg_err("Multiple capture files requested, but "
1585 "the capture is being written to the standard output.");
1588 if (global_capture_opts.output_to_pipe) {
1589 cmdarg_err("Multiple capture files requested, but "
1590 "the capture file is a pipe.");
1593 if (!global_capture_opts.has_autostop_filesize &&
1594 !global_capture_opts.has_file_duration) {
1595 cmdarg_err("Multiple capture files requested, but "
1596 "no maximum capture file size or duration was specified.");
1600 /* Currently, we don't support read or display filters when capturing
1601 and saving the packets. */
1602 if (rfilter != NULL) {
1603 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1606 if (dfilter != NULL) {
1607 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1610 global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1612 /* They didn't specify a "-w" flag, so we won't be saving to a
1613 capture file. Check for options that only make sense if
1614 we're saving to a file. */
1615 if (global_capture_opts.has_autostop_filesize) {
1616 cmdarg_err("Maximum capture file size specified, but "
1617 "capture isn't being saved to a file.");
1620 if (global_capture_opts.multi_files_on) {
1621 cmdarg_err("Multiple capture files requested, but "
1622 "the capture isn't being saved to a file.");
1625 if (global_capture_opts.capture_comment) {
1626 cmdarg_err("A capture comment was specified, but "
1627 "the capture isn't being saved to a file.");
1636 /* Start windows sockets */
1637 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1640 /* Notify all registered modules that have had any of their preferences
1641 changed either from one of the preferences file or from the command
1642 line that their preferences have changed. */
1645 /* At this point MATE will have registered its field array so we can
1646 have a tap filter with one of MATE's late-registered fields as part
1647 of the filter. We can now process all the "-z" arguments. */
1648 start_requested_stats();
1650 /* At this point MATE will have registered its field array so we can
1651 check if the fields specified by the user are all good.
1655 GSList *invalid_fields = output_fields_valid(output_fields);
1656 if (invalid_fields != NULL) {
1658 cmdarg_err("Some fields aren't valid:");
1659 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1660 cmdarg_err_cont("\t%s", (gchar *)it->data);
1662 g_slist_free(invalid_fields);
1667 /* We currently don't support taps, or printing dissected packets,
1668 if we're writing to a pipe. */
1669 if (global_capture_opts.saving_to_file &&
1670 global_capture_opts.output_to_pipe) {
1671 if (tap_listeners_require_dissection()) {
1672 cmdarg_err("Taps aren't supported when saving to a pipe.");
1675 if (print_packet_info) {
1676 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1682 if (ex_opt_count("read_format") > 0) {
1683 const gchar* name = ex_opt_get_next("read_format");
1684 in_file_type = open_info_name_to_type(name);
1685 if (in_file_type == WTAP_TYPE_AUTO) {
1686 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1687 list_read_capture_types();
1692 /* disabled protocols as per configuration file */
1693 if (gdp_path == NULL && dp_path == NULL) {
1694 set_disabled_protos_list();
1695 set_disabled_heur_dissector_list();
1698 if(disable_protocol_slist) {
1699 GSList *proto_disable;
1700 for (proto_disable = disable_protocol_slist; proto_disable != NULL; proto_disable = g_slist_next(proto_disable))
1702 proto_disable_proto_by_name((char*)proto_disable->data);
1706 if(enable_heur_slist) {
1707 GSList *heur_enable;
1708 for (heur_enable = enable_heur_slist; heur_enable != NULL; heur_enable = g_slist_next(heur_enable))
1710 proto_enable_heuristic_by_name((char*)heur_enable->data, TRUE);
1714 if(disable_heur_slist) {
1715 GSList *heur_disable;
1716 for (heur_disable = disable_heur_slist; heur_disable != NULL; heur_disable = g_slist_next(heur_disable))
1718 proto_enable_heuristic_by_name((char*)heur_disable->data, FALSE);
1722 /* Build the column format array */
1723 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1726 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1727 capture_opts_trim_ring_num_files(&global_capture_opts);
1730 if (rfilter != NULL) {
1731 tshark_debug("Compiling read filter: '%s'", rfilter);
1732 if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1733 cmdarg_err("%s", err_msg);
1739 #ifdef HAVE_PCAP_OPEN_DEAD
1743 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1745 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1747 " Note: That read filter code looks like a valid capture filter;\n"
1748 " maybe you mixed them up?");
1757 cfile.rfcode = rfcode;
1759 if (dfilter != NULL) {
1760 tshark_debug("Compiling display filter: '%s'", dfilter);
1761 if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1762 cmdarg_err("%s", err_msg);
1768 #ifdef HAVE_PCAP_OPEN_DEAD
1772 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1774 if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1776 " Note: That display filter code looks like a valid capture filter;\n"
1777 " maybe you mixed them up?");
1786 cfile.dfcode = dfcode;
1788 if (print_packet_info) {
1789 /* If we're printing as text or PostScript, we have
1790 to create a print stream. */
1791 if (output_action == WRITE_TEXT) {
1792 switch (print_format) {
1795 print_stream = print_stream_text_stdio_new(stdout);
1799 print_stream = print_stream_ps_stdio_new(stdout);
1803 g_assert_not_reached();
1808 /* PDU export requested. Take the ownership of the '-w' file, apply tap
1809 * filters and start tapping. */
1810 if (pdu_export_arg) {
1811 const char *exp_pdu_filename;
1812 const char *exp_pdu_tap_name = pdu_export_arg;
1813 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1814 char *exp_pdu_error;
1818 cmdarg_err("PDUs export requires a capture file (specify with -r).");
1821 /* Take ownership of the '-w' output file. */
1823 exp_pdu_filename = global_capture_opts.save_file;
1824 global_capture_opts.save_file = NULL;
1826 exp_pdu_filename = output_file_name;
1827 output_file_name = NULL;
1829 if (exp_pdu_filename == NULL) {
1830 cmdarg_err("PDUs export requires an output file (-w).");
1834 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1836 if (exp_pdu_error) {
1837 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1838 g_free(exp_pdu_error);
1842 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1844 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
1848 /* Activate the export PDU tap */
1849 err = exp_pdu_open(&exp_pdu_tap_data, exp_fd,
1850 g_strdup_printf("Dump of PDUs from %s", cf_name));
1852 cmdarg_err("Failed to start the PDU export: %s", g_strerror(err));
1857 /* We have to dissect each packet if:
1859 we're printing information about each packet;
1861 we're using a read filter on the packets;
1863 we're using a display filter on the packets;
1865 we're exporting PDUs;
1867 we're using any taps that need dissection. */
1868 do_dissection = print_packet_info || rfcode || dfcode || pdu_export_arg ||
1869 tap_listeners_require_dissection();
1870 tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
1873 tshark_debug("tshark: Opening capture file: %s", cf_name);
1875 * We're reading a capture file.
1877 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
1885 /* Process the packets in the file */
1886 tshark_debug("tshark: invoking load_cap_file() to process the packets");
1889 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
1890 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1891 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1893 err = load_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, 0, 0);
1896 CATCH(OutOfMemoryError) {
1900 "Sorry, but TShark has to terminate now.\n"
1902 "More information and workarounds can be found at\n"
1903 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
1908 /* We still dump out the results of taps, etc., as we might have
1909 read some packets; however, we exit with an error status. */
1913 if (pdu_export_arg) {
1914 err = exp_pdu_close(&exp_pdu_tap_data);
1916 cmdarg_err("%s", wtap_strerror(err));
1919 g_free(pdu_export_arg);
1922 tshark_debug("tshark: no capture file specified");
1923 /* No capture file specified, so we're supposed to do a live capture
1924 or get a list of link-layer types for a live capture device;
1925 do we have support for live captures? */
1927 /* if no interface was specified, pick a default */
1928 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
1929 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
1930 if (exit_status != 0)
1933 /* if requested, list the link layer types and exit */
1934 if (list_link_layer_types) {
1937 /* Get the list of link-layer types for the capture devices. */
1938 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1939 interface_options interface_opts;
1940 if_capabilities_t *caps;
1941 char *auth_str = NULL;
1943 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1944 #ifdef HAVE_PCAP_REMOTE
1945 if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
1946 auth_str = g_strdup_printf("%s:%s", interface_opts.auth_username, interface_opts.auth_password);
1949 caps = capture_get_if_capabilities(interface_opts.name, interface_opts.monitor_mode, auth_str, &err_str, NULL);
1952 cmdarg_err("%s", err_str);
1956 if (caps->data_link_types == NULL) {
1957 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
1960 capture_opts_print_if_capabilities(caps, interface_opts.name, interface_opts.monitor_mode);
1961 free_if_capabilities(caps);
1967 * If the standard error isn't a terminal, don't print packet counts,
1968 * as they won't show up on the user's terminal and they'll get in
1969 * the way of error messages in the file (to which we assume the
1970 * standard error was redirected; if it's redirected to the null
1971 * device, there's no point in printing packet counts anyway).
1973 * Otherwise, if we're printing packet information and the standard
1974 * output is a terminal (which we assume means the standard output and
1975 * error are going to the same terminal), don't print packet counts,
1976 * as they'll get in the way of the packet information.
1978 * Otherwise, if the user specified -q, don't print packet counts.
1980 * Otherwise, print packet counts.
1982 * XXX - what if the user wants to do a live capture, doesn't want
1983 * to save it to a file, doesn't want information printed for each
1984 * packet, does want some "-z" statistic, and wants packet counts
1985 * so they know whether they're seeing any packets? -q will
1986 * suppress the information printed for each packet, but it'll
1987 * also suppress the packet counts.
1989 if (!ws_isatty(ws_fileno(stderr)))
1990 print_packet_counts = FALSE;
1991 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
1992 print_packet_counts = FALSE;
1994 print_packet_counts = FALSE;
1996 print_packet_counts = TRUE;
1998 if (print_packet_info) {
1999 if (!write_preamble(&cfile)) {
2000 show_print_file_io_error(errno);
2005 tshark_debug("tshark: performing live capture");
2007 * XXX - this returns FALSE if an error occurred, but it also
2008 * returns FALSE if the capture stops because a time limit
2009 * was reached (and possibly other limits), so we can't assume
2010 * it means an error.
2012 * The capture code is a bit twisty, so it doesn't appear to
2013 * be an easy fix. We just ignore the return value for now.
2014 * Instead, pass on the exit status from the capture child.
2017 exit_status = global_capture_session.fork_child_status;
2019 if (print_packet_info) {
2020 if (!write_finale()) {
2022 show_print_file_io_error(err);
2026 /* No - complain. */
2027 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2034 if (cfile.frames != NULL) {
2035 free_frame_data_sequence(cfile.frames);
2036 cfile.frames = NULL;
2039 draw_tap_listeners(TRUE);
2040 funnel_dump_all_text_windows();
2041 epan_free(cfile.epan);
2047 output_fields_free(output_fields);
2048 output_fields = NULL;
2053 /*#define USE_BROKEN_G_MAIN_LOOP*/
2055 #ifdef USE_BROKEN_G_MAIN_LOOP
2058 gboolean loop_running = FALSE;
2060 guint32 packet_count = 0;
2063 typedef struct pipe_input_tag {
2066 ws_process_id *child_process;
2067 pipe_input_cb_t input_cb;
2068 guint pipe_input_id;
2070 GMutex *callback_running;
2074 static pipe_input_t pipe_input;
2077 /* The timer has expired, see if there's stuff to read from the pipe,
2078 if so, do the callback */
2080 pipe_timer_cb(gpointer data)
2086 pipe_input_t *pipe_input_p = data;
2087 gint iterations = 0;
2089 g_mutex_lock (pipe_input_p->callback_running);
2091 /* try to read data from the pipe only 5 times, to avoid blocking */
2092 while(iterations < 5) {
2093 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2095 /* Oddly enough although Named pipes don't work on win9x,
2096 PeekNamedPipe does !!! */
2097 handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2098 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2100 /* Get the child process exit status */
2101 GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2104 /* If the Peek returned an error, or there are bytes to be read
2105 or the childwatcher thread has terminated then call the normal
2107 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2109 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2111 /* And call the real handler */
2112 if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2113 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2114 /* pipe closed, return false so that the timer is stopped */
2115 g_mutex_unlock (pipe_input_p->callback_running);
2120 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2121 /* No data, stop now */
2128 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2130 g_mutex_unlock (pipe_input_p->callback_running);
2132 /* we didn't stopped the timer, so let it run */
2139 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2142 pipe_input.source = source;
2143 pipe_input.child_process = child_process;
2144 pipe_input.user_data = user_data;
2145 pipe_input.input_cb = input_cb;
2148 #if GLIB_CHECK_VERSION(2,31,0)
2149 pipe_input.callback_running = g_malloc(sizeof(GMutex));
2150 g_mutex_init(pipe_input.callback_running);
2152 pipe_input.callback_running = g_mutex_new();
2154 /* Tricky to use pipes in win9x, as no concept of wait. NT can
2155 do this but that doesn't cover all win32 platforms. GTK can do
2156 this but doesn't seem to work over processes. Attempt to do
2157 something similar here, start a timer and check for data on every
2159 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2160 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2164 static const nstime_t *
2165 tshark_get_frame_ts(void *data, guint32 frame_num)
2167 capture_file *cf = (capture_file *) data;
2169 if (ref && ref->num == frame_num)
2170 return &ref->abs_ts;
2172 if (prev_dis && prev_dis->num == frame_num)
2173 return &prev_dis->abs_ts;
2175 if (prev_cap && prev_cap->num == frame_num)
2176 return &prev_cap->abs_ts;
2179 frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);
2181 return (fd) ? &fd->abs_ts : NULL;
2188 tshark_epan_new(capture_file *cf)
2190 epan_t *epan = epan_new();
2193 epan->get_frame_ts = tshark_get_frame_ts;
2194 epan->get_interface_name = cap_file_get_interface_name;
2195 epan->get_user_comment = NULL;
2207 #ifdef USE_TSHARK_SELECT
2211 struct sigaction action, oldaction;
2214 /* Create new dissection section. */
2215 epan_free(cfile.epan);
2216 cfile.epan = tshark_epan_new(&cfile);
2219 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2220 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2222 /* Catch SIGINT and SIGTERM and, if we get either of them,
2223 clean up and exit. If SIGHUP isn't being ignored, catch
2224 it too and, if we get it, clean up and exit.
2226 We restart any read that was in progress, so that it doesn't
2227 disrupt reading from the sync pipe. The signal handler tells
2228 the capture child to finish; it will report that it finished,
2229 or will exit abnormally, so we'll stop reading from the sync
2230 pipe, pick up the exit status, and quit. */
2231 memset(&action, 0, sizeof(action));
2232 action.sa_handler = capture_cleanup;
2233 action.sa_flags = SA_RESTART;
2234 sigemptyset(&action.sa_mask);
2235 sigaction(SIGTERM, &action, NULL);
2236 sigaction(SIGINT, &action, NULL);
2237 sigaction(SIGHUP, NULL, &oldaction);
2238 if (oldaction.sa_handler == SIG_DFL)
2239 sigaction(SIGHUP, &action, NULL);
2242 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2243 quiet mode, report the number of packets we've captured.
2245 Again, restart any read that was in progress, so that it doesn't
2246 disrupt reading from the sync pipe. */
2247 action.sa_handler = report_counts_siginfo;
2248 action.sa_flags = SA_RESTART;
2249 sigemptyset(&action.sa_mask);
2250 sigaction(SIGINFO, &action, NULL);
2251 #endif /* SIGINFO */
2254 global_capture_session.state = CAPTURE_PREPARING;
2256 /* Let the user know which interfaces were chosen. */
2257 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2258 interface_options interface_opts;
2260 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
2261 interface_opts.descr = get_interface_descriptive_name(interface_opts.name);
2262 global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
2263 g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
2265 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2266 if (really_quiet == FALSE)
2267 fprintf(stderr, "Capturing on %s\n", str->str);
2269 g_string_free(str, TRUE);
2271 ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2276 /* the actual capture loop
2278 * XXX - glib doesn't seem to provide any event based loop handling.
2280 * XXX - for whatever reason,
2281 * calling g_main_loop_new() ends up in 100% cpu load.
2283 * But that doesn't matter: in UNIX we can use select() to find an input
2284 * source with something to do.
2286 * But that doesn't matter because we're in a CLI (that doesn't need to
2287 * update a GUI or something at the same time) so it's OK if we block
2288 * trying to read from the pipe.
2290 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2291 * wrong (but I leave it there in case I am...).
2294 #ifdef USE_TSHARK_SELECT
2296 FD_SET(pipe_input.source, &readfds);
2299 loop_running = TRUE;
2303 while (loop_running)
2305 #ifdef USE_TSHARK_SELECT
2306 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2310 fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2312 } else if (ret == 1) {
2314 /* Call the real handler */
2315 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2316 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2319 #ifdef USE_TSHARK_SELECT
2324 CATCH(OutOfMemoryError) {
2328 "Sorry, but TShark has to terminate now.\n"
2330 "More information and workarounds can be found at\n"
2331 "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2338 /* capture child detected an error */
2340 capture_input_error_message(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2342 cmdarg_err("%s", error_msg);
2343 cmdarg_err_cont("%s", secondary_error_msg);
2347 /* capture child detected an capture filter related error */
2349 capture_input_cfilter_error_message(capture_session *cap_session, guint i, char *error_message)
2351 capture_options *capture_opts = cap_session->capture_opts;
2352 dfilter_t *rfcode = NULL;
2353 interface_options interface_opts;
2355 g_assert(i < capture_opts->ifaces->len);
2356 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2358 if (dfilter_compile(interface_opts.cfilter, &rfcode, NULL) && rfcode != NULL) {
2360 "Invalid capture filter \"%s\" for interface '%s'.\n"
2362 "That string looks like a valid display filter; however, it isn't a valid\n"
2363 "capture filter (%s).\n"
2365 "Note that display filters and capture filters don't have the same syntax,\n"
2366 "so you can't use most display filter expressions as capture filters.\n"
2368 "See the User's Guide for a description of the capture filter syntax.",
2369 interface_opts.cfilter, interface_opts.descr, error_message);
2370 dfilter_free(rfcode);
2373 "Invalid capture filter \"%s\" for interface '%s'.\n"
2375 "That string isn't a valid capture filter (%s).\n"
2376 "See the User's Guide for a description of the capture filter syntax.",
2377 interface_opts.cfilter, interface_opts.descr, error_message);
2382 /* capture child tells us we have a new (or the first) capture file */
2384 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2386 capture_options *capture_opts = cap_session->capture_opts;
2387 capture_file *cf = (capture_file *) cap_session->cf;
2388 gboolean is_tempfile;
2391 if (cap_session->state == CAPTURE_PREPARING) {
2392 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2394 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2396 g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2398 /* free the old filename */
2399 if (capture_opts->save_file != NULL) {
2401 /* we start a new capture file, close the old one (if we had one before) */
2402 if (cf->state != FILE_CLOSED) {
2403 if (cf->wth != NULL) {
2404 wtap_close(cf->wth);
2407 cf->state = FILE_CLOSED;
2410 g_free(capture_opts->save_file);
2411 is_tempfile = FALSE;
2413 epan_free(cf->epan);
2414 cf->epan = tshark_epan_new(cf);
2416 /* we didn't had a save_file before, must be a tempfile */
2420 /* save the new filename */
2421 capture_opts->save_file = g_strdup(new_file);
2423 /* if we are in real-time mode, open the new file now */
2424 if (do_dissection) {
2425 /* this is probably unecessary, but better safe than sorry */
2426 ((capture_file *)cap_session->cf)->open_type = WTAP_TYPE_AUTO;
2427 /* Attempt to open the capture file and set up to read from it. */
2428 switch(cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2432 /* Don't unlink (delete) the save file - leave it around,
2433 for debugging purposes. */
2434 g_free(capture_opts->save_file);
2435 capture_opts->save_file = NULL;
2440 cap_session->state = CAPTURE_RUNNING;
2446 /* capture child tells us we have new packets to read */
2448 capture_input_new_packets(capture_session *cap_session, int to_read)
2454 capture_file *cf = (capture_file *)cap_session->cf;
2455 gboolean filtering_tap_listeners;
2460 * Prevent a SIGINFO handler from writing to the standard error while
2461 * we're doing so or writing to the standard output; instead, have it
2462 * just set a flag telling us to print that information when we're done.
2465 #endif /* SIGINFO */
2467 /* Do we have any tap listeners with filters? */
2468 filtering_tap_listeners = have_filtering_tap_listeners();
2470 /* Get the union of the flags for all tap listeners. */
2471 tap_flags = union_of_tap_listener_flags();
2473 if (do_dissection) {
2474 gboolean create_proto_tree;
2475 epan_dissect_t *edt;
2477 if (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2478 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2479 create_proto_tree = TRUE;
2481 create_proto_tree = FALSE;
2483 /* The protocol tree will be "visible", i.e., printed, only if we're
2484 printing packet details, which is true if we're printing stuff
2485 ("print_packet_info" is true) and we're in verbose mode
2486 ("packet_details" is true). */
2487 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2489 while (to_read-- && cf->wth) {
2490 wtap_cleareof(cf->wth);
2491 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2493 /* read from file failed, tell the capture child to stop */
2494 sync_pipe_stop(cap_session);
2495 wtap_close(cf->wth);
2498 ret = process_packet(cf, edt, data_offset, wtap_phdr(cf->wth),
2499 wtap_buf_ptr(cf->wth),
2503 /* packet successfully read and gone through the "Read Filter" */
2508 epan_dissect_free(edt);
2512 * Dumpcap's doing all the work; we're not doing any dissection.
2513 * Count all the packets it wrote.
2515 packet_count += to_read;
2518 if (print_packet_counts) {
2519 /* We're printing packet counts. */
2520 if (packet_count != 0) {
2521 fprintf(stderr, "\r%u ", packet_count);
2522 /* stderr could be line buffered */
2529 * Allow SIGINFO handlers to write.
2534 * If a SIGINFO handler asked us to write out capture counts, do so.
2538 #endif /* SIGINFO */
2544 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2545 /* Report the count only if we aren't printing a packet count
2546 as packets arrive. */
2547 fprintf(stderr, "%u packet%s captured\n", packet_count,
2548 plurality(packet_count, "", "s"));
2551 infoprint = FALSE; /* we just reported it */
2552 #endif /* SIGINFO */
2557 report_counts_siginfo(int signum _U_)
2559 int sav_errno = errno;
2560 /* If we've been told to delay printing, just set a flag asking
2561 that we print counts (if we're supposed to), otherwise print
2562 the count of packets captured (if we're supposed to). */
2569 #endif /* SIGINFO */
2572 /* capture child detected any packet drops? */
2574 capture_input_drops(capture_session *cap_session _U_, guint32 dropped)
2576 if (print_packet_counts) {
2577 /* We're printing packet counts to stderr.
2578 Send a newline so that we move to the line after the packet count. */
2579 fprintf(stderr, "\n");
2583 /* We're printing packet counts to stderr.
2584 Send a newline so that we move to the line after the packet count. */
2585 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2591 * Capture child closed its side of the pipe, report any error and
2592 * do the required cleanup.
2595 capture_input_closed(capture_session *cap_session, gchar *msg)
2597 capture_file *cf = (capture_file *) cap_session->cf;
2600 fprintf(stderr, "tshark: %s\n", msg);
2604 if (cf != NULL && cf->wth != NULL) {
2605 wtap_close(cf->wth);
2606 if (cf->is_tempfile) {
2607 ws_unlink(cf->filename);
2610 #ifdef USE_BROKEN_G_MAIN_LOOP
2611 /*g_main_loop_quit(loop);*/
2612 g_main_loop_quit(loop);
2614 loop_running = FALSE;
2623 capture_cleanup(DWORD ctrltype _U_)
2625 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2626 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2627 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2628 like SIGTERM at least when the machine's shutting down.
2630 For now, we handle them all as indications that we should clean up
2631 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2634 We must return TRUE so that no other handler - such as one that would
2635 terminate the process - gets called.
2637 XXX - for some reason, typing ^C to TShark, if you run this in
2638 a Cygwin console window in at least some versions of Cygwin,
2639 causes TShark to terminate immediately; this routine gets
2640 called, but the main loop doesn't get a chance to run and
2641 exit cleanly, at least if this is compiled with Microsoft Visual
2642 C++ (i.e., it's a property of the Cygwin console window or Bash;
2643 it happens if TShark is not built with Cygwin - for all I know,
2644 building it with Cygwin may make the problem go away). */
2646 /* tell the capture child to stop */
2647 sync_pipe_stop(&global_capture_session);
2649 /* don't stop our own loop already here, otherwise status messages and
2650 * cleanup wouldn't be done properly. The child will indicate the stop of
2651 * everything by calling capture_input_closed() later */
2657 capture_cleanup(int signum _U_)
2659 /* tell the capture child to stop */
2660 sync_pipe_stop(&global_capture_session);
2662 /* don't stop our own loop already here, otherwise status messages and
2663 * cleanup wouldn't be done properly. The child will indicate the stop of
2664 * everything by calling capture_input_closed() later */
2667 #endif /* HAVE_LIBPCAP */
2670 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2671 gint64 offset, struct wtap_pkthdr *whdr,
2678 /* The frame number of this packet is one more than the count of
2679 frames in this packet. */
2680 framenum = cf->count + 1;
2682 /* If we're not running a display filter and we're not printing any
2683 packet information, we don't need to do a dissection. This means
2684 that all packets can be marked as 'passed'. */
2687 frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
2689 /* If we're going to print packet information, or we're going to
2690 run a read filter, or display filter, or we're going to process taps, set up to
2691 do a dissection and do so. */
2693 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2694 gbl_resolv_flags.transport_name)
2695 /* Grab any resolved addresses */
2696 host_name_lookup_process();
2698 /* If we're running a read filter, prime the epan_dissect_t with that
2701 epan_dissect_prime_dfilter(edt, cf->rfcode);
2704 epan_dissect_prime_dfilter(edt, cf->dfcode);
2706 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2708 if (ref == &fdlocal) {
2709 ref_frame = fdlocal;
2713 epan_dissect_run(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdlocal, pd), &fdlocal, NULL);
2715 /* Run the read filter if we have one. */
2717 passed = dfilter_apply_edt(cf->rfcode, edt);
2721 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2722 prev_cap = prev_dis = frame_data_sequence_add(cf->frames, &fdlocal);
2724 /* If we're not doing dissection then there won't be any dependent frames.
2725 * More importantly, edt.pi.dependent_frames won't be initialized because
2726 * epan hasn't been initialized.
2727 * if we *are* doing dissection, then mark the dependent frames, but only
2728 * if a display filter was given and it matches this packet.
2730 if (edt && cf->dfcode) {
2731 if (dfilter_apply_edt(cf->dfcode, edt)) {
2732 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
2738 /* if we don't add it to the frame_data_sequence, clean it up right now
2740 frame_data_destroy(&fdlocal);
2744 epan_dissect_reset(edt);
2750 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt, frame_data *fdata,
2751 struct wtap_pkthdr *phdr, Buffer *buf,
2757 /* If we're not running a display filter and we're not printing any
2758 packet information, we don't need to do a dissection. This means
2759 that all packets can be marked as 'passed'. */
2762 /* If we're going to print packet information, or we're going to
2763 run a read filter, or we're going to process taps, set up to
2764 do a dissection and do so. */
2766 if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2767 gbl_resolv_flags.transport_name)
2768 /* Grab any resolved addresses */
2769 host_name_lookup_process();
2771 /* If we're running a display filter, prime the epan_dissect_t with that
2774 epan_dissect_prime_dfilter(edt, cf->dfcode);
2776 col_custom_prime_edt(edt, &cf->cinfo);
2778 /* We only need the columns if either
2779 1) some tap needs the columns
2781 2) we're printing packet info but we're *not* verbose; in verbose
2782 mode, we print the protocol tree, not the protocol summary.
2784 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
2789 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2796 epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new_buffer(fdata, buf), fdata, cinfo);
2798 /* Run the read/display filter if we have one. */
2800 passed = dfilter_apply_edt(cf->dfcode, edt);
2804 frame_data_set_after_dissect(fdata, &cum_bytes);
2805 /* Process this packet. */
2806 if (print_packet_info) {
2807 /* We're printing packet information; print the information for
2809 print_packet(cf, edt);
2811 /* The ANSI C standard does not appear to *require* that a line-buffered
2812 stream be flushed to the host environment whenever a newline is
2813 written, it just says that, on such a stream, characters "are
2814 intended to be transmitted to or from the host environment as a
2815 block when a new-line character is encountered".
2817 The Visual C++ 6.0 C implementation doesn't do what is intended;
2818 even if you set a stream to be line-buffered, it still doesn't
2819 flush the buffer at the end of every line.
2821 So, if the "-l" flag was specified, we flush the standard output
2822 at the end of a packet. This will do the right thing if we're
2823 printing packet summary lines, and, as we print the entire protocol
2824 tree for a single packet without waiting for anything to happen,
2825 it should be as good as line-buffered mode if we're printing
2826 protocol trees. (The whole reason for the "-l" flag in either
2827 tcpdump or TShark is to allow the output of a live capture to
2828 be piped to a program or script and to have that script see the
2829 information for the packet as soon as it's printed, rather than
2830 having to wait until a standard I/O buffer fills up. */
2834 if (ferror(stdout)) {
2835 show_print_file_io_error(errno);
2844 epan_dissect_reset(edt);
2846 return passed || fdata->flags.dependent_of_displayed;
2850 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2851 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
2854 int snapshot_length;
2858 gchar *err_info = NULL;
2860 char *save_file_string = NULL;
2861 gboolean filtering_tap_listeners;
2863 GArray *shb_hdrs = NULL;
2864 wtapng_iface_descriptions_t *idb_inf = NULL;
2865 GArray *nrb_hdrs = NULL;
2866 struct wtap_pkthdr phdr;
2868 epan_dissect_t *edt = NULL;
2869 char *shb_user_appl;
2871 wtap_phdr_init(&phdr);
2873 idb_inf = wtap_file_get_idb_info(cf->wth);
2874 #ifdef PCAP_NG_DEFAULT
2875 if (idb_inf->interface_data->len > 1) {
2876 linktype = WTAP_ENCAP_PER_PACKET;
2878 linktype = wtap_file_encap(cf->wth);
2881 linktype = wtap_file_encap(cf->wth);
2883 if (save_file != NULL) {
2884 /* Get a string that describes what we're writing to */
2885 save_file_string = output_file_description(save_file);
2887 /* Set up to write to the capture file. */
2888 snapshot_length = wtap_snapshot_length(cf->wth);
2889 if (snapshot_length == 0) {
2890 /* Snapshot length of input file not known. */
2891 snapshot_length = WTAP_MAX_PACKET_SIZE;
2893 tshark_debug("tshark: snapshot_length = %d", snapshot_length);
2895 shb_hdrs = wtap_file_get_shb_for_new_file(cf->wth);
2896 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->wth);
2898 /* If we don't have an application name add Tshark */
2899 if (wtap_block_get_string_option_value(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
2900 /* this is free'd by wtap_block_free() later */
2901 wtap_block_add_string_option_format(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "TShark (Wireshark) %s", get_ws_vcs_version_info());
2904 if (linktype != WTAP_ENCAP_PER_PACKET &&
2905 out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAP) {
2906 tshark_debug("tshark: writing PCAP format to %s", save_file);
2907 if (strcmp(save_file, "-") == 0) {
2908 /* Write to the standard output. */
2909 pdh = wtap_dump_open_stdout(out_file_type, linktype,
2910 snapshot_length, FALSE /* compressed */, &err);
2912 pdh = wtap_dump_open(save_file, out_file_type, linktype,
2913 snapshot_length, FALSE /* compressed */, &err);
2917 tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
2918 if (strcmp(save_file, "-") == 0) {
2919 /* Write to the standard output. */
2920 pdh = wtap_dump_open_stdout_ng(out_file_type, linktype,
2921 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
2923 pdh = wtap_dump_open_ng(save_file, out_file_type, linktype,
2924 snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
2932 /* We couldn't set up to write to the capture file. */
2935 case WTAP_ERR_UNWRITABLE_FILE_TYPE:
2936 cmdarg_err("Capture files can't be written in that format.");
2939 case WTAP_ERR_UNWRITABLE_ENCAP:
2940 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2941 cmdarg_err("The capture file being read can't be written as a "
2942 "\"%s\" file.", wtap_file_type_subtype_short_string(out_file_type));
2945 case WTAP_ERR_CANT_OPEN:
2946 cmdarg_err("The %s couldn't be created for some "
2947 "unknown reason.", save_file_string);
2950 case WTAP_ERR_SHORT_WRITE:
2951 cmdarg_err("A full header couldn't be written to the %s.",
2956 cmdarg_err("The %s could not be created: %s.", save_file_string,
2957 wtap_strerror(err));
2963 if (print_packet_info) {
2964 if (!write_preamble(cf)) {
2966 show_print_file_io_error(err);
2975 /* Do we have any tap listeners with filters? */
2976 filtering_tap_listeners = have_filtering_tap_listeners();
2978 /* Get the union of the flags for all tap listeners. */
2979 tap_flags = union_of_tap_listener_flags();
2981 if (perform_two_pass_analysis) {
2984 tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
2986 /* Allocate a frame_data_sequence for all the frames. */
2987 cf->frames = new_frame_data_sequence();
2989 if (do_dissection) {
2990 gboolean create_proto_tree = FALSE;
2992 /* If we're going to be applying a filter, we'll need to
2993 create a protocol tree against which to apply the filter. */
2994 if (cf->rfcode || cf->dfcode)
2995 create_proto_tree = TRUE;
2997 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
2999 /* We're not going to display the protocol tree on this pass,
3000 so it's not going to be "visible". */
3001 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
3004 tshark_debug("tshark: reading records for first pass");
3005 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
3006 if (process_packet_first_pass(cf, edt, data_offset, wtap_phdr(cf->wth),
3007 wtap_buf_ptr(cf->wth))) {
3008 /* Stop reading if we have the maximum number of packets;
3009 * When the -c option has not been used, max_packet_count
3010 * starts at 0, which practically means, never stop reading.
3011 * (unless we roll over max_packet_count ?)
3013 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3014 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3015 max_packet_count, data_offset, max_byte_count);
3016 err = 0; /* This is not an error */
3023 epan_dissect_free(edt);
3027 /* Close the sequential I/O side, to free up memory it requires. */
3028 wtap_sequential_close(cf->wth);
3030 /* Allow the protocol dissectors to free up memory that they
3031 * don't need after the sequential run-through of the packets. */
3032 postseq_cleanup_all_protocols();
3036 ws_buffer_init(&buf, 1500);
3038 tshark_debug("tshark: done with first pass");
3040 if (do_dissection) {
3041 gboolean create_proto_tree;
3043 if (cf->dfcode || print_details || filtering_tap_listeners ||
3044 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3045 create_proto_tree = TRUE;
3047 create_proto_tree = FALSE;
3049 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3051 /* The protocol tree will be "visible", i.e., printed, only if we're
3052 printing packet details, which is true if we're printing stuff
3053 ("print_packet_info" is true) and we're in verbose mode
3054 ("packet_details" is true). */
3055 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3058 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
3059 fdata = frame_data_sequence_find(cf->frames, framenum);
3060 if (wtap_seek_read(cf->wth, fdata->file_off, &phdr, &buf, &err,
3062 tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3063 if (process_packet_second_pass(cf, edt, fdata, &phdr, &buf,
3065 /* Either there's no read filtering or this packet passed the
3066 filter, so, if we're writing to a capture file, write
3069 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3070 if (!wtap_dump(pdh, &phdr, ws_buffer_start_ptr(&buf), &err, &err_info)) {
3071 /* Error writing to a capture file */
3072 tshark_debug("tshark: error writing to a capture file (%d)", err);
3075 case WTAP_ERR_UNWRITABLE_ENCAP:
3077 * This is a problem with the particular frame we're writing
3078 * and the file type and subtype we're writing; note that,
3079 * and report the frame number and file type/subtype.
3081 * XXX - framenum is not necessarily the frame number in
3082 * the input file if there was a read filter.
3085 "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
3086 framenum, cf->filename,
3087 wtap_file_type_subtype_short_string(out_file_type));
3090 case WTAP_ERR_PACKET_TOO_LARGE:
3092 * This is a problem with the particular frame we're writing
3093 * and the file type and subtype we're writing; note that,
3094 * and report the frame number and file type/subtype.
3096 * XXX - framenum is not necessarily the frame number in
3097 * the input file if there was a read filter.
3100 "Frame %u of \"%s\" is too large for a \"%s\" file.\n",
3101 framenum, cf->filename,
3102 wtap_file_type_subtype_short_string(out_file_type));
3105 case WTAP_ERR_UNWRITABLE_REC_TYPE:
3107 * This is a problem with the particular record we're writing
3108 * and the file type and subtype we're writing; note that,
3109 * and report the record number and file type/subtype.
3111 * XXX - framenum is not necessarily the record number in
3112 * the input file if there was a read filter.
3115 "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
3116 framenum, cf->filename,
3117 wtap_file_type_subtype_short_string(out_file_type));
3120 case WTAP_ERR_UNWRITABLE_REC_DATA:
3122 * This is a problem with the particular record we're writing
3123 * and the file type and subtype we're writing; note that,
3124 * and report the record number and file type/subtype.
3126 * XXX - framenum is not necessarily the record number in
3127 * the input file if there was a read filter.
3130 "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
3131 framenum, cf->filename,
3132 wtap_file_type_subtype_short_string(out_file_type),
3133 err_info != NULL ? err_info : "no information supplied");
3138 show_capture_file_io_error(save_file, err, FALSE);
3141 wtap_dump_close(pdh, &err);
3142 wtap_block_array_free(shb_hdrs);
3143 wtap_block_array_free(nrb_hdrs);
3152 epan_dissect_free(edt);
3156 ws_buffer_free(&buf);
3158 tshark_debug("tshark: done with second pass");
3161 /* !perform_two_pass_analysis */
3164 tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3166 if (do_dissection) {
3167 gboolean create_proto_tree;
3169 if (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3170 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3171 create_proto_tree = TRUE;
3173 create_proto_tree = FALSE;
3175 tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3177 /* The protocol tree will be "visible", i.e., printed, only if we're
3178 printing packet details, which is true if we're printing stuff
3179 ("print_packet_info" is true) and we're in verbose mode
3180 ("packet_details" is true). */
3181 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3184 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
3187 tshark_debug("tshark: processing packet #%d", framenum);
3189 if (process_packet(cf, edt, data_offset, wtap_phdr(cf->wth),
3190 wtap_buf_ptr(cf->wth),
3192 /* Either there's no read filtering or this packet passed the
3193 filter, so, if we're writing to a capture file, write
3196 tshark_debug("tshark: writing packet #%d to outfile", framenum);
3197 if (!wtap_dump(pdh, wtap_phdr(cf->wth), wtap_buf_ptr(cf->wth), &err, &err_info)) {
3198 /* Error writing to a capture file */
3199 tshark_debug("tshark: error writing to a capture file (%d)", err);
3202 case WTAP_ERR_UNWRITABLE_ENCAP:
3204 * This is a problem with the particular frame we're writing
3205 * and the file type and subtype we're writing; note that,
3206 * and report the frame number and file type/subtype.
3209 "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
3210 framenum, cf->filename,
3211 wtap_file_type_subtype_short_string(out_file_type));
3214 case WTAP_ERR_PACKET_TOO_LARGE:
3216 * This is a problem with the particular frame we're writing
3217 * and the file type and subtype we're writing; note that,
3218 * and report the frame number and file type/subtype.
3221 "Frame %u of \"%s\" is too large for a \"%s\" file.\n",
3222 framenum, cf->filename,
3223 wtap_file_type_subtype_short_string(out_file_type));
3226 case WTAP_ERR_UNWRITABLE_REC_TYPE:
3228 * This is a problem with the particular record we're writing
3229 * and the file type and subtype we're writing; note that,
3230 * and report the record number and file type/subtype.
3233 "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
3234 framenum, cf->filename,
3235 wtap_file_type_subtype_short_string(out_file_type));
3238 case WTAP_ERR_UNWRITABLE_REC_DATA:
3240 * This is a problem with the particular record we're writing
3241 * and the file type and subtype we're writing; note that,
3242 * and report the record number and file type/subtype.
3245 "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
3246 framenum, cf->filename,
3247 wtap_file_type_subtype_short_string(out_file_type),
3248 err_info != NULL ? err_info : "no information supplied");
3253 show_capture_file_io_error(save_file, err, FALSE);
3256 wtap_dump_close(pdh, &err);
3257 wtap_block_array_free(shb_hdrs);
3258 wtap_block_array_free(nrb_hdrs);
3263 /* Stop reading if we have the maximum number of packets;
3264 * When the -c option has not been used, max_packet_count
3265 * starts at 0, which practically means, never stop reading.
3266 * (unless we roll over max_packet_count ?)
3268 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3269 tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3270 max_packet_count, data_offset, max_byte_count);
3271 err = 0; /* This is not an error */
3277 epan_dissect_free(edt);
3282 wtap_phdr_cleanup(&phdr);
3285 tshark_debug("tshark: something failed along the line (%d)", err);
3287 * Print a message noting that the read failed somewhere along the line.
3289 * If we're printing packet data, and the standard output and error are
3290 * going to the same place, flush the standard output, so everything
3291 * buffered up is written, and then print a newline to the standard error
3292 * before printing the error message, to separate it from the packet
3293 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
3294 * the _fstat() documentation at Microsoft doesn't indicate whether
3295 * st_ino is even supported.)
3298 if (print_packet_info) {
3299 ws_statb64 stat_stdout, stat_stderr;
3301 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3302 if (stat_stdout.st_dev == stat_stderr.st_dev &&
3303 stat_stdout.st_ino == stat_stderr.st_ino) {
3305 fprintf(stderr, "\n");
3312 case WTAP_ERR_UNSUPPORTED:
3313 cmdarg_err("The file \"%s\" contains record data that TShark doesn't support.\n(%s)",
3315 err_info != NULL ? err_info : "no information supplied");
3319 case WTAP_ERR_SHORT_READ:
3320 cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
3324 case WTAP_ERR_BAD_FILE:
3325 cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
3327 err_info != NULL ? err_info : "no information supplied");
3331 case WTAP_ERR_DECOMPRESS:
3332 cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
3333 "(%s)", cf->filename,
3334 err_info != NULL ? err_info : "no information supplied");
3339 cmdarg_err("An error occurred while reading the file \"%s\": %s.",
3340 cf->filename, wtap_strerror(err));
3343 if (save_file != NULL) {
3344 /* Now close the capture file. */
3345 if (!wtap_dump_close(pdh, &err))
3346 show_capture_file_io_error(save_file, err, TRUE);
3349 if (save_file != NULL) {
3350 if (pdh && out_file_name_res) {
3351 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3352 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3353 wtap_file_type_subtype_short_string(out_file_type));
3356 /* Now close the capture file. */
3357 if (!wtap_dump_close(pdh, &err))
3358 show_capture_file_io_error(save_file, err, TRUE);
3360 if (print_packet_info) {
3361 if (!write_finale()) {
3363 show_print_file_io_error(err);
3370 wtap_close(cf->wth);
3373 g_free(save_file_string);
3374 wtap_block_array_free(shb_hdrs);
3375 wtap_block_array_free(nrb_hdrs);
3381 process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset, struct wtap_pkthdr *whdr,
3382 const guchar *pd, guint tap_flags)
3388 /* Count this packet. */
3391 /* If we're not running a display filter and we're not printing any
3392 packet information, we don't need to do a dissection. This means
3393 that all packets can be marked as 'passed'. */
3396 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
3398 /* If we're going to print packet information, or we're going to
3399 run a read filter, or we're going to process taps, set up to
3400 do a dissection and do so. */
3402 if (print_packet_info && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
3403 gbl_resolv_flags.transport_name))
3404 /* Grab any resolved addresses */
3405 host_name_lookup_process();
3407 /* If we're running a filter, prime the epan_dissect_t with that
3410 epan_dissect_prime_dfilter(edt, cf->dfcode);
3412 col_custom_prime_edt(edt, &cf->cinfo);
3414 /* We only need the columns if either
3415 1) some tap needs the columns
3417 2) we're printing packet info but we're *not* verbose; in verbose
3418 mode, we print the protocol tree, not the protocol summary.
3420 3) there is a column mapped as an individual field */
3421 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3426 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3428 if (ref == &fdata) {
3433 epan_dissect_run_with_taps(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdata, pd), &fdata, cinfo);
3435 /* Run the filter if we have it. */
3437 passed = dfilter_apply_edt(cf->dfcode, edt);
3441 frame_data_set_after_dissect(&fdata, &cum_bytes);
3443 /* Process this packet. */
3444 if (print_packet_info) {
3445 /* We're printing packet information; print the information for
3447 print_packet(cf, edt);
3449 /* The ANSI C standard does not appear to *require* that a line-buffered
3450 stream be flushed to the host environment whenever a newline is
3451 written, it just says that, on such a stream, characters "are
3452 intended to be transmitted to or from the host environment as a
3453 block when a new-line character is encountered".
3455 The Visual C++ 6.0 C implementation doesn't do what is intended;
3456 even if you set a stream to be line-buffered, it still doesn't
3457 flush the buffer at the end of every line.
3459 So, if the "-l" flag was specified, we flush the standard output
3460 at the end of a packet. This will do the right thing if we're
3461 printing packet summary lines, and, as we print the entire protocol
3462 tree for a single packet without waiting for anything to happen,
3463 it should be as good as line-buffered mode if we're printing
3464 protocol trees. (The whole reason for the "-l" flag in either
3465 tcpdump or TShark is to allow the output of a live capture to
3466 be piped to a program or script and to have that script see the
3467 information for the packet as soon as it's printed, rather than
3468 having to wait until a standard I/O buffer fills up. */
3472 if (ferror(stdout)) {
3473 show_print_file_io_error(errno);
3478 /* this must be set after print_packet() [bug #8160] */
3479 prev_dis_frame = fdata;
3480 prev_dis = &prev_dis_frame;
3483 prev_cap_frame = fdata;
3484 prev_cap = &prev_cap_frame;
3487 epan_dissect_reset(edt);
3488 frame_data_destroy(&fdata);
3494 write_preamble(capture_file *cf)
3496 switch (output_action) {
3499 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3503 write_pdml_preamble(stdout, cf->filename);
3505 write_psml_preamble(&cf->cinfo, stdout);
3506 return !ferror(stdout);
3509 write_fields_preamble(output_fields, stdout);
3510 return !ferror(stdout);
3513 write_json_preamble(stdout);
3514 return !ferror(stdout);
3517 return !ferror(stdout);
3520 g_assert_not_reached();
3526 get_line_buf(size_t len)
3528 static char *line_bufp = NULL;
3529 static size_t line_buf_len = 256;
3530 size_t new_line_buf_len;
3532 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3533 new_line_buf_len *= 2)
3535 if (line_bufp == NULL) {
3536 line_buf_len = new_line_buf_len;
3537 line_bufp = (char *)g_malloc(line_buf_len + 1);
3539 if (new_line_buf_len > line_buf_len) {
3540 line_buf_len = new_line_buf_len;
3541 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3548 put_string(char *dest, const char *str, size_t str_len)
3550 memcpy(dest, str, str_len);
3551 dest[str_len] = '\0';
3555 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3559 for (i = str_len; i < str_with_spaces; i++)
3562 put_string(dest, str, str_len);
3566 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3570 memcpy(dest, str, str_len);
3571 for (i = str_len; i < str_with_spaces; i++)
3574 dest[str_with_spaces] = '\0';
3578 print_columns(capture_file *cf)
3585 col_item_t* col_item;
3587 line_bufp = get_line_buf(256);
3590 for (i = 0; i < cf->cinfo.num_cols; i++) {
3591 col_item = &cf->cinfo.columns[i];
3592 /* Skip columns not marked as visible. */
3593 if (!get_column_visible(i))
3595 switch (col_item->col_fmt) {
3597 column_len = col_len = strlen(col_item->col_data);
3600 line_bufp = get_line_buf(buf_offset + column_len);
3601 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3607 case COL_ABS_YMD_TIME: /* XXX - wider */
3608 case COL_ABS_YDOY_TIME: /* XXX - wider */
3610 case COL_UTC_YMD_TIME: /* XXX - wider */
3611 case COL_UTC_YDOY_TIME: /* XXX - wider */
3612 column_len = col_len = strlen(col_item->col_data);
3613 if (column_len < 10)
3615 line_bufp = get_line_buf(buf_offset + column_len);
3616 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3622 case COL_DEF_DL_SRC:
3623 case COL_RES_DL_SRC:
3624 case COL_UNRES_DL_SRC:
3625 case COL_DEF_NET_SRC:
3626 case COL_RES_NET_SRC:
3627 case COL_UNRES_NET_SRC:
3628 column_len = col_len = strlen(col_item->col_data);
3629 if (column_len < 12)
3631 line_bufp = get_line_buf(buf_offset + column_len);
3632 put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3638 case COL_DEF_DL_DST:
3639 case COL_RES_DL_DST:
3640 case COL_UNRES_DL_DST:
3641 case COL_DEF_NET_DST:
3642 case COL_RES_NET_DST:
3643 case COL_UNRES_NET_DST:
3644 column_len = col_len = strlen(col_item->col_data);
3645 if (column_len < 12)
3647 line_bufp = get_line_buf(buf_offset + column_len);
3648 put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3652 column_len = strlen(col_item->col_data);
3653 line_bufp = get_line_buf(buf_offset + column_len);
3654 put_string(line_bufp + buf_offset, col_item->col_data, column_len);
3657 buf_offset += column_len;
3658 if (i != cf->cinfo.num_cols - 1) {
3660 * This isn't the last column, so we need to print a
3661 * separator between this column and the next.
3663 * If we printed a network source and are printing a
3664 * network destination of the same type next, separate
3665 * them with a UTF-8 right arrow; if we printed a network
3666 * destination and are printing a network source of the same
3667 * type next, separate them with a UTF-8 left arrow;
3668 * otherwise separate them with a space.
3670 * We add enough space to the buffer for " \xe2\x86\x90 "
3671 * or " \xe2\x86\x92 ", even if we're only adding " ".
3673 line_bufp = get_line_buf(buf_offset + 5);
3674 switch (col_item->col_fmt) {
3679 switch (cf->cinfo.columns[i+1].col_fmt) {
3684 put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3689 put_string(line_bufp + buf_offset, " ", 1);
3695 case COL_DEF_DL_SRC:
3696 case COL_RES_DL_SRC:
3697 case COL_UNRES_DL_SRC:
3698 switch (cf->cinfo.columns[i+1].col_fmt) {
3700 case COL_DEF_DL_DST:
3701 case COL_RES_DL_DST:
3702 case COL_UNRES_DL_DST:
3703 put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3708 put_string(line_bufp + buf_offset, " ", 1);
3714 case COL_DEF_NET_SRC:
3715 case COL_RES_NET_SRC:
3716 case COL_UNRES_NET_SRC:
3717 switch (cf->cinfo.columns[i+1].col_fmt) {
3719 case COL_DEF_NET_DST:
3720 case COL_RES_NET_DST:
3721 case COL_UNRES_NET_DST:
3722 put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3727 put_string(line_bufp + buf_offset, " ", 1);
3736 switch (cf->cinfo.columns[i+1].col_fmt) {
3741 put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3746 put_string(line_bufp + buf_offset, " ", 1);
3752 case COL_DEF_DL_DST:
3753 case COL_RES_DL_DST:
3754 case COL_UNRES_DL_DST:
3755 switch (cf->cinfo.columns[i+1].col_fmt) {
3757 case COL_DEF_DL_SRC:
3758 case COL_RES_DL_SRC:
3759 case COL_UNRES_DL_SRC:
3760 put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3765 put_string(line_bufp + buf_offset, " ", 1);
3771 case COL_DEF_NET_DST:
3772 case COL_RES_NET_DST:
3773 case COL_UNRES_NET_DST:
3774 switch (cf->cinfo.columns[i+1].col_fmt) {
3776 case COL_DEF_NET_SRC:
3777 case COL_RES_NET_SRC:
3778 case COL_UNRES_NET_SRC:
3779 put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3784 put_string(line_bufp + buf_offset, " ", 1);
3791 put_string(line_bufp + buf_offset, " ", 1);
3797 return print_line(print_stream, 0, line_bufp);
3801 print_packet(capture_file *cf, epan_dissect_t *edt)
3803 print_args_t print_args;
3805 if (print_summary || output_fields_has_cols(output_fields)) {
3806 /* Just fill in the columns. */
3807 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3809 if (print_summary) {
3810 /* Now print them. */
3811 switch (output_action) {
3814 if (!print_columns(cf))
3819 write_psml_columns(edt, stdout);
3820 return !ferror(stdout);
3821 case WRITE_FIELDS: /*No non-verbose "fields" format */
3824 g_assert_not_reached();
3829 if (print_details) {
3830 /* Print the information in the protocol tree. */
3831 switch (output_action) {
3834 /* Only initialize the fields that are actually used in proto_tree_print.
3835 * This is particularly important for .range, as that's heap memory which
3836 * we would otherwise have to g_free().
3837 print_args.to_file = TRUE;
3838 print_args.format = print_format;
3839 print_args.print_summary = print_summary;
3840 print_args.print_formfeed = FALSE;
3841 packet_range_init(&print_args.range, &cfile);
3843 print_args.print_hex = print_hex;
3844 print_args.print_dissections = print_details ? print_dissections_expanded : print_dissections_none;
3846 if (!proto_tree_print(&print_args, edt, output_only_tables, print_stream))
3849 if (!print_line(print_stream, 0, separator))
3855 write_pdml_proto_tree(output_fields, protocolfilter, edt, stdout);
3857 return !ferror(stdout);
3859 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
3861 return !ferror(stdout);
3863 print_args.print_hex = print_hex;
3864 write_json_proto_tree(output_fields, &print_args, protocolfilter, edt, stdout);
3866 return !ferror(stdout);
3868 print_args.print_hex = print_hex;
3869 write_ek_proto_tree(output_fields, &print_args, protocolfilter, edt, stdout);
3871 return !ferror(stdout);
3875 if (print_summary || print_details) {
3876 if (!print_line(print_stream, 0, ""))
3879 if (!print_hex_data(print_stream, edt))
3881 if (!print_line(print_stream, 0, separator))
3890 switch (output_action) {
3893 return print_finale(print_stream);
3897 write_pdml_finale(stdout);
3899 write_psml_finale(stdout);
3900 return !ferror(stdout);
3903 write_fields_finale(output_fields, stdout);
3904 return !ferror(stdout);
3907 write_json_finale(stdout);
3908 return !ferror(stdout);
3911 return !ferror(stdout);
3914 g_assert_not_reached();
3920 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
3924 char err_msg[2048+1];
3926 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
3930 /* The open succeeded. Fill in the information for this file. */
3932 /* Create new epan session for dissection. */
3933 epan_free(cf->epan);
3934 cf->epan = tshark_epan_new(cf);
3937 cf->f_datalen = 0; /* not used, but set it anyway */
3939 /* Set the file name because we need it to set the follow stream filter.
3940 XXX - is that still true? We need it for other reasons, though,
3942 cf->filename = g_strdup(fname);
3944 /* Indicate whether it's a permanent or temporary file. */
3945 cf->is_tempfile = is_tempfile;
3947 /* No user changes yet. */
3948 cf->unsaved_changes = FALSE;
3950 cf->cd_t = wtap_file_type_subtype(cf->wth);
3951 cf->open_type = type;
3953 cf->drops_known = FALSE;
3955 cf->snap = wtap_snapshot_length(cf->wth);
3956 if (cf->snap == 0) {
3957 /* Snapshot length not known. */
3958 cf->has_snap = FALSE;
3959 cf->snap = WTAP_MAX_PACKET_SIZE;
3961 cf->has_snap = TRUE;
3962 nstime_set_zero(&cf->elapsed_time);
3967 cf->state = FILE_READ_IN_PROGRESS;
3969 wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
3970 wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
3975 g_snprintf(err_msg, sizeof err_msg,
3976 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3977 cmdarg_err("%s", err_msg);
3982 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3984 char *save_file_string;
3986 save_file_string = output_file_description(fname);
3991 cmdarg_err("Not all the packets could be written to the %s because there is "
3992 "no space left on the file system.",
3998 cmdarg_err("Not all the packets could be written to the %s because you are "
3999 "too close to, or over your disk quota.",
4004 case WTAP_ERR_CANT_CLOSE:
4005 cmdarg_err("The %s couldn't be closed for some unknown reason.",
4009 case WTAP_ERR_SHORT_WRITE:
4010 cmdarg_err("Not all the packets could be written to the %s.",
4016 cmdarg_err("The %s could not be closed: %s.", save_file_string,
4017 wtap_strerror(err));
4019 cmdarg_err("An error occurred while writing to the %s: %s.",
4020 save_file_string, wtap_strerror(err));
4024 g_free(save_file_string);
4028 show_print_file_io_error(int err)
4033 cmdarg_err("Not all the packets could be printed because there is "
4034 "no space left on the file system.");
4039 cmdarg_err("Not all the packets could be printed because you are "
4040 "too close to, or over your disk quota.");
4045 cmdarg_err("An error occurred while printing packets: %s.",
4052 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
4056 static char errmsg_errno[1024+1];
4059 /* Wiretap error. */
4062 case WTAP_ERR_NOT_REGULAR_FILE:
4063 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
4066 case WTAP_ERR_RANDOM_OPEN_PIPE:
4067 /* Seen only when opening a capture file for reading. */
4068 errmsg = "The file \"%s\" is a pipe or FIFO; TShark can't read pipe or FIFO files in two-pass mode.";
4071 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4072 /* Seen only when opening a capture file for reading. */
4073 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
4076 case WTAP_ERR_UNSUPPORTED:
4077 /* Seen only when opening a capture file for reading. */
4078 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4079 "The file \"%%s\" contains record data that TShark doesn't support.\n"
4081 err_info != NULL ? err_info : "no information supplied");
4083 errmsg = errmsg_errno;
4086 case WTAP_ERR_CANT_WRITE_TO_PIPE:
4087 /* Seen only when opening a capture file for writing. */
4088 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4089 "The file \"%%s\" is a pipe, and \"%s\" capture files can't be "
4090 "written to a pipe.", wtap_file_type_subtype_short_string(file_type));
4091 errmsg = errmsg_errno;
4094 case WTAP_ERR_UNWRITABLE_FILE_TYPE:
4095 /* Seen only when opening a capture file for writing. */
4096 errmsg = "TShark doesn't support writing capture files in that format.";
4099 case WTAP_ERR_UNWRITABLE_ENCAP:
4100 /* Seen only when opening a capture file for writing. */
4101 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4102 "TShark can't save this capture as a \"%s\" file.",
4103 wtap_file_type_subtype_short_string(file_type));
4104 errmsg = errmsg_errno;
4107 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4109 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4110 "TShark can't save this capture as a \"%s\" file.",
4111 wtap_file_type_subtype_short_string(file_type));
4112 errmsg = errmsg_errno;
4114 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
4117 case WTAP_ERR_BAD_FILE:
4118 /* Seen only when opening a capture file for reading. */
4119 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4120 "The file \"%%s\" appears to be damaged or corrupt.\n"
4122 err_info != NULL ? err_info : "no information supplied");
4124 errmsg = errmsg_errno;
4127 case WTAP_ERR_CANT_OPEN:
4129 errmsg = "The file \"%s\" could not be created for some unknown reason.";
4131 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
4134 case WTAP_ERR_SHORT_READ:
4135 errmsg = "The file \"%s\" appears to have been cut short"
4136 " in the middle of a packet or other data.";
4139 case WTAP_ERR_SHORT_WRITE:
4140 errmsg = "A full header couldn't be written to the file \"%s\".";
4143 case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4144 errmsg = "This file type cannot be written as a compressed file.";
4147 case WTAP_ERR_DECOMPRESS:
4148 /* Seen only when opening a capture file for reading. */
4149 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4150 "The compressed file \"%%s\" appears to be damaged or corrupt.\n"
4152 err_info != NULL ? err_info : "no information supplied");
4154 errmsg = errmsg_errno;
4158 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4159 "The file \"%%s\" could not be %s: %s.",
4160 for_writing ? "created" : "opened",
4161 wtap_strerror(err));
4162 errmsg = errmsg_errno;
4166 errmsg = file_open_error_message(err, for_writing);
4171 * Open/create errors are reported with an console message in TShark.
4174 open_failure_message(const char *filename, int err, gboolean for_writing)
4176 fprintf(stderr, "tshark: ");
4177 fprintf(stderr, file_open_error_message(err, for_writing), filename);
4178 fprintf(stderr, "\n");
4182 * General errors are reported with an console message in TShark.
4185 failure_message(const char *msg_format, va_list ap)
4187 fprintf(stderr, "tshark: ");
4188 vfprintf(stderr, msg_format, ap);
4189 fprintf(stderr, "\n");
4193 * Read errors are reported with an console message in TShark.
4196 read_failure_message(const char *filename, int err)
4198 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4199 filename, g_strerror(err));
4203 * Write errors are reported with an console message in TShark.
4206 write_failure_message(const char *filename, int err)
4208 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4209 filename, g_strerror(err));
4213 * Report additional information for an error in command-line arguments.
4216 failure_message_cont(const char *msg_format, va_list ap)
4218 vfprintf(stderr, msg_format, ap);
4219 fprintf(stderr, "\n");
4223 * Editor modelines - https://www.wireshark.org/tools/modelines.html
4228 * indent-tabs-mode: nil
4231 * vi: set shiftwidth=2 tabstop=8 expandtab:
4232 * :indentSize=2:tabSize=8:noTabs=true: