NSIS: Don't install the CloudTrail Falco plugin
[wireshark.git] / tshark.c
blob047d515fa7449b155547bd5f8fd04b2c24536b9d
1 /* tshark.c
3 * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4 * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * SPDX-License-Identifier: GPL-2.0-or-later
13 #include <config.h>
15 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <locale.h>
21 #include <limits.h>
23 #include <wsutil/ws_getopt.h>
25 #include <errno.h>
27 #ifdef _WIN32
28 # include <winsock2.h>
29 #endif
31 #ifndef _WIN32
32 #include <signal.h>
33 #endif
35 #include <glib.h>
37 #include <epan/exceptions.h>
38 #include <epan/epan.h>
40 #include <ws_exit_codes.h>
41 #include <wsutil/clopts_common.h>
42 #include <wsutil/cmdarg_err.h>
43 #include <ui/urls.h>
44 #include <wsutil/filesystem.h>
45 #include <wsutil/file_util.h>
46 #include <wsutil/time_util.h>
47 #include <wsutil/socket.h>
48 #include <wsutil/privileges.h>
49 #include <wsutil/report_message.h>
50 #include <wsutil/please_report_bug.h>
51 #include <wsutil/wslog.h>
52 #include <wsutil/ws_assert.h>
53 #include <wsutil/strtoi.h>
54 #include <cli_main.h>
55 #include <wsutil/version_info.h>
56 #include <wiretap/wtap_opttypes.h>
58 #include "globals.h"
59 #include <epan/timestamp.h>
60 #include <epan/packet.h>
61 #ifdef HAVE_LUA
62 #include <epan/wslua/init_wslua.h>
63 #endif
64 #include "frame_tvbuff.h"
65 #include <epan/disabled_protos.h>
66 #include <epan/prefs.h>
67 #include <epan/column.h>
68 #include <epan/decode_as.h>
69 #include <epan/print.h>
70 #include <epan/addr_resolv.h>
71 #include <epan/enterprises.h>
72 #include <epan/manuf.h>
73 #include <epan/services.h>
74 #ifdef HAVE_LIBPCAP
75 #include "ui/capture_ui_utils.h"
76 #endif
77 #include "ui/taps.h"
78 #include "ui/util.h"
79 #include "ui/ws_ui_util.h"
80 #include "ui/decode_as_utils.h"
81 #include "wsutil/filter_files.h"
82 #include "ui/cli/tshark-tap.h"
83 #include "ui/cli/tap-exportobject.h"
84 #include "ui/tap_export_pdu.h"
85 #include "ui/dissect_opts.h"
86 #include "ui/ssl_key_export.h"
87 #include "ui/failure_message.h"
88 #if defined(HAVE_LIBSMI)
89 #include "epan/oids.h"
90 #endif
91 #include "epan/maxmind_db.h"
92 #include <epan/epan_dissect.h>
93 #include <epan/tap.h>
94 #include <epan/stat_tap_ui.h>
95 #include <epan/conversation_table.h>
96 #include <epan/srt_table.h>
97 #include <epan/rtd_table.h>
98 #include <epan/ex-opt.h>
99 #include <epan/exported_pdu.h>
100 #include <epan/secrets.h>
102 #include "capture_opts.h"
104 #include "capture/capture-pcap-util.h"
106 #ifdef HAVE_LIBPCAP
107 #include "capture/capture_ifinfo.h"
108 #ifdef _WIN32
109 #include "capture/capture-wpcap.h"
110 #endif /* _WIN32 */
111 #include <capture/capture_session.h>
112 #include <capture/capture_sync.h>
113 #include <ui/capture_info.h>
114 #endif /* HAVE_LIBPCAP */
115 #include <epan/funnel.h>
117 #include <wsutil/str_util.h>
118 #include <wsutil/utf8_entities.h>
119 #include <wsutil/json_dumper.h>
120 #include <wsutil/wslog.h>
121 #ifdef _WIN32
122 #include <wsutil/win32-utils.h>
123 #endif
125 #include "extcap.h"
127 #ifdef HAVE_PLUGINS
128 #include <wsutil/codecs.h>
129 #include <wsutil/plugins.h>
130 #endif
132 /* Additional exit codes */
133 #define INVALID_EXPORT 2
134 #define INVALID_TAP 2
135 #define INVALID_CAPTURE 2
137 #define LONGOPT_EXPORT_OBJECTS LONGOPT_BASE_APPLICATION+1
138 #define LONGOPT_COLOR LONGOPT_BASE_APPLICATION+2
139 #define LONGOPT_NO_DUPLICATE_KEYS LONGOPT_BASE_APPLICATION+3
140 #define LONGOPT_ELASTIC_MAPPING_FILTER LONGOPT_BASE_APPLICATION+4
141 #define LONGOPT_EXPORT_TLS_SESSION_KEYS LONGOPT_BASE_APPLICATION+5
142 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
143 #define LONGOPT_HEXDUMP LONGOPT_BASE_APPLICATION+7
144 #define LONGOPT_SELECTED_FRAME LONGOPT_BASE_APPLICATION+8
145 #define LONGOPT_PRINT_TIMERS LONGOPT_BASE_APPLICATION+9
147 capture_file cfile;
149 static guint32 cum_bytes;
150 static frame_data ref_frame;
151 static frame_data prev_dis_frame;
152 static frame_data prev_cap_frame;
154 static gboolean perform_two_pass_analysis;
155 static guint32 epan_auto_reset_count;
156 static gboolean epan_auto_reset;
158 static guint32 selected_frame_number;
161 * The way the packet decode is to be written.
163 typedef enum {
164 WRITE_NONE, /* dummy initial state */
165 WRITE_TEXT, /* summary or detail text */
166 WRITE_XML, /* PDML or PSML */
167 WRITE_FIELDS, /* User defined list of fields */
168 WRITE_JSON, /* JSON */
169 WRITE_JSON_RAW, /* JSON only raw hex */
170 WRITE_EK /* JSON bulk insert to Elasticsearch */
171 /* Add CSV and the like here */
172 } output_action_e;
174 static output_action_e output_action;
175 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
176 static gboolean print_packet_info; /* TRUE if we're to print packet information */
177 static gboolean print_summary; /* TRUE if we're to print packet summary information */
178 static gboolean print_details; /* TRUE if we're to print packet details information */
179 static gboolean print_hex; /* TRUE if we're to print hex/ascii information */
180 static gboolean line_buffered;
181 static gboolean quiet;
182 static gboolean really_quiet;
183 static gchar* delimiter_char = " ";
184 static gboolean dissect_color;
185 static guint hexdump_source_option = HEXDUMP_SOURCE_MULTI; /* Default - Enable legacy multi-source mode */
186 static guint hexdump_ascii_option = HEXDUMP_ASCII_INCLUDE; /* Default - Enable legacy undelimited ASCII dump */
188 static print_format_e print_format = PR_FMT_TEXT;
189 static print_stream_t *print_stream;
191 static char *output_file_name;
193 static output_fields_t* output_fields;
195 static gboolean no_duplicate_keys;
196 static proto_node_children_grouper_func node_children_grouper = proto_node_group_children_by_unique;
198 static json_dumper jdumper;
200 /* The line separator used between packets, changeable via the -S option */
201 static const char *separator = "";
203 /* Per-file comments to be added to the output file. */
204 static GPtrArray *capture_comments;
206 static gboolean prefs_loaded;
208 #ifdef HAVE_LIBPCAP
210 * TRUE if we're to print packet counts to keep track of captured packets.
212 static gboolean print_packet_counts;
214 static capture_options global_capture_opts;
215 static capture_session global_capture_session;
216 static info_data_t global_info_data;
218 #ifdef SIGINFO
219 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
220 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
221 #endif /* SIGINFO */
223 static gboolean capture(void);
224 static bool capture_input_new_file(capture_session *cap_session,
225 gchar *new_file);
226 static void capture_input_new_packets(capture_session *cap_session,
227 int to_read);
228 static void capture_input_drops(capture_session *cap_session, guint32 dropped,
229 const char* interface_name);
230 static void capture_input_error(capture_session *cap_session,
231 char *error_msg, char *secondary_error_msg);
232 static void capture_input_cfilter_error(capture_session *cap_session,
233 guint i, const char *error_message);
234 static void capture_input_closed(capture_session *cap_session, gchar *msg);
236 static void report_counts(void);
237 #ifdef _WIN32
238 static BOOL WINAPI capture_cleanup(DWORD);
239 #else /* _WIN32 */
240 static void capture_cleanup(int);
241 #ifdef SIGINFO
242 static void report_counts_siginfo(int);
243 #endif /* SIGINFO */
244 #endif /* _WIN32 */
245 #endif /* HAVE_LIBPCAP */
247 static void reset_epan_mem(capture_file *cf, epan_dissect_t *edt, gboolean tree, gboolean visual);
249 typedef enum {
250 PROCESS_FILE_SUCCEEDED,
251 PROCESS_FILE_NO_FILE_PROCESSED,
252 PROCESS_FILE_ERROR,
253 PROCESS_FILE_INTERRUPTED
254 } process_file_status_t;
255 static process_file_status_t process_cap_file(capture_file *, char *, int, gboolean, int, gint64, int);
257 static gboolean process_packet_single_pass(capture_file *cf,
258 epan_dissect_t *edt, gint64 offset, wtap_rec *rec, Buffer *buf,
259 guint tap_flags);
260 static void show_print_file_io_error(void);
261 static gboolean write_preamble(capture_file *cf);
262 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
263 static gboolean write_finale(void);
265 static void tshark_cmdarg_err(const char *msg_format, va_list ap);
266 static void tshark_cmdarg_err_cont(const char *msg_format, va_list ap);
268 static GHashTable *output_only_tables;
270 static gboolean opt_print_timers;
271 struct elapsed_pass_s {
272 gint64 dissect;
273 gint64 dfilter_read;
274 gint64 dfilter_filter;
276 static struct {
277 gint64 dfilter_expand;
278 gint64 dfilter_compile;
279 struct elapsed_pass_s first_pass;
280 gint64 elapsed_first_pass;
281 struct elapsed_pass_s second_pass;
282 gint64 elapsed_second_pass;
284 tshark_elapsed;
286 static void
287 print_elapsed_json(const char *cf_name, const char *dfilter)
289 json_dumper dumper = {
290 .output_file = stderr,
291 .flags = JSON_DUMPER_FLAGS_PRETTY_PRINT,
294 if (tshark_elapsed.elapsed_first_pass == 0) {
295 // Should not happen
296 ws_warning("Print timers requested but no timing info provided");
297 return;
300 #define DUMP(name, val) \
301 json_dumper_set_member_name(&dumper, name); \
302 json_dumper_value_anyf(&dumper, "%"PRId64, val)
304 json_dumper_begin_object(&dumper);
305 json_dumper_set_member_name(&dumper, "version");
306 json_dumper_value_string(&dumper, get_ws_vcs_version_info_short());
307 if (cf_name) {
308 json_dumper_set_member_name(&dumper, "path");
309 json_dumper_value_string(&dumper, cf_name);
311 if (dfilter) {
312 json_dumper_set_member_name(&dumper, "filter");
313 json_dumper_value_string(&dumper, dfilter);
315 json_dumper_set_member_name(&dumper, "time_unit");
316 json_dumper_value_string(&dumper, "microseconds");
317 DUMP("elapsed", tshark_elapsed.elapsed_first_pass +
318 tshark_elapsed.elapsed_second_pass);
319 DUMP("dfilter_expand", tshark_elapsed.dfilter_expand);
320 DUMP("dfilter_compile", tshark_elapsed.dfilter_compile);
321 json_dumper_begin_array(&dumper);
322 json_dumper_begin_object(&dumper);
323 DUMP("elapsed", tshark_elapsed.elapsed_first_pass);
324 DUMP("dissect", tshark_elapsed.first_pass.dissect);
325 DUMP("display_filter", tshark_elapsed.first_pass.dfilter_filter);
326 DUMP("read_filter", tshark_elapsed.first_pass.dfilter_read);
327 json_dumper_end_object(&dumper);
328 if (tshark_elapsed.elapsed_second_pass) {
329 json_dumper_begin_object(&dumper);
330 DUMP("elapsed", tshark_elapsed.elapsed_second_pass);
331 DUMP("dissect", tshark_elapsed.second_pass.dissect);
332 DUMP("display_filter", tshark_elapsed.second_pass.dfilter_filter);
333 DUMP("read_filter", tshark_elapsed.second_pass.dfilter_read);
334 json_dumper_end_object(&dumper);
336 json_dumper_end_array(&dumper);
337 json_dumper_end_object(&dumper);
338 json_dumper_finish(&dumper);
341 static void
342 list_capture_types(void)
344 GArray *writable_type_subtypes;
346 fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
347 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
348 for (guint i = 0; i < writable_type_subtypes->len; i++) {
349 int ft = g_array_index(writable_type_subtypes, int, i);
350 fprintf(stderr, " %s - %s\n", wtap_file_type_subtype_name(ft),
351 wtap_file_type_subtype_description(ft));
353 g_array_free(writable_type_subtypes, TRUE);
356 struct string_elem {
357 const char *sstr; /* The short string */
358 const char *lstr; /* The long string */
361 static gint
362 string_compare(gconstpointer a, gconstpointer b)
364 return strcmp(((const struct string_elem *)a)->sstr,
365 ((const struct string_elem *)b)->sstr);
368 static void
369 string_elem_print(gpointer data)
371 fprintf(stderr, " %s - %s\n",
372 ((struct string_elem *)data)->sstr,
373 ((struct string_elem *)data)->lstr);
376 static void
377 list_read_capture_types(void)
379 guint i;
380 size_t num_file_types;
381 struct string_elem *captypes;
382 GSList *list = NULL;
383 const char *magic = "Magic-value-based";
384 const char *heuristic = "Heuristics-based";
386 /* How many readable file types are there? */
387 num_file_types = 0;
388 for (i = 0; open_routines[i].name != NULL; i++)
389 num_file_types++;
390 captypes = g_new(struct string_elem, num_file_types);
392 fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
393 for (i = 0; i < num_file_types && open_routines[i].name != NULL; i++) {
394 captypes[i].sstr = open_routines[i].name;
395 captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
396 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
398 g_slist_free_full(list, string_elem_print);
399 g_free(captypes);
402 static void
403 list_export_pdu_taps(void)
405 fprintf(stderr, "tshark: The available export tap names and the encapsulation types they produce for the \"-U tap_name\" option are:\n");
406 for (GSList *export_pdu_tap_name_list = get_export_pdu_tap_list();
407 export_pdu_tap_name_list != NULL;
408 export_pdu_tap_name_list = g_slist_next(export_pdu_tap_name_list)) {
409 fprintf(stderr, " %s - %s\n", (const char*)(export_pdu_tap_name_list->data), wtap_encap_description(export_pdu_tap_get_encap((const char*)export_pdu_tap_name_list->data)));
413 static void
414 print_usage(FILE *output)
416 fprintf(output, "\n");
417 fprintf(output, "Usage: tshark [options] ...\n");
418 fprintf(output, "\n");
420 #ifdef HAVE_LIBPCAP
421 fprintf(output, "Capture interface:\n");
422 fprintf(output, " -i <interface>, --interface <interface>\n");
423 fprintf(output, " name or idx of interface (def: first non-loopback)\n");
424 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
425 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
426 #ifdef HAVE_PCAP_CREATE
427 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
428 #else
429 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
430 #endif
431 fprintf(output, " -p, --no-promiscuous-mode\n");
432 fprintf(output, " don't capture in promiscuous mode\n");
433 #ifdef HAVE_PCAP_CREATE
434 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
435 #endif
436 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
437 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
438 fprintf(output, " size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
439 #endif
440 fprintf(output, " -y <link type>, --linktype <link type>\n");
441 fprintf(output, " link layer type (def: first appropriate)\n");
442 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
443 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
444 fprintf(output, " -L, --list-data-link-types\n");
445 fprintf(output, " print list of link-layer types of iface and exit\n");
446 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
447 fprintf(output, " --update-interval interval between updates with new packets (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
448 fprintf(output, "\n");
449 fprintf(output, "Capture stop conditions:\n");
450 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
451 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
452 fprintf(output, " duration:NUM - stop after NUM seconds\n");
453 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
454 fprintf(output, " files:NUM - stop after NUM files\n");
455 fprintf(output, " packets:NUM - stop after NUM packets\n");
456 /*fprintf(output, "\n");*/
457 fprintf(output, "Capture output:\n");
458 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
459 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
460 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
461 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
462 fprintf(output, " packets:NUM - switch to next file after NUM packets\n");
463 fprintf(output, " interval:NUM - switch to next file when the time is\n");
464 fprintf(output, " an exact multiple of NUM secs\n");
465 fprintf(output, " printname:FILE - print filename to FILE when written\n");
466 fprintf(output, " (can use 'stdout' or 'stderr')\n");
467 #endif /* HAVE_LIBPCAP */
468 #ifdef HAVE_PCAP_REMOTE
469 fprintf(output, "RPCAP options:\n");
470 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
471 #endif
472 /*fprintf(output, "\n");*/
473 fprintf(output, "Input file:\n");
474 fprintf(output, " -r <infile>, --read-file <infile>\n");
475 fprintf(output, " set the filename to read from (or '-' for stdin)\n");
477 fprintf(output, "\n");
478 fprintf(output, "Processing:\n");
479 fprintf(output, " -2 perform a two-pass analysis\n");
480 fprintf(output, " -M <packet count> perform session auto reset\n");
481 fprintf(output, " -R <read filter>, --read-filter <read filter>\n");
482 fprintf(output, " packet Read filter in Wireshark display filter syntax\n");
483 fprintf(output, " (requires -2)\n");
484 fprintf(output, " -Y <display filter>, --display-filter <display filter>\n");
485 fprintf(output, " packet displaY filter in Wireshark display filter\n");
486 fprintf(output, " syntax\n");
487 fprintf(output, " -n disable all name resolutions (def: \"mNd\" enabled, or\n");
488 fprintf(output, " as set in preferences)\n");
489 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mnNtdv\"\n");
490 fprintf(output, " -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
491 fprintf(output, " \"Decode As\", see the man page for details\n");
492 fprintf(output, " Example: tcp.port==8888,http\n");
493 fprintf(output, " -H <hosts file> read a list of entries from a hosts file, which will\n");
494 fprintf(output, " then be written to a capture file. (Implies -W n)\n");
495 fprintf(output, " --enable-protocol <proto_name>\n");
496 fprintf(output, " enable dissection of proto_name\n");
497 fprintf(output, " --disable-protocol <proto_name>\n");
498 fprintf(output, " disable dissection of proto_name\n");
499 fprintf(output, " --only-protocols <protocols>\n");
500 fprintf(output, " Only enable dissection of these protocols, comma\n");
501 fprintf(output, " separated. Disable everything else\n");
502 fprintf(output, " --disable-all-protocols\n");
503 fprintf(output, " Disable dissection of all protocols\n");
504 fprintf(output, " --enable-heuristic <short_name>\n");
505 fprintf(output, " enable dissection of heuristic protocol\n");
506 fprintf(output, " --disable-heuristic <short_name>\n");
507 fprintf(output, " disable dissection of heuristic protocol\n");
509 /*fprintf(output, "\n");*/
510 fprintf(output, "Output:\n");
511 fprintf(output, " -w <outfile|-> write packets to a pcapng-format file named \"outfile\"\n");
512 fprintf(output, " (or '-' for stdout)\n");
513 fprintf(output, " --capture-comment <comment>\n");
514 fprintf(output, " add a capture file comment, if supported\n");
515 fprintf(output, " -C <config profile> start with specified configuration profile\n");
516 fprintf(output, " -F <output file type> set the output file type; default is pcapng.\n");
517 fprintf(output, " an empty \"-F\" option will list the file types\n");
518 fprintf(output, " -V add output of packet tree (Packet Details)\n");
519 fprintf(output, " -O <protocols> Only show packet details of these protocols, comma\n");
520 fprintf(output, " separated\n");
521 fprintf(output, " -P, --print print packet summary even when writing to a file\n");
522 fprintf(output, " -S <separator> the line separator to print between packets\n");
523 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
524 fprintf(output, " --hexdump <hexoption> add hexdump, set options for data source and ASCII dump\n");
525 fprintf(output, " all dump all data sources (-x default)\n");
526 fprintf(output, " frames dump only frame data source\n");
527 fprintf(output, " ascii include ASCII dump text (-x default)\n");
528 fprintf(output, " delimit delimit ASCII dump text with '|' characters\n");
529 fprintf(output, " noascii exclude ASCII dump text\n");
530 fprintf(output, " help display help for --hexdump and exit\n");
531 fprintf(output, " -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|?\n");
532 fprintf(output, " format of text output (def: text)\n");
533 fprintf(output, " -j <protocolfilter> protocols layers filter if -T ek|pdml|json selected\n");
534 fprintf(output, " (e.g. \"ip ip.flags text\", filter does not expand child\n");
535 fprintf(output, " nodes, unless child is specified also in the filter)\n");
536 fprintf(output, " -J <protocolfilter> top level protocol filter if -T ek|pdml|json selected\n");
537 fprintf(output, " (e.g. \"http tcp\", filter which expands all child nodes)\n");
538 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port,\n");
539 fprintf(output, " _ws.col.info)\n");
540 fprintf(output, " this option can be repeated to print multiple fields\n");
541 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
542 fprintf(output, " bom=y|n print a UTF-8 BOM\n");
543 fprintf(output, " header=y|n switch headers on and off\n");
544 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
545 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
546 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as\n");
547 fprintf(output, " aggregator\n");
548 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
549 fprintf(output, " -t (a|ad|adoy|d|dd|e|r|u|ud|udoy)[.[N]]|.[N]\n");
550 fprintf(output, " output format of time stamps (def: r: rel. to first)\n");
551 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
552 fprintf(output, " -l flush standard output after each packet\n");
553 fprintf(output, " (implies --update-interval 0)\n");
554 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
555 fprintf(output, " -Q only log true errors to stderr (quieter than -q)\n");
556 fprintf(output, " -g enable group read access on the output file(s)\n");
557 fprintf(output, " -W n Save extra information in the file, if supported.\n");
558 fprintf(output, " n = write network address resolution information\n");
559 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
560 fprintf(output, " -U tap_name PDUs export mode, see the man page for details\n");
561 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
562 fprintf(output, " --export-objects <protocol>,<destdir>\n");
563 fprintf(output, " save exported objects for a protocol to a directory\n");
564 fprintf(output, " named \"destdir\"\n");
565 fprintf(output, " --export-tls-session-keys <keyfile>\n");
566 fprintf(output, " export TLS Session Keys to a file named \"keyfile\"\n");
567 fprintf(output, " --color color output text similarly to the Wireshark GUI,\n");
568 fprintf(output, " requires a terminal with 24-bit color support\n");
569 fprintf(output, " Also supplies color attributes to pdml and psml formats\n");
570 fprintf(output, " (Note that attributes are nonstandard)\n");
571 fprintf(output, " --no-duplicate-keys If -T json is specified, merge duplicate keys in an object\n");
572 fprintf(output, " into a single key with as value a json array containing all\n");
573 fprintf(output, " values\n");
574 fprintf(output, " --elastic-mapping-filter <protocols> If -G elastic-mapping is specified, put only the\n");
575 fprintf(output, " specified protocols within the mapping file\n");
576 fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
577 fprintf(output, " (default: %s)\n", g_get_tmp_dir());
578 fprintf(output, "\n");
580 ws_log_print_usage(output);
581 fprintf(output, "\n");
583 fprintf(output, "Miscellaneous:\n");
584 fprintf(output, " -h, --help display this help and exit\n");
585 fprintf(output, " -v, --version display version info and exit\n");
586 fprintf(output, " -o <name>:<value> ... override preference setting\n");
587 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
588 fprintf(output, " -G [report] dump one of several available reports and exit\n");
589 fprintf(output, " default report=\"fields\"\n");
590 fprintf(output, " use \"-G help\" for more help\n");
591 #ifdef __linux__
592 fprintf(output, "\n");
593 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
594 fprintf(output, "You might want to enable it by executing:\n");
595 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
596 fprintf(output, "Note that this can make your system less secure!\n");
597 #endif
601 static void
602 glossary_option_help(void)
604 FILE *output;
606 output = stdout;
608 fprintf(output, "%s\n", get_appname_and_version());
610 fprintf(output, "\n");
611 fprintf(output, "Usage: tshark -G [report]\n");
612 fprintf(output, "\n");
613 fprintf(output, "Glossary table reports:\n");
614 fprintf(output, " -G column-formats dump column format codes and exit\n");
615 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
616 fprintf(output, " -G dissector-tables dump dissector table names, types, and properties\n");
617 fprintf(output, " -G dissectors dump registered dissector names\n");
618 fprintf(output, " -G elastic-mapping dump ElasticSearch mapping file\n");
619 fprintf(output, " -G enterprises dump IANA Private Enterprise Number (PEN) table\n");
620 fprintf(output, " -G fieldcount dump count of header fields and exit\n");
621 fprintf(output, " -G fields [prefix] dump fields glossary and exit\n");
622 fprintf(output, " -G ftypes dump field type basic and descriptive names\n");
623 fprintf(output, " -G heuristic-decodes dump heuristic dissector tables\n");
624 fprintf(output, " -G manuf dump ethernet manufacturer tables\n");
625 fprintf(output, " -G plugins dump installed plugins and exit\n");
626 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
627 fprintf(output, " -G services dump transport service (port) names\n");
628 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
629 fprintf(output, "\n");
630 fprintf(output, "Preference reports:\n");
631 fprintf(output, " -G currentprefs dump current preferences and exit\n");
632 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
633 fprintf(output, " -G folders dump about:folders\n");
634 fprintf(output, "\n");
637 static void
638 hexdump_option_help(FILE *output)
640 fprintf(output, "%s\n", get_appname_and_version());
641 fprintf(output, "\n");
642 fprintf(output, "tshark: Valid --hexdump <hexoption> values include:\n");
643 fprintf(output, "\n");
644 fprintf(output, "Data source options:\n");
645 fprintf(output, " all add hexdump, dump all data sources (-x default)\n");
646 fprintf(output, " frames add hexdump, dump only frame data source\n");
647 fprintf(output, "\n");
648 fprintf(output, "ASCII options:\n");
649 fprintf(output, " ascii add hexdump, include ASCII dump text (-x default)\n");
650 fprintf(output, " delimit add hexdump, delimit ASCII dump text with '|' characters\n");
651 fprintf(output, " noascii add hexdump, exclude ASCII dump text\n");
652 fprintf(output, "\n");
653 fprintf(output, "Miscellaneous:\n");
654 fprintf(output, " help display this help and exit\n");
655 fprintf(output, "\n");
656 fprintf(output, "Example:\n");
657 fprintf(output, "\n");
658 fprintf(output, " $ tshark ... --hexdump frames --hexdump delimit ...\n");
659 fprintf(output, "\n");
662 static void
663 print_current_user(void)
665 gchar *cur_user, *cur_group;
667 if (started_with_special_privs()) {
668 cur_user = get_cur_username();
669 cur_group = get_cur_groupname();
670 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
671 cur_user, cur_group);
672 g_free(cur_user);
673 g_free(cur_group);
674 if (running_with_special_privs()) {
675 fprintf(stderr, " This could be dangerous.");
677 fprintf(stderr, "\n");
681 static void
682 gather_tshark_compile_info(feature_list l)
684 /* Capture libraries */
685 gather_caplibs_compile_info(l);
686 epan_gather_compile_info(l);
689 static void
690 gather_tshark_runtime_info(feature_list l)
692 #ifdef HAVE_LIBPCAP
693 gather_caplibs_runtime_info(l);
694 #endif
696 /* stuff used by libwireshark */
697 epan_gather_runtime_info(l);
700 static gboolean
701 _compile_dfilter(const char *text, dfilter_t **dfp, const char *caller)
703 gboolean ok;
704 df_error_t *df_err;
705 char *err_off;
706 char *expanded;
707 gint64 elapsed_start;
709 elapsed_start = g_get_monotonic_time();
710 expanded = dfilter_expand(text, &df_err);
711 if (expanded == NULL) {
712 cmdarg_err("%s", df_err->msg);
713 df_error_free(&df_err);
714 return FALSE;
716 tshark_elapsed.dfilter_expand = g_get_monotonic_time() - elapsed_start;
718 elapsed_start = g_get_monotonic_time();
719 ok = dfilter_compile_full(expanded, dfp, &df_err, DF_OPTIMIZE, caller);
720 if (!ok ) {
721 cmdarg_err("%s", df_err->msg);
723 if (df_err->loc.col_start >= 0) {
724 err_off = ws_strdup_underline(NULL, df_err->loc.col_start, df_err->loc.col_len);
725 cmdarg_err_cont(" %s", expanded);
726 cmdarg_err_cont(" %s", err_off);
727 g_free(err_off);
729 df_error_free(&df_err);
731 tshark_elapsed.dfilter_compile = g_get_monotonic_time() - elapsed_start;
733 g_free(expanded);
734 return ok;
737 #define compile_dfilter(text, dfp) _compile_dfilter(text, dfp, __func__)
739 static gboolean
740 protocolfilter_add_opt(const char* arg, pf_flags filter_flags)
742 gchar **newfilter = NULL;
743 for (newfilter = wmem_strsplit(wmem_epan_scope(), arg, " ", -1); *newfilter; newfilter++) {
744 if (strcmp(*newfilter, "") == 0) {
745 /* Don't treat the empty string as an intended field abbreviation
746 * to output, consecutive spaces on the command line probably
747 * aren't intentional.
749 continue;
751 if (!output_fields_add_protocolfilter(output_fields, *newfilter, filter_flags)) {
752 cmdarg_err("%s was already specified with different filter flags. Overwriting previous protocol filter.", *newfilter);
755 return TRUE;
758 static void
759 about_folders(void)
761 const char *constpath;
762 char *path;
763 gint i;
764 gchar **resultArray;
766 /* "file open" */
769 * Fetching the "File" dialogs folder not implemented.
770 * This is arguably just a pwd for a ui/cli .
773 /* temp */
774 constpath = g_get_tmp_dir();
775 #ifdef HAVE_LIBPCAP
776 /* global_capture_opts only exists in this case */
777 if (global_capture_opts.temp_dir)
778 constpath = global_capture_opts.temp_dir;
779 #endif
780 printf("%-21s\t%s\n", "Temp:", constpath);
782 /* pers conf */
783 path = get_persconffile_path("", FALSE);
784 printf("%-21s\t%s\n", "Personal configuration:", path);
785 g_free(path);
787 /* global conf */
788 constpath = get_datafile_dir();
789 if (constpath != NULL) {
790 printf("%-21s\t%s\n", "Global configuration:", constpath);
793 /* system */
794 constpath = get_systemfile_dir();
795 printf("%-21s\t%s\n", "System:", constpath);
797 /* program */
798 constpath = get_progfile_dir();
799 printf("%-21s\t%s\n", "Program:", constpath);
801 #ifdef HAVE_PLUGINS
802 /* pers plugins */
803 printf("%-21s\t%s\n", "Personal Plugins:", get_plugins_pers_dir_with_version());
805 /* global plugins */
806 printf("%-21s\t%s\n", "Global Plugins:", get_plugins_dir_with_version());
807 #endif
809 #ifdef HAVE_LUA
810 /* pers lua plugins */
811 printf("%-21s\t%s\n", "Personal Lua Plugins:", get_plugins_pers_dir());
813 /* global lua plugins */
814 printf("%-21s\t%s\n", "Global Lua Plugins:", get_plugins_dir());
815 #endif
817 /* Personal Extcap */
818 constpath = get_extcap_pers_dir();
820 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
821 for(i = 0; resultArray[i]; i++)
822 printf("%-21s\t%s\n", "Personal Extcap path:", g_strstrip(resultArray[i]));
824 g_strfreev(resultArray);
826 /* Global Extcap */
827 constpath = get_extcap_dir();
829 resultArray = g_strsplit(constpath, G_SEARCHPATH_SEPARATOR_S, 10);
830 for(i = 0; resultArray[i]; i++)
831 printf("%-21s\t%s\n", "Global Extcap path:", g_strstrip(resultArray[i]));
833 g_strfreev(resultArray);
835 /* MaxMindDB */
836 path = maxmind_db_get_paths();
838 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 10);
840 for(i = 0; resultArray[i]; i++)
841 printf("%-21s\t%s\n", "MaxMind database path:", g_strstrip(resultArray[i]));
843 g_strfreev(resultArray);
844 g_free(path);
846 #ifdef HAVE_LIBSMI
847 /* SMI MIBs/PIBs */
848 path = oid_get_default_mib_path();
850 resultArray = g_strsplit(path, G_SEARCHPATH_SEPARATOR_S, 20);
852 for(i = 0; resultArray[i]; i++)
853 printf("%-21s\t%s\n", "MIB/PIB path:", g_strstrip(resultArray[i]));
855 g_strfreev(resultArray);
856 g_free(path);
857 #endif
861 static gboolean
862 must_do_dissection(dfilter_t *rfcode, dfilter_t *dfcode,
863 gchar *volatile pdu_export_arg)
865 /* We have to dissect each packet if:
867 we're printing information about each packet;
869 we're using a read filter on the packets;
871 we're using a display filter on the packets;
873 we're exporting PDUs;
875 we're using any taps that need dissection. */
876 return print_packet_info || rfcode || dfcode || pdu_export_arg ||
877 tap_listeners_require_dissection();
880 #ifdef HAVE_LIBPCAP
882 * Check whether a purported *shark packet-matching expression (display
883 * or read filter) looks like a capture filter and, if so, print a
884 * warning.
886 * Used, for example, if the string in question isn't a valid packet-
887 * matching expression.
889 static void
890 warn_about_capture_filter(const char *rfilter)
892 struct bpf_program fcode;
893 pcap_t *pc;
895 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
896 if (pc != NULL) {
897 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
898 pcap_freecode(&fcode);
899 cmdarg_err_cont(
900 " Note: That read filter code looks like a valid capture filter;\n"
901 " maybe you mixed them up?");
903 pcap_close(pc);
906 #endif
908 #ifdef HAVE_LIBPCAP
909 static GList *cached_if_list;
911 static GList *
912 capture_opts_get_interface_list(int *err, char **err_str)
914 if (cached_if_list == NULL) {
916 * This isn't a GUI tool, so no need for a callback.
918 cached_if_list = capture_interface_list(err, err_str, NULL);
921 * Routines expect to free the returned interface list, so return
922 * a deep copy.
924 return interface_list_copy(cached_if_list);
926 #endif
929 main(int argc, char *argv[])
931 char *err_msg;
932 static const struct report_message_routines tshark_report_routines = {
933 failure_message,
934 failure_message,
935 open_failure_message,
936 read_failure_message,
937 write_failure_message,
938 cfile_open_failure_message,
939 cfile_dump_open_failure_message,
940 cfile_read_failure_message,
941 cfile_write_failure_message,
942 cfile_close_failure_message
944 int opt;
945 static const struct ws_option long_options[] = {
946 {"help", ws_no_argument, NULL, 'h'},
947 {"version", ws_no_argument, NULL, 'v'},
948 LONGOPT_CAPTURE_COMMON
949 LONGOPT_DISSECT_COMMON
950 LONGOPT_READ_CAPTURE_COMMON
951 {"print", ws_no_argument, NULL, 'P'},
952 {"export-objects", ws_required_argument, NULL, LONGOPT_EXPORT_OBJECTS},
953 {"export-tls-session-keys", ws_required_argument, NULL, LONGOPT_EXPORT_TLS_SESSION_KEYS},
954 {"color", ws_no_argument, NULL, LONGOPT_COLOR},
955 {"no-duplicate-keys", ws_no_argument, NULL, LONGOPT_NO_DUPLICATE_KEYS},
956 {"elastic-mapping-filter", ws_required_argument, NULL, LONGOPT_ELASTIC_MAPPING_FILTER},
957 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
958 {"hexdump", ws_required_argument, NULL, LONGOPT_HEXDUMP},
959 {"selected-frame", ws_required_argument, NULL, LONGOPT_SELECTED_FRAME},
960 {"print-timers", ws_no_argument, NULL, LONGOPT_PRINT_TIMERS},
961 {0, 0, 0, 0}
963 gboolean arg_error = FALSE;
964 gboolean has_extcap_options = FALSE;
965 gboolean is_capturing = TRUE;
967 int err;
968 gchar *err_info;
969 gboolean exp_pdu_status;
970 volatile process_file_status_t status;
971 volatile gboolean draw_taps = FALSE;
972 volatile int exit_status = EXIT_SUCCESS;
973 #ifdef HAVE_LIBPCAP
974 int caps_queries = 0;
975 GList *if_list;
976 gchar *err_str, *err_str_secondary;
977 #else
978 gboolean capture_option_specified = FALSE;
979 volatile int max_packet_count = 0;
980 #endif
981 volatile int out_file_type = WTAP_FILE_TYPE_SUBTYPE_UNKNOWN;
982 volatile gboolean out_file_name_res = FALSE;
983 volatile int in_file_type = WTAP_TYPE_AUTO;
984 gchar *volatile cf_name = NULL;
985 gchar *rfilter = NULL;
986 gchar *volatile dfilter = NULL;
987 dfilter_t *rfcode = NULL;
988 dfilter_t *dfcode = NULL;
989 e_prefs *prefs_p;
990 gchar *output_only = NULL;
991 gchar *volatile pdu_export_arg = NULL;
992 char *volatile exp_pdu_filename = NULL;
993 const gchar *volatile tls_session_keys_file = NULL;
994 exp_pdu_t exp_pdu_tap_data;
995 const gchar* elastic_mapping_filter = NULL;
998 * The leading + ensures that getopt_long() does not permute the argv[]
999 * entries.
1001 * We have to make sure that the first getopt_long() preserves the content
1002 * of argv[] for the subsequent getopt_long() call.
1004 * We use getopt_long() in both cases to ensure that we're using a routine
1005 * whose permutation behavior we can control in the same fashion on all
1006 * platforms, and so that, if we ever need to process a long argument before
1007 * doing further initialization, we can do so.
1009 * Glibc and Solaris libc document that a leading + disables permutation
1010 * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
1011 * and macOS don't document it, but do so anyway.
1013 * We do *not* use a leading - because the behavior of a leading - is
1014 * platform-dependent.
1016 #define OPTSTRING "+2" OPTSTRING_CAPTURE_COMMON OPTSTRING_DISSECT_COMMON OPTSTRING_READ_CAPTURE_COMMON "M:C:e:E:F:gG:hH:j:J:lo:O:PqQS:T:U:vVw:W:xX:z:"
1018 static const char optstring[] = OPTSTRING;
1021 * Set the C-language locale to the native environment and set the
1022 * code page to UTF-8 on Windows.
1024 #ifdef _WIN32
1025 setlocale(LC_ALL, ".UTF-8");
1026 #else
1027 setlocale(LC_ALL, "");
1028 #endif
1030 ws_tzset();
1032 cmdarg_err_init(tshark_cmdarg_err, tshark_cmdarg_err_cont);
1034 /* Initialize log handler early so we can have proper logging during startup. */
1035 ws_log_init("tshark", vcmdarg_err);
1037 /* Early logging command-line initialization. */
1038 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1040 ws_noisy("Finished log init and parsing command line log arguments");
1041 ws_debug("tshark started with %d args", argc);
1043 #ifdef _WIN32
1044 create_app_running_mutex();
1045 #endif /* _WIN32 */
1048 * Get credential information for later use, and drop privileges
1049 * before doing anything else.
1050 * Let the user know if anything happened.
1052 init_process_policies();
1053 relinquish_special_privs_perm();
1054 print_current_user();
1057 * Attempt to get the pathname of the directory containing the
1058 * executable file.
1060 err_msg = configuration_init(argv[0], NULL);
1061 if (err_msg != NULL) {
1062 fprintf(stderr,
1063 "tshark: Can't get pathname of directory containing the tshark program: %s.\n"
1064 "It won't be possible to capture traffic.\n"
1065 "Report this to the Wireshark developers.",
1066 err_msg);
1067 g_free(err_msg);
1070 initialize_funnel_ops();
1072 #ifdef _WIN32
1073 ws_init_dll_search_path();
1074 #ifdef HAVE_LIBPCAP
1075 /* Load wpcap if possible. Do this before collecting the run-time version information */
1076 load_wpcap();
1077 #endif /* HAVE_LIBPCAP */
1078 #endif /* _WIN32 */
1080 /* Initialize the version information. */
1081 ws_init_version_info("TShark",
1082 gather_tshark_compile_info, gather_tshark_runtime_info);
1084 /* Fail sometimes. Useful for testing fuzz scripts. */
1085 /* if (g_random_int_range(0, 100) < 5) abort(); */
1088 * In order to have the -X opts assigned before the wslua machine starts
1089 * we need to call getopt_long before epan_init() gets called.
1091 * In order to handle, for example, -o options, we also need to call it
1092 * *after* epan_init() gets called, so that the dissectors have had a
1093 * chance to register their preferences.
1095 * Spawning a bunch of extcap processes can delay program startup,
1096 * particularly on Windows. Check to see if we have any options that
1097 * might require extcap and set has_extcap_options = TRUE if that's
1098 * the case.
1100 * XXX - can we do this all with one getopt_long() call, saving the
1101 * arguments we can't handle until after initializing libwireshark,
1102 * and then process them after initializing libwireshark?
1104 ws_opterr = 0;
1106 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1107 switch (opt) {
1108 case 'C': /* Configuration Profile */
1109 if (profile_exists (ws_optarg, FALSE)) {
1110 set_profile_name (ws_optarg);
1111 } else if (profile_exists (ws_optarg, TRUE)) {
1112 char *pf_dir_path, *pf_dir_path2, *pf_filename;
1113 /* Copy from global profile */
1114 if (create_persconffile_profile(ws_optarg, &pf_dir_path) == -1) {
1115 cmdarg_err("Can't create directory\n\"%s\":\n%s.",
1116 pf_dir_path, g_strerror(errno));
1118 g_free(pf_dir_path);
1119 exit_status = WS_EXIT_INVALID_FILE;
1120 goto clean_exit;
1122 if (copy_persconffile_profile(ws_optarg, ws_optarg, TRUE, &pf_filename,
1123 &pf_dir_path, &pf_dir_path2) == -1) {
1124 cmdarg_err("Can't copy file \"%s\" in directory\n\"%s\" to\n\"%s\":\n%s.",
1125 pf_filename, pf_dir_path2, pf_dir_path, g_strerror(errno));
1127 g_free(pf_filename);
1128 g_free(pf_dir_path);
1129 g_free(pf_dir_path2);
1130 exit_status = WS_EXIT_INVALID_FILE;
1131 goto clean_exit;
1133 set_profile_name (ws_optarg);
1134 } else {
1135 cmdarg_err("Configuration Profile \"%s\" does not exist", ws_optarg);
1136 exit_status = WS_EXIT_INVALID_OPTION;
1137 goto clean_exit;
1139 break;
1140 case 'G':
1141 if (g_str_has_suffix(ws_optarg, "prefs")) {
1142 has_extcap_options = TRUE;
1144 is_capturing = FALSE;
1145 break;
1146 case 'i':
1147 has_extcap_options = TRUE;
1148 break;
1149 case 'o':
1150 if (g_str_has_prefix(ws_optarg, "extcap.")) {
1151 has_extcap_options = TRUE;
1153 break;
1154 case 'P': /* Print packet summary info even when writing to a file */
1155 print_packet_info = TRUE;
1156 print_summary = TRUE;
1157 break;
1158 case 'r': /* Read capture file x */
1159 cf_name = g_strdup(ws_optarg);
1160 is_capturing = FALSE;
1161 break;
1162 case 'O': /* Only output these protocols */
1163 output_only = g_strdup(ws_optarg);
1164 /* FALLTHROUGH */
1165 case 'V': /* Verbose */
1166 print_details = TRUE;
1167 print_packet_info = TRUE;
1168 break;
1169 case 'x': /* Print packet data in hex (and ASCII) */
1170 print_hex = TRUE;
1171 /* The user asked for hex output, so let's ensure they get it,
1172 * even if they're writing to a file.
1174 print_packet_info = TRUE;
1175 break;
1176 case 'X':
1177 ex_opt_add(ws_optarg);
1178 break;
1179 case 'h':
1180 case 'v':
1181 is_capturing = FALSE;
1182 break;
1183 case LONGOPT_ELASTIC_MAPPING_FILTER:
1184 elastic_mapping_filter = ws_optarg;
1185 break;
1186 default:
1187 break;
1191 #ifndef HAVE_LUA
1192 if (ex_opt_count("lua_script") > 0) {
1193 cmdarg_err("This version of TShark was not built with support for Lua scripting.");
1194 exit_status = WS_EXIT_INIT_FAILED;
1195 goto clean_exit;
1197 #endif /* HAVE_LUA */
1199 init_report_message("TShark", &tshark_report_routines);
1201 #ifdef HAVE_LIBPCAP
1202 capture_opts_init(&global_capture_opts, capture_opts_get_interface_list);
1203 capture_session_init(&global_capture_session, &cfile,
1204 capture_input_new_file, capture_input_new_packets,
1205 capture_input_drops, capture_input_error,
1206 capture_input_cfilter_error, capture_input_closed);
1207 #endif
1209 timestamp_set_type(TS_RELATIVE);
1210 timestamp_set_precision(TS_PREC_AUTO);
1211 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1214 * Libwiretap must be initialized before libwireshark is, so that
1215 * dissection-time handlers for file-type-dependent blocks can
1216 * register using the file type/subtype value for the file type.
1218 wtap_init(TRUE);
1220 /* Register all dissectors; we must do this before checking for the
1221 "-G" flag, as the "-G" flag dumps information registered by the
1222 dissectors, and we must do it before we read the preferences, in
1223 case any dissectors register preferences. */
1224 if (!epan_init(NULL, NULL, TRUE)) {
1225 exit_status = WS_EXIT_INIT_FAILED;
1226 goto clean_exit;
1229 /* Register all tap listeners; we do this before we parse the arguments,
1230 as the "-z" argument can specify a registered tap. */
1232 register_all_tap_listeners(tap_reg_listener);
1234 /* Register extcap preferences only when needed. */
1235 if (has_extcap_options || is_capturing) {
1236 extcap_register_preferences();
1239 conversation_table_set_gui_info(init_iousers);
1240 endpoint_table_set_gui_info(init_endpoints);
1241 srt_table_iterate_tables(register_srt_tables, NULL);
1242 rtd_table_iterate_tables(register_rtd_tables, NULL);
1243 stat_tap_iterate_tables(register_simple_stat_tables, NULL);
1245 /* If invoked with the "-G" flag, we dump out information based on
1246 the argument to the "-G" flag; if no argument is specified,
1247 for backwards compatibility we dump out a glossary of display
1248 filter symbols.
1250 XXX - we do this here, for now, to support "-G" with no arguments.
1251 If none of our build or other processes uses "-G" with no arguments,
1252 we can just process it with the other arguments. */
1254 /* NOTE: This is before the preferences are loaded with
1255 * epan_load_settings() below, so if you add a new report
1256 * and it depends on the profile settings, call epan_load_settings()
1257 * first.
1259 * It is after addr_resolv_init() is called (done by epan_init()),
1260 * so "manuf", "enterprises", and "services" have the values from
1261 * the global and personal profile files already loaded.
1263 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
1264 proto_initialize_all_prefixes();
1266 if (argc == 2) {
1267 cmdarg_err("-G with no argument is deprecated and will removed in a future version.");
1268 cmdarg_err_cont("Generating fields glossary.");
1269 proto_registrar_dump_fields();
1270 } else {
1271 if (strcmp(argv[2], "column-formats") == 0)
1272 column_dump_column_formats();
1273 else if (strcmp(argv[2], "currentprefs") == 0) {
1274 epan_load_settings();
1275 write_prefs(NULL);
1277 else if (strcmp(argv[2], "decodes") == 0) {
1278 epan_load_settings();
1279 dissector_dump_decodes();
1280 } else if (strcmp(argv[2], "defaultprefs") == 0)
1281 write_prefs(NULL);
1282 else if (strcmp(argv[2], "dissector-tables") == 0)
1283 dissector_dump_dissector_tables();
1284 else if (strcmp(argv[2], "dissectors") == 0)
1285 dissector_dump_dissectors();
1286 else if (strcmp(argv[2], "elastic-mapping") == 0)
1287 proto_registrar_dump_elastic(elastic_mapping_filter);
1288 else if (strcmp(argv[2], "fieldcount") == 0) {
1289 /* return value for the test suite */
1290 exit_status = proto_registrar_dump_fieldcount();
1291 goto clean_exit;
1293 else if (strcmp(argv[2], "fields") == 0) {
1294 if (argc >= 4) {
1295 gboolean matched = proto_registrar_dump_field_completions(argv[3]);
1296 if (!matched) {
1297 cmdarg_err("No field or protocol begins with \"%s\"", argv[3]);
1298 exit_status = EXIT_FAILURE;
1299 goto clean_exit;
1302 else {
1303 proto_registrar_dump_fields();
1306 else if (strcmp(argv[2], "folders") == 0) {
1307 epan_load_settings();
1308 about_folders();
1309 } else if (strcmp(argv[2], "ftypes") == 0)
1310 proto_registrar_dump_ftypes();
1311 else if (strcmp(argv[2], "heuristic-decodes") == 0) {
1312 epan_load_settings();
1313 dissector_dump_heur_decodes();
1314 } else if (strcmp(argv[2], "manuf") == 0)
1315 ws_manuf_dump(stdout);
1316 else if (strcmp(argv[2], "enterprises") == 0)
1317 global_enterprises_dump(stdout);
1318 else if (strcmp(argv[2], "services") == 0)
1319 global_services_dump(stdout);
1320 else if (strcmp(argv[2], "plugins") == 0) {
1321 #ifdef HAVE_PLUGINS
1322 codecs_init();
1323 plugins_dump_all();
1324 #endif
1325 #ifdef HAVE_LUA
1326 wslua_plugins_dump_all();
1327 #endif
1328 extcap_dump_all();
1330 else if (strcmp(argv[2], "protocols") == 0) {
1331 epan_load_settings();
1332 proto_registrar_dump_protocols();
1333 } else if (strcmp(argv[2], "values") == 0)
1334 proto_registrar_dump_values();
1335 else if (strcmp(argv[2], "help") == 0)
1336 glossary_option_help();
1337 /* These are supported only for backwards compatibility and may or may not work
1338 * for a given user in a given directory on a given operating system with a given
1339 * command-line interpreter.
1341 else if (strcmp(argv[2], "?") == 0)
1342 glossary_option_help();
1343 else if (strcmp(argv[2], "-?") == 0)
1344 glossary_option_help();
1345 else {
1346 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G help for more help.", argv[2]);
1347 exit_status = WS_EXIT_INVALID_OPTION;
1348 goto clean_exit;
1351 exit_status = EXIT_SUCCESS;
1352 goto clean_exit;
1355 ws_debug("tshark reading settings");
1357 /* Load libwireshark settings from the current profile. */
1358 prefs_p = epan_load_settings();
1359 prefs_loaded = TRUE;
1361 cap_file_init(&cfile);
1363 /* Print format defaults to this. */
1364 print_format = PR_FMT_TEXT;
1365 delimiter_char = " ";
1367 output_fields = output_fields_new();
1370 * To reset the options parser, set ws_optreset to 1 and set ws_optind to 1.
1372 * Also reset ws_opterr to 1, so that error messages are printed by
1373 * getopt_long().
1375 ws_optreset = 1;
1376 ws_optind = 1;
1377 ws_opterr = 1;
1379 /* Now get our args */
1380 while ((opt = ws_getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
1381 switch (opt) {
1382 case '2': /* Perform two-pass analysis */
1383 if(epan_auto_reset){
1384 cmdarg_err("-2 does not support auto session reset.");
1385 arg_error=TRUE;
1387 perform_two_pass_analysis = TRUE;
1388 break;
1389 case 'M':
1390 if(perform_two_pass_analysis){
1391 cmdarg_err("-M does not support two-pass analysis.");
1392 arg_error=TRUE;
1394 epan_auto_reset_count = get_positive_int(ws_optarg, "epan reset count");
1395 epan_auto_reset = TRUE;
1396 break;
1397 case 'a': /* autostop criteria */
1398 case 'b': /* Ringbuffer option */
1399 case 'f': /* capture filter */
1400 case 'g': /* enable group read access on file(s) */
1401 case 'i': /* Use interface x */
1402 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
1403 case 'p': /* Don't capture in promiscuous mode */
1404 #ifdef HAVE_PCAP_REMOTE
1405 case 'A': /* Authentication */
1406 #endif
1407 #ifdef HAVE_PCAP_CREATE
1408 case 'I': /* Capture in monitor mode, if available */
1409 #endif
1410 case 's': /* Set the snapshot (capture) length */
1411 case 'y': /* Set the pcap data link type */
1412 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1413 case 'B': /* Buffer size */
1414 #endif
1415 case LONGOPT_COMPRESS_TYPE: /* compress type */
1416 case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
1417 case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
1418 /* These are options only for packet capture. */
1419 #ifdef HAVE_LIBPCAP
1420 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1421 if (exit_status != 0) {
1422 goto clean_exit;
1424 #else
1425 capture_option_specified = TRUE;
1426 arg_error = TRUE;
1427 #endif
1428 break;
1429 case 'c': /* Stop after x packets */
1430 #ifdef HAVE_LIBPCAP
1431 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1432 if (exit_status != 0) {
1433 goto clean_exit;
1435 #else
1436 max_packet_count = get_positive_int(ws_optarg, "packet count");
1437 #endif
1438 break;
1439 case 'w': /* Write to file x */
1440 output_file_name = g_strdup(ws_optarg);
1441 #ifdef HAVE_LIBPCAP
1442 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1443 if (exit_status != 0) {
1444 goto clean_exit;
1446 #endif
1447 break;
1448 case 'C':
1449 /* already processed; just ignore it now */
1450 break;
1451 case 'D': /* Print a list of capture devices and exit */
1452 #ifdef HAVE_LIBPCAP
1453 exit_status = EXIT_SUCCESS;
1454 if_list = capture_interface_list(&err, &err_str,NULL);
1455 if (err != 0) {
1457 * An error occurred when fetching the local
1458 * interfaces. Report it.
1460 cmdarg_err("%s", err_str);
1461 g_free(err_str);
1462 exit_status = WS_EXIT_PCAP_ERROR;
1464 if (if_list == NULL) {
1466 * No interfaces were found. If that's not the
1467 * result of an error when fetching the local
1468 * interfaces, let the user know.
1470 if (err == 0) {
1471 cmdarg_err("There are no interfaces on which a capture can be done");
1472 exit_status = WS_EXIT_NO_INTERFACES;
1474 goto clean_exit;
1476 capture_opts_print_interfaces(if_list);
1477 free_interface_list(if_list);
1478 goto clean_exit;
1479 #else
1480 capture_option_specified = TRUE;
1481 arg_error = TRUE;
1482 #endif
1483 break;
1484 case 'e':
1485 /* Field entry */
1487 const char* col_field = try_convert_to_column_field(ws_optarg);
1488 if (col_field) {
1489 output_fields_add(output_fields, col_field);
1490 } else {
1491 header_field_info *hfi = proto_registrar_get_byalias(ws_optarg);
1492 if (hfi)
1493 output_fields_add(output_fields, hfi->abbrev);
1494 else
1495 output_fields_add(output_fields, ws_optarg);
1498 break;
1499 case 'E':
1500 /* Field option */
1501 if (!output_fields_set_option(output_fields, ws_optarg)) {
1502 cmdarg_err("\"%s\" is not a valid field output option=value pair.", ws_optarg);
1503 output_fields_list_options(stderr);
1504 exit_status = WS_EXIT_INVALID_OPTION;
1505 goto clean_exit;
1507 break;
1508 case 'F':
1509 out_file_type = wtap_name_to_file_type_subtype(ws_optarg);
1510 if (out_file_type < 0) {
1511 cmdarg_err("\"%s\" isn't a valid capture file type", ws_optarg);
1512 list_capture_types();
1513 exit_status = WS_EXIT_INVALID_OPTION;
1514 goto clean_exit;
1516 break;
1517 case 'G':
1518 cmdarg_err("-G only valid as first option");
1519 exit_status = WS_EXIT_INVALID_OPTION;
1520 goto clean_exit;
1521 break;
1522 case 'j':
1523 if (!protocolfilter_add_opt(ws_optarg, PF_NONE)) {
1524 exit_status = WS_EXIT_INVALID_OPTION;
1525 goto clean_exit;
1527 break;
1528 case 'J':
1529 if (!protocolfilter_add_opt(ws_optarg, PF_INCLUDE_CHILDREN)) {
1530 exit_status = WS_EXIT_INVALID_OPTION;
1531 goto clean_exit;
1533 break;
1534 case 'W': /* Select extra information to save in our capture file */
1535 /* This is patterned after the -N flag which may not be the best idea. */
1536 if (strchr(ws_optarg, 'n')) {
1537 out_file_name_res = TRUE;
1538 } else {
1539 cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", ws_optarg);
1540 cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1541 exit_status = WS_EXIT_INVALID_OPTION;
1542 goto clean_exit;
1544 break;
1545 case 'H': /* Read address to name mappings from a hosts file */
1546 if (! add_hosts_file(ws_optarg))
1548 cmdarg_err("Can't read host entries from \"%s\"", ws_optarg);
1549 exit_status = WS_EXIT_INVALID_OPTION;
1550 goto clean_exit;
1552 out_file_name_res = TRUE;
1553 break;
1555 case 'h': /* Print help and exit */
1556 show_help_header("Dump and analyze network traffic.");
1557 print_usage(stdout);
1558 exit_status = EXIT_SUCCESS;
1559 goto clean_exit;
1560 break;
1561 case 'l': /* "Line-buffer" standard output */
1562 /* The ANSI C standard does not appear to *require* that a line-buffered
1563 stream be flushed to the host environment whenever a newline is
1564 written, it just says that, on such a stream, characters "are
1565 intended to be transmitted to or from the host environment as a
1566 block when a new-line character is encountered".
1568 The Visual C++ 6.0 C implementation doesn't do what is intended;
1569 even if you set a stream to be line-buffered, it still doesn't
1570 flush the buffer at the end of every line.
1572 The whole reason for the "-l" flag in either tcpdump or TShark
1573 is to allow the output of a live capture to be piped to a program
1574 or script and to have that script see the information for the
1575 packet as soon as it's printed, rather than having to wait until
1576 a standard I/O buffer fills up.
1578 So, if the "-l" flag is specified, we flush the standard output
1579 at the end of a packet. This will do the right thing if we're
1580 printing packet summary lines, and, as we print the entire protocol
1581 tree for a single packet without waiting for anything to happen,
1582 it should be as good as line-buffered mode if we're printing
1583 protocol trees - arguably even better, as it may do fewer
1584 writes. */
1585 line_buffered = TRUE;
1586 #ifdef HAVE_LIBPCAP
1587 /* Set the update-interval to 0 so that dumpcap reports packets
1588 * as soon as available instead of buffering them.
1590 exit_status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
1591 if (exit_status != 0) {
1592 goto clean_exit;
1594 #endif
1595 break;
1596 case 'L': /* Print list of link-layer types and exit */
1597 #ifdef HAVE_LIBPCAP
1598 caps_queries |= CAPS_QUERY_LINK_TYPES;
1599 #else
1600 capture_option_specified = TRUE;
1601 arg_error = TRUE;
1602 #endif
1603 break;
1604 case LONGOPT_LIST_TSTAMP_TYPES: /* List possible timestamp types */
1605 #ifdef HAVE_LIBPCAP
1606 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
1607 #else
1608 capture_option_specified = TRUE;
1609 arg_error = TRUE;
1610 #endif
1611 break;
1612 case 'o': /* Override preference from command line */
1614 char *errmsg = NULL;
1616 switch (prefs_set_pref(ws_optarg, &errmsg)) {
1618 case PREFS_SET_OK:
1619 break;
1621 case PREFS_SET_SYNTAX_ERR:
1622 cmdarg_err("Invalid -o flag \"%s\"%s%s", ws_optarg,
1623 errmsg ? ": " : "", errmsg ? errmsg : "");
1624 g_free(errmsg);
1625 exit_status = WS_EXIT_INVALID_OPTION;
1626 goto clean_exit;
1627 break;
1629 case PREFS_SET_NO_SUCH_PREF:
1630 cmdarg_err("-o flag \"%s\" specifies unknown preference", ws_optarg);
1631 exit_status = WS_EXIT_INVALID_OPTION;
1632 goto clean_exit;
1633 break;
1635 case PREFS_SET_OBSOLETE:
1636 cmdarg_err("-o flag \"%s\" specifies obsolete preference", ws_optarg);
1637 exit_status = WS_EXIT_INVALID_OPTION;
1638 goto clean_exit;
1639 break;
1641 break;
1643 case 'q': /* Quiet */
1644 quiet = TRUE;
1645 break;
1646 case 'Q': /* Really quiet */
1647 quiet = TRUE;
1648 really_quiet = TRUE;
1649 break;
1650 case 'r':
1651 /* already processed; just ignore it now */
1652 break;
1653 case 'R': /* Read file filter */
1654 rfilter = ws_optarg;
1655 break;
1656 case 'P':
1657 /* already processed; just ignore it now */
1658 break;
1659 case 'S': /* Set the line Separator to be printed between packets */
1660 separator = ws_optarg;
1661 break;
1662 case 'T': /* printing Type */
1663 /* output_action has been already set. It means multiple -T. */
1664 if (output_action > WRITE_NONE) {
1665 cmdarg_err("Multiple -T parameters are unsupported");
1666 exit_status = WS_EXIT_INVALID_OPTION;
1667 goto clean_exit;
1669 print_packet_info = TRUE;
1670 if (strcmp(ws_optarg, "text") == 0) {
1671 output_action = WRITE_TEXT;
1672 print_format = PR_FMT_TEXT;
1673 } else if (strcmp(ws_optarg, "tabs") == 0) {
1674 output_action = WRITE_TEXT;
1675 print_format = PR_FMT_TEXT;
1676 delimiter_char = "\t";
1677 } else if (strcmp(ws_optarg, "ps") == 0) {
1678 output_action = WRITE_TEXT;
1679 print_format = PR_FMT_PS;
1680 } else if (strcmp(ws_optarg, "pdml") == 0) {
1681 output_action = WRITE_XML;
1682 print_details = TRUE; /* Need details */
1683 print_summary = FALSE; /* Don't allow summary */
1684 } else if (strcmp(ws_optarg, "psml") == 0) {
1685 output_action = WRITE_XML;
1686 print_details = FALSE; /* Don't allow details */
1687 print_summary = TRUE; /* Need summary */
1688 } else if (strcmp(ws_optarg, "fields") == 0) {
1689 output_action = WRITE_FIELDS;
1690 print_details = TRUE; /* Need full tree info */
1691 print_summary = FALSE; /* Don't allow summary */
1692 } else if (strcmp(ws_optarg, "json") == 0) {
1693 output_action = WRITE_JSON;
1694 print_details = TRUE; /* Need details */
1695 print_summary = FALSE; /* Don't allow summary */
1696 } else if (strcmp(ws_optarg, "ek") == 0) {
1697 output_action = WRITE_EK;
1698 if (!print_summary)
1699 print_details = TRUE;
1700 } else if (strcmp(ws_optarg, "jsonraw") == 0) {
1701 output_action = WRITE_JSON_RAW;
1702 print_details = TRUE; /* Need details */
1703 print_summary = FALSE; /* Don't allow summary */
1705 else {
1706 cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", ws_optarg); /* x */
1707 cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1708 "\t specified by the -E option.\n"
1709 "\t\"pdml\" Packet Details Markup Language, an XML-based format for the\n"
1710 "\t details of a decoded packet. This information is equivalent to\n"
1711 "\t the packet details printed with the -V flag.\n"
1712 "\t\"ps\" PostScript for a human-readable one-line summary of each of\n"
1713 "\t the packets, or a multi-line view of the details of each of\n"
1714 "\t the packets, depending on whether the -V flag was specified.\n"
1715 "\t\"psml\" Packet Summary Markup Language, an XML-based format for the\n"
1716 "\t summary information of a decoded packet. This information is\n"
1717 "\t equivalent to the information shown in the one-line summary\n"
1718 "\t printed by default.\n"
1719 "\t\"json\" Packet Summary, an JSON-based format for the details\n"
1720 "\t summary information of a decoded packet. This information is \n"
1721 "\t equivalent to the packet details printed with the -V flag.\n"
1722 "\t\"jsonraw\" Packet Details, a JSON-based format for machine parsing\n"
1723 "\t including only raw hex decoded fields (same as -T json -x but\n"
1724 "\t without text decoding, only raw fields included). \n"
1725 "\t\"ek\" Packet Details, an EK JSON-based format for the bulk insert \n"
1726 "\t into elastic search cluster. This information is \n"
1727 "\t equivalent to the packet details printed with the -V flag.\n"
1728 "\t\"text\" Text of a human-readable one-line summary of each of the\n"
1729 "\t packets, or a multi-line view of the details of each of the\n"
1730 "\t packets, depending on whether the -V flag was specified.\n"
1731 "\t This is the default.\n"
1732 "\t\"tabs\" Similar to the text report except that each column of the\n"
1733 "\t human-readable one-line summary is delimited with an ASCII\n"
1734 "\t horizontal tab character.");
1735 exit_status = WS_EXIT_INVALID_OPTION;
1736 goto clean_exit;
1738 break;
1739 case 'U': /* Export PDUs to file */
1740 if (strcmp(ws_optarg, "") == 0 || strcmp(ws_optarg, "?") == 0) {
1741 list_export_pdu_taps();
1742 exit_status = WS_EXIT_INVALID_OPTION;
1743 goto clean_exit;
1745 pdu_export_arg = g_strdup(ws_optarg);
1746 break;
1747 case 'v': /* Show version and exit */
1748 show_version();
1749 /* We don't really have to cleanup here, but it's a convenient way to test
1750 * start-up and shut-down of the epan library without any UI-specific
1751 * cruft getting in the way. Makes the results of running
1752 * $ ./tools/valgrind-wireshark -n
1753 * much more useful. */
1754 epan_cleanup();
1755 extcap_cleanup();
1756 exit_status = EXIT_SUCCESS;
1757 goto clean_exit;
1758 case 'O': /* Only output these protocols */
1759 /* already processed; just ignore it now */
1760 break;
1761 case 'V': /* Verbose */
1762 /* already processed; just ignore it now */
1763 break;
1764 case 'x': /* Print packet data in hex (and ASCII) */
1765 /* already processed; just ignore it now */
1766 break;
1767 case 'X':
1768 /* already processed; just ignore it now */
1769 break;
1770 case 'Y':
1771 dfilter = g_strdup(ws_optarg);
1772 break;
1773 case 'z':
1774 /* We won't call the init function for the stat this soon
1775 as it would disallow MATE's fields (which are registered
1776 by the preferences set callback) from being used as
1777 part of a tap filter. Instead, we just add the argument
1778 to a list of stat arguments. */
1779 if (strcmp("help", ws_optarg) == 0) {
1780 fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1781 list_stat_cmd_args();
1782 exit_status = EXIT_SUCCESS;
1783 goto clean_exit;
1785 if (!process_stat_cmd_arg(ws_optarg)) {
1786 cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", ws_optarg);
1787 list_stat_cmd_args();
1788 exit_status = WS_EXIT_INVALID_OPTION;
1789 goto clean_exit;
1791 break;
1792 case 'd': /* Decode as rule */
1793 case 'K': /* Kerberos keytab file */
1794 case 'n': /* No name resolution */
1795 case 'N': /* Select what types of addresses/port #s to resolve */
1796 case 't': /* Time stamp type */
1797 case 'u': /* Seconds type */
1798 case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1799 case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1800 case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1801 case LONGOPT_ENABLE_PROTOCOL: /* enable dissection of protocol (that is disabled by default) */
1802 case LONGOPT_ONLY_PROTOCOLS: /* enable dissection of only this comma separated list of protocols */
1803 case LONGOPT_DISABLE_ALL_PROTOCOLS: /* enable dissection of protocol (that is disabled by default) */
1804 if (!dissect_opts_handle_opt(opt, ws_optarg)) {
1805 exit_status = WS_EXIT_INVALID_OPTION;
1806 goto clean_exit;
1808 break;
1809 case LONGOPT_EXPORT_OBJECTS: /* --export-objects */
1810 if (strcmp("help", ws_optarg) == 0) {
1811 fprintf(stderr, "tshark: The available export object types for the \"--export-objects\" option are:\n");
1812 eo_list_object_types();
1813 exit_status = EXIT_SUCCESS;
1814 goto clean_exit;
1816 if (!eo_tap_opt_add(ws_optarg)) {
1817 exit_status = WS_EXIT_INVALID_OPTION;
1818 goto clean_exit;
1820 break;
1821 case LONGOPT_EXPORT_TLS_SESSION_KEYS: /* --export-tls-session-keys */
1822 tls_session_keys_file = ws_optarg;
1823 break;
1824 case LONGOPT_COLOR: /* print in color where appropriate */
1825 dissect_color = TRUE;
1826 /* This has no effect if we don't print packet info or filter
1827 (we can filter on the coloring rules). Should we warn or
1828 error later if so, instead of silently ignoring it? */
1829 break;
1830 case LONGOPT_NO_DUPLICATE_KEYS:
1831 no_duplicate_keys = TRUE;
1832 node_children_grouper = proto_node_group_children_by_json_key;
1833 break;
1834 case LONGOPT_CAPTURE_COMMENT: /* capture comment */
1835 if (capture_comments == NULL) {
1836 capture_comments = g_ptr_array_new_with_free_func(g_free);
1838 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
1839 break;
1840 case LONGOPT_HEXDUMP:
1841 print_hex = TRUE;
1842 print_packet_info = TRUE;
1843 if (strcmp(ws_optarg, "all") == 0)
1844 hexdump_source_option = HEXDUMP_SOURCE_MULTI;
1845 else if (strcmp(ws_optarg, "frames") == 0)
1846 hexdump_source_option = HEXDUMP_SOURCE_PRIMARY;
1847 else if (strcmp(ws_optarg, "ascii") == 0)
1848 hexdump_ascii_option = HEXDUMP_ASCII_INCLUDE;
1849 else if (strcmp(ws_optarg, "delimit") == 0)
1850 hexdump_ascii_option = HEXDUMP_ASCII_DELIMIT;
1851 else if (strcmp(ws_optarg, "noascii") == 0)
1852 hexdump_ascii_option = HEXDUMP_ASCII_EXCLUDE;
1853 else if (strcmp("help", ws_optarg) == 0) {
1854 hexdump_option_help(stdout);
1855 exit_status = EXIT_SUCCESS;
1856 goto clean_exit;
1857 } else {
1858 fprintf(stderr, "tshark: \"%s\" is an invalid value for --hexdump <hexoption>\n", ws_optarg);
1859 fprintf(stderr, "For valid <hexoption> values enter: tshark --hexdump help\n");
1860 exit_status = WS_EXIT_INVALID_OPTION;
1861 goto clean_exit;
1863 break;
1864 case LONGOPT_SELECTED_FRAME:
1865 /* Hidden option to mark a frame as "selected". Used for testing and debugging.
1866 * Only active in two-pass mode. */
1867 if (!ws_strtou32(ws_optarg, NULL, &selected_frame_number)) {
1868 fprintf(stderr, "tshark: \"%s\" is not a valid frame number\n", ws_optarg);
1869 exit_status = WS_EXIT_INVALID_OPTION;
1870 goto clean_exit;
1872 break;
1873 case LONGOPT_PRINT_TIMERS:
1874 opt_print_timers = TRUE;
1875 break;
1876 default:
1877 case '?': /* Bad flag - print usage message */
1878 switch(ws_optopt) {
1879 case 'F':
1880 list_capture_types();
1881 break;
1882 default:
1883 print_usage(stderr);
1885 exit_status = WS_EXIT_INVALID_OPTION;
1886 goto clean_exit;
1887 break;
1891 /* set the default output action to TEXT */
1892 if (output_action == WRITE_NONE)
1893 output_action = WRITE_TEXT;
1895 /* set the default file type to pcapng */
1896 if (out_file_type == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN)
1897 out_file_type = wtap_pcapng_file_type_subtype();
1900 * Print packet summary information is the default if neither -V or -x
1901 * were specified. Note that this is new behavior, which allows for the
1902 * possibility of printing only hex/ascii output without necessarily
1903 * requiring that either the summary or details be printed too.
1905 if (!print_summary && !print_details && !print_hex)
1906 print_summary = TRUE;
1908 if (no_duplicate_keys && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW) {
1909 cmdarg_err("--no-duplicate-keys can only be used with \"-T json\" and \"-T jsonraw\"");
1910 exit_status = WS_EXIT_INVALID_OPTION;
1911 goto clean_exit;
1914 /* If we specified output fields, but not the output field type... */
1915 /* XXX: If we specfied both output fields with -e *and* protocol filters
1916 * with -j/-J, only the former are used. Should we warn or abort?
1917 * This also doesn't distinguish PDML from PSML, but shouldn't allow the
1918 * latter.
1920 if ((WRITE_FIELDS != output_action && WRITE_XML != output_action && WRITE_JSON != output_action && WRITE_EK != output_action) && 0 != output_fields_num_fields(output_fields)) {
1921 cmdarg_err("Output fields were specified with \"-e\", "
1922 "but \"-Tek, -Tfields, -Tjson or -Tpdml\" was not specified.");
1923 exit_status = WS_EXIT_INVALID_OPTION;
1924 goto clean_exit;
1925 } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1926 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1927 "specified with \"-e\".");
1929 exit_status = WS_EXIT_INVALID_OPTION;
1930 goto clean_exit;
1933 if (dissect_color) {
1934 if (!color_filters_init(&err_msg, NULL)) {
1935 fprintf(stderr, "%s\n", err_msg);
1936 g_free(err_msg);
1940 /* If no capture filter or display filter has been specified, and there are
1941 still command-line arguments, treat them as the tokens of a capture
1942 filter (if no "-r" flag was specified) or a display filter (if a "-r"
1943 flag was specified. */
1944 if (ws_optind < argc) {
1945 if (cf_name != NULL) {
1946 if (dfilter != NULL) {
1947 cmdarg_err("Display filters were specified both with \"-Y\" "
1948 "and with additional command-line arguments.");
1949 exit_status = WS_EXIT_INVALID_OPTION;
1950 goto clean_exit;
1952 dfilter = get_args_as_string(argc, argv, ws_optind);
1953 } else {
1954 #ifdef HAVE_LIBPCAP
1955 guint i;
1957 if (global_capture_opts.default_options.cfilter) {
1958 cmdarg_err("A default capture filter was specified both with \"-f\""
1959 " and with additional command-line arguments.");
1960 exit_status = WS_EXIT_INVALID_OPTION;
1961 goto clean_exit;
1963 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1964 interface_options *interface_opts;
1965 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
1966 if (interface_opts->cfilter == NULL) {
1967 interface_opts->cfilter = get_args_as_string(argc, argv, ws_optind);
1968 } else {
1969 cmdarg_err("A capture filter was specified both with \"-f\""
1970 " and with additional command-line arguments.");
1971 exit_status = WS_EXIT_INVALID_OPTION;
1972 goto clean_exit;
1975 global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, ws_optind);
1976 #else
1977 capture_option_specified = TRUE;
1978 #endif
1982 if (!output_file_name) {
1983 /* We're not saving the capture to a file; if "-q" wasn't specified,
1984 we should print packet information */
1985 if (!quiet)
1986 print_packet_info = TRUE;
1987 } else {
1988 const char *save_file = output_file_name;
1989 /* We're saving to a file; if we're writing to the standard output.
1990 and we'll also be writing dissected packets to the standard
1991 output, reject the request. At best, we could redirect that
1992 to the standard error; we *can't* write both to the standard
1993 output and have either of them be useful. */
1994 if (strcmp(save_file, "-") == 0 && print_packet_info) {
1995 cmdarg_err("You can't write both raw packet data and dissected packets"
1996 " to the standard output.");
1997 exit_status = WS_EXIT_INVALID_OPTION;
1998 goto clean_exit;
2002 #ifndef HAVE_LIBPCAP
2003 if (capture_option_specified)
2004 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2005 #endif
2006 if (arg_error) {
2007 print_usage(stderr);
2008 exit_status = WS_EXIT_INVALID_OPTION;
2009 goto clean_exit;
2012 if (print_hex) {
2013 if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_JSON_RAW && output_action != WRITE_EK) {
2014 cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON, JSONRAW or EK JSON");
2015 exit_status = WS_EXIT_INVALID_OPTION;
2016 goto clean_exit;
2020 if (output_only != NULL) {
2021 char *ps;
2023 if (!print_details) {
2024 cmdarg_err("-O requires -V");
2025 exit_status = WS_EXIT_INVALID_OPTION;
2026 goto clean_exit;
2029 output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
2030 for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
2031 const char *name = ps;
2032 header_field_info *hfi = proto_registrar_get_byalias(name);
2033 if (hfi) {
2034 name = hfi->abbrev;
2036 g_hash_table_insert(output_only_tables, (gpointer)name, (gpointer)name);
2040 if (rfilter != NULL && !perform_two_pass_analysis) {
2041 cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
2042 exit_status = WS_EXIT_INVALID_OPTION;
2043 goto clean_exit;
2046 #ifdef HAVE_LIBPCAP
2047 if (caps_queries) {
2048 /* We're supposed to list the link-layer/timestamp types for an interface;
2049 did the user also specify a capture file to be read? */
2050 if (cf_name) {
2051 /* Yes - that's bogus. */
2052 cmdarg_err("You can't specify %s and a capture file to be read.",
2053 caps_queries & CAPS_QUERY_LINK_TYPES ? "-L" : "--list-time-stamp-types");
2054 exit_status = WS_EXIT_INVALID_OPTION;
2055 goto clean_exit;
2057 /* No - did they specify a ring buffer option? */
2058 if (global_capture_opts.multi_files_on) {
2059 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2060 exit_status = WS_EXIT_INVALID_OPTION;
2061 goto clean_exit;
2063 } else {
2064 if (cf_name) {
2066 * "-r" was specified, so we're reading a capture file.
2067 * Capture options don't apply here.
2070 /* We don't support capture filters when reading from a capture file
2071 (the BPF compiler doesn't support all link-layer types that we
2072 support in capture files we read). */
2073 if (global_capture_opts.default_options.cfilter) {
2074 cmdarg_err("Only read filters, not capture filters, "
2075 "can be specified when reading a capture file.");
2076 exit_status = WS_EXIT_INVALID_OPTION;
2077 goto clean_exit;
2079 if (global_capture_opts.multi_files_on) {
2080 cmdarg_err("Multiple capture files requested, but "
2081 "a capture isn't being done.");
2082 exit_status = WS_EXIT_INVALID_OPTION;
2083 goto clean_exit;
2085 if (global_capture_opts.has_file_duration) {
2086 cmdarg_err("Switching capture files after a time period was specified, but "
2087 "a capture isn't being done.");
2088 exit_status = WS_EXIT_INVALID_OPTION;
2089 goto clean_exit;
2091 if (global_capture_opts.has_file_interval) {
2092 cmdarg_err("Switching capture files after a time interval was specified, but "
2093 "a capture isn't being done.");
2094 exit_status = WS_EXIT_INVALID_OPTION;
2095 goto clean_exit;
2097 if (global_capture_opts.has_ring_num_files) {
2098 cmdarg_err("A ring buffer of capture files was specified, but "
2099 "a capture isn't being done.");
2100 exit_status = WS_EXIT_INVALID_OPTION;
2101 goto clean_exit;
2103 if (global_capture_opts.has_autostop_files) {
2104 cmdarg_err("A maximum number of capture files was specified, but "
2105 "a capture isn't being done.");
2106 exit_status = WS_EXIT_INVALID_OPTION;
2107 goto clean_exit;
2110 /* Note: TShark now allows the restriction of a _read_ file by packet count
2111 * and byte count as well as a write file. Other autostop options remain valid
2112 * only for a write file.
2114 if (global_capture_opts.has_autostop_duration) {
2115 cmdarg_err("A maximum capture time was specified, but "
2116 "a capture isn't being done.");
2117 exit_status = WS_EXIT_INVALID_OPTION;
2118 goto clean_exit;
2120 } else {
2122 * "-r" wasn't specified, so we're doing a live capture.
2124 gboolean use_pcapng = TRUE;
2126 if (perform_two_pass_analysis) {
2127 /* Two-pass analysis doesn't work with live capture since it requires us
2128 * to buffer packets until we've read all of them, but a live capture
2129 * has no useful/meaningful definition of "all" */
2130 cmdarg_err("Live captures do not support two-pass analysis.");
2131 exit_status = WS_EXIT_INVALID_OPTION;
2132 goto clean_exit;
2135 if (global_capture_opts.saving_to_file) {
2136 /* They specified a "-w" flag, so we'll be saving to a capture file. */
2138 /* When capturing, we only support writing pcap or pcapng format. */
2139 if (out_file_type == wtap_pcapng_file_type_subtype()) {
2140 use_pcapng = TRUE;
2141 } else if (out_file_type == wtap_pcap_file_type_subtype()) {
2142 use_pcapng = FALSE;
2143 } else if (out_file_type == wtap_pcap_nsec_file_type_subtype()) {
2144 /* XXX - We request nanosecond time resolution regardless.
2145 * In the future wiretap might treat the two pcap subtypes
2146 * the same.
2148 use_pcapng = FALSE;
2149 } else {
2150 cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
2151 capture_opts_list_file_types();
2152 exit_status = WS_EXIT_INVALID_OPTION;
2153 goto clean_exit;
2155 if (capture_comments != NULL && !use_pcapng) {
2156 cmdarg_err("Capture comments can only be written to a pcapng file.");
2157 exit_status = WS_EXIT_INVALID_OPTION;
2158 goto clean_exit;
2160 if (global_capture_opts.multi_files_on) {
2161 /* Multiple-file mode doesn't work under certain conditions:
2162 a) it doesn't work if you're writing to the standard output;
2163 b) it doesn't work if you're writing to a pipe;
2165 if (strcmp(global_capture_opts.save_file, "-") == 0) {
2166 cmdarg_err("Multiple capture files requested, but "
2167 "the capture is being written to the standard output.");
2168 exit_status = WS_EXIT_INVALID_OPTION;
2169 goto clean_exit;
2171 if (global_capture_opts.output_to_pipe) {
2172 cmdarg_err("Multiple capture files requested, but "
2173 "the capture file is a pipe.");
2174 exit_status = WS_EXIT_INVALID_OPTION;
2175 goto clean_exit;
2177 if (!global_capture_opts.has_autostop_filesize &&
2178 !global_capture_opts.has_file_duration &&
2179 !global_capture_opts.has_file_interval &&
2180 !global_capture_opts.has_file_packets) {
2181 cmdarg_err("Multiple capture files requested, but "
2182 "no maximum capture file size, duration, interval or packets were specified.");
2183 exit_status = WS_EXIT_INVALID_OPTION;
2184 goto clean_exit;
2187 /* Currently, we don't support read or display filters when capturing
2188 and saving the packets. */
2189 if (rfilter != NULL) {
2190 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
2191 exit_status = WS_EXIT_INVALID_OPTION;
2192 goto clean_exit;
2194 if (dfilter != NULL) {
2195 cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
2196 exit_status = WS_EXIT_INVALID_OPTION;
2197 goto clean_exit;
2199 global_capture_opts.use_pcapng = use_pcapng;
2200 } else {
2201 /* They didn't specify a "-w" flag, so we won't be saving to a
2202 capture file. Check for options that only make sense if
2203 we're saving to a file. */
2204 if (global_capture_opts.has_autostop_filesize) {
2205 cmdarg_err("Maximum capture file size specified, but "
2206 "capture isn't being saved to a file.");
2207 exit_status = WS_EXIT_INVALID_OPTION;
2208 goto clean_exit;
2210 if (global_capture_opts.multi_files_on) {
2211 cmdarg_err("Multiple capture files requested, but "
2212 "the capture isn't being saved to a file.");
2213 exit_status = WS_EXIT_INVALID_OPTION;
2214 goto clean_exit;
2216 if (capture_comments != NULL) {
2217 cmdarg_err("Capture comments were specified, but "
2218 "the capture isn't being saved to a file.");
2219 exit_status = WS_EXIT_INVALID_OPTION;
2220 goto clean_exit;
2225 #endif
2228 * If capture comments were specified, -w also has to have been specified.
2230 if (capture_comments != NULL) {
2231 if (output_file_name) {
2232 /* They specified a "-w" flag, so we'll be saving to a capture file.
2233 * This is fine if they're writing in a format that supports
2234 * section block comments.
2236 if (wtap_file_type_subtype_supports_option(out_file_type,
2237 WTAP_BLOCK_SECTION,
2238 OPT_COMMENT) == OPTION_NOT_SUPPORTED) {
2239 GArray *writable_type_subtypes;
2241 cmdarg_err("Capture comments can only be written to files of the following types:");
2242 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
2243 for (guint i = 0; i < writable_type_subtypes->len; i++) {
2244 int ft = g_array_index(writable_type_subtypes, int, i);
2246 if (wtap_file_type_subtype_supports_option(ft, WTAP_BLOCK_SECTION,
2247 OPT_COMMENT) != OPTION_NOT_SUPPORTED)
2248 cmdarg_err_cont(" %s - %s", wtap_file_type_subtype_name(ft),
2249 wtap_file_type_subtype_description(ft));
2251 exit_status = WS_EXIT_INVALID_OPTION;
2252 goto clean_exit;
2255 else {
2256 cmdarg_err("Capture comments were specified, but you aren't writing a capture file.");
2257 exit_status = WS_EXIT_INVALID_OPTION;
2258 goto clean_exit;
2262 err_msg = ws_init_sockets();
2263 if (err_msg != NULL)
2265 cmdarg_err("%s", err_msg);
2266 g_free(err_msg);
2267 cmdarg_err_cont("%s", please_report_bug());
2268 exit_status = WS_EXIT_INIT_FAILED;
2269 goto clean_exit;
2272 /* Notify all registered modules that have had any of their preferences
2273 changed either from one of the preferences file or from the command
2274 line that their preferences have changed. */
2275 prefs_apply_all();
2277 /* We can also enable specified taps for export object */
2278 start_exportobjects();
2280 /* At this point MATE will have registered its field array so we can
2281 check if the fields specified by the user are all good.
2284 GSList* it = NULL;
2285 GSList *invalid_fields = output_fields_valid(output_fields);
2286 if (invalid_fields != NULL) {
2288 cmdarg_err("Some fields aren't valid:");
2289 for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
2290 cmdarg_err_cont("\t%s", (gchar *)it->data);
2292 g_slist_free(invalid_fields);
2293 exit_status = WS_EXIT_INVALID_OPTION;
2294 goto clean_exit;
2298 if (ex_opt_count("read_format") > 0) {
2299 const gchar* name = ex_opt_get_next("read_format");
2300 in_file_type = open_info_name_to_type(name);
2301 if (in_file_type == WTAP_TYPE_AUTO) {
2302 cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
2303 list_read_capture_types();
2304 exit_status = WS_EXIT_INVALID_OPTION;
2305 goto clean_exit;
2309 if (global_dissect_options.time_format != TS_NOT_SET)
2310 timestamp_set_type(global_dissect_options.time_format);
2311 if (global_dissect_options.time_precision != TS_PREC_NOT_SET)
2312 timestamp_set_precision(global_dissect_options.time_precision);
2315 * Enabled and disabled protocols and heuristic dissectors as per
2316 * command-line options.
2318 if (!setup_enabled_and_disabled_protocols()) {
2319 exit_status = WS_EXIT_INVALID_OPTION;
2320 goto clean_exit;
2323 /* Build the column format array */
2324 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
2326 #ifdef HAVE_LIBPCAP
2327 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2328 capture_opts_trim_ring_num_files(&global_capture_opts);
2329 #endif
2331 if (rfilter != NULL) {
2332 ws_debug("Compiling read filter: '%s'", rfilter);
2333 if (!compile_dfilter(rfilter, &rfcode)) {
2334 epan_cleanup();
2335 extcap_cleanup();
2337 #ifdef HAVE_LIBPCAP
2338 warn_about_capture_filter(rfilter);
2339 #endif
2341 exit_status = WS_EXIT_INVALID_INTERFACE;
2342 goto clean_exit;
2345 cfile.rfcode = rfcode;
2347 if (dfilter != NULL) {
2348 ws_debug("Compiling display filter: '%s'", dfilter);
2349 if (!compile_dfilter(dfilter, &dfcode)) {
2350 epan_cleanup();
2351 extcap_cleanup();
2353 #ifdef HAVE_LIBPCAP
2354 warn_about_capture_filter(dfilter);
2355 #endif
2357 exit_status = WS_EXIT_INVALID_FILTER;
2358 goto clean_exit;
2361 cfile.dfcode = dfcode;
2363 if (print_packet_info) {
2364 /* If we're printing as text or PostScript, we have
2365 to create a print stream. */
2366 if (output_action == WRITE_TEXT) {
2367 switch (print_format) {
2369 case PR_FMT_TEXT:
2370 print_stream = print_stream_text_stdio_new(stdout);
2371 break;
2373 case PR_FMT_PS:
2374 print_stream = print_stream_ps_stdio_new(stdout);
2375 break;
2377 default:
2378 ws_assert_not_reached();
2383 /* PDU export requested. Take the ownership of the '-w' file, apply tap
2384 * filters and start tapping. */
2385 if (pdu_export_arg) {
2386 const char *exp_pdu_tap_name = pdu_export_arg;
2387 const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
2388 char *exp_pdu_error;
2389 int exp_fd;
2390 char *comment;
2392 if (!cf_name) {
2393 cmdarg_err("PDUs export requires a capture file (specify with -r).");
2394 exit_status = WS_EXIT_INVALID_OPTION;
2395 goto clean_exit;
2397 /* Take ownership of the '-w' output file. */
2398 exp_pdu_filename = output_file_name;
2399 output_file_name = NULL;
2400 #ifdef HAVE_LIBPCAP
2401 global_capture_opts.save_file = NULL;
2402 #endif
2403 if (exp_pdu_filename == NULL) {
2404 cmdarg_err("PDUs export requires an output file (-w).");
2405 exit_status = WS_EXIT_INVALID_OPTION;
2406 goto clean_exit;
2409 exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
2410 &exp_pdu_tap_data);
2411 if (exp_pdu_error) {
2412 cmdarg_err("Cannot register tap: %s", exp_pdu_error);
2413 g_free(exp_pdu_error);
2414 list_export_pdu_taps();
2415 exit_status = INVALID_TAP;
2416 goto clean_exit;
2419 if (strcmp(exp_pdu_filename, "-") == 0) {
2420 /* Write to the standard output. */
2421 exp_fd = 1;
2422 } else {
2423 exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2424 if (exp_fd == -1) {
2425 cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
2426 exit_status = WS_EXIT_INVALID_FILE;
2427 goto clean_exit;
2431 /* Activate the export PDU tap */
2432 /* Write to our output file with this comment (if the type supports it,
2433 * otherwise exp_pdu_open() will ignore the comment) */
2434 comment = ws_strdup_printf("Dump of PDUs from %s", cf_name);
2435 exp_pdu_status = exp_pdu_open(&exp_pdu_tap_data, exp_pdu_filename,
2436 out_file_type, exp_fd, comment,
2437 &err, &err_info);
2438 g_free(comment);
2439 if (!exp_pdu_status) {
2440 cfile_dump_open_failure_message(exp_pdu_filename, err, err_info,
2441 out_file_type);
2442 exit_status = INVALID_EXPORT;
2443 goto clean_exit;
2447 if (cf_name) {
2448 ws_debug("tshark: Opening capture file: %s", cf_name);
2450 * We're reading a capture file.
2452 if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
2453 epan_cleanup();
2454 extcap_cleanup();
2455 exit_status = WS_EXIT_INVALID_FILE;
2456 goto clean_exit;
2459 /* Start statistics taps; we do so after successfully opening the
2460 capture file, so we know we have something to compute stats
2461 on, and after registering all dissectors, so that MATE will
2462 have registered its field array so we can have a tap filter
2463 with one of MATE's late-registered fields as part of the
2464 filter. */
2465 start_requested_stats();
2467 /* Do we need to do dissection of packets? That depends on, among
2468 other things, what taps are listening, so determine that after
2469 starting the statistics taps. */
2470 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2471 ws_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2473 /* Process the packets in the file */
2474 ws_debug("tshark: invoking process_cap_file() to process the packets");
2475 TRY {
2476 status = process_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res,
2477 #ifdef HAVE_LIBPCAP
2478 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
2479 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0,
2480 global_capture_opts.has_autostop_written_packets ? global_capture_opts.autostop_written_packets : 0);
2481 #else
2482 max_packet_count,
2485 #endif
2487 CATCH(OutOfMemoryError) {
2488 fprintf(stderr,
2489 "Out Of Memory.\n"
2490 "\n"
2491 "Sorry, but TShark has to terminate now.\n"
2492 "\n"
2493 "More information and workarounds can be found at\n"
2494 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
2495 status = PROCESS_FILE_ERROR;
2497 ENDTRY;
2499 switch (status) {
2501 case PROCESS_FILE_SUCCEEDED:
2502 /* Everything worked OK; draw the taps. */
2503 draw_taps = TRUE;
2504 break;
2506 case PROCESS_FILE_NO_FILE_PROCESSED:
2507 /* We never got to try to read the file, so there are no tap
2508 results to dump. Exit with an error status. */
2509 exit_status = 2;
2510 break;
2512 case PROCESS_FILE_ERROR:
2513 /* We still dump out the results of taps, etc., as we might have
2514 read some packets; however, we exit with an error status. */
2515 draw_taps = TRUE;
2516 exit_status = 2;
2517 break;
2519 case PROCESS_FILE_INTERRUPTED:
2520 /* The user interrupted the read process; Don't dump out the
2521 result of taps, etc., and exit with an error status. */
2522 exit_status = 2;
2523 break;
2526 if (pdu_export_arg) {
2527 if (!exp_pdu_close(&exp_pdu_tap_data, &err, &err_info)) {
2528 cfile_close_failure_message(exp_pdu_filename, err, err_info);
2529 exit_status = 2;
2531 g_free(pdu_export_arg);
2532 g_free(exp_pdu_filename);
2534 } else {
2535 ws_debug("tshark: no capture file specified");
2536 /* No capture file specified, so we're supposed to do a live capture
2537 or get a list of link-layer types for a live capture device;
2538 do we have support for live captures? */
2539 #ifdef HAVE_LIBPCAP
2540 #ifdef _WIN32
2541 /* Warn the user if npf.sys isn't loaded. */
2542 if (!npf_sys_is_running()) {
2543 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
2544 "capturing or\nlisting interfaces.\n");
2546 #endif /* _WIN32 */
2548 /* if no interface was specified, pick a default */
2549 exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
2550 ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
2551 if (exit_status != 0) {
2552 goto clean_exit;
2556 * If requested, list the link layer types and/or time stamp types
2557 * and exit.
2559 if (caps_queries) {
2560 guint i;
2562 /* Get the list of link-layer types for the capture devices. */
2563 exit_status = EXIT_SUCCESS;
2564 GList *if_cap_queries = NULL;
2565 if_cap_query_t *if_cap_query;
2566 GHashTable *capability_hash;
2567 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2568 interface_options *interface_opts;
2569 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2570 if_cap_query = g_new(if_cap_query_t, 1);
2571 if_cap_query->name = interface_opts->name;
2572 if_cap_query->monitor_mode = interface_opts->monitor_mode;
2573 if_cap_query->auth_username = NULL;
2574 if_cap_query->auth_password = NULL;
2575 #ifdef HAVE_PCAP_REMOTE
2576 if (interface_opts->auth_type == CAPTURE_AUTH_PWD) {
2577 if_cap_query->auth_username = interface_opts->auth_username;
2578 if_cap_query->auth_password = interface_opts->auth_password;
2580 #endif
2581 if_cap_queries = g_list_prepend(if_cap_queries, if_cap_query);
2583 if_cap_queries = g_list_reverse(if_cap_queries);
2584 capability_hash = capture_get_if_list_capabilities(if_cap_queries, &err_str, &err_str_secondary, NULL);
2585 g_list_free_full(if_cap_queries, g_free);
2586 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2587 interface_options *interface_opts;
2588 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, i);
2589 if_capabilities_t *caps;
2590 caps = g_hash_table_lookup(capability_hash, interface_opts->name);
2591 if (caps == NULL) {
2592 cmdarg_err("%s%s%s", err_str, err_str_secondary ? "\n" : "", err_str_secondary ? err_str_secondary : "");
2593 g_free(err_str);
2594 g_free(err_str_secondary);
2595 exit_status = WS_EXIT_INVALID_CAPABILITY;
2596 break;
2598 exit_status = capture_opts_print_if_capabilities(caps, interface_opts,
2599 caps_queries);
2600 if (exit_status != EXIT_SUCCESS) {
2601 break;
2604 g_hash_table_destroy(capability_hash);
2605 goto clean_exit;
2609 * If the standard error isn't a terminal, don't print packet counts,
2610 * as they won't show up on the user's terminal and they'll get in
2611 * the way of error messages in the file (to which we assume the
2612 * standard error was redirected; if it's redirected to the null
2613 * device, there's no point in printing packet counts anyway).
2615 * Otherwise, if we're printing packet information and the standard
2616 * output is a terminal (which we assume means the standard output and
2617 * error are going to the same terminal), don't print packet counts,
2618 * as they'll get in the way of the packet information.
2620 * Otherwise, if the user specified -q, don't print packet counts.
2622 * Otherwise, print packet counts.
2624 * XXX - what if the user wants to do a live capture, doesn't want
2625 * to save it to a file, doesn't want information printed for each
2626 * packet, does want some "-z" statistic, and wants packet counts
2627 * so they know whether they're seeing any packets? -q will
2628 * suppress the information printed for each packet, but it'll
2629 * also suppress the packet counts.
2631 if (!ws_isatty(ws_fileno(stderr)))
2632 print_packet_counts = FALSE;
2633 else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
2634 print_packet_counts = FALSE;
2635 else if (quiet)
2636 print_packet_counts = FALSE;
2637 else
2638 print_packet_counts = TRUE;
2640 ws_debug("tshark: performing live capture");
2642 /* Start statistics taps; we should only do so after the capture
2643 started successfully, so we know we have something to compute
2644 stats, but we currently don't check for that - see below.
2646 We do so after registering all dissectors, so that MATE will
2647 have registered its field array so we can have a tap filter
2648 with one of MATE's late-registered fields as part of the
2649 filter. */
2650 start_requested_stats();
2652 /* Do we need to do dissection of packets? That depends on, among
2653 other things, what taps are listening, so determine that after
2654 starting the statistics taps. */
2655 do_dissection = must_do_dissection(rfcode, dfcode, pdu_export_arg);
2656 ws_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
2658 /* We're doing live capture; if the capture child is writing to a pipe,
2659 we can't do dissection, because that would mean two readers for
2660 the pipe, tshark and whatever else. */
2661 if (do_dissection && global_capture_opts.output_to_pipe) {
2662 if (tap_listeners_require_dissection()) {
2663 cmdarg_err("Taps aren't supported when capturing and saving to a pipe.");
2664 exit_status = WS_EXIT_INVALID_OPTION;
2665 goto clean_exit;
2667 if (print_packet_info) {
2668 cmdarg_err("Printing dissected packets isn't supported when capturing and saving to a pipe.");
2669 exit_status = WS_EXIT_INVALID_OPTION;
2670 goto clean_exit;
2672 /* We already checked the next three reasons for supersets of
2673 capturing and saving to a pipe, but this doesn't hurt. */
2674 if (pdu_export_arg) {
2675 cmdarg_err("PDUs export isn't supported when capturing and saving to a pipe.");
2676 exit_status = WS_EXIT_INVALID_OPTION;
2677 goto clean_exit;
2679 if (rfcode != NULL) {
2680 cmdarg_err("Read filters aren't supported when capturing and saving to a pipe.");
2681 exit_status = WS_EXIT_INVALID_OPTION;
2682 goto clean_exit;
2684 if (dfcode != NULL) {
2685 cmdarg_err("Display filters aren't supported when capturing and saving to a pipe.");
2686 exit_status = WS_EXIT_INVALID_OPTION;
2687 goto clean_exit;
2689 /* There's some other reason we're dissecting. */
2690 cmdarg_err("Dissection isn't supported when capturing and saving to a pipe.");
2691 exit_status = WS_EXIT_INVALID_OPTION;
2692 goto clean_exit;
2695 /* Write a preamble if we're printing one. Do this after all checking
2696 * for invalid options, so we don't print just a preamble and quit. */
2697 if (print_packet_info) {
2698 if (!write_preamble(&cfile)) {
2699 show_print_file_io_error();
2700 exit_status = WS_EXIT_INVALID_FILE;
2701 goto clean_exit;
2706 * XXX - this returns FALSE if an error occurred, but it also
2707 * returns FALSE if the capture stops because a time limit
2708 * was reached (and possibly other limits), so we can't assume
2709 * it means an error.
2711 * The capture code is a bit twisty, so it doesn't appear to
2712 * be an easy fix. We just ignore the return value for now.
2713 * Instead, pass on the exit status from the capture child.
2715 capture();
2716 exit_status = global_capture_session.fork_child_status;
2718 if (print_packet_info) {
2719 if (!write_finale()) {
2720 show_print_file_io_error();
2725 * If we never got a capture file, don't draw the taps; we not only
2726 * didn't capture any packets, we never even did any capturing.
2728 if (cfile.filename != NULL)
2729 draw_taps = TRUE;
2730 #else
2731 /* No - complain. */
2732 cmdarg_err("This version of TShark was not built with support for capturing packets.");
2733 exit_status = INVALID_CAPTURE;
2734 goto clean_exit;
2735 #endif
2738 if (cfile.provider.frames != NULL) {
2739 free_frame_data_sequence(cfile.provider.frames);
2740 cfile.provider.frames = NULL;
2743 if (draw_taps)
2744 draw_tap_listeners(TRUE);
2746 if (tls_session_keys_file) {
2747 gsize keylist_length;
2748 gchar *keylist = ssl_export_sessions(&keylist_length);
2749 write_file_binary_mode(tls_session_keys_file, keylist, keylist_length);
2750 g_free(keylist);
2753 if (opt_print_timers) {
2754 if (cf_name == NULL) {
2755 /* We're doind a live capture. That isn't currently supported
2756 * with timers. */
2757 ws_message("Ignoring option --print-timers because we are doing a live capture");
2759 else {
2760 print_elapsed_json(cf_name, dfilter);
2764 /* Memory cleanup */
2765 reset_tap_listeners();
2766 funnel_dump_all_text_windows();
2767 epan_free(cfile.epan);
2768 epan_cleanup();
2769 extcap_cleanup();
2771 output_fields_free(output_fields);
2772 output_fields = NULL;
2774 clean_exit:
2775 cf_close(&cfile);
2776 g_free(cf_name);
2777 destroy_print_stream(print_stream);
2778 g_free(output_file_name);
2779 #ifdef HAVE_LIBPCAP
2780 capture_opts_cleanup(&global_capture_opts);
2781 if (cached_if_list) {
2782 free_interface_list(cached_if_list);
2784 #endif
2785 col_cleanup(&cfile.cinfo);
2786 wtap_cleanup();
2787 free_progdirs();
2788 dfilter_free(dfcode);
2789 g_free(dfilter);
2790 return exit_status;
2793 gboolean loop_running;
2794 guint32 packet_count;
2796 static epan_t *
2797 tshark_epan_new(capture_file *cf)
2799 static const struct packet_provider_funcs funcs = {
2800 cap_file_provider_get_frame_ts,
2801 cap_file_provider_get_interface_name,
2802 cap_file_provider_get_interface_description,
2803 NULL,
2806 return epan_new(&cf->provider, &funcs);
2809 #ifdef HAVE_LIBPCAP
2810 static gboolean
2811 capture(void)
2813 volatile gboolean ret = TRUE;
2814 GString *str;
2815 GMainContext *ctx;
2816 #ifndef _WIN32
2817 struct sigaction action, oldaction;
2818 #endif
2820 /* Create new dissection section. */
2821 epan_free(cfile.epan);
2822 cfile.epan = tshark_epan_new(&cfile);
2824 #ifdef _WIN32
2825 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2826 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2827 #else /* _WIN32 */
2828 /* Catch SIGINT and SIGTERM and, if we get either of them,
2829 clean up and exit. If SIGHUP isn't being ignored, catch
2830 it too and, if we get it, clean up and exit.
2832 We restart any read that was in progress, so that it doesn't
2833 disrupt reading from the sync pipe. The signal handler tells
2834 the capture child to finish; it will report that it finished,
2835 or will exit abnormally, so we'll stop reading from the sync
2836 pipe, pick up the exit status, and quit. */
2837 memset(&action, 0, sizeof(action));
2838 action.sa_handler = capture_cleanup;
2839 action.sa_flags = SA_RESTART;
2840 sigemptyset(&action.sa_mask);
2841 sigaction(SIGTERM, &action, NULL);
2842 sigaction(SIGINT, &action, NULL);
2843 sigaction(SIGHUP, NULL, &oldaction);
2844 if (oldaction.sa_handler == SIG_DFL)
2845 sigaction(SIGHUP, &action, NULL);
2847 #ifdef SIGINFO
2848 /* Catch SIGINFO and, if we get it and we're capturing to a file in
2849 quiet mode, report the number of packets we've captured.
2851 Again, restart any read that was in progress, so that it doesn't
2852 disrupt reading from the sync pipe. */
2853 action.sa_handler = report_counts_siginfo;
2854 action.sa_flags = SA_RESTART;
2855 sigemptyset(&action.sa_mask);
2856 sigaction(SIGINFO, &action, NULL);
2857 #endif /* SIGINFO */
2858 #endif /* _WIN32 */
2860 global_capture_session.state = CAPTURE_PREPARING;
2862 /* Let the user know which interfaces were chosen. */
2863 str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2864 if (really_quiet == FALSE)
2865 fprintf(stderr, "Capturing on %s\n", str->str);
2866 fflush(stderr);
2867 g_string_free(str, TRUE);
2869 ret = sync_pipe_start(&global_capture_opts, capture_comments,
2870 &global_capture_session, &global_info_data, NULL);
2872 if (!ret)
2873 return FALSE;
2876 * Force synchronous resolution of IP addresses; we're doing only
2877 * one pass, so we can't do it in the background and fix up past
2878 * dissections.
2880 set_resolution_synchrony(TRUE);
2882 /* the actual capture loop */
2883 ctx = g_main_context_default();
2884 loop_running = TRUE;
2888 while (loop_running)
2890 g_main_context_iteration(ctx, TRUE);
2893 CATCH(OutOfMemoryError) {
2894 fprintf(stderr,
2895 "Out Of Memory.\n"
2896 "\n"
2897 "Sorry, but TShark has to terminate now.\n"
2898 "\n"
2899 "More information and workarounds can be found at\n"
2900 WS_WIKI_URL("KnownBugs/OutOfMemory") "\n");
2901 abort();
2903 ENDTRY;
2904 return ret;
2907 /* capture child detected an error */
2908 static void
2909 capture_input_error(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2911 /* The primary message might be an empty string, e.g. when the error was
2912 * from extcap. (The extcap stderr is gathered when the session closes
2913 * and printed in capture_input_closed below.) */
2914 if (*error_msg != '\0') {
2915 cmdarg_err("%s", error_msg);
2916 if (secondary_error_msg != NULL && *secondary_error_msg != '\0') {
2917 /* We have both primary and secondary messages. */
2918 cmdarg_err_cont("%s", secondary_error_msg);
2924 /* capture child detected an capture filter related error */
2925 static void
2926 capture_input_cfilter_error(capture_session *cap_session, guint i, const char *error_message)
2928 capture_options *capture_opts = cap_session->capture_opts;
2929 dfilter_t *rfcode = NULL;
2930 interface_options *interface_opts;
2932 ws_assert(i < capture_opts->ifaces->len);
2933 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2935 if (dfilter_compile(interface_opts->cfilter, &rfcode, NULL) && rfcode != NULL) {
2936 cmdarg_err(
2937 "Invalid capture filter \"%s\" for interface '%s'.\n"
2938 "\n"
2939 "That string looks like a valid display filter; however, it isn't a valid\n"
2940 "capture filter (%s).\n"
2941 "\n"
2942 "Note that display filters and capture filters don't have the same syntax,\n"
2943 "so you can't use most display filter expressions as capture filters.\n"
2944 "\n"
2945 "See the User's Guide for a description of the capture filter syntax.",
2946 interface_opts->cfilter, interface_opts->descr, error_message);
2947 dfilter_free(rfcode);
2948 } else {
2949 cmdarg_err(
2950 "Invalid capture filter \"%s\" for interface '%s'.\n"
2951 "\n"
2952 "That string isn't a valid capture filter (%s).\n"
2953 "See the User's Guide for a description of the capture filter syntax.",
2954 interface_opts->cfilter, interface_opts->descr, error_message);
2959 /* capture child tells us we have a new (or the first) capture file */
2960 static bool
2961 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2963 capture_options *capture_opts = cap_session->capture_opts;
2964 capture_file *cf = cap_session->cf;
2965 gboolean is_tempfile;
2966 int err;
2968 if (really_quiet == FALSE) {
2969 if (cap_session->state == CAPTURE_PREPARING) {
2970 ws_info("Capture started.");
2972 ws_info("File: \"%s\"", new_file);
2975 ws_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2977 /* free the old filename */
2978 if (capture_opts->save_file != NULL) {
2980 /* we start a new capture file, close the old one (if we had one before) */
2981 if (cf->state != FILE_CLOSED) {
2982 cf_close(cf);
2985 g_free(capture_opts->save_file);
2986 is_tempfile = FALSE;
2988 epan_free(cf->epan);
2989 cf->epan = tshark_epan_new(cf);
2990 } else {
2991 /* we didn't had a save_file before, must be a tempfile */
2992 is_tempfile = TRUE;
2995 /* save the new filename */
2996 capture_opts->save_file = g_strdup(new_file);
2998 /* if we are in real-time mode, open the new file now */
2999 if (do_dissection) {
3000 /* this is probably unnecessary, but better safe than sorry */
3001 cap_session->cf->open_type = WTAP_TYPE_AUTO;
3002 /* Attempt to open the capture file and set up to read from it. */
3003 switch(cf_open(cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
3004 case CF_OK:
3005 break;
3006 case CF_ERROR:
3007 /* Don't unlink (delete) the save file - leave it around,
3008 for debugging purposes. */
3009 g_free(capture_opts->save_file);
3010 capture_opts->save_file = NULL;
3011 return FALSE;
3013 } else if (quiet && is_tempfile) {
3014 cf->state = FILE_READ_ABORTED;
3015 cf->filename = g_strdup(new_file);
3016 cf->is_tempfile = is_tempfile;
3019 cap_session->state = CAPTURE_RUNNING;
3021 return TRUE;
3025 /* capture child tells us we have new packets to read */
3026 static void
3027 capture_input_new_packets(capture_session *cap_session, int to_read)
3029 gboolean ret;
3030 int err;
3031 gchar *err_info;
3032 gint64 data_offset;
3033 capture_file *cf = cap_session->cf;
3034 gboolean filtering_tap_listeners;
3035 guint tap_flags;
3037 #ifdef SIGINFO
3039 * Prevent a SIGINFO handler from writing to the standard error while
3040 * we're doing so or writing to the standard output; instead, have it
3041 * just set a flag telling us to print that information when we're done.
3043 infodelay = TRUE;
3044 #endif /* SIGINFO */
3046 /* Do we have any tap listeners with filters? */
3047 filtering_tap_listeners = have_filtering_tap_listeners();
3049 /* Get the union of the flags for all tap listeners. */
3050 tap_flags = union_of_tap_listener_flags();
3052 if (do_dissection) {
3053 gboolean create_proto_tree;
3054 epan_dissect_t *edt;
3055 wtap_rec rec;
3056 Buffer buf;
3059 * Determine whether we need to create a protocol tree.
3060 * We do if:
3062 * we're going to apply a read filter;
3064 * we're going to apply a display filter;
3066 * we're going to print the protocol tree;
3068 * one of the tap listeners is going to apply a filter;
3070 * one of the tap listeners requires a protocol tree;
3072 * a postdissector wants field values or protocols
3073 * on the first pass;
3075 * we have custom columns (which require field values, which
3076 * currently requires that we build a protocol tree).
3078 create_proto_tree =
3079 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3080 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3081 have_custom_cols(&cf->cinfo) || dissect_color);
3083 /* The protocol tree will be "visible", i.e., nothing faked, only if
3084 we're printing packet details, which is true if we're printing stuff
3085 ("print_packet_info" is true) and we're in verbose mode
3086 ("packet_details" is true). But if we specified certain fields with
3087 "-e", we'll prime those directly later. */
3088 bool visible = print_packet_info && print_details && output_fields_num_fields(output_fields) == 0;
3089 edt = epan_dissect_new(cf->epan, create_proto_tree, visible);
3091 wtap_rec_init(&rec);
3092 ws_buffer_init(&buf, 1514);
3094 while (to_read-- && cf->provider.wth) {
3095 wtap_cleareof(cf->provider.wth);
3096 ret = wtap_read(cf->provider.wth, &rec, &buf, &err, &err_info, &data_offset);
3097 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3098 if (ret == FALSE) {
3099 /* read from file failed, tell the capture child to stop */
3100 sync_pipe_stop(cap_session);
3101 wtap_close(cf->provider.wth);
3102 cf->provider.wth = NULL;
3103 } else {
3104 ret = process_packet_single_pass(cf, edt, data_offset, &rec, &buf,
3105 tap_flags);
3107 if (ret != FALSE) {
3108 /* packet successfully read and gone through the "Read Filter" */
3109 packet_count++;
3111 wtap_rec_reset(&rec);
3114 epan_dissect_free(edt);
3116 wtap_rec_cleanup(&rec);
3117 ws_buffer_free(&buf);
3119 } else {
3121 * Dumpcap's doing all the work; we're not doing any dissection.
3122 * Count all the packets it wrote.
3124 packet_count += to_read;
3127 if (print_packet_counts) {
3128 /* We're printing packet counts. */
3129 if (packet_count != 0) {
3130 fprintf(stderr, "\r%u ", packet_count);
3131 /* stderr could be line buffered */
3132 fflush(stderr);
3136 #ifdef SIGINFO
3138 * Allow SIGINFO handlers to write.
3140 infodelay = FALSE;
3143 * If a SIGINFO handler asked us to write out capture counts, do so.
3145 if (infoprint)
3146 report_counts();
3147 #endif /* SIGINFO */
3150 static void
3151 report_counts(void)
3153 if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
3154 /* Report the count only if we aren't printing a packet count
3155 as packets arrive. */
3156 fprintf(stderr, "%u packet%s captured\n", packet_count,
3157 plurality(packet_count, "", "s"));
3159 #ifdef SIGINFO
3160 infoprint = FALSE; /* we just reported it */
3161 #endif /* SIGINFO */
3164 #ifdef SIGINFO
3165 static void
3166 report_counts_siginfo(int signum _U_)
3168 int sav_errno = errno;
3169 /* If we've been told to delay printing, just set a flag asking
3170 that we print counts (if we're supposed to), otherwise print
3171 the count of packets captured (if we're supposed to). */
3172 if (infodelay)
3173 infoprint = TRUE;
3174 else
3175 report_counts();
3176 errno = sav_errno;
3178 #endif /* SIGINFO */
3181 /* capture child detected any packet drops? */
3182 static void
3183 capture_input_drops(capture_session *cap_session _U_, guint32 dropped, const char* interface_name)
3185 if (print_packet_counts) {
3186 /* We're printing packet counts to stderr.
3187 Send a newline so that we move to the line after the packet count. */
3188 fprintf(stderr, "\n");
3191 if (dropped != 0) {
3192 /* We're printing packet counts to stderr.
3193 Send a newline so that we move to the line after the packet count. */
3194 if (interface_name != NULL) {
3195 fprintf(stderr, "%u packet%s dropped from %s\n", dropped, plurality(dropped, "", "s"), interface_name);
3196 } else {
3197 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
3204 * Capture child closed its side of the pipe, report any error and
3205 * do the required cleanup.
3207 static void
3208 capture_input_closed(capture_session *cap_session _U_, gchar *msg)
3210 if (msg != NULL && *msg != '\0')
3211 fprintf(stderr, "tshark: %s\n", msg);
3213 report_counts();
3215 loop_running = FALSE;
3218 #ifdef _WIN32
3219 static BOOL WINAPI
3220 capture_cleanup(DWORD ctrltype _U_)
3222 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
3223 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
3224 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
3225 like SIGTERM at least when the machine's shutting down.
3227 For now, we handle them all as indications that we should clean up
3228 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
3229 way on UNIX.
3231 We must return TRUE so that no other handler - such as one that would
3232 terminate the process - gets called.
3234 XXX - for some reason, typing ^C to TShark, if you run this in
3235 a Cygwin console window in at least some versions of Cygwin,
3236 causes TShark to terminate immediately; this routine gets
3237 called, but the main loop doesn't get a chance to run and
3238 exit cleanly, at least if this is compiled with Microsoft Visual
3239 C++ (i.e., it's a property of the Cygwin console window or Bash;
3240 it happens if TShark is not built with Cygwin - for all I know,
3241 building it with Cygwin may make the problem go away). */
3243 /* tell the capture child to stop */
3244 sync_pipe_stop(&global_capture_session);
3246 /* don't stop our own loop already here, otherwise status messages and
3247 * cleanup wouldn't be done properly. The child will indicate the stop of
3248 * everything by calling capture_input_closed() later */
3250 return TRUE;
3252 #else
3253 static void
3254 capture_cleanup(int signum _U_)
3256 /* tell the capture child to stop */
3257 sync_pipe_stop(&global_capture_session);
3259 /* don't stop our own loop already here, otherwise status messages and
3260 * cleanup wouldn't be done properly. The child will indicate the stop of
3261 * everything by calling capture_input_closed() later */
3263 #endif /* _WIN32 */
3264 #endif /* HAVE_LIBPCAP */
3266 static gboolean
3267 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
3268 gint64 offset, wtap_rec *rec, Buffer *buf)
3270 frame_data fdlocal;
3271 guint32 framenum;
3272 gboolean passed;
3273 gint64 elapsed_start;
3275 /* The frame number of this packet is one more than the count of
3276 frames in this packet. */
3277 framenum = cf->count + 1;
3279 /* If we're not running a display filter and we're not printing any
3280 packet information, we don't need to do a dissection. This means
3281 that all packets can be marked as 'passed'. */
3282 passed = TRUE;
3284 frame_data_init(&fdlocal, framenum, rec, offset, cum_bytes);
3286 /* If we're going to run a read filter or a display filter, set up to
3287 do a dissection and do so. (This is the first pass of two passes
3288 over the packets, so we will not be printing any information
3289 from the dissection or running taps on the packet; if we're doing
3290 any of that, we'll do it in the second pass.) */
3291 if (edt) {
3292 if (gbl_resolv_flags.network_name || gbl_resolv_flags.maxmind_geoip) {
3293 /* If we're doing async lookups, send any that are queued and
3294 * retrieve results.
3296 * Ideally we'd force any lookups that need to happen on the second pass
3297 * to be sent asynchronously on this pass so the results would be ready.
3298 * That will happen if they're involved in a filter (because we prime the
3299 * tree below), but not currently for taps, if we're printing packet
3300 * summaries or details, etc.
3302 * XXX - If we're running a read filter that depends on a resolved
3303 * name, we should be doing synchronous lookups in that case. Also
3304 * marking the dependent frames below might not work with a display
3305 * filter that depends on a resolved name.
3307 host_name_lookup_process();
3310 column_info *cinfo = NULL;
3312 /* If we're running a read filter, prime the epan_dissect_t with that
3313 filter. */
3314 if (cf->rfcode)
3315 epan_dissect_prime_with_dfilter(edt, cf->rfcode);
3317 if (cf->dfcode)
3318 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3320 /* This is the first pass, so prime the epan_dissect_t with the
3321 hfids postdissectors want on the first pass. */
3322 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
3324 frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
3325 &cf->provider.ref, cf->provider.prev_dis);
3326 if (cf->provider.ref == &fdlocal) {
3327 ref_frame = fdlocal;
3328 cf->provider.ref = &ref_frame;
3331 /* If we're applying a filter that needs the columns, construct them. */
3332 if (dfilter_requires_columns(cf->rfcode) || dfilter_requires_columns(cf->dfcode)) {
3333 cinfo = &cf->cinfo;
3336 elapsed_start = g_get_monotonic_time();
3337 epan_dissect_run(edt, cf->cd_t, rec,
3338 frame_tvbuff_new_buffer(&cf->provider, &fdlocal, buf),
3339 &fdlocal, cinfo);
3340 tshark_elapsed.first_pass.dissect += g_get_monotonic_time() - elapsed_start;
3342 /* Run the read filter if we have one. */
3343 if (cf->rfcode) {
3344 elapsed_start = g_get_monotonic_time();
3345 passed = dfilter_apply_edt(cf->rfcode, edt);
3346 tshark_elapsed.first_pass.dfilter_read += g_get_monotonic_time() - elapsed_start;
3350 if (passed) {
3351 frame_data_set_after_dissect(&fdlocal, &cum_bytes);
3352 cf->provider.prev_cap = cf->provider.prev_dis = frame_data_sequence_add(cf->provider.frames, &fdlocal);
3354 /* If we're not doing dissection then there won't be any dependent frames.
3355 * More importantly, edt.pi.fd.dependent_frames won't be initialized because
3356 * epan hasn't been initialized.
3357 * if we *are* doing dissection, then mark the dependent frames, but only
3358 * if a display filter was given and it matches this packet.
3360 if (edt && cf->dfcode) {
3361 elapsed_start = g_get_monotonic_time();
3362 if (dfilter_apply_edt(cf->dfcode, edt) && edt->pi.fd->dependent_frames) {
3363 g_hash_table_foreach(edt->pi.fd->dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
3366 if (selected_frame_number != 0 && selected_frame_number == cf->count + 1) {
3367 /* If we are doing dissection and we have a "selected frame"
3368 * then load that frame's references (if any) onto the compiled
3369 * display filter. Selected frame number is ordinal, count is cardinal. */
3370 dfilter_load_field_references(cf->dfcode, edt->tree);
3372 tshark_elapsed.first_pass.dfilter_filter += g_get_monotonic_time() - elapsed_start;
3375 cf->count++;
3376 } else {
3377 /* if we don't add it to the frame_data_sequence, clean it up right now
3378 * to avoid leaks */
3379 frame_data_destroy(&fdlocal);
3382 if (edt)
3383 epan_dissect_reset(edt);
3385 return passed;
3389 * Set if reading a file was interrupted by a CTRL_ event on Windows or
3390 * a signal on UN*X.
3392 static gboolean read_interrupted;
3394 #ifdef _WIN32
3395 static BOOL WINAPI
3396 read_cleanup(DWORD ctrltype _U_)
3398 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
3399 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
3400 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
3401 like SIGTERM at least when the machine's shutting down.
3403 For now, we handle them all as indications that we should clean up
3404 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
3405 way on UNIX.
3407 We must return TRUE so that no other handler - such as one that would
3408 terminate the process - gets called.
3410 XXX - for some reason, typing ^C to TShark, if you run this in
3411 a Cygwin console window in at least some versions of Cygwin,
3412 causes TShark to terminate immediately; this routine gets
3413 called, but the main loop doesn't get a chance to run and
3414 exit cleanly, at least if this is compiled with Microsoft Visual
3415 C++ (i.e., it's a property of the Cygwin console window or Bash;
3416 it happens if TShark is not built with Cygwin - for all I know,
3417 building it with Cygwin may make the problem go away). */
3419 /* tell the read to stop */
3420 read_interrupted = TRUE;
3422 return TRUE;
3424 #else
3425 static void
3426 read_cleanup(int signum _U_)
3428 /* tell the read to stop */
3429 read_interrupted = TRUE;
3431 #endif /* _WIN32 */
3433 typedef enum {
3434 PASS_SUCCEEDED,
3435 PASS_READ_ERROR,
3436 PASS_WRITE_ERROR,
3437 PASS_INTERRUPTED
3438 } pass_status_t;
3440 static pass_status_t
3441 process_cap_file_first_pass(capture_file *cf, int max_packet_count,
3442 gint64 max_byte_count, int *err, gchar **err_info)
3444 wtap_rec rec;
3445 Buffer buf;
3446 epan_dissect_t *edt = NULL;
3447 gint64 data_offset;
3448 pass_status_t status = PASS_SUCCEEDED;
3449 int framenum = 0;
3451 wtap_rec_init(&rec);
3452 ws_buffer_init(&buf, 1514);
3454 /* Allocate a frame_data_sequence for all the frames. */
3455 cf->provider.frames = new_frame_data_sequence();
3457 if (do_dissection) {
3458 gboolean create_proto_tree;
3461 * Determine whether we need to create a protocol tree.
3462 * We do if:
3464 * we're going to apply a read filter;
3466 * we're going to apply a display filter;
3468 * a postdissector wants field values or protocols
3469 * on the first pass.
3471 create_proto_tree =
3472 (cf->rfcode != NULL || cf->dfcode != NULL || postdissectors_want_hfids() || dissect_color);
3474 ws_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3476 /* We're not going to display the protocol tree on this pass,
3477 so it's not going to be "visible". */
3478 edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
3481 ws_debug("tshark: reading records for first pass");
3482 *err = 0;
3483 while (wtap_read(cf->provider.wth, &rec, &buf, err, err_info, &data_offset)) {
3484 if (read_interrupted) {
3485 status = PASS_INTERRUPTED;
3486 break;
3488 framenum++;
3490 if (process_packet_first_pass(cf, edt, data_offset, &rec, &buf)) {
3491 /* Stop reading if we hit a stop condition */
3492 if (max_packet_count > 0 && framenum >= max_packet_count) {
3493 ws_debug("tshark: max_packet_count (%d) reached", max_packet_count);
3494 *err = 0; /* This is not an error */
3495 break;
3497 if (max_byte_count != 0 && data_offset >= max_byte_count) {
3498 ws_debug("tshark: max_byte_count (%" PRId64 "/%" PRId64 ") reached",
3499 data_offset, max_byte_count);
3500 *err = 0; /* This is not an error */
3501 break;
3504 wtap_rec_reset(&rec);
3506 if (*err != 0)
3507 status = PASS_READ_ERROR;
3509 if (edt)
3510 epan_dissect_free(edt);
3512 /* Close the sequential I/O side, to free up memory it requires. */
3513 wtap_sequential_close(cf->provider.wth);
3515 /* Allow the protocol dissectors to free up memory that they
3516 * don't need after the sequential run-through of the packets. */
3517 postseq_cleanup_all_protocols();
3519 cf->provider.prev_dis = NULL;
3520 cf->provider.prev_cap = NULL;
3522 ws_buffer_free(&buf);
3523 wtap_rec_cleanup(&rec);
3525 return status;
3528 static gboolean
3529 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt,
3530 frame_data *fdata, wtap_rec *rec,
3531 Buffer *buf, guint tap_flags _U_)
3533 column_info *cinfo;
3534 gboolean passed;
3535 wtap_block_t block = NULL;
3536 gint64 elapsed_start;
3538 /* If we're not running a display filter and we're not printing any
3539 packet information, we don't need to do a dissection. This means
3540 that all packets can be marked as 'passed'. */
3541 passed = TRUE;
3543 /* If we're going to print packet information, or we're going to
3544 run a read filter, or we're going to process taps, set up to
3545 do a dissection and do so. (This is the second pass of two
3546 passes over the packets; that's the pass where we print
3547 packet information or run taps.) */
3548 if (edt) {
3549 /* If we're running a display filter, prime the epan_dissect_t with that
3550 filter. */
3551 if (cf->dfcode)
3552 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
3554 col_custom_prime_edt(edt, &cf->cinfo);
3556 output_fields_prime_edt(edt, output_fields);
3557 /* The PDML spec requires a 'geninfo' pseudo-protocol that needs
3558 * information from our 'frame' protocol.
3560 if (output_fields_num_fields(output_fields) != 0 &&
3561 output_action == WRITE_XML) {
3562 epan_dissect_prime_with_hfid(edt, proto_registrar_get_id_byname("frame"));
3565 /* We only need the columns if either
3566 1) some tap or filter needs the columns
3568 2) we're printing packet info but we're *not* verbose; in verbose
3569 mode, we print the protocol tree, not the protocol summary.
3571 3) there is a column mapped to an individual field
3573 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields) || dfilter_requires_columns(cf->dfcode))
3574 cinfo = &cf->cinfo;
3575 else
3576 cinfo = NULL;
3578 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
3579 &cf->provider.ref, cf->provider.prev_dis);
3580 if (cf->provider.ref == fdata) {
3581 ref_frame = *fdata;
3582 cf->provider.ref = &ref_frame;
3585 if (dissect_color) {
3586 color_filters_prime_edt(edt);
3587 fdata->need_colorize = 1;
3590 /* epan_dissect_run (and epan_dissect_reset) unref the block.
3591 * We need it later, e.g. in order to copy the options. */
3592 block = wtap_block_ref(rec->block);
3593 elapsed_start = g_get_monotonic_time();
3594 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
3595 frame_tvbuff_new_buffer(&cf->provider, fdata, buf),
3596 fdata, cinfo);
3597 tshark_elapsed.second_pass.dissect += g_get_monotonic_time() - elapsed_start;
3599 /* Run the display filter if we have one. */
3600 if (cf->dfcode) {
3601 elapsed_start = g_get_monotonic_time();
3602 passed = dfilter_apply_edt(cf->dfcode, edt);
3603 tshark_elapsed.second_pass.dfilter_filter += g_get_monotonic_time() - elapsed_start;
3607 if (passed) {
3608 frame_data_set_after_dissect(fdata, &cum_bytes);
3609 /* Process this packet. */
3610 if (print_packet_info) {
3611 /* We're printing packet information; print the information for
3612 this packet. */
3613 print_packet(cf, edt);
3615 /* If we're doing "line-buffering", flush the standard output
3616 after every packet. See the comment above, for the "-l"
3617 option, for an explanation of why we do that. */
3618 if (line_buffered)
3619 fflush(stdout);
3621 if (ferror(stdout)) {
3622 show_print_file_io_error();
3623 exit(2);
3626 cf->provider.prev_dis = fdata;
3628 cf->provider.prev_cap = fdata;
3630 if (edt) {
3631 epan_dissect_reset(edt);
3632 rec->block = block;
3634 return passed || fdata->dependent_of_displayed;
3637 static gboolean
3638 process_new_idbs(wtap *wth, wtap_dumper *pdh, int *err, gchar **err_info)
3640 wtap_block_t if_data;
3642 while ((if_data = wtap_get_next_interface_description(wth)) != NULL) {
3644 * Only add interface blocks if the output file supports (meaning
3645 * *requires*) them.
3647 * That mean that the abstract interface provided by libwiretap
3648 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
3650 if (pdh != NULL) {
3651 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh), WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
3652 if (!wtap_dump_add_idb(pdh, if_data, err, err_info))
3653 return FALSE;
3657 return TRUE;
3660 static pass_status_t
3661 process_cap_file_second_pass(capture_file *cf, wtap_dumper *pdh,
3662 int *err, gchar **err_info,
3663 volatile guint32 *err_framenum,
3664 int max_write_packet_count)
3666 wtap_rec rec;
3667 Buffer buf;
3668 int framenum = 0;
3669 int write_framenum = 0;
3670 frame_data *fdata;
3671 gboolean filtering_tap_listeners;
3672 guint tap_flags;
3673 epan_dissect_t *edt = NULL;
3674 pass_status_t status = PASS_SUCCEEDED;
3677 * Process whatever IDBs we haven't seen yet. This will be all
3678 * the IDBs in the file, as we've finished reading it; they'll
3679 * all be at the beginning of the output file.
3681 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3682 *err_framenum = 0;
3683 return PASS_WRITE_ERROR;
3686 wtap_rec_init(&rec);
3687 ws_buffer_init(&buf, 1514);
3689 /* Do we have any tap listeners with filters? */
3690 filtering_tap_listeners = have_filtering_tap_listeners();
3692 /* Get the union of the flags for all tap listeners. */
3693 tap_flags = union_of_tap_listener_flags();
3695 if (do_dissection) {
3696 gboolean create_proto_tree;
3699 * Determine whether we need to create a protocol tree.
3700 * We do if:
3702 * we're going to apply a display filter;
3704 * we're going to print the protocol tree;
3706 * one of the tap listeners requires a protocol tree;
3708 * we have custom columns (which require field values, which
3709 * currently requires that we build a protocol tree).
3711 create_proto_tree =
3712 (cf->dfcode || print_details || filtering_tap_listeners ||
3713 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo) || dissect_color);
3715 ws_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3717 /* The protocol tree will be "visible", i.e., nothing faked, only if
3718 we're printing packet details, which is true if we're printing stuff
3719 ("print_packet_info" is true) and we're in verbose mode
3720 ("packet_details" is true). But if we specified certain fields with
3721 "-e", we'll prime those directly later. */
3722 bool visible = print_packet_info && print_details && output_fields_num_fields(output_fields) == 0;
3723 edt = epan_dissect_new(cf->epan, create_proto_tree, visible);
3727 * Force synchronous resolution of IP addresses; in this pass, we
3728 * can't do it in the background and fix up past dissections.
3730 set_resolution_synchrony(TRUE);
3732 for (framenum = 1; framenum <= (int)cf->count; framenum++) {
3733 if (read_interrupted) {
3734 status = PASS_INTERRUPTED;
3735 break;
3737 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3738 if (!wtap_seek_read(cf->provider.wth, fdata->file_off, &rec, &buf, err,
3739 err_info)) {
3740 /* Error reading from the input file. */
3741 status = PASS_READ_ERROR;
3742 break;
3744 ws_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3745 if (process_packet_second_pass(cf, edt, fdata, &rec, &buf, tap_flags)) {
3746 /* Either there's no read filtering or this packet passed the
3747 filter, so, if we're writing to a capture file, write
3748 this packet out. */
3749 write_framenum++;
3750 if (pdh != NULL) {
3751 ws_debug("tshark: writing packet #%d to outfile packet #%d", framenum, write_framenum);
3752 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&buf), err, err_info)) {
3753 /* Error writing to the output file. */
3754 ws_debug("tshark: error writing to a capture file (%d)", *err);
3755 *err_framenum = framenum;
3756 status = PASS_WRITE_ERROR;
3757 break;
3759 /* Stop reading if we hit a stop condition */
3760 if (max_write_packet_count > 0 && write_framenum >= max_write_packet_count) {
3761 ws_debug("tshark: max_write_packet_count (%d) reached", max_write_packet_count);
3762 *err = 0; /* This is not an error */
3763 break;
3767 wtap_rec_reset(&rec);
3770 if (edt)
3771 epan_dissect_free(edt);
3773 ws_buffer_free(&buf);
3774 wtap_rec_cleanup(&rec);
3776 return status;
3779 static pass_status_t
3780 process_cap_file_single_pass(capture_file *cf, wtap_dumper *pdh,
3781 int max_packet_count, gint64 max_byte_count,
3782 int max_write_packet_count,
3783 int *err, gchar **err_info,
3784 volatile guint32 *err_framenum)
3786 wtap_rec rec;
3787 Buffer buf;
3788 gboolean create_proto_tree = FALSE;
3789 gboolean filtering_tap_listeners;
3790 guint tap_flags;
3791 int framenum = 0;
3792 int write_framenum = 0;
3793 epan_dissect_t *edt = NULL;
3794 gint64 data_offset;
3795 pass_status_t status = PASS_SUCCEEDED;
3797 wtap_rec_init(&rec);
3798 ws_buffer_init(&buf, 1514);
3800 /* Do we have any tap listeners with filters? */
3801 filtering_tap_listeners = have_filtering_tap_listeners();
3803 /* Get the union of the flags for all tap listeners. */
3804 tap_flags = union_of_tap_listener_flags();
3806 if (do_dissection) {
3808 * Determine whether we need to create a protocol tree.
3809 * We do if:
3811 * we're going to apply a read filter;
3813 * we're going to apply a display filter;
3815 * we're going to print the protocol tree;
3817 * one of the tap listeners is going to apply a filter;
3819 * one of the tap listeners requires a protocol tree;
3821 * a postdissector wants field values or protocols
3822 * on the first pass;
3824 * we have custom columns (which require field values, which
3825 * currently requires that we build a protocol tree).
3827 create_proto_tree =
3828 (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3829 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids() ||
3830 have_custom_cols(&cf->cinfo) || dissect_color);
3832 ws_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3834 /* The protocol tree will be "visible", i.e., nothing faked, only if
3835 we're printing packet details, which is true if we're printing stuff
3836 ("print_packet_info" is true) and we're in verbose mode
3837 ("packet_details" is true). But if we specified certain fields with
3838 "-e", we'll prime those directly later. */
3839 bool visible = print_packet_info && print_details && output_fields_num_fields(output_fields) == 0;
3840 edt = epan_dissect_new(cf->epan, create_proto_tree, visible);
3844 * Force synchronous resolution of IP addresses; we're doing only
3845 * one pass, so we can't do it in the background and fix up past
3846 * dissections.
3848 set_resolution_synchrony(TRUE);
3850 *err = 0;
3851 while (wtap_read(cf->provider.wth, &rec, &buf, err, err_info, &data_offset)) {
3852 if (read_interrupted) {
3853 status = PASS_INTERRUPTED;
3854 break;
3856 framenum++;
3859 * Process whatever IDBs we haven't seen yet.
3861 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3862 *err_framenum = framenum;
3863 status = PASS_WRITE_ERROR;
3864 break;
3867 ws_debug("tshark: processing packet #%d", framenum);
3869 reset_epan_mem(cf, edt, create_proto_tree, print_packet_info && print_details);
3871 if (process_packet_single_pass(cf, edt, data_offset, &rec, &buf, tap_flags)) {
3872 /* Either there's no read filtering or this packet passed the
3873 filter, so, if we're writing to a capture file, write
3874 this packet out. */
3875 write_framenum++;
3876 if (pdh != NULL) {
3877 ws_debug("tshark: writing packet #%d to outfile as #%d",
3878 framenum, write_framenum);
3879 if (!wtap_dump(pdh, &rec, ws_buffer_start_ptr(&buf), err, err_info)) {
3880 /* Error writing to the output file. */
3881 ws_debug("tshark: error writing to a capture file (%d)", *err);
3882 *err_framenum = framenum;
3883 status = PASS_WRITE_ERROR;
3884 break;
3888 /* Stop reading if we hit a stop condition */
3889 if (max_packet_count > 0 && framenum >= max_packet_count) {
3890 ws_debug("tshark: max_packet_count (%d) reached", max_packet_count);
3891 *err = 0; /* This is not an error */
3892 break;
3894 if (max_write_packet_count > 0 && write_framenum >= max_write_packet_count) {
3895 ws_debug("tshark: max_write_packet_count (%d) reached", max_write_packet_count);
3896 *err = 0; /* This is not an error */
3897 break;
3899 if (max_byte_count != 0 && data_offset >= max_byte_count) {
3900 ws_debug("tshark: max_byte_count (%" PRId64 "/%" PRId64 ") reached",
3901 data_offset, max_byte_count);
3902 *err = 0; /* This is not an error */
3903 break;
3905 wtap_rec_reset(&rec);
3907 if (status == PASS_SUCCEEDED) {
3908 if (*err != 0) {
3909 /* Error reading from the input file. */
3910 status = PASS_READ_ERROR;
3911 } else {
3913 * Process whatever IDBs we haven't seen yet.
3915 if (!process_new_idbs(cf->provider.wth, pdh, err, err_info)) {
3916 *err_framenum = framenum;
3917 status = PASS_WRITE_ERROR;
3922 if (edt)
3923 epan_dissect_free(edt);
3925 ws_buffer_free(&buf);
3926 wtap_rec_cleanup(&rec);
3928 return status;
3931 static process_file_status_t
3932 process_cap_file(capture_file *cf, char *save_file, int out_file_type,
3933 gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count,
3934 int max_write_packet_count)
3936 process_file_status_t status = PROCESS_FILE_SUCCEEDED;
3937 wtap_dumper *pdh;
3938 #ifndef _WIN32
3939 struct sigaction action, oldaction;
3940 #endif
3941 int err = 0, err_pass1 = 0;
3942 gchar *err_info = NULL, *err_info_pass1 = NULL;
3943 volatile guint32 err_framenum;
3944 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
3945 char *shb_user_appl;
3946 pass_status_t first_pass_status, second_pass_status;
3947 gint64 elapsed_start;
3949 if (save_file != NULL) {
3950 /* Set up to write to the capture file. */
3951 wtap_dump_params_init_no_idbs(&params, cf->provider.wth);
3953 /* If we don't have an application name add TShark */
3954 if (wtap_block_get_string_option_value(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
3955 /* this is free'd by wtap_block_unref() later */
3956 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
3958 if (capture_comments != NULL) {
3959 for (guint i = 0; i < capture_comments->len; i++) {
3960 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0),
3961 OPT_COMMENT, "%s",
3962 (char *)g_ptr_array_index(capture_comments, i));
3966 ws_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
3967 if (strcmp(save_file, "-") == 0) {
3968 /* Write to the standard output. */
3969 pdh = wtap_dump_open_stdout(out_file_type, WTAP_UNCOMPRESSED, &params,
3970 &err, &err_info);
3971 } else {
3972 pdh = wtap_dump_open(save_file, out_file_type, WTAP_UNCOMPRESSED, &params,
3973 &err, &err_info);
3976 g_free(params.idb_inf);
3977 params.idb_inf = NULL;
3979 if (pdh == NULL) {
3980 /* We couldn't set up to write to the capture file. */
3981 cfile_dump_open_failure_message(save_file, err, err_info,
3982 out_file_type);
3983 status = PROCESS_FILE_NO_FILE_PROCESSED;
3984 goto out;
3986 } else {
3987 /* Set up to print packet information. */
3988 if (print_packet_info) {
3989 if (!write_preamble(cf)) {
3990 show_print_file_io_error();
3991 status = PROCESS_FILE_NO_FILE_PROCESSED;
3992 goto out;
3995 pdh = NULL;
3998 #ifdef _WIN32
3999 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
4000 SetConsoleCtrlHandler(read_cleanup, TRUE);
4001 #else /* _WIN32 */
4002 /* Catch SIGINT and SIGTERM and, if we get either of them,
4003 clean up and exit. If SIGHUP isn't being ignored, catch
4004 it too and, if we get it, clean up and exit.
4006 We restart any read that was in progress, so that it doesn't
4007 disrupt reading from the sync pipe. The signal handler tells
4008 the capture child to finish; it will report that it finished,
4009 or will exit abnormally, so we'll stop reading from the sync
4010 pipe, pick up the exit status, and quit. */
4011 memset(&action, 0, sizeof(action));
4012 action.sa_handler = read_cleanup;
4013 action.sa_flags = SA_RESTART;
4014 sigemptyset(&action.sa_mask);
4015 sigaction(SIGTERM, &action, NULL);
4016 sigaction(SIGINT, &action, NULL);
4017 sigaction(SIGHUP, NULL, &oldaction);
4018 if (oldaction.sa_handler == SIG_DFL)
4019 sigaction(SIGHUP, &action, NULL);
4020 #endif /* _WIN32 */
4022 if (perform_two_pass_analysis) {
4023 ws_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
4025 elapsed_start = g_get_monotonic_time();
4026 first_pass_status = process_cap_file_first_pass(cf, max_packet_count,
4027 max_byte_count,
4028 &err_pass1,
4029 &err_info_pass1);
4030 tshark_elapsed.elapsed_first_pass = g_get_monotonic_time() - elapsed_start;
4032 ws_debug("tshark: done with first pass");
4034 if (first_pass_status == PASS_INTERRUPTED) {
4035 /* The first pass was interrupted; skip the second pass.
4036 It won't be run, so it won't get an error. */
4037 second_pass_status = PASS_SUCCEEDED;
4038 } else {
4040 * If we got a read error on the first pass, we still do the second
4041 * pass, so we can at least process the packets we read, and then
4042 * report the first-pass error after the second pass (and before
4043 * we report any second-pass errors), so all the errors show up
4044 * at the end.
4046 elapsed_start = g_get_monotonic_time();
4047 second_pass_status = process_cap_file_second_pass(cf, pdh, &err, &err_info,
4048 &err_framenum,
4049 max_write_packet_count);
4050 tshark_elapsed.elapsed_second_pass = g_get_monotonic_time() - elapsed_start;
4052 ws_debug("tshark: done with second pass");
4055 else {
4056 /* !perform_two_pass_analysis */
4057 ws_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
4059 first_pass_status = PASS_SUCCEEDED; /* There is no first pass */
4061 elapsed_start = g_get_monotonic_time();
4062 second_pass_status = process_cap_file_single_pass(cf, pdh,
4063 max_packet_count,
4064 max_byte_count,
4065 max_write_packet_count,
4066 &err, &err_info,
4067 &err_framenum);
4068 tshark_elapsed.elapsed_first_pass = g_get_monotonic_time() - elapsed_start;
4070 ws_debug("tshark: done with single pass");
4073 if (first_pass_status != PASS_SUCCEEDED ||
4074 second_pass_status != PASS_SUCCEEDED) {
4076 * At least one of the passes didn't succeed; either it got a failure
4077 * or it was interrupted.
4079 if (first_pass_status != PASS_INTERRUPTED ||
4080 second_pass_status != PASS_INTERRUPTED) {
4081 /* At least one of the passes got an error. */
4082 ws_debug("tshark: something failed along the line (%d)", err);
4084 * If we're printing packet data, and the standard output and error
4085 * are going to the same place, flush the standard output, so everything
4086 * buffered up is written, and then print a newline to the standard
4087 * error before printing the error message, to separate it from the
4088 * packet data. (Alas, that only works on UN*X; st_dev is meaningless,
4089 * and the _fstat() documentation at Microsoft doesn't indicate whether
4090 * st_ino is even supported.)
4092 #ifndef _WIN32
4093 if (print_packet_info) {
4094 ws_statb64 stat_stdout, stat_stderr;
4096 if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
4097 if (stat_stdout.st_dev == stat_stderr.st_dev &&
4098 stat_stdout.st_ino == stat_stderr.st_ino) {
4099 fflush(stdout);
4100 fprintf(stderr, "\n");
4104 #endif
4106 /* Report status of pass 1 of two-pass processing. */
4107 switch (first_pass_status) {
4109 case PASS_SUCCEEDED:
4110 /* No problem. */
4111 break;
4113 case PASS_READ_ERROR:
4114 /* Read error. */
4115 cfile_read_failure_message(cf->filename, err_pass1, err_info_pass1);
4116 status = PROCESS_FILE_ERROR;
4117 break;
4119 case PASS_WRITE_ERROR:
4120 /* Won't happen on the first pass. */
4121 break;
4123 case PASS_INTERRUPTED:
4124 /* Not an error, so nothing to report. */
4125 status = PROCESS_FILE_INTERRUPTED;
4126 break;
4129 /* Report status of pass 2 of two-pass processing or the only pass
4130 of one-pass processing. */
4131 switch (second_pass_status) {
4133 case PASS_SUCCEEDED:
4134 /* No problem. */
4135 break;
4137 case PASS_READ_ERROR:
4138 /* Read error. */
4139 cfile_read_failure_message(cf->filename, err, err_info);
4140 status = PROCESS_FILE_ERROR;
4141 break;
4143 case PASS_WRITE_ERROR:
4144 /* Write error.
4145 XXX - framenum is not necessarily the frame number in
4146 the input file if there was a read filter. */
4147 cfile_write_failure_message(cf->filename, save_file, err, err_info,
4148 err_framenum, out_file_type);
4149 status = PROCESS_FILE_ERROR;
4150 break;
4152 case PASS_INTERRUPTED:
4153 /* Not an error, so nothing to report. */
4154 status = PROCESS_FILE_INTERRUPTED;
4155 break;
4158 if (save_file != NULL) {
4159 if (second_pass_status != PASS_WRITE_ERROR) {
4160 if (pdh && out_file_name_res) {
4161 /* XXX: This doesn't work as expected. First, it should be
4162 * moved to between the first and second passes (if doing
4163 * two-pass mode), so that the new NRB appears before packets,
4164 * which is better for subsequent one-pass mode. It never works
4165 * well in one-pass mode.
4167 * Second, it only writes hosts that we've done lookups for,
4168 * which means unless packet details are printed (or there's
4169 * a display filter that matches something that will do a host
4170 * lookup, e.g. -Y "ip") it doesn't actually have anything
4171 * in the list to save. Notably, that includes the case of
4172 * "tshark [-2] -H hosts.txt -r <infile> -w <outfile>",
4173 * which a user would certainly expect to dissect packets,
4174 * lookup hostnames, and add them to an NRB for later use.
4175 * A workaround is if "-V > /dev/null" is added, but who
4176 * expects that?
4178 * A third issue is that name resolution blocks aren't
4179 * written for live captures.
4181 if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
4182 cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
4183 wtap_file_type_subtype_name(out_file_type));
4186 /* Now close the capture file. */
4187 if (!wtap_dump_close(pdh, NULL, &err, &err_info)) {
4188 cfile_close_failure_message(save_file, err, err_info);
4189 status = PROCESS_FILE_ERROR;
4191 } else {
4192 /* We got a write error; it was reported, so just close the dump file
4193 without bothering to check for further errors. */
4194 wtap_dump_close(pdh, NULL, &err, &err_info);
4195 g_free(err_info);
4196 status = PROCESS_FILE_ERROR;
4198 } else {
4199 if (print_packet_info) {
4200 if (!write_finale()) {
4201 show_print_file_io_error();
4202 status = PROCESS_FILE_ERROR;
4207 out:
4208 wtap_close(cf->provider.wth);
4209 cf->provider.wth = NULL;
4211 wtap_dump_params_cleanup(&params);
4213 return status;
4216 static gboolean
4217 process_packet_single_pass(capture_file *cf, epan_dissect_t *edt, gint64 offset,
4218 wtap_rec *rec, Buffer *buf, guint tap_flags _U_)
4220 frame_data fdata;
4221 column_info *cinfo;
4222 gboolean passed;
4223 wtap_block_t block = NULL;
4224 gint64 elapsed_start;
4226 /* Count this packet. */
4227 cf->count++;
4229 /* If we're not running a display filter and we're not printing any
4230 packet information, we don't need to do a dissection. This means
4231 that all packets can be marked as 'passed'. */
4232 passed = TRUE;
4234 frame_data_init(&fdata, cf->count, rec, offset, cum_bytes);
4236 /* If we're going to print packet information, or we're going to
4237 run a read filter, or we're going to process taps, set up to
4238 do a dissection and do so. (This is the one and only pass
4239 over the packets, so, if we'll be printing packet information
4240 or running taps, we'll be doing it here.) */
4241 if (edt) {
4242 /* If we're running a filter, prime the epan_dissect_t with that
4243 filter. */
4244 if (cf->dfcode)
4245 epan_dissect_prime_with_dfilter(edt, cf->dfcode);
4247 /* This is the first and only pass, so prime the epan_dissect_t
4248 with the hfids postdissectors want on the first pass. */
4249 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
4251 col_custom_prime_edt(edt, &cf->cinfo);
4253 output_fields_prime_edt(edt, output_fields);
4254 /* The PDML spec requires a 'geninfo' pseudo-protocol that needs
4255 * information from our 'frame' protocol.
4257 if (output_fields_num_fields(output_fields) != 0 &&
4258 output_action == WRITE_XML) {
4259 epan_dissect_prime_with_hfid(edt, proto_registrar_get_id_byname("frame"));
4262 /* We only need the columns if either
4263 1) some tap or filter needs the columns
4265 2) we're printing packet info but we're *not* verbose; in verbose
4266 mode, we print the protocol tree, not the protocol summary.
4268 3) there is a column mapped as an individual field */
4269 if ((tap_listeners_require_columns()) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields) || dfilter_requires_columns(cf->dfcode))
4270 cinfo = &cf->cinfo;
4271 else
4272 cinfo = NULL;
4274 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
4275 &cf->provider.ref, cf->provider.prev_dis);
4276 if (cf->provider.ref == &fdata) {
4277 ref_frame = fdata;
4278 cf->provider.ref = &ref_frame;
4281 if (dissect_color) {
4282 color_filters_prime_edt(edt);
4283 fdata.need_colorize = 1;
4286 /* epan_dissect_run (and epan_dissect_reset) unref the block.
4287 * We need it later, e.g. in order to copy the options. */
4288 block = wtap_block_ref(rec->block);
4289 elapsed_start = g_get_monotonic_time();
4290 epan_dissect_run_with_taps(edt, cf->cd_t, rec,
4291 frame_tvbuff_new_buffer(&cf->provider, &fdata, buf),
4292 &fdata, cinfo);
4293 tshark_elapsed.first_pass.dissect += g_get_monotonic_time() - elapsed_start;
4295 /* Run the filter if we have it. */
4296 if (cf->dfcode) {
4297 elapsed_start = g_get_monotonic_time();
4298 passed = dfilter_apply_edt(cf->dfcode, edt);
4299 tshark_elapsed.first_pass.dfilter_filter += g_get_monotonic_time() - elapsed_start;
4303 if (passed) {
4304 frame_data_set_after_dissect(&fdata, &cum_bytes);
4306 /* Process this packet. */
4307 if (print_packet_info) {
4308 /* We're printing packet information; print the information for
4309 this packet. */
4310 ws_assert(edt);
4311 print_packet(cf, edt);
4313 /* If we're doing "line-buffering", flush the standard output
4314 after every packet. See the comment above, for the "-l"
4315 option, for an explanation of why we do that. */
4316 if (line_buffered)
4317 fflush(stdout);
4319 if (ferror(stdout)) {
4320 show_print_file_io_error();
4321 exit(2);
4325 /* this must be set after print_packet() [bug #8160] */
4326 prev_dis_frame = fdata;
4327 cf->provider.prev_dis = &prev_dis_frame;
4330 prev_cap_frame = fdata;
4331 cf->provider.prev_cap = &prev_cap_frame;
4333 if (edt) {
4334 epan_dissect_reset(edt);
4335 frame_data_destroy(&fdata);
4336 rec->block = block;
4338 return passed;
4341 static gboolean
4342 write_preamble(capture_file *cf)
4344 switch (output_action) {
4346 case WRITE_TEXT:
4347 return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
4349 case WRITE_XML:
4350 if (print_details)
4351 write_pdml_preamble(stdout, cf->filename);
4352 else
4353 write_psml_preamble(&cf->cinfo, stdout);
4354 return !ferror(stdout);
4356 case WRITE_FIELDS:
4357 write_fields_preamble(output_fields, stdout);
4358 return !ferror(stdout);
4360 case WRITE_JSON:
4361 case WRITE_JSON_RAW:
4362 jdumper = write_json_preamble(stdout);
4363 return !ferror(stdout);
4365 case WRITE_EK:
4366 return TRUE;
4368 default:
4369 ws_assert_not_reached();
4370 return FALSE;
4374 static char *
4375 get_line_buf(size_t len)
4377 static char *line_bufp = NULL;
4378 static size_t line_buf_len = 256;
4379 size_t new_line_buf_len;
4381 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
4382 new_line_buf_len *= 2)
4384 if (line_bufp == NULL) {
4385 line_buf_len = new_line_buf_len;
4386 line_bufp = (char *)g_malloc(line_buf_len + 1);
4387 } else {
4388 if (new_line_buf_len > line_buf_len) {
4389 line_buf_len = new_line_buf_len;
4390 line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
4393 return line_bufp;
4396 static inline void
4397 put_string(char *dest, const char *str, size_t str_len)
4399 memcpy(dest, str, str_len);
4400 dest[str_len] = '\0';
4403 static inline void
4404 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
4406 size_t i;
4408 for (i = str_len; i < str_with_spaces; i++)
4409 *dest++ = ' ';
4411 put_string(dest, str, str_len);
4414 static inline void
4415 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
4417 size_t i;
4419 memcpy(dest, str, str_len);
4420 for (i = str_len; i < str_with_spaces; i++)
4421 dest[i] = ' ';
4423 dest[str_with_spaces] = '\0';
4426 static gboolean
4427 print_columns(capture_file *cf, const epan_dissect_t *edt)
4429 char *line_bufp;
4430 int i;
4431 size_t buf_offset;
4432 size_t column_len;
4433 size_t col_len;
4434 col_item_t* col_item;
4435 gchar str_format[11];
4436 const color_filter_t *color_filter = NULL;
4438 line_bufp = get_line_buf(256);
4439 buf_offset = 0;
4440 *line_bufp = '\0';
4442 if (dissect_color)
4443 color_filter = edt->pi.fd->color_filter;
4445 for (i = 0; i < cf->cinfo.num_cols; i++) {
4446 col_item = &cf->cinfo.columns[i];
4447 /* Skip columns not marked as visible. */
4448 if (!get_column_visible(i))
4449 continue;
4450 const gchar* col_text = get_column_text(&cf->cinfo, i);
4451 switch (col_item->col_fmt) {
4452 case COL_NUMBER:
4453 column_len = col_len = strlen(col_text);
4454 if (column_len < 5)
4455 column_len = 5;
4456 line_bufp = get_line_buf(buf_offset + column_len);
4457 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
4458 break;
4460 case COL_CLS_TIME:
4461 case COL_REL_TIME:
4462 case COL_ABS_TIME:
4463 case COL_ABS_YMD_TIME: /* XXX - wider */
4464 case COL_ABS_YDOY_TIME: /* XXX - wider */
4465 case COL_UTC_TIME:
4466 case COL_UTC_YMD_TIME: /* XXX - wider */
4467 case COL_UTC_YDOY_TIME: /* XXX - wider */
4468 column_len = col_len = strlen(col_text);
4469 if (column_len < 10)
4470 column_len = 10;
4471 line_bufp = get_line_buf(buf_offset + column_len);
4472 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
4473 break;
4475 case COL_DEF_SRC:
4476 case COL_RES_SRC:
4477 case COL_UNRES_SRC:
4478 case COL_DEF_DL_SRC:
4479 case COL_RES_DL_SRC:
4480 case COL_UNRES_DL_SRC:
4481 case COL_DEF_NET_SRC:
4482 case COL_RES_NET_SRC:
4483 case COL_UNRES_NET_SRC:
4484 column_len = col_len = strlen(col_text);
4485 if (column_len < 12)
4486 column_len = 12;
4487 line_bufp = get_line_buf(buf_offset + column_len);
4488 put_spaces_string(line_bufp + buf_offset, col_text, col_len, column_len);
4489 break;
4491 case COL_DEF_DST:
4492 case COL_RES_DST:
4493 case COL_UNRES_DST:
4494 case COL_DEF_DL_DST:
4495 case COL_RES_DL_DST:
4496 case COL_UNRES_DL_DST:
4497 case COL_DEF_NET_DST:
4498 case COL_RES_NET_DST:
4499 case COL_UNRES_NET_DST:
4500 column_len = col_len = strlen(col_text);
4501 if (column_len < 12)
4502 column_len = 12;
4503 line_bufp = get_line_buf(buf_offset + column_len);
4504 put_string_spaces(line_bufp + buf_offset, col_text, col_len, column_len);
4505 break;
4507 default:
4508 column_len = strlen(col_text);
4509 line_bufp = get_line_buf(buf_offset + column_len);
4510 put_string(line_bufp + buf_offset, col_text, column_len);
4511 break;
4513 buf_offset += column_len;
4514 if (i != cf->cinfo.num_cols - 1) {
4516 * This isn't the last column, so we need to print a
4517 * separator between this column and the next.
4519 * If we printed a network source and are printing a
4520 * network destination of the same type next, separate
4521 * them with a UTF-8 right arrow; if we printed a network
4522 * destination and are printing a network source of the same
4523 * type next, separate them with a UTF-8 left arrow;
4524 * otherwise separate them with a space.
4526 * We add enough space to the buffer for " \xe2\x86\x90 "
4527 * or " \xe2\x86\x92 ", even if we're only adding " ".
4529 line_bufp = get_line_buf(buf_offset + 5);
4530 switch (col_item->col_fmt) {
4532 case COL_DEF_SRC:
4533 case COL_RES_SRC:
4534 case COL_UNRES_SRC:
4535 switch (cf->cinfo.columns[i+1].col_fmt) {
4537 case COL_DEF_DST:
4538 case COL_RES_DST:
4539 case COL_UNRES_DST:
4540 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4541 put_string(line_bufp + buf_offset, str_format, 5);
4542 buf_offset += 5;
4543 break;
4545 default:
4546 put_string(line_bufp + buf_offset, delimiter_char, 1);
4547 buf_offset += 1;
4548 break;
4550 break;
4552 case COL_DEF_DL_SRC:
4553 case COL_RES_DL_SRC:
4554 case COL_UNRES_DL_SRC:
4555 switch (cf->cinfo.columns[i+1].col_fmt) {
4557 case COL_DEF_DL_DST:
4558 case COL_RES_DL_DST:
4559 case COL_UNRES_DL_DST:
4560 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4561 put_string(line_bufp + buf_offset, str_format, 5);
4562 buf_offset += 5;
4563 break;
4565 default:
4566 put_string(line_bufp + buf_offset, delimiter_char, 1);
4567 buf_offset += 1;
4568 break;
4570 break;
4572 case COL_DEF_NET_SRC:
4573 case COL_RES_NET_SRC:
4574 case COL_UNRES_NET_SRC:
4575 switch (cf->cinfo.columns[i+1].col_fmt) {
4577 case COL_DEF_NET_DST:
4578 case COL_RES_NET_DST:
4579 case COL_UNRES_NET_DST:
4580 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_RIGHTWARDS_ARROW, delimiter_char);
4581 put_string(line_bufp + buf_offset, str_format, 5);
4582 buf_offset += 5;
4583 break;
4585 default:
4586 put_string(line_bufp + buf_offset, delimiter_char, 1);
4587 buf_offset += 1;
4588 break;
4590 break;
4592 case COL_DEF_DST:
4593 case COL_RES_DST:
4594 case COL_UNRES_DST:
4595 switch (cf->cinfo.columns[i+1].col_fmt) {
4597 case COL_DEF_SRC:
4598 case COL_RES_SRC:
4599 case COL_UNRES_SRC:
4600 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4601 put_string(line_bufp + buf_offset, str_format, 5);
4602 buf_offset += 5;
4603 break;
4605 default:
4606 put_string(line_bufp + buf_offset, delimiter_char, 1);
4607 buf_offset += 1;
4608 break;
4610 break;
4612 case COL_DEF_DL_DST:
4613 case COL_RES_DL_DST:
4614 case COL_UNRES_DL_DST:
4615 switch (cf->cinfo.columns[i+1].col_fmt) {
4617 case COL_DEF_DL_SRC:
4618 case COL_RES_DL_SRC:
4619 case COL_UNRES_DL_SRC:
4620 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4621 put_string(line_bufp + buf_offset, str_format, 5);
4622 buf_offset += 5;
4623 break;
4625 default:
4626 put_string(line_bufp + buf_offset, delimiter_char, 1);
4627 buf_offset += 1;
4628 break;
4630 break;
4632 case COL_DEF_NET_DST:
4633 case COL_RES_NET_DST:
4634 case COL_UNRES_NET_DST:
4635 switch (cf->cinfo.columns[i+1].col_fmt) {
4637 case COL_DEF_NET_SRC:
4638 case COL_RES_NET_SRC:
4639 case COL_UNRES_NET_SRC:
4640 snprintf(str_format, sizeof(str_format), "%s%s%s", delimiter_char, UTF8_LEFTWARDS_ARROW, delimiter_char);
4641 put_string(line_bufp + buf_offset, str_format, 5);
4642 buf_offset += 5;
4643 break;
4645 default:
4646 put_string(line_bufp + buf_offset, delimiter_char, 1);
4647 buf_offset += 1;
4648 break;
4650 break;
4652 default:
4653 put_string(line_bufp + buf_offset, delimiter_char, 1);
4654 buf_offset += 1;
4655 break;
4660 if (dissect_color && color_filter != NULL)
4661 return print_line_color(print_stream, 0, line_bufp, &color_filter->fg_color, &color_filter->bg_color);
4662 else
4663 return print_line(print_stream, 0, line_bufp);
4666 static gboolean
4667 print_packet(capture_file *cf, epan_dissect_t *edt)
4669 if (print_summary || output_fields_has_cols(output_fields))
4670 /* Just fill in the columns. */
4671 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
4673 /* Print summary columns and/or protocol tree */
4674 switch (output_action) {
4676 case WRITE_TEXT:
4677 if (print_summary && !print_columns(cf, edt))
4678 return FALSE;
4679 if (print_details) {
4680 if (!proto_tree_print(print_details ? print_dissections_expanded : print_dissections_none,
4681 print_hex, edt, output_only_tables, print_stream))
4682 return FALSE;
4683 if (!print_hex) {
4684 if (!print_line(print_stream, 0, separator))
4685 return FALSE;
4688 break;
4690 case WRITE_XML:
4691 if (print_summary) {
4692 write_psml_columns(edt, stdout, dissect_color);
4693 return !ferror(stdout);
4695 if (print_details) {
4696 write_pdml_proto_tree(output_fields, edt, &cf->cinfo, stdout, dissect_color);
4697 printf("\n");
4698 return !ferror(stdout);
4700 break;
4702 case WRITE_FIELDS:
4703 if (print_summary) {
4704 /*No non-verbose "fields" format */
4705 ws_assert_not_reached();
4707 if (print_details) {
4708 write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
4709 printf("\n");
4710 return !ferror(stdout);
4712 break;
4714 case WRITE_JSON:
4715 if (print_summary)
4716 ws_assert_not_reached();
4717 if (print_details) {
4718 write_json_proto_tree(output_fields, print_dissections_expanded,
4719 print_hex, edt, &cf->cinfo, node_children_grouper, &jdumper);
4720 return !ferror(stdout);
4722 break;
4724 case WRITE_JSON_RAW:
4725 if (print_summary)
4726 ws_assert_not_reached();
4727 if (print_details) {
4728 write_json_proto_tree(output_fields, print_dissections_none,
4729 TRUE, edt, &cf->cinfo, node_children_grouper, &jdumper);
4730 return !ferror(stdout);
4732 break;
4734 case WRITE_EK:
4735 write_ek_proto_tree(output_fields, print_summary, print_hex,
4736 edt, &cf->cinfo, stdout);
4737 return !ferror(stdout);
4739 default:
4740 ws_assert_not_reached();
4743 if (print_hex) {
4744 if (print_summary || print_details) {
4745 if (!print_line(print_stream, 0, ""))
4746 return FALSE;
4748 if (!print_hex_data(print_stream, edt, hexdump_source_option | hexdump_ascii_option))
4749 return FALSE;
4750 if (!print_line(print_stream, 0, separator))
4751 return FALSE;
4753 return TRUE;
4756 static gboolean
4757 write_finale(void)
4759 switch (output_action) {
4761 case WRITE_TEXT:
4762 return print_finale(print_stream);
4764 case WRITE_XML:
4765 if (print_details)
4766 write_pdml_finale(stdout);
4767 else
4768 write_psml_finale(stdout);
4769 return !ferror(stdout);
4771 case WRITE_FIELDS:
4772 write_fields_finale(output_fields, stdout);
4773 return !ferror(stdout);
4775 case WRITE_JSON:
4776 case WRITE_JSON_RAW:
4777 write_json_finale(&jdumper);
4778 return !ferror(stdout);
4780 case WRITE_EK:
4781 return TRUE;
4783 default:
4784 ws_assert_not_reached();
4785 return FALSE;
4789 void
4790 cf_close(capture_file *cf)
4792 if (cf->state == FILE_CLOSED)
4793 return; /* Nothing to do */
4795 if (cf->provider.wth != NULL) {
4796 wtap_close(cf->provider.wth);
4797 cf->provider.wth = NULL;
4799 /* We have no file open... */
4800 if (cf->filename != NULL) {
4801 /* If it's a temporary file, remove it. */
4802 if (cf->is_tempfile)
4803 ws_unlink(cf->filename);
4804 g_free(cf->filename);
4805 cf->filename = NULL;
4808 /* We have no file open. */
4809 cf->state = FILE_CLOSED;
4812 cf_status_t
4813 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
4815 wtap *wth;
4816 gchar *err_info;
4818 wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
4819 if (wth == NULL)
4820 goto fail;
4822 /* The open succeeded. Fill in the information for this file. */
4824 cf->provider.wth = wth;
4825 cf->f_datalen = 0; /* not used, but set it anyway */
4827 /* Set the file name because we need it to set the follow stream filter.
4828 XXX - is that still true? We need it for other reasons, though,
4829 in any case. */
4830 cf->filename = g_strdup(fname);
4832 /* Indicate whether it's a permanent or temporary file. */
4833 cf->is_tempfile = is_tempfile;
4835 /* No user changes yet. */
4836 cf->unsaved_changes = FALSE;
4838 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
4839 cf->open_type = type;
4840 cf->count = 0;
4841 cf->drops_known = FALSE;
4842 cf->drops = 0;
4843 cf->snap = wtap_snapshot_length(cf->provider.wth);
4844 nstime_set_zero(&cf->elapsed_time);
4845 cf->provider.ref = NULL;
4846 cf->provider.prev_dis = NULL;
4847 cf->provider.prev_cap = NULL;
4849 cf->state = FILE_READ_IN_PROGRESS;
4851 /* Create new epan session for dissection. */
4852 epan_free(cf->epan);
4853 cf->epan = tshark_epan_new(cf);
4855 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
4856 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
4857 wtap_set_cb_new_secrets(cf->provider.wth, secrets_wtap_callback);
4859 return CF_OK;
4861 fail:
4862 cfile_open_failure_message(fname, *err, err_info);
4863 return CF_ERROR;
4866 static void
4867 show_print_file_io_error(void)
4869 switch (errno) {
4871 case ENOSPC:
4872 cmdarg_err("Not all the packets could be printed because there is "
4873 "no space left on the file system.");
4874 break;
4876 #ifdef EDQUOT
4877 case EDQUOT:
4878 cmdarg_err("Not all the packets could be printed because you are "
4879 "too close to, or over your disk quota.");
4880 break;
4881 #endif
4883 case EPIPE:
4885 * This almost certainly means "the next program after us in
4886 * the pipeline exited before we were finished writing", so
4887 * this isn't a real error, it just means we're done. (We
4888 * don't get SIGPIPE because libwireshark ignores SIGPIPE
4889 * to avoid getting killed if writing to the MaxMind process
4890 * gets SIGPIPE because that process died.)
4892 * Presumably either that program exited deliberately (for
4893 * example, "head -N" read N lines and printed them), in
4894 * which case there's no error to report, or it terminated
4895 * due to an error or a signal, in which case *that's* the
4896 * error and that error has been reported.
4898 break;
4900 default:
4901 #ifdef _WIN32
4902 if (errno == EINVAL && _doserrno == ERROR_NO_DATA) {
4904 * XXX - on Windows, a write to a pipe where the read side
4905 * has been closed apparently may return the Windows error
4906 * ERROR_BROKEN_PIPE, which the Visual Studio C library maps
4907 * to EPIPE, or may return the Windows error ERROR_NO_DATA,
4908 * which the Visual Studio C library maps to EINVAL.
4910 * Either of those almost certainly means "the next program
4911 * after us in the pipeline exited before we were finished
4912 * writing", so, if _doserrno is ERROR_NO_DATA, this isn't
4913 * a real error, it just means we're done. (Windows doesn't
4914 * SIGPIPE.)
4916 * Presumably either that program exited deliberately (for
4917 * example, "head -N" read N lines and printed them), in
4918 * which case there's no error to report, or it terminated
4919 * due to an error or a signal, in which case *that's* the
4920 * error and that error has been reported.
4922 break;
4926 * It's a different error; report it, but with the error
4927 * message for _doserrno, which will give more detail
4928 * than just "Invalid argument".
4930 cmdarg_err("An error occurred while printing packets: %s.",
4931 win32strerror(_doserrno));
4932 #else
4933 cmdarg_err("An error occurred while printing packets: %s.",
4934 g_strerror(errno));
4935 #endif
4936 break;
4941 * Report an error in command-line arguments.
4943 static void
4944 tshark_cmdarg_err(const char *msg_format, va_list ap)
4946 fprintf(stderr, "tshark: ");
4947 vfprintf(stderr, msg_format, ap);
4948 fprintf(stderr, "\n");
4952 * Report additional information for an error in command-line arguments.
4954 static void
4955 tshark_cmdarg_err_cont(const char *msg_format, va_list ap)
4957 vfprintf(stderr, msg_format, ap);
4958 fprintf(stderr, "\n");
4961 static void
4962 reset_epan_mem(capture_file *cf,epan_dissect_t *edt, gboolean tree, gboolean visual)
4964 if (!epan_auto_reset || (cf->count < epan_auto_reset_count))
4965 return;
4967 fprintf(stderr, "resetting session.\n");
4969 epan_dissect_cleanup(edt);
4970 epan_free(cf->epan);
4972 cf->epan = tshark_epan_new(cf);
4973 epan_dissect_init(edt, cf->epan, tree, visual);
4974 cf->count = 0;