TODO netlogon_user_flags_ntlmv2_enabled
[wireshark-sm.git] / tfshark.c
blobd08ca78906701d1caa6921517e03d9afa31f7164
1 /* tfshark.c
3 * Text-mode variant of Fileshark, based off of TShark,
5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * SPDX-License-Identifier: GPL-2.0-or-later
12 #include <config.h>
14 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <locale.h>
20 #include <limits.h>
22 #include <ws_exit_codes.h>
23 #include <wsutil/ws_getopt.h>
25 #include <errno.h>
27 #include <glib.h>
29 #include <epan/exceptions.h>
30 #include <epan/epan.h>
32 #include <wsutil/clopts_common.h>
33 #include <wsutil/cmdarg_err.h>
34 #include <ui/urls.h>
35 #include <wsutil/filesystem.h>
36 #include <wsutil/file_util.h>
37 #include <wsutil/privileges.h>
38 #include <wsutil/wslog.h>
39 #include <wsutil/ws_assert.h>
40 #include <cli_main.h>
41 #include <wsutil/version_info.h>
43 #include "globals.h"
44 #include <epan/timestamp.h>
45 #include <epan/packet.h>
46 #ifdef HAVE_LUA
47 #include <epan/wslua/init_wslua.h>
48 #endif
49 #include "file.h"
50 #include <epan/disabled_protos.h>
51 #include <epan/prefs.h>
52 #include <epan/column.h>
53 #include <epan/print.h>
54 #include <epan/addr_resolv.h>
55 #include "ui/util.h"
56 #include "ui/decode_as_utils.h"
57 #include "ui/dissect_opts.h"
58 #include "ui/failure_message.h"
59 #include <epan/epan_dissect.h>
60 #include <epan/tap.h>
61 #include <epan/stat_tap_ui.h>
62 #include <epan/ex-opt.h>
64 #include <wiretap/wtap-int.h>
65 #include <wiretap/file_wrappers.h>
67 #include <epan/funnel.h>
69 #ifdef HAVE_PLUGINS
70 #include <wsutil/plugins.h>
71 #endif
73 /* Additional exit codes */
74 #define NO_FILE_SPECIFIED 1
76 capture_file cfile;
78 static uint32_t cum_bytes;
79 static frame_data ref_frame;
80 static frame_data prev_dis_frame;
81 static frame_data prev_cap_frame;
83 static bool prefs_loaded;
85 static bool perform_two_pass_analysis;
88 * The way the packet decode is to be written.
90 typedef enum {
91 WRITE_TEXT, /* summary or detail text */
92 WRITE_XML, /* PDML or PSML */
93 WRITE_FIELDS /* User defined list of fields */
94 /* Add CSV and the like here */
95 } output_action_e;
97 static output_action_e output_action;
98 static bool do_dissection; /* true if we have to dissect each packet */
99 static bool print_packet_info; /* true if we're to print packet information */
100 static int print_summary = -1; /* true if we're to print packet summary information */
101 static bool print_details; /* true if we're to print packet details information */
102 static bool print_hex; /* true if we're to print hex/ascii information */
103 static bool line_buffered;
104 static bool really_quiet;
106 static print_format_e print_format = PR_FMT_TEXT;
107 static print_stream_t *print_stream;
109 static output_fields_t* output_fields;
111 /* The line separator used between packets, changeable via the -S option */
112 static const char *separator = "";
114 static bool process_file(capture_file *);
115 static bool process_packet_single_pass(capture_file *cf,
116 epan_dissect_t *edt, int64_t offset, wtap_rec *rec);
117 static void show_print_file_io_error(int err);
118 static bool write_preamble(capture_file *cf);
119 static bool print_packet(capture_file *cf, epan_dissect_t *edt);
120 static bool write_finale(void);
122 static GHashTable *output_only_tables;
124 #if 0
125 struct string_elem {
126 const char *sstr; /* The short string */
127 const char *lstr; /* The long string */
130 static int
131 string_compare(const void *a, const void *b)
133 return strcmp(((const struct string_elem *)a)->sstr,
134 ((const struct string_elem *)b)->sstr);
137 static void
138 string_elem_print(void *data, void *not_used _U_)
140 fprintf(stderr, " %s - %s\n",
141 ((struct string_elem *)data)->sstr,
142 ((struct string_elem *)data)->lstr);
144 #endif
146 static void
147 print_usage(FILE *output)
149 fprintf(output, "\n");
150 fprintf(output, "Usage: tfshark [options] ...\n");
151 fprintf(output, "\n");
153 /*fprintf(output, "\n");*/
154 fprintf(output, "Input file:\n");
155 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin)\n");
157 fprintf(output, "\n");
158 fprintf(output, "Processing:\n");
159 fprintf(output, " -2 perform a two-pass analysis\n");
160 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
161 fprintf(output, " (requires -2)\n");
162 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
163 fprintf(output, " syntax\n");
164 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
165 fprintf(output, " \"Decode As\", see the man page for details\n");
166 fprintf(output, " Example: tcp.port==8888,http\n");
168 /*fprintf(output, "\n");*/
169 fprintf(output, "Output:\n");
170 fprintf(output, " -C <config profile> start with specified configuration profile\n");
171 fprintf(output, " -V add output of packet tree (Packet Details)\n");
172 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
173 fprintf(output, " separated\n");
174 fprintf(output, " -S <separator> the line separator to print between packets\n");
175 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
176 fprintf(output, " -T pdml|ps|psml|text|fields\n");
177 fprintf(output, " format of text output (def: text)\n");
178 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
179 fprintf(output, " _ws.col.info)\n");
180 fprintf(output, " this option can be repeated to print multiple fields\n");
181 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
182 fprintf(output, " header=y|n switch headers on and off\n");
183 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
184 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
185 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
186 fprintf(output, " aggregator\n");
187 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
188 fprintf(output, " -t a|ad|d|dd|e|r|u|ud output format of time stamps (def: r: rel. to first)\n");
189 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
190 fprintf(output, " -l flush standard output after each packet\n");
191 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
192 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
193 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
194 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
195 fprintf(output, "\n");
197 ws_log_print_usage(output);
198 fprintf(output, "\n");
200 fprintf(output, "Miscellaneous:\n");
201 fprintf(output, " -h display this help and exit\n");
202 fprintf(output, " -v display version info and exit\n");
203 fprintf(output, " -o <name>:<value> ... override preference setting\n");
204 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
205 fprintf(output, " -G [report] dump one of several available reports and exit\n");
206 fprintf(output, " default report=\"fields\"\n");
207 fprintf(output, " use \"-G ?\" for more help\n");
210 static void
211 glossary_option_help(void)
213 FILE *output;
215 output = stdout;
217 fprintf(output, "%s\n", get_appname_and_version());
219 fprintf(output, "\n");
220 fprintf(output, "Usage: tfshark -G [report]\n");
221 fprintf(output, "\n");
222 fprintf(output, "Glossary table reports:\n");
223 fprintf(output, " -G column-formats dump column format codes and exit\n");
224 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
225 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
226 fprintf(output, " -G fields dump fields glossary and exit\n");
227 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
228 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
229 fprintf(output, " -G plugins dump installed plugins and exit\n");
230 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
231 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
232 fprintf(output, "\n");
233 fprintf(output, "Preference reports:\n");
234 fprintf(output, " -G currentprefs dump current preferences and exit\n");
235 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
236 fprintf(output, "\n");
239 static void
240 print_current_user(void)
242 char *cur_user, *cur_group;
244 if (started_with_special_privs()) {
245 cur_user = get_cur_username();
246 cur_group = get_cur_groupname();
247 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
248 cur_user, cur_group);
249 g_free(cur_user);
250 g_free(cur_group);
251 if (running_with_special_privs()) {
252 fprintf(stderr, " This could be dangerous.");
254 fprintf(stderr, "\n");
259 main(int argc, char *argv[])
261 char *configuration_init_error;
262 int opt;
263 static const struct ws_option long_options[] = {
264 {"help", ws_no_argument, NULL, 'h'},
265 {"version", ws_no_argument, NULL, 'v'},
266 {0, 0, 0, 0 }
268 bool arg_error = false;
270 int err;
271 volatile bool success;
272 volatile int exit_status = 0;
273 bool quiet = false;
274 char *volatile cf_name = NULL;
275 char *rfilter = NULL;
276 char *dfilter = NULL;
277 dfilter_t *rfcode = NULL;
278 dfilter_t *dfcode = NULL;
279 df_error_t *df_err;
280 e_prefs *prefs_p;
281 char *output_only = NULL;
284 * The leading + ensures that getopt_long() does not permute the argv[]
285 * entries.
287 * We have to make sure that the first getopt_long() preserves the content
288 * of argv[] for the subsequent getopt_long() call.
290 * We use getopt_long() in both cases to ensure that we're using a routine
291 * whose permutation behavior we can control in the same fashion on all
292 * platforms, and so that, if we ever need to process a long argument before
293 * doing further initialization, we can do so.
295 * Glibc and Solaris libc document that a leading + disables permutation
296 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
297 * and macOS don't document it, but do so anyway.
299 * We do *not* use a leading - because the behavior of a leading - is
300 * platform-dependent.
302 #define OPTSTRING "+2C:d:e:E:hK:lo:O:qQr:R:S:t:T:u:vVxX:Y:z:"
304 static const char optstring[] = OPTSTRING;
306 /* Set the program name. */
307 g_set_prgname("tfshark");
310 * Set the C-language locale to the native environment and set the
311 * code page to UTF-8 on Windows.
313 #ifdef _WIN32
314 setlocale(LC_ALL, ".UTF-8");
315 #else
316 setlocale(LC_ALL, "");
317 #endif
319 cmdarg_err_init(stderr_cmdarg_err, stderr_cmdarg_err_cont);
321 /* Initialize log handler early so we can have proper logging during startup. */
322 ws_log_init(vcmdarg_err);
324 /* Early logging command-line initialization. */
325 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
327 ws_noisy("Finished log init and parsing command line log arguments");
329 #ifdef _WIN32
330 create_app_running_mutex();
331 #endif /* _WIN32 */
334 * Get credential information for later use, and drop privileges
335 * before doing anything else.
336 * Let the user know if anything happened.
338 init_process_policies();
339 relinquish_special_privs_perm();
340 print_current_user();
343 * Attempt to get the pathname of the directory containing the
344 * executable file.
346 configuration_init_error = configuration_init(argv[0]);
347 if (configuration_init_error != NULL) {
348 fprintf(stderr,
349 "tfshark: Can't get pathname of directory containing the tfshark program: %s.\n",
350 configuration_init_error);
351 g_free(configuration_init_error);
354 initialize_funnel_ops();
356 /* Initialize the version information. */
357 ws_init_version_info("TFShark",
358 epan_gather_compile_info,
359 epan_gather_runtime_info);
361 * In order to have the -X opts assigned before the wslua machine starts
362 * we need to call getopts before epan_init() gets called.
364 * In order to handle, for example, -o options, we also need to call it
365 * *after* epan_init() gets called, so that the dissectors have had a
366 * chance to register their preferences.
368 * XXX - can we do this all with one getopt_long() call, saving the
369 * arguments we can't handle until after initializing libwireshark,
370 * and then process them after initializing libwireshark?
372 ws_opterr = 0;
374 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
375 switch (opt) {
376 case 'C': /* Configuration Profile */
377 if (profile_exists (ws_optarg, false)) {
378 set_profile_name (ws_optarg);
379 } else if (profile_exists (ws_optarg, true)) {
380 char *pf_dir_path, *pf_dir_path2, *pf_filename;
381 /* Copy from global profile */
382 if (create_persconffile_profile(ws_optarg, &pf_dir_path) == -1) {
383 cmdarg_err("Can't create directory\n\"%s\":\n%s.",
384 pf_dir_path, g_strerror(errno));
386 g_free(pf_dir_path);
387 exit_status = WS_EXIT_INVALID_FILE;
388 goto clean_exit;
390 if (copy_persconffile_profile(ws_optarg, ws_optarg, true, &pf_filename,
391 &pf_dir_path, &pf_dir_path2) == -1) {
392 cmdarg_err("Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
393 pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno));
395 g_free(pf_filename);
396 g_free(pf_dir_path);
397 g_free(pf_dir_path2);
398 exit_status = WS_EXIT_INVALID_FILE;
399 goto clean_exit;
401 set_profile_name (ws_optarg);
402 } else {
403 cmdarg_err("Configuration Profile \"%s\" does not exist", ws_optarg);
404 return 1;
406 break;
407 case 'O': /* Only output these protocols */
408 output_only = g_strdup(ws_optarg);
409 /* FALLTHROUGH */
410 case 'V': /* Verbose */
411 print_details = true;
412 print_packet_info = true;
413 break;
414 case 'x': /* Print packet data in hex (and ASCII) */
415 print_hex = true;
416 /* The user asked for hex output, so let's ensure they get it,
417 * even if they're writing to a file.
419 print_packet_info = true;
420 break;
421 case 'X':
422 ex_opt_add(ws_optarg);
423 break;
424 default:
425 break;
430 * Print packet summary information is the default, unless either -V or -x
431 * were specified. Note that this is new behavior, which
432 * allows for the possibility of printing only hex/ascii output without
433 * necessarily requiring that either the summary or details be printed too.
435 if (print_summary == -1)
436 print_summary = (print_details || print_hex) ? false : true;
438 init_report_failure_message("tfshark");
440 timestamp_set_type(TS_RELATIVE);
441 timestamp_set_precision(TS_PREC_AUTO);
442 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
445 * Libwiretap must be initialized before libwireshark is, so that
446 * dissection-time handlers for file-type-dependent blocks can
447 * register using the file type/subtype value for the file type.
449 * XXX - TFShark shouldn't use libwiretap, as it's a file dissector
450 * and should read all files as raw bytes and then try to dissect them.
451 * It needs to handle file types its own way, because we would want
452 * to support dissecting file-type-specific blocks when dissecting
453 * capture files, but that mechanism should support plugins for
454 * other files, too, if *their* formats are extensible.
456 wtap_init(true);
458 /* Register all dissectors; we must do this before checking for the
459 "-G" flag, as the "-G" flag dumps information registered by the
460 dissectors, and we must do it before we read the preferences, in
461 case any dissectors register preferences. */
462 if (!epan_init(NULL, NULL, true)) {
463 exit_status = WS_EXIT_INIT_FAILED;
464 goto clean_exit;
467 /* Register all tap listeners; we do this before we parse the arguments,
468 as the "-z" argument can specify a registered tap. */
470 /* we register the plugin taps before the other taps because
471 stats_tree taps plugins will be registered as tap listeners
472 by stats_tree_stat.c and need to registered before that */
474 /* XXX Disable tap registration for now until we can get tfshark set up with
475 * its own set of taps and the necessary registration function etc.
476 register_all_tap_listeners();
479 /* If invoked with the "-G" flag, we dump out information based on
480 the argument to the "-G" flag; if no argument is specified,
481 for backwards compatibility we dump out a glossary of display
482 filter symbols.
484 XXX - we do this here, for now, to support "-G" with no arguments.
485 If none of our build or other processes uses "-G" with no arguments,
486 we can just process it with the other arguments. */
487 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
488 proto_initialize_all_prefixes();
490 if (argc == 2)
491 proto_registrar_dump_fields();
492 else {
493 if (strcmp(argv[2], "column-formats") == 0)
494 column_dump_column_formats();
495 else if (strcmp(argv[2], "currentprefs") == 0) {
496 epan_load_settings();
497 write_prefs(NULL);
499 else if (strcmp(argv[2], "decodes") == 0)
500 dissector_dump_decodes();
501 else if (strcmp(argv[2], "defaultprefs") == 0)
502 write_prefs(NULL);
503 else if (strcmp(argv[2], "dissector-tables") == 0)
504 dissector_dump_dissector_tables();
505 else if (strcmp(argv[2], "fields") == 0)
506 proto_registrar_dump_fields();
507 else if (strcmp(argv[2], "ftypes") == 0)
508 proto_registrar_dump_ftypes();
509 else if (strcmp(argv[2], "heuristic-decodes") == 0)
510 dissector_dump_heur_decodes();
511 else if (strcmp(argv[2], "plugins") == 0) {
512 #ifdef HAVE_PLUGINS
513 plugins_dump_all();
514 #endif
515 #ifdef HAVE_LUA
516 wslua_plugins_dump_all();
517 #endif
519 else if (strcmp(argv[2], "protocols") == 0)
520 proto_registrar_dump_protocols();
521 else if (strcmp(argv[2], "values") == 0)
522 proto_registrar_dump_values();
523 else if (strcmp(argv[2], "?") == 0)
524 glossary_option_help();
525 else if (strcmp(argv[2], "-?") == 0)
526 glossary_option_help();
527 else {
528 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
529 exit_status = WS_EXIT_INVALID_OPTION;
530 goto clean_exit;
533 goto clean_exit;
536 /* Load libwireshark settings from the current profile. */
537 prefs_p = epan_load_settings();
538 prefs_loaded = true;
540 cap_file_init(&cfile);
542 /* Print format defaults to this. */
543 print_format = PR_FMT_TEXT;
545 output_fields = output_fields_new();
548 * To reset the options parser, set ws_optreset to 1 and set ws_optind to 1.
550 * Also reset ws_opterr to 1, so that error messages are printed by
551 * getopt_long().
553 ws_optreset = 1;
554 ws_optind = 1;
555 ws_opterr = 1;
557 /* Now get our args */
558 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
559 switch (opt) {
560 case '2': /* Perform two-pass analysis */
561 perform_two_pass_analysis = true;
562 break;
563 case 'C':
564 /* already processed; just ignore it now */
565 break;
566 case 'e':
567 /* Field entry */
568 output_fields_add(output_fields, ws_optarg);
569 break;
570 case 'E':
571 /* Field option */
572 if (!output_fields_set_option(output_fields, ws_optarg)) {
573 cmdarg_err("\"%s\" is not a valid field output option=value pair.", ws_optarg);
574 output_fields_list_options(stderr);
575 exit_status = WS_EXIT_INVALID_OPTION;
576 goto clean_exit;
578 break;
580 case 'h': /* Print help and exit */
581 show_help_header("Analyze file structure.");
582 print_usage(stdout);
583 goto clean_exit;
584 break;
585 case 'l': /* "Line-buffer" standard output */
586 /* The ANSI C standard does not appear to *require* that a
587 line-buffered stream be flushed to the host environment
588 whenever a newline is written, it just says that, on such a
589 stream, characters "are intended to be transmitted to or
590 from the host environment as a block when a new-line
591 character is encountered".
593 The Visual C++ 6.0 C implementation doesn't do what is
594 intended; even if you set a stream to be line-buffered, it
595 still doesn't flush the buffer at the end of every line.
597 The whole reason for the "-l" flag in either tcpdump or
598 TShark is to allow the output of a live capture to be piped
599 to a program or script and to have that script see the
600 information for the packet as soon as it's printed, rather
601 than having to wait until a standard I/O buffer fills up.
603 So, if the "-l" flag is specified, we flush the standard
604 output at the end of a packet. This will do the right thing
605 if we're printing packet summary lines, and, as we print the
606 entire protocol tree for a single packet without waiting for
607 anything to happen, it should be as good as line-buffered
608 mode if we're printing protocol trees - arguably even
609 better, as it may do fewer writes. */
610 line_buffered = true;
611 break;
612 case 'o': /* Override preference from command line */
614 char *errmsg = NULL;
616 switch (prefs_set_pref(ws_optarg, &errmsg)) {
618 case PREFS_SET_OK:
619 break;
621 case PREFS_SET_SYNTAX_ERR:
622 cmdarg_err("Invalid -o flag \"%s\"%s%s", ws_optarg,
623 errmsg ? ": " : "", errmsg ? errmsg : "");
624 g_free(errmsg);
625 exit_status = WS_EXIT_INVALID_OPTION;
626 goto clean_exit;
627 break;
629 case PREFS_SET_NO_SUCH_PREF:
630 cmdarg_err("-o flag \"%s\" specifies unknown preference", ws_optarg);
631 exit_status = WS_EXIT_INVALID_OPTION;
632 goto clean_exit;
633 break;
635 case PREFS_SET_OBSOLETE:
636 cmdarg_err("-o flag \"%s\" specifies obsolete preference", ws_optarg);
637 exit_status = WS_EXIT_INVALID_OPTION;
638 goto clean_exit;
639 break;
641 break;
643 case 'q': /* Quiet */
644 quiet = true;
645 break;
646 case 'Q': /* Really quiet */
647 quiet = true;
648 really_quiet = true;
649 break;
650 case 'r': /* Read capture file x */
651 cf_name = g_strdup(ws_optarg);
652 break;
653 case 'R': /* Read file filter */
654 rfilter = ws_optarg;
655 break;
656 case 'S': /* Set the line Separator to be printed between packets */
657 separator = g_strdup(ws_optarg);
658 break;
659 case 'T': /* printing Type */
660 if (strcmp(ws_optarg, "text") == 0) {
661 output_action = WRITE_TEXT;
662 print_format = PR_FMT_TEXT;
663 } else if (strcmp(ws_optarg, "ps") == 0) {
664 output_action = WRITE_TEXT;
665 print_format = PR_FMT_PS;
666 } else if (strcmp(ws_optarg, "pdml") == 0) {
667 output_action = WRITE_XML;
668 print_details = true; /* Need details */
669 print_summary = false; /* Don't allow summary */
670 } else if (strcmp(ws_optarg, "psml") == 0) {
671 output_action = WRITE_XML;
672 print_details = false; /* Don't allow details */
673 print_summary = true; /* Need summary */
674 } else if (strcmp(ws_optarg, "fields") == 0) {
675 output_action = WRITE_FIELDS;
676 print_details = true; /* Need full tree info */
677 print_summary = false; /* Don't allow summary */
678 } else {
679 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", ws_optarg); /* x */
680 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
681 "\t specified by the -E option.\n"
682 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
683 "\t details of a decoded packet. This information is equivalent to\n"
684 "\t the packet details printed with the -V flag.\n"
685 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
686 "\t the packets, or a multi-line view of the details of each of\n"
687 "\t the packets, depending on whether the -V flag was specified.\n"
688 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
689 "\t summary information of a decoded packet. This information is\n"
690 "\t equivalent to the information shown in the one-line summary\n"
691 "\t printed by default.\n"
692 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
693 "\t packets, or a multi-line view of the details of each of the\n"
694 "\t packets, depending on whether the -V flag was specified.\n"
695 "\t This is the default.");
696 exit_status = WS_EXIT_INVALID_OPTION;
697 goto clean_exit;
699 break;
700 case 'v': /* Show version and exit */
701 show_version();
702 goto clean_exit;
703 case 'O': /* Only output these protocols */
704 /* already processed; just ignore it now */
705 break;
706 case 'V': /* Verbose */
707 /* already processed; just ignore it now */
708 break;
709 case 'x': /* Print packet data in hex (and ASCII) */
710 /* already processed; just ignore it now */
711 break;
712 case 'X':
713 /* already processed; just ignore it now */
714 break;
715 case 'Y':
716 dfilter = ws_optarg;
717 break;
718 case 'z':
719 /* We won't call the init function for the stat this soon
720 as it would disallow MATE's fields (which are registered
721 by the preferences set callback) from being used as
722 part of a tap filter. Instead, we just add the argument
723 to a list of stat arguments. */
724 if (strcmp("help", ws_optarg) == 0) {
725 fprintf(stderr, "tfshark: The available statistics for the \"-z\" option are:\n");
726 list_stat_cmd_args();
727 goto clean_exit;
729 if (!process_stat_cmd_arg(ws_optarg)) {
730 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", ws_optarg);
731 list_stat_cmd_args();
732 exit_status = WS_EXIT_INVALID_OPTION;
733 goto clean_exit;
735 break;
736 case 'd': /* Decode as rule */
737 case 'K': /* Kerberos keytab file */
738 case 't': /* Time stamp type */
739 case 'u': /* Seconds type */
740 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
741 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
742 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
743 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
744 if (!dissect_opts_handle_opt(opt, ws_optarg)) {
745 exit_status = WS_EXIT_INVALID_OPTION;
746 goto clean_exit;
748 break;
749 default:
750 case '?': /* Bad flag - print usage message */
751 print_usage(stderr);
752 exit_status = WS_EXIT_INVALID_OPTION;
753 goto clean_exit;
754 break;
758 /* If we specified output fields, but not the output field type... */
759 if (WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
760 cmdarg_err("Output fields were specified with \"-e\", "
761 "but \"-Tfields\" was not specified.");
762 return 1;
763 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
764 cmdarg_err("\"-Tfields\" was specified, but no fields were "
765 "specified with \"-e\".");
767 exit_status = WS_EXIT_INVALID_OPTION;
768 goto clean_exit;
771 /* We require a -r flag specifying a file to read. */
772 if (cf_name == NULL) {
773 cmdarg_err("A file to read must be specified with \"-r\".");
774 exit_status = NO_FILE_SPECIFIED;
775 goto clean_exit;
778 /* If no display filter has been specified, and there are still command-
779 line arguments, treat them as the tokens of a display filter. */
780 if (ws_optind < argc) {
781 if (dfilter != NULL) {
782 cmdarg_err("Display filters were specified both with \"-Y\" "
783 "and with additional command-line arguments.");
784 exit_status = WS_EXIT_INVALID_OPTION;
785 goto clean_exit;
787 dfilter = get_args_as_string(argc, argv, ws_optind);
790 /* if "-q" wasn't specified, we should print packet information */
791 if (!quiet)
792 print_packet_info = true;
794 if (arg_error) {
795 print_usage(stderr);
796 exit_status = WS_EXIT_INVALID_OPTION;
797 goto clean_exit;
800 if (print_hex) {
801 if (output_action != WRITE_TEXT) {
802 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
803 exit_status = WS_EXIT_INVALID_OPTION;
804 goto clean_exit;
808 if (output_only != NULL) {
809 char *ps;
811 if (!print_details) {
812 cmdarg_err("-O requires -V");
813 exit_status = WS_EXIT_INVALID_OPTION;
814 goto clean_exit;
817 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
818 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
819 g_hash_table_insert(output_only_tables, (void *)ps, (void *)ps);
823 if (rfilter != NULL && !perform_two_pass_analysis) {
824 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
825 exit_status = WS_EXIT_INVALID_OPTION;
826 goto clean_exit;
829 /* Notify all registered modules that have had any of their preferences
830 changed either from one of the preferences file or from the command
831 line that their preferences have changed. */
832 prefs_apply_all();
835 * Enabled and disabled protocols and heuristic dissectors as per
836 * command-line options.
838 if (!setup_enabled_and_disabled_protocols()) {
839 exit_status = WS_EXIT_INVALID_OPTION;
840 goto clean_exit;
843 /* Build the column format array */
844 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, true);
846 if (rfilter != NULL) {
847 if (!dfilter_compile(rfilter, &rfcode, &df_err)) {
848 cmdarg_err("%s", df_err->msg);
849 df_error_free(&df_err);
850 exit_status = WS_EXIT_INVALID_FILTER;
851 goto clean_exit;
854 cfile.rfcode = rfcode;
856 if (dfilter != NULL) {
857 if (!dfilter_compile(dfilter, &dfcode, &df_err)) {
858 cmdarg_err("%s", df_err->msg);
859 df_error_free(&df_err);
860 exit_status = WS_EXIT_INVALID_FILTER;
861 goto clean_exit;
864 cfile.dfcode = dfcode;
866 if (print_packet_info) {
867 /* If we're printing as text or PostScript, we have
868 to create a print stream. */
869 if (output_action == WRITE_TEXT) {
870 switch (print_format) {
872 case PR_FMT_TEXT:
873 print_stream = print_stream_text_stdio_new(stdout);
874 break;
876 case PR_FMT_PS:
877 print_stream = print_stream_ps_stdio_new(stdout);
878 break;
880 default:
881 ws_assert_not_reached();
886 /* We have to dissect each packet if:
888 we're printing information about each packet;
890 we're using a read filter on the packets;
892 we're using a display filter on the packets;
894 we're using any taps that need dissection. */
895 do_dissection = print_packet_info || rfcode || dfcode || tap_listeners_require_dissection();
898 * Read the file.
901 /* TODO: if tfshark is ever changed to give the user a choice of which
902 open_routine reader to use, then the following needs to change. */
903 if (cf_open(&cfile, cf_name, WTAP_TYPE_AUTO, false, &err) != CF_OK) {
904 exit_status = WS_EXIT_OPEN_ERROR;
905 goto clean_exit;
908 /* Start statistics taps; we do so after successfully opening the
909 capture file, so we know we have something to compute stats
910 on, and after registering all dissectors, so that MATE will
911 have registered its field array so we can have a tap filter
912 with one of MATE's late-registered fields as part of the
913 filter. */
914 start_requested_stats();
916 /* Process the packets in the file */
917 TRY {
918 /* XXX - for now there is only 1 packet */
919 success = process_file(&cfile);
921 CATCH(OutOfMemoryError) {
922 fprintf(stderr,
923 "Out Of Memory.\n"
924 "\n"
925 "Sorry, but TFShark has to terminate now.\n"
926 "\n"
927 "Some infos / workarounds can be found at:\n"
928 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
929 success = false;
931 ENDTRY;
933 if (!success) {
934 /* We still dump out the results of taps, etc., as we might have
935 read some packets; however, we exit with an error status. */
936 exit_status = 2;
939 g_free(cf_name);
941 if (cfile.provider.frames != NULL) {
942 free_frame_data_sequence(cfile.provider.frames);
943 cfile.provider.frames = NULL;
946 draw_tap_listeners(true);
947 funnel_dump_all_text_windows();
949 clean_exit:
950 destroy_print_stream(print_stream);
951 epan_free(cfile.epan);
952 epan_cleanup();
954 output_fields_free(output_fields);
955 output_fields = NULL;
957 col_cleanup(&cfile.cinfo);
958 wtap_cleanup();
959 return exit_status;
962 static const char *
963 no_interface_name(struct packet_provider_data *prov _U_, uint32_t interface_id _U_, unsigned section_number _U_)
965 return "";
968 static epan_t *
969 tfshark_epan_new(capture_file *cf)
971 static const struct packet_provider_funcs funcs = {
972 /* XXX - there should be no need for time stamps */
973 cap_file_provider_get_frame_ts,
974 no_interface_name,
975 NULL,
976 NULL,
979 return epan_new(&cf->provider, &funcs);
982 static bool
983 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
984 int64_t offset, wtap_rec *rec)
986 frame_data fdlocal;
987 uint32_t framenum;
988 bool passed;
990 /* The frame number of this packet is one more than the count of
991 frames in this packet. */
992 framenum = cf->count + 1;
994 /* If we're not running a display filter and we're not printing any
995 packet information, we don't need to do a dissection. This means
996 that all packets can be marked as 'passed'. */
997 passed = true;
999 frame_data_init(&fdlocal, framenum, rec, offset, cum_bytes);
1001 /* If we're going to print packet information, or we're going to
1002 run a read filter, or display filter, or we're going to process taps, set up to
1003 do a dissection and do so. */
1004 if (edt) {
1005 /* If we're running a read filter, prime the epan_dissect_t with that
1006 filter. */
1007 if (cf->rfcode)
1008 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
1010 /* This is the first pass, so prime the epan_dissect_t with the
1011 hfids postdissectors want on the first pass. */
1012 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1014 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
1015 &cf->provider.ref, cf->provider.prev_dis);
1016 if (cf->provider.ref == &fdlocal) {
1017 ref_frame = fdlocal;
1018 cf->provider.ref = &ref_frame;
1021 epan_dissect_file_run(edt, rec, &fdlocal, NULL);
1023 /* Run the read filter if we have one. */
1024 if (cf->rfcode)
1025 passed = dfilter_apply_edt(cf->rfcode, edt);
1028 if (passed) {
1029 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
1030 cf->provider.prev_cap = cf->provider.prev_dis = frame_data_sequence_add(cf->provider.frames, &fdlocal);
1032 /* If we're not doing dissection then there won't be any dependent frames.
1033 * More importantly, edt.pi.fd.dependent_frames won't be initialized because
1034 * epan hasn't been initialized.
1036 if (edt && edt->pi.fd->dependent_frames) {
1037 g_hash_table_foreach(edt->pi.fd->dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
1040 cf->count++;
1041 } else {
1042 /* if we don't add it to the frame_data_sequence, clean it up right now
1043 * to avoid leaks */
1044 frame_data_destroy(&fdlocal);
1047 if (edt)
1048 epan_dissect_reset(edt);
1050 return passed;
1053 static bool
1054 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
1055 frame_data *fdata, wtap_rec *rec)
1057 column_info *cinfo;
1058 bool passed;
1060 /* If we're not running a display filter and we're not printing any
1061 packet information, we don't need to do a dissection. This means
1062 that all packets can be marked as 'passed'. */
1063 passed = true;
1065 /* If we're going to print packet information, or we're going to
1066 run a read filter, or we're going to process taps, set up to
1067 do a dissection and do so. */
1068 if (edt) {
1070 /* If we're running a display filter, prime the epan_dissect_t with that
1071 filter. */
1072 if (cf->dfcode)
1073 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
1075 /* This is the first and only pass, so prime the epan_dissect_t
1076 with the hfids postdissectors want on the first pass. */
1077 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1079 col_custom_prime_edt(edt, &cf->cinfo);
1081 /* We only need the columns if either
1082 1) some tap needs the columns
1084 2) we're printing packet info but we're *not* verbose; in verbose
1085 mode, we print the protocol tree, not the protocol summary.
1087 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary))
1088 cinfo = &cf->cinfo;
1089 else
1090 cinfo = NULL;
1092 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1093 &cf->provider.ref, cf->provider.prev_dis);
1094 if (cf->provider.ref == fdata) {
1095 ref_frame = *fdata;
1096 cf->provider.ref = &ref_frame;
1099 epan_dissect_file_run_with_taps(edt, rec, fdata, cinfo);
1101 /* Run the read/display filter if we have one. */
1102 if (cf->dfcode)
1103 passed = dfilter_apply_edt(cf->dfcode, edt);
1106 if (passed) {
1107 frame_data_set_after_dissect(fdata, &cum_bytes);
1108 /* Process this packet. */
1109 if (print_packet_info) {
1110 /* We're printing packet information; print the information for
1111 this packet. */
1112 print_packet(cf, edt);
1114 /* If we're doing "line-buffering", flush the standard output
1115 after every packet. See the comment above, for the "-l"
1116 option, for an explanation of why we do that. */
1117 if (line_buffered)
1118 fflush(stdout);
1120 if (ferror(stdout)) {
1121 show_print_file_io_error(errno);
1122 return false;
1125 cf->provider.prev_dis = fdata;
1127 cf->provider.prev_cap = fdata;
1129 if (edt) {
1130 epan_dissect_reset(edt);
1132 return passed || fdata->dependent_of_displayed;
1136 * XXX - this routine doesn't read in files larger than UINT_MAX bytes;
1137 * it would need to loop over the file.
1139 * But if we read the entire file in, that might, for sufficiently
1140 * large files, eat up address space or other resources (especially
1141 * on 32-bit platforms).
1143 static bool
1144 full_file_read(capture_file *cf, wtap_rec *rec, int *err, char **err_info)
1146 int64_t file_size;
1147 int packet_size = 0;
1148 const int block_size = 1024 * 1024;
1150 if ((file_size = wtap_file_size(cf->provider.wth, err)) == -1)
1151 return false;
1153 if (file_size > INT_MAX) {
1155 * Avoid allocating space for an immensely-large file.
1157 *err = WTAP_ERR_BAD_FILE;
1158 *err_info = ws_strdup_printf("File is %" PRId64 " bytes in size, bigger than maximum of %u",
1159 file_size, INT_MAX);
1160 return false;
1164 * Compressed files might expand to a larger size than the actual file
1165 * size. Try to read the full size and then read in smaller increments
1166 * to avoid frequent memory reallocations.
1168 int buffer_size = block_size * (1 + (int)file_size / block_size);
1169 for (;;) {
1170 if (buffer_size <= 0) {
1171 *err = WTAP_ERR_BAD_FILE;
1172 *err_info = ws_strdup_printf("%s: Uncompressed file is bigger than maximum of %u",
1173 wtap_encap_name(cf->provider.wth->file_encap), INT_MAX);
1174 return false;
1176 ws_buffer_assure_space(&rec->data, buffer_size);
1177 int nread = file_read(ws_buffer_start_ptr(&rec->data) + packet_size, buffer_size - packet_size, cf->provider.wth->fh);
1178 if (nread < 0) {
1179 *err = file_error(cf->provider.wth->fh, err_info);
1180 if (*err == 0)
1181 *err = WTAP_ERR_BAD_FILE;
1182 return false;
1184 packet_size += nread;
1185 if (packet_size != buffer_size) {
1186 /* EOF */
1187 break;
1189 buffer_size += block_size;
1192 rec->rec_type = REC_TYPE_PACKET;
1193 rec->presence_flags = 0; /* yes, we have no bananas^Wtime stamp */
1194 rec->ts.secs = 0;
1195 rec->ts.nsecs = 0;
1196 rec->rec_header.packet_header.caplen = packet_size;
1197 rec->rec_header.packet_header.len = packet_size;
1199 return true;
1202 static bool
1203 process_file(capture_file *cf)
1205 uint32_t framenum;
1206 int err;
1207 char *err_info = NULL;
1208 bool filtering_tap_listeners;
1209 unsigned tap_flags;
1210 epan_dissect_t *edt = NULL;
1211 wtap_rec file_rec;
1213 if (print_packet_info) {
1214 if (!write_preamble(cf)) {
1215 err = errno;
1216 show_print_file_io_error(err);
1217 goto out;
1221 /* Do we have any tap listeners with filters? */
1222 filtering_tap_listeners = have_filtering_tap_listeners();
1224 /* Get the union of the flags for all tap listeners. */
1225 tap_flags = union_of_tap_listener_flags();
1227 wtap_rec_init(&file_rec, 1514);
1229 /* XXX - TEMPORARY HACK TO ELF DISSECTOR */
1230 file_rec.rec_header.packet_header.pkt_encap = 1234;
1232 if (perform_two_pass_analysis) {
1233 frame_data *fdata;
1235 /* Allocate a frame_data_sequence for all the frames. */
1236 cf->provider.frames = new_frame_data_sequence();
1238 if (do_dissection) {
1239 bool create_proto_tree;
1242 * Determine whether we need to create a protocol tree.
1243 * We do if:
1245 * we're going to apply a read filter;
1247 * a postdissector wants field values or protocols
1248 * on the first pass.
1250 create_proto_tree =
1251 (cf->rfcode != NULL || postdissectors_want_hfids());
1253 /* We're not going to display the protocol tree on this pass,
1254 so it's not going to be "visible". */
1255 edt = epan_dissect_new(cf->epan, create_proto_tree, false);
1258 /* XXX - check for failure and report it */
1259 full_file_read(cf, &file_rec, &err, &err_info);
1260 /* XXX - check return value? */
1261 process_packet_first_pass(cf, edt, 0, &file_rec);
1263 if (edt) {
1264 epan_dissect_free(edt);
1265 edt = NULL;
1268 #if 0
1269 /* Close the sequential I/O side, to free up memory it requires. */
1270 wtap_sequential_close(cf->provider.wth);
1271 #endif
1273 /* Allow the protocol dissectors to free up memory that they
1274 * don't need after the sequential run-through of the packets. */
1275 postseq_cleanup_all_protocols();
1277 cf->provider.prev_dis = NULL;
1278 cf->provider.prev_cap = NULL;
1280 if (do_dissection) {
1281 bool create_proto_tree;
1284 * Determine whether we need to create a protocol tree.
1285 * We do if:
1287 * we're going to apply a display filter;
1289 * we're going to print the protocol tree;
1291 * one of the tap listeners requires a protocol tree;
1293 * we have custom columns (which require field values, which
1294 * currently requires that we build a protocol tree).
1296 create_proto_tree =
1297 (cf->dfcode || print_details || filtering_tap_listeners ||
1298 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo));
1300 /* The protocol tree will be "visible", i.e., printed, only if we're
1301 printing packet details, which is true if we're printing stuff
1302 ("print_packet_info" is true) and we're in verbose mode
1303 ("packet_details" is true). */
1304 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
1307 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
1308 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1309 if (!process_packet_second_pass(cf, edt, fdata, &file_rec))
1310 return false;
1313 if (edt) {
1314 epan_dissect_free(edt);
1315 edt = NULL;
1318 else {
1319 framenum = 0;
1321 if (do_dissection) {
1322 bool create_proto_tree;
1325 * Determine whether we need to create a protocol tree.
1326 * We do if:
1328 * we're going to apply a read filter;
1330 * we're going to apply a display filter;
1332 * we're going to print the protocol tree;
1334 * one of the tap listeners is going to apply a filter;
1336 * one of the tap listeners requires a protocol tree;
1338 * a postdissector wants field values or protocols
1339 * on the first pass;
1341 * we have custom columns (which require field values, which
1342 * currently requires that we build a protocol tree).
1344 create_proto_tree =
1345 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
1346 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
1347 have_custom_cols(&cf->cinfo));
1349 /* The protocol tree will be "visible", i.e., printed, only if we're
1350 printing packet details, which is true if we're printing stuff
1351 ("print_packet_info" is true) and we're in verbose mode
1352 ("packet_details" is true). */
1353 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
1356 /* XXX - check for failure and report it */
1357 if (full_file_read(cf, &file_rec, &err, &err_info)) {
1358 if (!process_packet_single_pass(cf, edt, 0, &file_rec))
1359 return false;
1362 if (edt) {
1363 epan_dissect_free(edt);
1364 edt = NULL;
1368 wtap_rec_cleanup(&file_rec);
1370 if (err != 0) {
1372 * Print a message noting that the read failed somewhere along the line.
1374 * If we're printing packet data, and the standard output and error are
1375 * going to the same place, flush the standard output, so everything
1376 * buffered up is written, and then print a newline to the standard error
1377 * before printing the error message, to separate it from the packet
1378 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
1379 * the _fstat() documentation at Microsoft doesn't indicate whether
1380 * st_ino is even supported.)
1382 #ifndef _WIN32
1383 if (print_packet_info) {
1384 ws_statb64 stat_stdout, stat_stderr;
1386 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
1387 if (stat_stdout.st_dev == stat_stderr.st_dev &&
1388 stat_stdout.st_ino == stat_stderr.st_ino) {
1389 fflush(stdout);
1390 fprintf(stderr, "\n");
1394 #endif
1395 #if 0
1396 switch (err) {
1398 case FTAP_ERR_UNSUPPORTED:
1399 cmdarg_err("The file \"%s\" contains record data that TFShark doesn't support.\n(%s)",
1400 cf->filename, err_info);
1401 g_free(err_info);
1402 break;
1404 case FTAP_ERR_UNSUPPORTED_ENCAP:
1405 cmdarg_err("The file \"%s\" has a packet with a network type that TFShark doesn't support.\n(%s)",
1406 cf->filename, err_info);
1407 g_free(err_info);
1408 break;
1410 case FTAP_ERR_CANT_READ:
1411 cmdarg_err("An attempt to read from the file \"%s\" failed for some unknown reason.",
1412 cf->filename);
1413 break;
1415 case FTAP_ERR_SHORT_READ:
1416 cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
1417 cf->filename);
1418 break;
1420 case FTAP_ERR_BAD_FILE:
1421 cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
1422 cf->filename, err_info);
1423 g_free(err_info);
1424 break;
1426 case FTAP_ERR_DECOMPRESS:
1427 cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
1428 "(%s)", cf->filename, err_info);
1429 break;
1431 default:
1432 cmdarg_err("An error occurred while reading the file \"%s\": %s.",
1433 cf->filename, ftap_strerror(err));
1434 break;
1436 #endif
1437 } else {
1438 if (print_packet_info) {
1439 if (!write_finale()) {
1440 err = errno;
1441 show_print_file_io_error(err);
1446 out:
1447 wtap_close(cf->provider.wth);
1448 cf->provider.wth = NULL;
1450 return (err != 0);
1453 static bool
1454 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, int64_t offset,
1455 wtap_rec *rec)
1457 frame_data fdata;
1458 column_info *cinfo;
1459 bool passed;
1461 /* Count this packet. */
1462 cf->count++;
1464 /* If we're not running a display filter and we're not printing any
1465 packet information, we don't need to do a dissection. This means
1466 that all packets can be marked as 'passed'. */
1467 passed = true;
1469 frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
1471 /* If we're going to print packet information, or we're going to
1472 run a read filter, or we're going to process taps, set up to
1473 do a dissection and do so. */
1474 if (edt) {
1475 /* If we're running a filter, prime the epan_dissect_t with that
1476 filter. */
1477 if (cf->dfcode)
1478 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
1480 col_custom_prime_edt(edt, &cf->cinfo);
1482 /* We only need the columns if either
1483 1) some tap needs the columns
1485 2) we're printing packet info but we're *not* verbose; in verbose
1486 mode, we print the protocol tree, not the protocol summary.
1488 3) there is a column mapped as an individual field */
1489 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
1490 cinfo = &cf->cinfo;
1491 else
1492 cinfo = NULL;
1494 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
1495 &cf->provider.ref, cf->provider.prev_dis);
1496 if (cf->provider.ref == &fdata) {
1497 ref_frame = fdata;
1498 cf->provider.ref = &ref_frame;
1501 epan_dissect_file_run_with_taps(edt, rec, &fdata, cinfo);
1503 /* Run the filter if we have it. */
1504 if (cf->dfcode)
1505 passed = dfilter_apply_edt(cf->dfcode, edt);
1508 if (passed) {
1509 frame_data_set_after_dissect(&fdata, &cum_bytes);
1511 /* Process this packet. */
1512 if (print_packet_info) {
1513 /* We're printing packet information; print the information for
1514 this packet. */
1515 print_packet(cf, edt);
1517 /* If we're doing "line-buffering", flush the standard output
1518 after every packet. See the comment above, for the "-l"
1519 option, for an explanation of why we do that. */
1520 if (line_buffered)
1521 fflush(stdout);
1523 if (ferror(stdout)) {
1524 show_print_file_io_error(errno);
1525 return false;
1529 /* this must be set after print_packet() [bug #8160] */
1530 prev_dis_frame = fdata;
1531 cf->provider.prev_dis = &prev_dis_frame;
1534 prev_cap_frame = fdata;
1535 cf->provider.prev_cap = &prev_cap_frame;
1537 if (edt) {
1538 epan_dissect_reset(edt);
1539 frame_data_destroy(&fdata);
1541 return passed;
1544 static bool
1545 write_preamble(capture_file *cf)
1547 switch (output_action) {
1549 case WRITE_TEXT:
1550 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
1552 case WRITE_XML:
1553 if (print_details)
1554 write_pdml_preamble(stdout, cf->filename);
1555 else
1556 write_psml_preamble(&cf->cinfo, stdout);
1557 return !ferror(stdout);
1559 case WRITE_FIELDS:
1560 write_fields_preamble(output_fields, stdout);
1561 return !ferror(stdout);
1563 default:
1564 ws_assert_not_reached();
1565 return false;
1569 static char *
1570 get_line_buf(size_t len)
1572 static char *line_bufp = NULL;
1573 static size_t line_buf_len = 256;
1574 size_t new_line_buf_len;
1576 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
1577 new_line_buf_len *= 2)
1579 if (line_bufp == NULL) {
1580 line_buf_len = new_line_buf_len;
1581 line_bufp = (char *)g_malloc(line_buf_len + 1);
1582 } else {
1583 if (new_line_buf_len > line_buf_len) {
1584 line_buf_len = new_line_buf_len;
1585 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
1588 return line_bufp;
1591 static inline void
1592 put_string(char *dest, const char *str, size_t str_len)
1594 memcpy(dest, str, str_len);
1595 dest[str_len] = '\0';
1598 static inline void
1599 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
1601 size_t i;
1603 for (i = str_len; i < str_with_spaces; i++)
1604 *dest++ = ' ';
1606 put_string(dest, str, str_len);
1609 static inline void
1610 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
1612 size_t i;
1614 memcpy(dest, str, str_len);
1615 for (i = str_len; i < str_with_spaces; i++)
1616 dest[i] = ' ';
1618 dest[str_with_spaces] = '\0';
1621 static bool
1622 print_columns(capture_file *cf)
1624 char *line_bufp;
1625 int i;
1626 size_t buf_offset;
1627 size_t column_len;
1628 size_t col_len;
1629 col_item_t* col_item;
1631 line_bufp = get_line_buf(256);
1632 buf_offset = 0;
1633 *line_bufp = '\0';
1634 for (i = 0; i < cf->cinfo.num_cols; i++) {
1635 col_item = &cf->cinfo.columns[i];
1636 /* Skip columns not marked as visible. */
1637 if (!get_column_visible(i))
1638 continue;
1639 const char* col_text = get_column_text(&cf->cinfo, i);
1640 switch (col_item->col_fmt) {
1641 case COL_NUMBER:
1642 case COL_NUMBER_DIS:
1643 column_len = col_len = strlen(col_text);
1644 if (column_len < 3)
1645 column_len = 3;
1646 line_bufp = get_line_buf(buf_offset + column_len);
1647 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
1648 break;
1650 case COL_CLS_TIME:
1651 case COL_REL_TIME:
1652 case COL_ABS_TIME:
1653 case COL_ABS_YMD_TIME: /* XXX - wider */
1654 case COL_ABS_YDOY_TIME: /* XXX - wider */
1655 case COL_UTC_TIME:
1656 case COL_UTC_YMD_TIME: /* XXX - wider */
1657 case COL_UTC_YDOY_TIME: /* XXX - wider */
1658 column_len = col_len = strlen(col_text);
1659 if (column_len < 10)
1660 column_len = 10;
1661 line_bufp = get_line_buf(buf_offset + column_len);
1662 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
1663 break;
1665 case COL_DEF_SRC:
1666 case COL_RES_SRC:
1667 case COL_UNRES_SRC:
1668 case COL_DEF_DL_SRC:
1669 case COL_RES_DL_SRC:
1670 case COL_UNRES_DL_SRC:
1671 case COL_DEF_NET_SRC:
1672 case COL_RES_NET_SRC:
1673 case COL_UNRES_NET_SRC:
1674 column_len = col_len = strlen(col_text);
1675 if (column_len < 12)
1676 column_len = 12;
1677 line_bufp = get_line_buf(buf_offset + column_len);
1678 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
1679 break;
1681 case COL_DEF_DST:
1682 case COL_RES_DST:
1683 case COL_UNRES_DST:
1684 case COL_DEF_DL_DST:
1685 case COL_RES_DL_DST:
1686 case COL_UNRES_DL_DST:
1687 case COL_DEF_NET_DST:
1688 case COL_RES_NET_DST:
1689 case COL_UNRES_NET_DST:
1690 column_len = col_len = strlen(col_text);
1691 if (column_len < 12)
1692 column_len = 12;
1693 line_bufp = get_line_buf(buf_offset + column_len);
1694 put_string_spaces(line_bufp + buf_offset, col_text, col_len, column_len);
1695 break;
1697 default:
1698 column_len = strlen(col_text);
1699 line_bufp = get_line_buf(buf_offset + column_len);
1700 put_string(line_bufp + buf_offset, col_text, column_len);
1701 break;
1703 buf_offset += column_len;
1704 if (i != cf->cinfo.num_cols - 1) {
1706 * This isn't the last column, so we need to print a
1707 * separator between this column and the next.
1709 * If we printed a network source and are printing a
1710 * network destination of the same type next, separate
1711 * them with " -> "; if we printed a network destination
1712 * and are printing a network source of the same type
1713 * next, separate them with " <- "; otherwise separate them
1714 * with a space.
1716 * We add enough space to the buffer for " <- " or " -> ",
1717 * even if we're only adding " ".
1719 line_bufp = get_line_buf(buf_offset + 4);
1720 switch (col_item->col_fmt) {
1722 case COL_DEF_SRC:
1723 case COL_RES_SRC:
1724 case COL_UNRES_SRC:
1725 switch (cf->cinfo.columns[i+1].col_fmt) {
1727 case COL_DEF_DST:
1728 case COL_RES_DST:
1729 case COL_UNRES_DST:
1730 put_string(line_bufp + buf_offset, " -> ", 4);
1731 buf_offset += 4;
1732 break;
1734 default:
1735 put_string(line_bufp + buf_offset, " ", 1);
1736 buf_offset += 1;
1737 break;
1739 break;
1741 case COL_DEF_DL_SRC:
1742 case COL_RES_DL_SRC:
1743 case COL_UNRES_DL_SRC:
1744 switch (cf->cinfo.columns[i+1].col_fmt) {
1746 case COL_DEF_DL_DST:
1747 case COL_RES_DL_DST:
1748 case COL_UNRES_DL_DST:
1749 put_string(line_bufp + buf_offset, " -> ", 4);
1750 buf_offset += 4;
1751 break;
1753 default:
1754 put_string(line_bufp + buf_offset, " ", 1);
1755 buf_offset += 1;
1756 break;
1758 break;
1760 case COL_DEF_NET_SRC:
1761 case COL_RES_NET_SRC:
1762 case COL_UNRES_NET_SRC:
1763 switch (cf->cinfo.columns[i+1].col_fmt) {
1765 case COL_DEF_NET_DST:
1766 case COL_RES_NET_DST:
1767 case COL_UNRES_NET_DST:
1768 put_string(line_bufp + buf_offset, " -> ", 4);
1769 buf_offset += 4;
1770 break;
1772 default:
1773 put_string(line_bufp + buf_offset, " ", 1);
1774 buf_offset += 1;
1775 break;
1777 break;
1779 case COL_DEF_DST:
1780 case COL_RES_DST:
1781 case COL_UNRES_DST:
1782 switch (cf->cinfo.columns[i+1].col_fmt) {
1784 case COL_DEF_SRC:
1785 case COL_RES_SRC:
1786 case COL_UNRES_SRC:
1787 put_string(line_bufp + buf_offset, " <- ", 4);
1788 buf_offset += 4;
1789 break;
1791 default:
1792 put_string(line_bufp + buf_offset, " ", 1);
1793 buf_offset += 1;
1794 break;
1796 break;
1798 case COL_DEF_DL_DST:
1799 case COL_RES_DL_DST:
1800 case COL_UNRES_DL_DST:
1801 switch (cf->cinfo.columns[i+1].col_fmt) {
1803 case COL_DEF_DL_SRC:
1804 case COL_RES_DL_SRC:
1805 case COL_UNRES_DL_SRC:
1806 put_string(line_bufp + buf_offset, " <- ", 4);
1807 buf_offset += 4;
1808 break;
1810 default:
1811 put_string(line_bufp + buf_offset, " ", 1);
1812 buf_offset += 1;
1813 break;
1815 break;
1817 case COL_DEF_NET_DST:
1818 case COL_RES_NET_DST:
1819 case COL_UNRES_NET_DST:
1820 switch (cf->cinfo.columns[i+1].col_fmt) {
1822 case COL_DEF_NET_SRC:
1823 case COL_RES_NET_SRC:
1824 case COL_UNRES_NET_SRC:
1825 put_string(line_bufp + buf_offset, " <- ", 4);
1826 buf_offset += 4;
1827 break;
1829 default:
1830 put_string(line_bufp + buf_offset, " ", 1);
1831 buf_offset += 1;
1832 break;
1834 break;
1836 default:
1837 put_string(line_bufp + buf_offset, " ", 1);
1838 buf_offset += 1;
1839 break;
1843 return print_line(print_stream, 0, line_bufp);
1846 static bool
1847 print_packet(capture_file *cf, epan_dissect_t *edt)
1849 if (print_summary || output_fields_has_cols(output_fields)) {
1850 /* Just fill in the columns. */
1851 epan_dissect_fill_in_columns(edt, false, true);
1853 if (print_summary) {
1854 /* Now print them. */
1855 switch (output_action) {
1857 case WRITE_TEXT:
1858 if (!print_columns(cf))
1859 return false;
1860 break;
1862 case WRITE_XML:
1863 write_psml_columns(edt, stdout, false);
1864 return !ferror(stdout);
1865 case WRITE_FIELDS: /*No non-verbose "fields" format */
1866 ws_assert_not_reached();
1867 break;
1871 if (print_details) {
1872 /* Print the information in the protocol tree. */
1873 switch (output_action) {
1875 case WRITE_TEXT:
1876 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
1877 print_hex, edt, output_only_tables, print_stream))
1878 return false;
1879 if (!print_hex) {
1880 if (!print_line(print_stream, 0, separator))
1881 return false;
1883 break;
1885 case WRITE_XML:
1886 write_pdml_proto_tree(NULL, edt, &cf->cinfo, stdout, false);
1887 printf("\n");
1888 return !ferror(stdout);
1889 case WRITE_FIELDS:
1890 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
1891 printf("\n");
1892 return !ferror(stdout);
1895 if (print_hex) {
1896 if (print_summary || print_details) {
1897 if (!print_line(print_stream, 0, ""))
1898 return false;
1900 if (!print_hex_data(print_stream, edt, HEXDUMP_SOURCE_MULTI | HEXDUMP_ASCII_INCLUDE))
1901 return false;
1902 if (!print_line(print_stream, 0, separator))
1903 return false;
1905 return true;
1908 static bool
1909 write_finale(void)
1911 switch (output_action) {
1913 case WRITE_TEXT:
1914 return print_finale(print_stream);
1916 case WRITE_XML:
1917 if (print_details)
1918 write_pdml_finale(stdout);
1919 else
1920 write_psml_finale(stdout);
1921 return !ferror(stdout);
1923 case WRITE_FIELDS:
1924 write_fields_finale(output_fields, stdout);
1925 return !ferror(stdout);
1927 default:
1928 ws_assert_not_reached();
1929 return false;
1933 cf_status_t
1934 cf_open(capture_file *cf, const char *fname, unsigned int type, bool is_tempfile, int *err _U_)
1936 /* The open isn't implemented yet. Fill in the information for this file. */
1938 /* Create new epan session for dissection. */
1939 epan_free(cf->epan);
1940 cf->epan = tfshark_epan_new(cf);
1942 cf->provider.wth = NULL; /**** XXX - DOESN'T WORK RIGHT NOW!!!! */
1943 cf->f_datalen = 0; /* not used, but set it anyway */
1945 /* Set the file name because we need it to set the follow stream filter.
1946 XXX - is that still true? We need it for other reasons, though,
1947 in any case. */
1948 cf->filename = g_strdup(fname);
1950 /* Indicate whether it's a permanent or temporary file. */
1951 cf->is_tempfile = is_tempfile;
1953 /* No user changes yet. */
1954 cf->unsaved_changes = false;
1956 cf->cd_t = 0; /**** XXX - DOESN'T WORK RIGHT NOW!!!! */
1957 cf->open_type = type;
1958 cf->count = 0;
1959 cf->drops_known = false;
1960 cf->drops = 0;
1961 cf->snap = 0; /**** XXX - DOESN'T WORK RIGHT NOW!!!! */
1962 nstime_set_zero(&cf->elapsed_time);
1963 cf->provider.ref = NULL;
1964 cf->provider.prev_dis = NULL;
1965 cf->provider.prev_cap = NULL;
1967 cf->state = FILE_READ_IN_PROGRESS;
1969 return CF_OK;
1971 /* fail: */
1973 char *err_info;
1974 char err_msg[2048+1];
1975 snprintf(err_msg, sizeof err_msg,
1976 cf_open_error_message(*err, err_info, false, cf->cd_t), fname);
1977 cmdarg_err("%s", err_msg);
1978 return CF_ERROR;
1982 static void
1983 show_print_file_io_error(int err)
1985 switch (err) {
1987 case ENOSPC:
1988 cmdarg_err("Not all the packets could be printed because there is "
1989 "no space left on the file system.");
1990 break;
1992 #ifdef EDQUOT
1993 case EDQUOT:
1994 cmdarg_err("Not all the packets could be printed because you are "
1995 "too close to, or over your disk quota.");
1996 break;
1997 #endif
1999 default:
2000 cmdarg_err("An error occurred while printing packets: %s.",
2001 g_strerror(err));
2002 break;