drsuapi fix proto_tree_add_text_internal string format
[wireshark-sm.git] / tfshark.c
blob857aaaccf38be5b030b769a9015418ad89092fd7
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 "frame_tvbuff.h"
51 #include <epan/disabled_protos.h>
52 #include <epan/prefs.h>
53 #include <epan/column.h>
54 #include <epan/print.h>
55 #include <epan/addr_resolv.h>
56 #include "ui/util.h"
57 #include "ui/decode_as_utils.h"
58 #include "ui/dissect_opts.h"
59 #include "ui/failure_message.h"
60 #include <epan/epan_dissect.h>
61 #include <epan/tap.h>
62 #include <epan/stat_tap_ui.h>
63 #include <epan/ex-opt.h>
65 #include <wiretap/wtap-int.h>
66 #include <wiretap/file_wrappers.h>
68 #include <epan/funnel.h>
70 #ifdef HAVE_PLUGINS
71 #include <wsutil/plugins.h>
72 #endif
74 /* Additional exit codes */
75 #define NO_FILE_SPECIFIED 1
77 capture_file cfile;
79 static uint32_t cum_bytes;
80 static frame_data ref_frame;
81 static frame_data prev_dis_frame;
82 static frame_data prev_cap_frame;
84 static bool prefs_loaded;
86 static bool perform_two_pass_analysis;
89 * The way the packet decode is to be written.
91 typedef enum {
92 WRITE_TEXT, /* summary or detail text */
93 WRITE_XML, /* PDML or PSML */
94 WRITE_FIELDS /* User defined list of fields */
95 /* Add CSV and the like here */
96 } output_action_e;
98 static output_action_e output_action;
99 static bool do_dissection; /* true if we have to dissect each packet */
100 static bool print_packet_info; /* true if we're to print packet information */
101 static int print_summary = -1; /* true if we're to print packet summary information */
102 static bool print_details; /* true if we're to print packet details information */
103 static bool print_hex; /* true if we're to print hex/ascii information */
104 static bool line_buffered;
105 static bool really_quiet;
107 static print_format_e print_format = PR_FMT_TEXT;
108 static print_stream_t *print_stream;
110 static output_fields_t* output_fields;
112 /* The line separator used between packets, changeable via the -S option */
113 static const char *separator = "";
115 static bool process_file(capture_file *, int, int64_t);
116 static bool process_packet_single_pass(capture_file *cf,
117 epan_dissect_t *edt, int64_t offset, wtap_rec *rec,
118 const unsigned char *pd);
119 static void show_print_file_io_error(int err);
120 static bool write_preamble(capture_file *cf);
121 static bool print_packet(capture_file *cf, epan_dissect_t *edt);
122 static bool write_finale(void);
124 static void tfshark_cmdarg_err(const char *msg_format, va_list ap);
125 static void tfshark_cmdarg_err_cont(const char *msg_format, va_list ap);
127 static GHashTable *output_only_tables;
129 #if 0
130 struct string_elem {
131 const char *sstr; /* The short string */
132 const char *lstr; /* The long string */
135 static int
136 string_compare(const void *a, const void *b)
138 return strcmp(((const struct string_elem *)a)->sstr,
139 ((const struct string_elem *)b)->sstr);
142 static void
143 string_elem_print(void *data, void *not_used _U_)
145 fprintf(stderr, " %s - %s\n",
146 ((struct string_elem *)data)->sstr,
147 ((struct string_elem *)data)->lstr);
149 #endif
151 static void
152 print_usage(FILE *output)
154 fprintf(output, "\n");
155 fprintf(output, "Usage: tfshark [options] ...\n");
156 fprintf(output, "\n");
158 /*fprintf(output, "\n");*/
159 fprintf(output, "Input file:\n");
160 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin)\n");
162 fprintf(output, "\n");
163 fprintf(output, "Processing:\n");
164 fprintf(output, " -2 perform a two-pass analysis\n");
165 fprintf(output, " -R <read filter> packet Read filter in Wireshark display filter syntax\n");
166 fprintf(output, " (requires -2)\n");
167 fprintf(output, " -Y <display filter> packet displaY filter in Wireshark display filter\n");
168 fprintf(output, " syntax\n");
169 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
170 fprintf(output, " \"Decode As\", see the man page for details\n");
171 fprintf(output, " Example: tcp.port==8888,http\n");
173 /*fprintf(output, "\n");*/
174 fprintf(output, "Output:\n");
175 fprintf(output, " -C <config profile> start with specified configuration profile\n");
176 fprintf(output, " -V add output of packet tree (Packet Details)\n");
177 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
178 fprintf(output, " separated\n");
179 fprintf(output, " -S <separator> the line separator to print between packets\n");
180 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
181 fprintf(output, " -T pdml|ps|psml|text|fields\n");
182 fprintf(output, " format of text output (def: text)\n");
183 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
184 fprintf(output, " _ws.col.info)\n");
185 fprintf(output, " this option can be repeated to print multiple fields\n");
186 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
187 fprintf(output, " header=y|n switch headers on and off\n");
188 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
189 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
190 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
191 fprintf(output, " aggregator\n");
192 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
193 fprintf(output, " -t a|ad|d|dd|e|r|u|ud output format of time stamps (def: r: rel. to first)\n");
194 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
195 fprintf(output, " -l flush standard output after each packet\n");
196 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
197 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
198 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
199 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
200 fprintf(output, "\n");
202 ws_log_print_usage(output);
203 fprintf(output, "\n");
205 fprintf(output, "Miscellaneous:\n");
206 fprintf(output, " -h display this help and exit\n");
207 fprintf(output, " -v display version info and exit\n");
208 fprintf(output, " -o <name>:<value> ... override preference setting\n");
209 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
210 fprintf(output, " -G [report] dump one of several available reports and exit\n");
211 fprintf(output, " default report=\"fields\"\n");
212 fprintf(output, " use \"-G ?\" for more help\n");
215 static void
216 glossary_option_help(void)
218 FILE *output;
220 output = stdout;
222 fprintf(output, "%s\n", get_appname_and_version());
224 fprintf(output, "\n");
225 fprintf(output, "Usage: tfshark -G [report]\n");
226 fprintf(output, "\n");
227 fprintf(output, "Glossary table reports:\n");
228 fprintf(output, " -G column-formats dump column format codes and exit\n");
229 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
230 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
231 fprintf(output, " -G fields dump fields glossary and exit\n");
232 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
233 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
234 fprintf(output, " -G plugins dump installed plugins and exit\n");
235 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
236 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
237 fprintf(output, "\n");
238 fprintf(output, "Preference reports:\n");
239 fprintf(output, " -G currentprefs dump current preferences and exit\n");
240 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
241 fprintf(output, "\n");
244 static void
245 print_current_user(void)
247 char *cur_user, *cur_group;
249 if (started_with_special_privs()) {
250 cur_user = get_cur_username();
251 cur_group = get_cur_groupname();
252 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
253 cur_user, cur_group);
254 g_free(cur_user);
255 g_free(cur_group);
256 if (running_with_special_privs()) {
257 fprintf(stderr, " This could be dangerous.");
259 fprintf(stderr, "\n");
264 main(int argc, char *argv[])
266 char *configuration_init_error;
267 int opt;
268 static const struct ws_option long_options[] = {
269 {"help", ws_no_argument, NULL, 'h'},
270 {"version", ws_no_argument, NULL, 'v'},
271 {0, 0, 0, 0 }
273 bool arg_error = false;
275 int err;
276 volatile bool success;
277 volatile int exit_status = 0;
278 bool quiet = false;
279 char *volatile cf_name = NULL;
280 char *rfilter = NULL;
281 char *dfilter = NULL;
282 dfilter_t *rfcode = NULL;
283 dfilter_t *dfcode = NULL;
284 df_error_t *df_err;
285 e_prefs *prefs_p;
286 char *output_only = NULL;
289 * The leading + ensures that getopt_long() does not permute the argv[]
290 * entries.
292 * We have to make sure that the first getopt_long() preserves the content
293 * of argv[] for the subsequent getopt_long() call.
295 * We use getopt_long() in both cases to ensure that we're using a routine
296 * whose permutation behavior we can control in the same fashion on all
297 * platforms, and so that, if we ever need to process a long argument before
298 * doing further initialization, we can do so.
300 * Glibc and Solaris libc document that a leading + disables permutation
301 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
302 * and macOS don't document it, but do so anyway.
304 * We do *not* use a leading - because the behavior of a leading - is
305 * platform-dependent.
307 #define OPTSTRING "+2C:d:e:E:hK:lo:O:qQr:R:S:t:T:u:vVxX:Y:z:"
309 static const char optstring[] = OPTSTRING;
312 * Set the C-language locale to the native environment and set the
313 * code page to UTF-8 on Windows.
315 #ifdef _WIN32
316 setlocale(LC_ALL, ".UTF-8");
317 #else
318 setlocale(LC_ALL, "");
319 #endif
321 cmdarg_err_init(tfshark_cmdarg_err, tfshark_cmdarg_err_cont);
323 /* Initialize log handler early so we can have proper logging during startup. */
324 ws_log_init("tfshark", vcmdarg_err);
326 /* Early logging command-line initialization. */
327 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
329 ws_noisy("Finished log init and parsing command line log arguments");
331 #ifdef _WIN32
332 create_app_running_mutex();
333 #endif /* _WIN32 */
336 * Get credential information for later use, and drop privileges
337 * before doing anything else.
338 * Let the user know if anything happened.
340 init_process_policies();
341 relinquish_special_privs_perm();
342 print_current_user();
345 * Attempt to get the pathname of the directory containing the
346 * executable file.
348 configuration_init_error = configuration_init(argv[0], NULL);
349 if (configuration_init_error != NULL) {
350 fprintf(stderr,
351 "tfshark: Can't get pathname of directory containing the tfshark program: %s.\n",
352 configuration_init_error);
353 g_free(configuration_init_error);
356 initialize_funnel_ops();
358 /* Initialize the version information. */
359 ws_init_version_info("TFShark",
360 epan_gather_compile_info,
361 epan_gather_runtime_info);
363 * In order to have the -X opts assigned before the wslua machine starts
364 * we need to call getopts before epan_init() gets called.
366 * In order to handle, for example, -o options, we also need to call it
367 * *after* epan_init() gets called, so that the dissectors have had a
368 * chance to register their preferences.
370 * XXX - can we do this all with one getopt_long() call, saving the
371 * arguments we can't handle until after initializing libwireshark,
372 * and then process them after initializing libwireshark?
374 ws_opterr = 0;
376 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
377 switch (opt) {
378 case 'C': /* Configuration Profile */
379 if (profile_exists (ws_optarg, false)) {
380 set_profile_name (ws_optarg);
381 } else if (profile_exists (ws_optarg, true)) {
382 char *pf_dir_path, *pf_dir_path2, *pf_filename;
383 /* Copy from global profile */
384 if (create_persconffile_profile(ws_optarg, &pf_dir_path) == -1) {
385 cmdarg_err("Can't create directory\n\"%s\":\n%s.",
386 pf_dir_path, g_strerror(errno));
388 g_free(pf_dir_path);
389 exit_status = WS_EXIT_INVALID_FILE;
390 goto clean_exit;
392 if (copy_persconffile_profile(ws_optarg, ws_optarg, true, &pf_filename,
393 &pf_dir_path, &pf_dir_path2) == -1) {
394 cmdarg_err("Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
395 pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno));
397 g_free(pf_filename);
398 g_free(pf_dir_path);
399 g_free(pf_dir_path2);
400 exit_status = WS_EXIT_INVALID_FILE;
401 goto clean_exit;
403 set_profile_name (ws_optarg);
404 } else {
405 cmdarg_err("Configuration Profile \"%s\" does not exist", ws_optarg);
406 return 1;
408 break;
409 case 'O': /* Only output these protocols */
410 output_only = g_strdup(ws_optarg);
411 /* FALLTHROUGH */
412 case 'V': /* Verbose */
413 print_details = true;
414 print_packet_info = true;
415 break;
416 case 'x': /* Print packet data in hex (and ASCII) */
417 print_hex = true;
418 /* The user asked for hex output, so let's ensure they get it,
419 * even if they're writing to a file.
421 print_packet_info = true;
422 break;
423 case 'X':
424 ex_opt_add(ws_optarg);
425 break;
426 default:
427 break;
432 * Print packet summary information is the default, unless either -V or -x
433 * were specified. Note that this is new behavior, which
434 * allows for the possibility of printing only hex/ascii output without
435 * necessarily requiring that either the summary or details be printed too.
437 if (print_summary == -1)
438 print_summary = (print_details || print_hex) ? false : true;
440 init_report_failure_message("tfshark");
442 timestamp_set_type(TS_RELATIVE);
443 timestamp_set_precision(TS_PREC_AUTO);
444 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
447 * Libwiretap must be initialized before libwireshark is, so that
448 * dissection-time handlers for file-type-dependent blocks can
449 * register using the file type/subtype value for the file type.
451 * XXX - TFShark shouldn't use libwiretap, as it's a file dissector
452 * and should read all files as raw bytes and then try to dissect them.
453 * It needs to handle file types its own way, because we would want
454 * to support dissecting file-type-specific blocks when dissecting
455 * capture files, but that mechanism should support plugins for
456 * other files, too, if *their* formats are extensible.
458 wtap_init(true);
460 /* Register all dissectors; we must do this before checking for the
461 "-G" flag, as the "-G" flag dumps information registered by the
462 dissectors, and we must do it before we read the preferences, in
463 case any dissectors register preferences. */
464 if (!epan_init(NULL, NULL, true)) {
465 exit_status = WS_EXIT_INIT_FAILED;
466 goto clean_exit;
469 /* Register all tap listeners; we do this before we parse the arguments,
470 as the "-z" argument can specify a registered tap. */
472 /* we register the plugin taps before the other taps because
473 stats_tree taps plugins will be registered as tap listeners
474 by stats_tree_stat.c and need to registered before that */
476 /* XXX Disable tap registration for now until we can get tfshark set up with
477 * its own set of taps and the necessary registration function etc.
478 register_all_tap_listeners();
481 /* If invoked with the "-G" flag, we dump out information based on
482 the argument to the "-G" flag; if no argument is specified,
483 for backwards compatibility we dump out a glossary of display
484 filter symbols.
486 XXX - we do this here, for now, to support "-G" with no arguments.
487 If none of our build or other processes uses "-G" with no arguments,
488 we can just process it with the other arguments. */
489 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
490 proto_initialize_all_prefixes();
492 if (argc == 2)
493 proto_registrar_dump_fields();
494 else {
495 if (strcmp(argv[2], "column-formats") == 0)
496 column_dump_column_formats();
497 else if (strcmp(argv[2], "currentprefs") == 0) {
498 epan_load_settings();
499 write_prefs(NULL);
501 else if (strcmp(argv[2], "decodes") == 0)
502 dissector_dump_decodes();
503 else if (strcmp(argv[2], "defaultprefs") == 0)
504 write_prefs(NULL);
505 else if (strcmp(argv[2], "dissector-tables") == 0)
506 dissector_dump_dissector_tables();
507 else if (strcmp(argv[2], "fields") == 0)
508 proto_registrar_dump_fields();
509 else if (strcmp(argv[2], "ftypes") == 0)
510 proto_registrar_dump_ftypes();
511 else if (strcmp(argv[2], "heuristic-decodes") == 0)
512 dissector_dump_heur_decodes();
513 else if (strcmp(argv[2], "plugins") == 0) {
514 #ifdef HAVE_PLUGINS
515 plugins_dump_all();
516 #endif
517 #ifdef HAVE_LUA
518 wslua_plugins_dump_all();
519 #endif
521 else if (strcmp(argv[2], "protocols") == 0)
522 proto_registrar_dump_protocols();
523 else if (strcmp(argv[2], "values") == 0)
524 proto_registrar_dump_values();
525 else if (strcmp(argv[2], "?") == 0)
526 glossary_option_help();
527 else if (strcmp(argv[2], "-?") == 0)
528 glossary_option_help();
529 else {
530 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
531 exit_status = WS_EXIT_INVALID_OPTION;
532 goto clean_exit;
535 goto clean_exit;
538 /* Load libwireshark settings from the current profile. */
539 prefs_p = epan_load_settings();
540 prefs_loaded = true;
542 cap_file_init(&cfile);
544 /* Print format defaults to this. */
545 print_format = PR_FMT_TEXT;
547 output_fields = output_fields_new();
550 * To reset the options parser, set ws_optreset to 1 and set ws_optind to 1.
552 * Also reset ws_opterr to 1, so that error messages are printed by
553 * getopt_long().
555 ws_optreset = 1;
556 ws_optind = 1;
557 ws_opterr = 1;
559 /* Now get our args */
560 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
561 switch (opt) {
562 case '2': /* Perform two-pass analysis */
563 perform_two_pass_analysis = true;
564 break;
565 case 'C':
566 /* already processed; just ignore it now */
567 break;
568 case 'e':
569 /* Field entry */
570 output_fields_add(output_fields, ws_optarg);
571 break;
572 case 'E':
573 /* Field option */
574 if (!output_fields_set_option(output_fields, ws_optarg)) {
575 cmdarg_err("\"%s\" is not a valid field output option=value pair.", ws_optarg);
576 output_fields_list_options(stderr);
577 exit_status = WS_EXIT_INVALID_OPTION;
578 goto clean_exit;
580 break;
582 case 'h': /* Print help and exit */
583 show_help_header("Analyze file structure.");
584 print_usage(stdout);
585 goto clean_exit;
586 break;
587 case 'l': /* "Line-buffer" standard output */
588 /* The ANSI C standard does not appear to *require* that a
589 line-buffered stream be flushed to the host environment
590 whenever a newline is written, it just says that, on such a
591 stream, characters "are intended to be transmitted to or
592 from the host environment as a block when a new-line
593 character is encountered".
595 The Visual C++ 6.0 C implementation doesn't do what is
596 intended; even if you set a stream to be line-buffered, it
597 still doesn't flush the buffer at the end of every line.
599 The whole reason for the "-l" flag in either tcpdump or
600 TShark is to allow the output of a live capture to be piped
601 to a program or script and to have that script see the
602 information for the packet as soon as it's printed, rather
603 than having to wait until a standard I/O buffer fills up.
605 So, if the "-l" flag is specified, we flush the standard
606 output at the end of a packet. This will do the right thing
607 if we're printing packet summary lines, and, as we print the
608 entire protocol tree for a single packet without waiting for
609 anything to happen, it should be as good as line-buffered
610 mode if we're printing protocol trees - arguably even
611 better, as it may do fewer writes. */
612 line_buffered = true;
613 break;
614 case 'o': /* Override preference from command line */
616 char *errmsg = NULL;
618 switch (prefs_set_pref(ws_optarg, &errmsg)) {
620 case PREFS_SET_OK:
621 break;
623 case PREFS_SET_SYNTAX_ERR:
624 cmdarg_err("Invalid -o flag \"%s\"%s%s", ws_optarg,
625 errmsg ? ": " : "", errmsg ? errmsg : "");
626 g_free(errmsg);
627 exit_status = WS_EXIT_INVALID_OPTION;
628 goto clean_exit;
629 break;
631 case PREFS_SET_NO_SUCH_PREF:
632 cmdarg_err("-o flag \"%s\" specifies unknown preference", ws_optarg);
633 exit_status = WS_EXIT_INVALID_OPTION;
634 goto clean_exit;
635 break;
637 case PREFS_SET_OBSOLETE:
638 cmdarg_err("-o flag \"%s\" specifies obsolete preference", ws_optarg);
639 exit_status = WS_EXIT_INVALID_OPTION;
640 goto clean_exit;
641 break;
643 break;
645 case 'q': /* Quiet */
646 quiet = true;
647 break;
648 case 'Q': /* Really quiet */
649 quiet = true;
650 really_quiet = true;
651 break;
652 case 'r': /* Read capture file x */
653 cf_name = g_strdup(ws_optarg);
654 break;
655 case 'R': /* Read file filter */
656 rfilter = ws_optarg;
657 break;
658 case 'S': /* Set the line Separator to be printed between packets */
659 separator = g_strdup(ws_optarg);
660 break;
661 case 'T': /* printing Type */
662 if (strcmp(ws_optarg, "text") == 0) {
663 output_action = WRITE_TEXT;
664 print_format = PR_FMT_TEXT;
665 } else if (strcmp(ws_optarg, "ps") == 0) {
666 output_action = WRITE_TEXT;
667 print_format = PR_FMT_PS;
668 } else if (strcmp(ws_optarg, "pdml") == 0) {
669 output_action = WRITE_XML;
670 print_details = true; /* Need details */
671 print_summary = false; /* Don't allow summary */
672 } else if (strcmp(ws_optarg, "psml") == 0) {
673 output_action = WRITE_XML;
674 print_details = false; /* Don't allow details */
675 print_summary = true; /* Need summary */
676 } else if (strcmp(ws_optarg, "fields") == 0) {
677 output_action = WRITE_FIELDS;
678 print_details = true; /* Need full tree info */
679 print_summary = false; /* Don't allow summary */
680 } else {
681 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", ws_optarg); /* x */
682 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
683 "\t specified by the -E option.\n"
684 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
685 "\t details of a decoded packet. This information is equivalent to\n"
686 "\t the packet details printed with the -V flag.\n"
687 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
688 "\t the packets, or a multi-line view of the details of each of\n"
689 "\t the packets, depending on whether the -V flag was specified.\n"
690 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
691 "\t summary information of a decoded packet. This information is\n"
692 "\t equivalent to the information shown in the one-line summary\n"
693 "\t printed by default.\n"
694 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
695 "\t packets, or a multi-line view of the details of each of the\n"
696 "\t packets, depending on whether the -V flag was specified.\n"
697 "\t This is the default.");
698 exit_status = WS_EXIT_INVALID_OPTION;
699 goto clean_exit;
701 break;
702 case 'v': /* Show version and exit */
703 show_version();
704 goto clean_exit;
705 case 'O': /* Only output these protocols */
706 /* already processed; just ignore it now */
707 break;
708 case 'V': /* Verbose */
709 /* already processed; just ignore it now */
710 break;
711 case 'x': /* Print packet data in hex (and ASCII) */
712 /* already processed; just ignore it now */
713 break;
714 case 'X':
715 /* already processed; just ignore it now */
716 break;
717 case 'Y':
718 dfilter = ws_optarg;
719 break;
720 case 'z':
721 /* We won't call the init function for the stat this soon
722 as it would disallow MATE's fields (which are registered
723 by the preferences set callback) from being used as
724 part of a tap filter. Instead, we just add the argument
725 to a list of stat arguments. */
726 if (strcmp("help", ws_optarg) == 0) {
727 fprintf(stderr, "tfshark: The available statistics for the \"-z\" option are:\n");
728 list_stat_cmd_args();
729 goto clean_exit;
731 if (!process_stat_cmd_arg(ws_optarg)) {
732 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", ws_optarg);
733 list_stat_cmd_args();
734 exit_status = WS_EXIT_INVALID_OPTION;
735 goto clean_exit;
737 break;
738 case 'd': /* Decode as rule */
739 case 'K': /* Kerberos keytab file */
740 case 't': /* Time stamp type */
741 case 'u': /* Seconds type */
742 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
743 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
744 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
745 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
746 if (!dissect_opts_handle_opt(opt, ws_optarg)) {
747 exit_status = WS_EXIT_INVALID_OPTION;
748 goto clean_exit;
750 break;
751 default:
752 case '?': /* Bad flag - print usage message */
753 print_usage(stderr);
754 exit_status = WS_EXIT_INVALID_OPTION;
755 goto clean_exit;
756 break;
760 /* If we specified output fields, but not the output field type... */
761 if (WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
762 cmdarg_err("Output fields were specified with \"-e\", "
763 "but \"-Tfields\" was not specified.");
764 return 1;
765 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
766 cmdarg_err("\"-Tfields\" was specified, but no fields were "
767 "specified with \"-e\".");
769 exit_status = WS_EXIT_INVALID_OPTION;
770 goto clean_exit;
773 /* We require a -r flag specifying a file to read. */
774 if (cf_name == NULL) {
775 cmdarg_err("A file to read must be specified with \"-r\".");
776 exit_status = NO_FILE_SPECIFIED;
777 goto clean_exit;
780 /* If no display filter has been specified, and there are still command-
781 line arguments, treat them as the tokens of a display filter. */
782 if (ws_optind < argc) {
783 if (dfilter != NULL) {
784 cmdarg_err("Display filters were specified both with \"-Y\" "
785 "and with additional command-line arguments.");
786 exit_status = WS_EXIT_INVALID_OPTION;
787 goto clean_exit;
789 dfilter = get_args_as_string(argc, argv, ws_optind);
792 /* if "-q" wasn't specified, we should print packet information */
793 if (!quiet)
794 print_packet_info = true;
796 if (arg_error) {
797 print_usage(stderr);
798 exit_status = WS_EXIT_INVALID_OPTION;
799 goto clean_exit;
802 if (print_hex) {
803 if (output_action != WRITE_TEXT) {
804 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
805 exit_status = WS_EXIT_INVALID_OPTION;
806 goto clean_exit;
810 if (output_only != NULL) {
811 char *ps;
813 if (!print_details) {
814 cmdarg_err("-O requires -V");
815 exit_status = WS_EXIT_INVALID_OPTION;
816 goto clean_exit;
819 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
820 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
821 g_hash_table_insert(output_only_tables, (void *)ps, (void *)ps);
825 if (rfilter != NULL && !perform_two_pass_analysis) {
826 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
827 exit_status = WS_EXIT_INVALID_OPTION;
828 goto clean_exit;
831 /* Notify all registered modules that have had any of their preferences
832 changed either from one of the preferences file or from the command
833 line that their preferences have changed. */
834 prefs_apply_all();
837 * Enabled and disabled protocols and heuristic dissectors as per
838 * command-line options.
840 if (!setup_enabled_and_disabled_protocols()) {
841 exit_status = WS_EXIT_INVALID_OPTION;
842 goto clean_exit;
845 /* Build the column format array */
846 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, true);
848 if (rfilter != NULL) {
849 if (!dfilter_compile(rfilter, &rfcode, &df_err)) {
850 cmdarg_err("%s", df_err->msg);
851 df_error_free(&df_err);
852 exit_status = WS_EXIT_INVALID_FILTER;
853 goto clean_exit;
856 cfile.rfcode = rfcode;
858 if (dfilter != NULL) {
859 if (!dfilter_compile(dfilter, &dfcode, &df_err)) {
860 cmdarg_err("%s", df_err->msg);
861 df_error_free(&df_err);
862 exit_status = WS_EXIT_INVALID_FILTER;
863 goto clean_exit;
866 cfile.dfcode = dfcode;
868 if (print_packet_info) {
869 /* If we're printing as text or PostScript, we have
870 to create a print stream. */
871 if (output_action == WRITE_TEXT) {
872 switch (print_format) {
874 case PR_FMT_TEXT:
875 print_stream = print_stream_text_stdio_new(stdout);
876 break;
878 case PR_FMT_PS:
879 print_stream = print_stream_ps_stdio_new(stdout);
880 break;
882 default:
883 ws_assert_not_reached();
888 /* We have to dissect each packet if:
890 we're printing information about each packet;
892 we're using a read filter on the packets;
894 we're using a display filter on the packets;
896 we're using any taps that need dissection. */
897 do_dissection = print_packet_info || rfcode || dfcode || tap_listeners_require_dissection();
900 * Read the file.
903 /* TODO: if tfshark is ever changed to give the user a choice of which
904 open_routine reader to use, then the following needs to change. */
905 if (cf_open(&cfile, cf_name, WTAP_TYPE_AUTO, false, &err) != CF_OK) {
906 exit_status = WS_EXIT_OPEN_ERROR;
907 goto clean_exit;
910 /* Start statistics taps; we do so after successfully opening the
911 capture file, so we know we have something to compute stats
912 on, and after registering all dissectors, so that MATE will
913 have registered its field array so we can have a tap filter
914 with one of MATE's late-registered fields as part of the
915 filter. */
916 start_requested_stats();
918 /* Process the packets in the file */
919 TRY {
920 /* XXX - for now there is only 1 packet */
921 success = process_file(&cfile, 1, 0);
923 CATCH(OutOfMemoryError) {
924 fprintf(stderr,
925 "Out Of Memory.\n"
926 "\n"
927 "Sorry, but TFShark has to terminate now.\n"
928 "\n"
929 "Some infos / workarounds can be found at:\n"
930 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
931 success = false;
933 ENDTRY;
935 if (!success) {
936 /* We still dump out the results of taps, etc., as we might have
937 read some packets; however, we exit with an error status. */
938 exit_status = 2;
941 g_free(cf_name);
943 if (cfile.provider.frames != NULL) {
944 free_frame_data_sequence(cfile.provider.frames);
945 cfile.provider.frames = NULL;
948 draw_tap_listeners(true);
949 funnel_dump_all_text_windows();
951 clean_exit:
952 destroy_print_stream(print_stream);
953 epan_free(cfile.epan);
954 epan_cleanup();
956 output_fields_free(output_fields);
957 output_fields = NULL;
959 col_cleanup(&cfile.cinfo);
960 wtap_cleanup();
961 return exit_status;
964 static const char *
965 no_interface_name(struct packet_provider_data *prov _U_, uint32_t interface_id _U_, unsigned section_number _U_)
967 return "";
970 static epan_t *
971 tfshark_epan_new(capture_file *cf)
973 static const struct packet_provider_funcs funcs = {
974 /* XXX - there should be no need for time stamps */
975 cap_file_provider_get_frame_ts,
976 no_interface_name,
977 NULL,
978 NULL,
981 return epan_new(&cf->provider, &funcs);
984 static bool
985 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
986 int64_t offset, wtap_rec *rec,
987 const unsigned char *pd)
989 frame_data fdlocal;
990 uint32_t framenum;
991 bool passed;
993 /* The frame number of this packet is one more than the count of
994 frames in this packet. */
995 framenum = cf->count + 1;
997 /* If we're not running a display filter and we're not printing any
998 packet information, we don't need to do a dissection. This means
999 that all packets can be marked as 'passed'. */
1000 passed = true;
1002 frame_data_init(&fdlocal, framenum, rec, offset, cum_bytes);
1004 /* If we're going to print packet information, or we're going to
1005 run a read filter, or display filter, or we're going to process taps, set up to
1006 do a dissection and do so. */
1007 if (edt) {
1008 /* If we're running a read filter, prime the epan_dissect_t with that
1009 filter. */
1010 if (cf->rfcode)
1011 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
1013 /* This is the first pass, so prime the epan_dissect_t with the
1014 hfids postdissectors want on the first pass. */
1015 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1017 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
1018 &cf->provider.ref, cf->provider.prev_dis);
1019 if (cf->provider.ref == &fdlocal) {
1020 ref_frame = fdlocal;
1021 cf->provider.ref = &ref_frame;
1024 epan_dissect_file_run(edt, rec,
1025 file_tvbuff_new(&cf->provider, &fdlocal, pd),
1026 &fdlocal, NULL);
1028 /* Run the read filter if we have one. */
1029 if (cf->rfcode)
1030 passed = dfilter_apply_edt(cf->rfcode, edt);
1033 if (passed) {
1034 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
1035 cf->provider.prev_cap = cf->provider.prev_dis = frame_data_sequence_add(cf->provider.frames, &fdlocal);
1037 /* If we're not doing dissection then there won't be any dependent frames.
1038 * More importantly, edt.pi.fd.dependent_frames won't be initialized because
1039 * epan hasn't been initialized.
1041 if (edt && edt->pi.fd->dependent_frames) {
1042 g_hash_table_foreach(edt->pi.fd->dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
1045 cf->count++;
1046 } else {
1047 /* if we don't add it to the frame_data_sequence, clean it up right now
1048 * to avoid leaks */
1049 frame_data_destroy(&fdlocal);
1052 if (edt)
1053 epan_dissect_reset(edt);
1055 return passed;
1058 static bool
1059 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
1060 frame_data *fdata, wtap_rec *rec,
1061 Buffer *buf)
1063 column_info *cinfo;
1064 bool passed;
1066 /* If we're not running a display filter and we're not printing any
1067 packet information, we don't need to do a dissection. This means
1068 that all packets can be marked as 'passed'. */
1069 passed = true;
1071 /* If we're going to print packet information, or we're going to
1072 run a read filter, or we're going to process taps, set up to
1073 do a dissection and do so. */
1074 if (edt) {
1076 /* If we're running a display filter, prime the epan_dissect_t with that
1077 filter. */
1078 if (cf->dfcode)
1079 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
1081 /* This is the first and only pass, so prime the epan_dissect_t
1082 with the hfids postdissectors want on the first pass. */
1083 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1085 col_custom_prime_edt(edt, &cf->cinfo);
1087 /* We only need the columns if either
1088 1) some tap needs the columns
1090 2) we're printing packet info but we're *not* verbose; in verbose
1091 mode, we print the protocol tree, not the protocol summary.
1093 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary))
1094 cinfo = &cf->cinfo;
1095 else
1096 cinfo = NULL;
1098 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1099 &cf->provider.ref, cf->provider.prev_dis);
1100 if (cf->provider.ref == fdata) {
1101 ref_frame = *fdata;
1102 cf->provider.ref = &ref_frame;
1105 epan_dissect_file_run_with_taps(edt, rec,
1106 file_tvbuff_new_buffer(&cf->provider, fdata, buf), fdata, cinfo);
1108 /* Run the read/display filter if we have one. */
1109 if (cf->dfcode)
1110 passed = dfilter_apply_edt(cf->dfcode, edt);
1113 if (passed) {
1114 frame_data_set_after_dissect(fdata, &cum_bytes);
1115 /* Process this packet. */
1116 if (print_packet_info) {
1117 /* We're printing packet information; print the information for
1118 this packet. */
1119 print_packet(cf, edt);
1121 /* If we're doing "line-buffering", flush the standard output
1122 after every packet. See the comment above, for the "-l"
1123 option, for an explanation of why we do that. */
1124 if (line_buffered)
1125 fflush(stdout);
1127 if (ferror(stdout)) {
1128 show_print_file_io_error(errno);
1129 return false;
1132 cf->provider.prev_dis = fdata;
1134 cf->provider.prev_cap = fdata;
1136 if (edt) {
1137 epan_dissect_reset(edt);
1139 return passed || fdata->dependent_of_displayed;
1142 static bool
1143 local_wtap_read(capture_file *cf, wtap_rec *file_rec _U_, int *err, char **err_info _U_, int64_t *data_offset _U_, uint8_t** data_buffer)
1145 /* int bytes_read; */
1146 int64_t packet_size = wtap_file_size(cf->provider.wth, err);
1148 *data_buffer = (uint8_t*)g_malloc((size_t)packet_size);
1149 /* bytes_read =*/ file_read(*data_buffer, (unsigned int)packet_size, cf->provider.wth->fh);
1151 #if 0 /* no more filetap */
1152 if (bytes_read < 0) {
1153 *err = file_error(cf->provider.wth->fh, err_info);
1154 if (*err == 0)
1155 *err = FTAP_ERR_SHORT_READ;
1156 return false;
1157 } else if (bytes_read == 0) {
1158 /* Done with file, no error */
1159 return false;
1163 /* XXX - SET FRAME SIZE EQUAL TO TOTAL FILE SIZE */
1164 file_rec->rec_header.packet_header.caplen = (uint32_t)packet_size;
1165 file_rec->rec_header.packet_header.len = (uint32_t)packet_size;
1168 * Set the packet encapsulation to the file's encapsulation
1169 * value; if that's not WTAP_ENCAP_PER_PACKET, it's the
1170 * right answer (and means that the read routine for this
1171 * capture file type doesn't have to set it), and if it
1172 * *is* WTAP_ENCAP_PER_PACKET, the caller needs to set it
1173 * anyway.
1175 wth->rec.rec_header.packet_header.pkt_encap = wth->file_encap;
1177 if (!wth->subtype_read(wth, err, err_info, data_offset)) {
1179 * If we didn't get an error indication, we read
1180 * the last packet. See if there's any deferred
1181 * error, as might, for example, occur if we're
1182 * reading a compressed file, and we got an error
1183 * reading compressed data from the file, but
1184 * got enough compressed data to decompress the
1185 * last packet of the file.
1187 if (*err == 0)
1188 *err = file_error(wth->fh, err_info);
1189 return false; /* failure */
1193 * It makes no sense for the captured data length to be bigger
1194 * than the actual data length.
1196 if (wth->rec.rec_header.packet_header.caplen > wth->rec.rec_header.packet_header.len)
1197 wth->rec.rec_header.packet_header.caplen = wth->rec.rec_header.packet_header.len;
1200 * Make sure that it's not WTAP_ENCAP_PER_PACKET, as that
1201 * probably means the file has that encapsulation type
1202 * but the read routine didn't set this packet's
1203 * encapsulation type.
1205 ws_assert(wth->rec.rec_header.packet_header.pkt_encap != WTAP_ENCAP_PER_PACKET);
1206 #endif
1208 return true; /* success */
1211 static bool
1212 process_file(capture_file *cf, int max_packet_count, int64_t max_byte_count)
1214 uint32_t framenum;
1215 int err;
1216 char *err_info = NULL;
1217 int64_t data_offset = 0;
1218 bool filtering_tap_listeners;
1219 unsigned tap_flags;
1220 Buffer buf;
1221 epan_dissect_t *edt = NULL;
1222 wtap_rec file_rec;
1223 uint8_t* raw_data;
1225 if (print_packet_info) {
1226 if (!write_preamble(cf)) {
1227 err = errno;
1228 show_print_file_io_error(err);
1229 goto out;
1233 /* Do we have any tap listeners with filters? */
1234 filtering_tap_listeners = have_filtering_tap_listeners();
1236 /* Get the union of the flags for all tap listeners. */
1237 tap_flags = union_of_tap_listener_flags();
1239 wtap_rec_init(&file_rec);
1241 /* XXX - TEMPORARY HACK TO ELF DISSECTOR */
1242 file_rec.rec_header.packet_header.pkt_encap = 1234;
1244 if (perform_two_pass_analysis) {
1245 frame_data *fdata;
1247 /* Allocate a frame_data_sequence for all the frames. */
1248 cf->provider.frames = new_frame_data_sequence();
1250 if (do_dissection) {
1251 bool create_proto_tree;
1254 * Determine whether we need to create a protocol tree.
1255 * We do if:
1257 * we're going to apply a read filter;
1259 * a postdissector wants field values or protocols
1260 * on the first pass.
1262 create_proto_tree =
1263 (cf->rfcode != NULL || postdissectors_want_hfids());
1265 /* We're not going to display the protocol tree on this pass,
1266 so it's not going to be "visible". */
1267 edt = epan_dissect_new(cf->epan, create_proto_tree, false);
1269 while (local_wtap_read(cf, &file_rec, &err, &err_info, &data_offset, &raw_data)) {
1270 if (process_packet_first_pass(cf, edt, data_offset, &file_rec, raw_data)) {
1272 /* Stop reading if we have the maximum number of packets;
1273 * When the -c option has not been used, max_packet_count
1274 * starts at 0, which practically means, never stop reading.
1275 * (unless we roll over max_packet_count ?)
1277 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
1278 err = 0; /* This is not an error */
1279 break;
1284 if (edt) {
1285 epan_dissect_free(edt);
1286 edt = NULL;
1289 #if 0
1290 /* Close the sequential I/O side, to free up memory it requires. */
1291 wtap_sequential_close(cf->provider.wth);
1292 #endif
1294 /* Allow the protocol dissectors to free up memory that they
1295 * don't need after the sequential run-through of the packets. */
1296 postseq_cleanup_all_protocols();
1298 cf->provider.prev_dis = NULL;
1299 cf->provider.prev_cap = NULL;
1300 ws_buffer_init(&buf, 1514);
1302 if (do_dissection) {
1303 bool create_proto_tree;
1306 * Determine whether we need to create a protocol tree.
1307 * We do if:
1309 * we're going to apply a display filter;
1311 * we're going to print the protocol tree;
1313 * one of the tap listeners requires a protocol tree;
1315 * we have custom columns (which require field values, which
1316 * currently requires that we build a protocol tree).
1318 create_proto_tree =
1319 (cf->dfcode || print_details || filtering_tap_listeners ||
1320 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo));
1322 /* The protocol tree will be "visible", i.e., printed, only if we're
1323 printing packet details, which is true if we're printing stuff
1324 ("print_packet_info" is true) and we're in verbose mode
1325 ("packet_details" is true). */
1326 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
1329 for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
1330 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1331 #if 0
1332 if (wtap_seek_read(cf->provider.wth, fdata->file_off,
1333 &buf, fdata->cap_len, &err, &err_info)) {
1334 process_packet_second_pass(cf, edt, fdata, &cf->rec, &buf, tap_flags);
1336 #else
1337 if (!process_packet_second_pass(cf, edt, fdata, &cf->rec, &buf))
1338 return false;
1339 #endif
1342 if (edt) {
1343 epan_dissect_free(edt);
1344 edt = NULL;
1347 ws_buffer_free(&buf);
1349 else {
1350 framenum = 0;
1352 if (do_dissection) {
1353 bool create_proto_tree;
1356 * Determine whether we need to create a protocol tree.
1357 * We do if:
1359 * we're going to apply a read filter;
1361 * we're going to apply a display filter;
1363 * we're going to print the protocol tree;
1365 * one of the tap listeners is going to apply a filter;
1367 * one of the tap listeners requires a protocol tree;
1369 * a postdissector wants field values or protocols
1370 * on the first pass;
1372 * we have custom columns (which require field values, which
1373 * currently requires that we build a protocol tree).
1375 create_proto_tree =
1376 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
1377 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
1378 have_custom_cols(&cf->cinfo));
1380 /* The protocol tree will be "visible", i.e., printed, only if we're
1381 printing packet details, which is true if we're printing stuff
1382 ("print_packet_info" is true) and we're in verbose mode
1383 ("packet_details" is true). */
1384 edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
1387 while (local_wtap_read(cf, &file_rec, &err, &err_info, &data_offset, &raw_data)) {
1389 framenum++;
1391 if (!process_packet_single_pass(cf, edt, data_offset,
1392 &file_rec/*wtap_get_rec(cf->provider.wth)*/,
1393 raw_data))
1394 return false;
1396 /* Stop reading if we have the maximum number of packets;
1397 * When the -c option has not been used, max_packet_count
1398 * starts at 0, which practically means, never stop reading.
1399 * (unless we roll over max_packet_count ?)
1401 if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
1402 err = 0; /* This is not an error */
1403 break;
1407 if (edt) {
1408 epan_dissect_free(edt);
1409 edt = NULL;
1413 wtap_rec_cleanup(&file_rec);
1415 if (err != 0) {
1417 * Print a message noting that the read failed somewhere along the line.
1419 * If we're printing packet data, and the standard output and error are
1420 * going to the same place, flush the standard output, so everything
1421 * buffered up is written, and then print a newline to the standard error
1422 * before printing the error message, to separate it from the packet
1423 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
1424 * the _fstat() documentation at Microsoft doesn't indicate whether
1425 * st_ino is even supported.)
1427 #ifndef _WIN32
1428 if (print_packet_info) {
1429 ws_statb64 stat_stdout, stat_stderr;
1431 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
1432 if (stat_stdout.st_dev == stat_stderr.st_dev &&
1433 stat_stdout.st_ino == stat_stderr.st_ino) {
1434 fflush(stdout);
1435 fprintf(stderr, "\n");
1439 #endif
1440 #if 0
1441 switch (err) {
1443 case FTAP_ERR_UNSUPPORTED:
1444 cmdarg_err("The file \"%s\" contains record data that TFShark doesn't support.\n(%s)",
1445 cf->filename, err_info);
1446 g_free(err_info);
1447 break;
1449 case FTAP_ERR_UNSUPPORTED_ENCAP:
1450 cmdarg_err("The file \"%s\" has a packet with a network type that TFShark doesn't support.\n(%s)",
1451 cf->filename, err_info);
1452 g_free(err_info);
1453 break;
1455 case FTAP_ERR_CANT_READ:
1456 cmdarg_err("An attempt to read from the file \"%s\" failed for some unknown reason.",
1457 cf->filename);
1458 break;
1460 case FTAP_ERR_SHORT_READ:
1461 cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
1462 cf->filename);
1463 break;
1465 case FTAP_ERR_BAD_FILE:
1466 cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
1467 cf->filename, err_info);
1468 g_free(err_info);
1469 break;
1471 case FTAP_ERR_DECOMPRESS:
1472 cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
1473 "(%s)", cf->filename, err_info);
1474 break;
1476 default:
1477 cmdarg_err("An error occurred while reading the file \"%s\": %s.",
1478 cf->filename, ftap_strerror(err));
1479 break;
1481 #endif
1482 } else {
1483 if (print_packet_info) {
1484 if (!write_finale()) {
1485 err = errno;
1486 show_print_file_io_error(err);
1491 out:
1492 wtap_close(cf->provider.wth);
1493 cf->provider.wth = NULL;
1495 return (err != 0);
1498 static bool
1499 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, int64_t offset,
1500 wtap_rec *rec, const unsigned char *pd)
1502 frame_data fdata;
1503 column_info *cinfo;
1504 bool passed;
1506 /* Count this packet. */
1507 cf->count++;
1509 /* If we're not running a display filter and we're not printing any
1510 packet information, we don't need to do a dissection. This means
1511 that all packets can be marked as 'passed'. */
1512 passed = true;
1514 frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
1516 /* If we're going to print packet information, or we're going to
1517 run a read filter, or we're going to process taps, set up to
1518 do a dissection and do so. */
1519 if (edt) {
1520 /* If we're running a filter, prime the epan_dissect_t with that
1521 filter. */
1522 if (cf->dfcode)
1523 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
1525 col_custom_prime_edt(edt, &cf->cinfo);
1527 /* We only need the columns if either
1528 1) some tap needs the columns
1530 2) we're printing packet info but we're *not* verbose; in verbose
1531 mode, we print the protocol tree, not the protocol summary.
1533 3) there is a column mapped as an individual field */
1534 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
1535 cinfo = &cf->cinfo;
1536 else
1537 cinfo = NULL;
1539 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
1540 &cf->provider.ref, cf->provider.prev_dis);
1541 if (cf->provider.ref == &fdata) {
1542 ref_frame = fdata;
1543 cf->provider.ref = &ref_frame;
1546 epan_dissect_file_run_with_taps(edt, rec,
1547 frame_tvbuff_new(&cf->provider, &fdata, pd),
1548 &fdata, cinfo);
1550 /* Run the filter if we have it. */
1551 if (cf->dfcode)
1552 passed = dfilter_apply_edt(cf->dfcode, edt);
1555 if (passed) {
1556 frame_data_set_after_dissect(&fdata, &cum_bytes);
1558 /* Process this packet. */
1559 if (print_packet_info) {
1560 /* We're printing packet information; print the information for
1561 this packet. */
1562 print_packet(cf, edt);
1564 /* If we're doing "line-buffering", flush the standard output
1565 after every packet. See the comment above, for the "-l"
1566 option, for an explanation of why we do that. */
1567 if (line_buffered)
1568 fflush(stdout);
1570 if (ferror(stdout)) {
1571 show_print_file_io_error(errno);
1572 return false;
1576 /* this must be set after print_packet() [bug #8160] */
1577 prev_dis_frame = fdata;
1578 cf->provider.prev_dis = &prev_dis_frame;
1581 prev_cap_frame = fdata;
1582 cf->provider.prev_cap = &prev_cap_frame;
1584 if (edt) {
1585 epan_dissect_reset(edt);
1586 frame_data_destroy(&fdata);
1588 return passed;
1591 static bool
1592 write_preamble(capture_file *cf)
1594 switch (output_action) {
1596 case WRITE_TEXT:
1597 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
1599 case WRITE_XML:
1600 if (print_details)
1601 write_pdml_preamble(stdout, cf->filename);
1602 else
1603 write_psml_preamble(&cf->cinfo, stdout);
1604 return !ferror(stdout);
1606 case WRITE_FIELDS:
1607 write_fields_preamble(output_fields, stdout);
1608 return !ferror(stdout);
1610 default:
1611 ws_assert_not_reached();
1612 return false;
1616 static char *
1617 get_line_buf(size_t len)
1619 static char *line_bufp = NULL;
1620 static size_t line_buf_len = 256;
1621 size_t new_line_buf_len;
1623 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
1624 new_line_buf_len *= 2)
1626 if (line_bufp == NULL) {
1627 line_buf_len = new_line_buf_len;
1628 line_bufp = (char *)g_malloc(line_buf_len + 1);
1629 } else {
1630 if (new_line_buf_len > line_buf_len) {
1631 line_buf_len = new_line_buf_len;
1632 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
1635 return line_bufp;
1638 static inline void
1639 put_string(char *dest, const char *str, size_t str_len)
1641 memcpy(dest, str, str_len);
1642 dest[str_len] = '\0';
1645 static inline void
1646 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
1648 size_t i;
1650 for (i = str_len; i < str_with_spaces; i++)
1651 *dest++ = ' ';
1653 put_string(dest, str, str_len);
1656 static inline void
1657 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
1659 size_t i;
1661 memcpy(dest, str, str_len);
1662 for (i = str_len; i < str_with_spaces; i++)
1663 dest[i] = ' ';
1665 dest[str_with_spaces] = '\0';
1668 static bool
1669 print_columns(capture_file *cf)
1671 char *line_bufp;
1672 int i;
1673 size_t buf_offset;
1674 size_t column_len;
1675 size_t col_len;
1676 col_item_t* col_item;
1678 line_bufp = get_line_buf(256);
1679 buf_offset = 0;
1680 *line_bufp = '\0';
1681 for (i = 0; i < cf->cinfo.num_cols; i++) {
1682 col_item = &cf->cinfo.columns[i];
1683 /* Skip columns not marked as visible. */
1684 if (!get_column_visible(i))
1685 continue;
1686 const char* col_text = get_column_text(&cf->cinfo, i);
1687 switch (col_item->col_fmt) {
1688 case COL_NUMBER:
1689 case COL_NUMBER_DIS:
1690 column_len = col_len = strlen(col_text);
1691 if (column_len < 3)
1692 column_len = 3;
1693 line_bufp = get_line_buf(buf_offset + column_len);
1694 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
1695 break;
1697 case COL_CLS_TIME:
1698 case COL_REL_TIME:
1699 case COL_ABS_TIME:
1700 case COL_ABS_YMD_TIME: /* XXX - wider */
1701 case COL_ABS_YDOY_TIME: /* XXX - wider */
1702 case COL_UTC_TIME:
1703 case COL_UTC_YMD_TIME: /* XXX - wider */
1704 case COL_UTC_YDOY_TIME: /* XXX - wider */
1705 column_len = col_len = strlen(col_text);
1706 if (column_len < 10)
1707 column_len = 10;
1708 line_bufp = get_line_buf(buf_offset + column_len);
1709 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
1710 break;
1712 case COL_DEF_SRC:
1713 case COL_RES_SRC:
1714 case COL_UNRES_SRC:
1715 case COL_DEF_DL_SRC:
1716 case COL_RES_DL_SRC:
1717 case COL_UNRES_DL_SRC:
1718 case COL_DEF_NET_SRC:
1719 case COL_RES_NET_SRC:
1720 case COL_UNRES_NET_SRC:
1721 column_len = col_len = strlen(col_text);
1722 if (column_len < 12)
1723 column_len = 12;
1724 line_bufp = get_line_buf(buf_offset + column_len);
1725 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
1726 break;
1728 case COL_DEF_DST:
1729 case COL_RES_DST:
1730 case COL_UNRES_DST:
1731 case COL_DEF_DL_DST:
1732 case COL_RES_DL_DST:
1733 case COL_UNRES_DL_DST:
1734 case COL_DEF_NET_DST:
1735 case COL_RES_NET_DST:
1736 case COL_UNRES_NET_DST:
1737 column_len = col_len = strlen(col_text);
1738 if (column_len < 12)
1739 column_len = 12;
1740 line_bufp = get_line_buf(buf_offset + column_len);
1741 put_string_spaces(line_bufp + buf_offset, col_text, col_len, column_len);
1742 break;
1744 default:
1745 column_len = strlen(col_text);
1746 line_bufp = get_line_buf(buf_offset + column_len);
1747 put_string(line_bufp + buf_offset, col_text, column_len);
1748 break;
1750 buf_offset += column_len;
1751 if (i != cf->cinfo.num_cols - 1) {
1753 * This isn't the last column, so we need to print a
1754 * separator between this column and the next.
1756 * If we printed a network source and are printing a
1757 * network destination of the same type next, separate
1758 * them with " -> "; if we printed a network destination
1759 * and are printing a network source of the same type
1760 * next, separate them with " <- "; otherwise separate them
1761 * with a space.
1763 * We add enough space to the buffer for " <- " or " -> ",
1764 * even if we're only adding " ".
1766 line_bufp = get_line_buf(buf_offset + 4);
1767 switch (col_item->col_fmt) {
1769 case COL_DEF_SRC:
1770 case COL_RES_SRC:
1771 case COL_UNRES_SRC:
1772 switch (cf->cinfo.columns[i+1].col_fmt) {
1774 case COL_DEF_DST:
1775 case COL_RES_DST:
1776 case COL_UNRES_DST:
1777 put_string(line_bufp + buf_offset, " -> ", 4);
1778 buf_offset += 4;
1779 break;
1781 default:
1782 put_string(line_bufp + buf_offset, " ", 1);
1783 buf_offset += 1;
1784 break;
1786 break;
1788 case COL_DEF_DL_SRC:
1789 case COL_RES_DL_SRC:
1790 case COL_UNRES_DL_SRC:
1791 switch (cf->cinfo.columns[i+1].col_fmt) {
1793 case COL_DEF_DL_DST:
1794 case COL_RES_DL_DST:
1795 case COL_UNRES_DL_DST:
1796 put_string(line_bufp + buf_offset, " -> ", 4);
1797 buf_offset += 4;
1798 break;
1800 default:
1801 put_string(line_bufp + buf_offset, " ", 1);
1802 buf_offset += 1;
1803 break;
1805 break;
1807 case COL_DEF_NET_SRC:
1808 case COL_RES_NET_SRC:
1809 case COL_UNRES_NET_SRC:
1810 switch (cf->cinfo.columns[i+1].col_fmt) {
1812 case COL_DEF_NET_DST:
1813 case COL_RES_NET_DST:
1814 case COL_UNRES_NET_DST:
1815 put_string(line_bufp + buf_offset, " -> ", 4);
1816 buf_offset += 4;
1817 break;
1819 default:
1820 put_string(line_bufp + buf_offset, " ", 1);
1821 buf_offset += 1;
1822 break;
1824 break;
1826 case COL_DEF_DST:
1827 case COL_RES_DST:
1828 case COL_UNRES_DST:
1829 switch (cf->cinfo.columns[i+1].col_fmt) {
1831 case COL_DEF_SRC:
1832 case COL_RES_SRC:
1833 case COL_UNRES_SRC:
1834 put_string(line_bufp + buf_offset, " <- ", 4);
1835 buf_offset += 4;
1836 break;
1838 default:
1839 put_string(line_bufp + buf_offset, " ", 1);
1840 buf_offset += 1;
1841 break;
1843 break;
1845 case COL_DEF_DL_DST:
1846 case COL_RES_DL_DST:
1847 case COL_UNRES_DL_DST:
1848 switch (cf->cinfo.columns[i+1].col_fmt) {
1850 case COL_DEF_DL_SRC:
1851 case COL_RES_DL_SRC:
1852 case COL_UNRES_DL_SRC:
1853 put_string(line_bufp + buf_offset, " <- ", 4);
1854 buf_offset += 4;
1855 break;
1857 default:
1858 put_string(line_bufp + buf_offset, " ", 1);
1859 buf_offset += 1;
1860 break;
1862 break;
1864 case COL_DEF_NET_DST:
1865 case COL_RES_NET_DST:
1866 case COL_UNRES_NET_DST:
1867 switch (cf->cinfo.columns[i+1].col_fmt) {
1869 case COL_DEF_NET_SRC:
1870 case COL_RES_NET_SRC:
1871 case COL_UNRES_NET_SRC:
1872 put_string(line_bufp + buf_offset, " <- ", 4);
1873 buf_offset += 4;
1874 break;
1876 default:
1877 put_string(line_bufp + buf_offset, " ", 1);
1878 buf_offset += 1;
1879 break;
1881 break;
1883 default:
1884 put_string(line_bufp + buf_offset, " ", 1);
1885 buf_offset += 1;
1886 break;
1890 return print_line(print_stream, 0, line_bufp);
1893 static bool
1894 print_packet(capture_file *cf, epan_dissect_t *edt)
1896 if (print_summary || output_fields_has_cols(output_fields)) {
1897 /* Just fill in the columns. */
1898 epan_dissect_fill_in_columns(edt, false, true);
1900 if (print_summary) {
1901 /* Now print them. */
1902 switch (output_action) {
1904 case WRITE_TEXT:
1905 if (!print_columns(cf))
1906 return false;
1907 break;
1909 case WRITE_XML:
1910 write_psml_columns(edt, stdout, false);
1911 return !ferror(stdout);
1912 case WRITE_FIELDS: /*No non-verbose "fields" format */
1913 ws_assert_not_reached();
1914 break;
1918 if (print_details) {
1919 /* Print the information in the protocol tree. */
1920 switch (output_action) {
1922 case WRITE_TEXT:
1923 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
1924 print_hex, edt, output_only_tables, print_stream))
1925 return false;
1926 if (!print_hex) {
1927 if (!print_line(print_stream, 0, separator))
1928 return false;
1930 break;
1932 case WRITE_XML:
1933 write_pdml_proto_tree(NULL, edt, &cf->cinfo, stdout, false);
1934 printf("\n");
1935 return !ferror(stdout);
1936 case WRITE_FIELDS:
1937 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
1938 printf("\n");
1939 return !ferror(stdout);
1942 if (print_hex) {
1943 if (print_summary || print_details) {
1944 if (!print_line(print_stream, 0, ""))
1945 return false;
1947 if (!print_hex_data(print_stream, edt, HEXDUMP_SOURCE_MULTI | HEXDUMP_ASCII_INCLUDE))
1948 return false;
1949 if (!print_line(print_stream, 0, separator))
1950 return false;
1952 return true;
1955 static bool
1956 write_finale(void)
1958 switch (output_action) {
1960 case WRITE_TEXT:
1961 return print_finale(print_stream);
1963 case WRITE_XML:
1964 if (print_details)
1965 write_pdml_finale(stdout);
1966 else
1967 write_psml_finale(stdout);
1968 return !ferror(stdout);
1970 case WRITE_FIELDS:
1971 write_fields_finale(output_fields, stdout);
1972 return !ferror(stdout);
1974 default:
1975 ws_assert_not_reached();
1976 return false;
1980 cf_status_t
1981 cf_open(capture_file *cf, const char *fname, unsigned int type, bool is_tempfile, int *err _U_)
1983 /* The open isn't implemented yet. Fill in the information for this file. */
1985 /* Create new epan session for dissection. */
1986 epan_free(cf->epan);
1987 cf->epan = tfshark_epan_new(cf);
1989 cf->provider.wth = NULL; /**** XXX - DOESN'T WORK RIGHT NOW!!!! */
1990 cf->f_datalen = 0; /* not used, but set it anyway */
1992 /* Set the file name because we need it to set the follow stream filter.
1993 XXX - is that still true? We need it for other reasons, though,
1994 in any case. */
1995 cf->filename = g_strdup(fname);
1997 /* Indicate whether it's a permanent or temporary file. */
1998 cf->is_tempfile = is_tempfile;
2000 /* No user changes yet. */
2001 cf->unsaved_changes = false;
2003 cf->cd_t = 0; /**** XXX - DOESN'T WORK RIGHT NOW!!!! */
2004 cf->open_type = type;
2005 cf->count = 0;
2006 cf->drops_known = false;
2007 cf->drops = 0;
2008 cf->snap = 0; /**** XXX - DOESN'T WORK RIGHT NOW!!!! */
2009 nstime_set_zero(&cf->elapsed_time);
2010 cf->provider.ref = NULL;
2011 cf->provider.prev_dis = NULL;
2012 cf->provider.prev_cap = NULL;
2014 cf->state = FILE_READ_IN_PROGRESS;
2016 return CF_OK;
2018 /* fail: */
2020 char *err_info;
2021 char err_msg[2048+1];
2022 snprintf(err_msg, sizeof err_msg,
2023 cf_open_error_message(*err, err_info, false, cf->cd_t), fname);
2024 cmdarg_err("%s", err_msg);
2025 return CF_ERROR;
2029 static void
2030 show_print_file_io_error(int err)
2032 switch (err) {
2034 case ENOSPC:
2035 cmdarg_err("Not all the packets could be printed because there is "
2036 "no space left on the file system.");
2037 break;
2039 #ifdef EDQUOT
2040 case EDQUOT:
2041 cmdarg_err("Not all the packets could be printed because you are "
2042 "too close to, or over your disk quota.");
2043 break;
2044 #endif
2046 default:
2047 cmdarg_err("An error occurred while printing packets: %s.",
2048 g_strerror(err));
2049 break;
2054 * Report an error in command-line arguments.
2056 static void
2057 tfshark_cmdarg_err(const char *msg_format, va_list ap)
2059 fprintf(stderr, "tfshark: ");
2060 vfprintf(stderr, msg_format, ap);
2061 fprintf(stderr, "\n");
2065 * Report additional information for an error in command-line arguments.
2067 static void
2068 tfshark_cmdarg_err_cont(const char *msg_format, va_list ap)
2070 vfprintf(stderr, msg_format, ap);
2071 fprintf(stderr, "\n");