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>.
8 * Wireshark - Network traffic analyzer
9 * By Gerald Combs <gerald@wireshark.org>
10 * Copyright 1998 Gerald Combs
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
54 #ifdef NEED_STRERROR_H
65 #include <epan/epan.h>
66 #include <epan/filesystem.h>
67 #include <wsutil/privileges.h>
70 #include <epan/timestamp.h>
71 #include <epan/packet.h>
73 #include "disabled_protos.h"
74 #include <epan/prefs.h>
75 #include <epan/column.h>
77 #include <epan/addr_resolv.h>
79 #include "clopts_common.h"
80 #include "console_io.h"
81 #include "cmdarg_err.h"
82 #include "version_info.h"
83 #include <epan/plugins.h>
85 #include <epan/epan_dissect.h>
87 #include <epan/stat_cmd_args.h>
88 #include <epan/timestamp.h>
89 #include <epan/ex-opt.h>
92 #include "capture_ui_utils.h"
93 #include "capture_ifinfo.h"
94 #include "capture-pcap-util.h"
96 #include "capture-wpcap.h"
97 #include "capture_errs.h"
99 #include "capture_sync.h"
100 #endif /* HAVE_LIBPCAP */
102 #include <epan/funnel.h>
106 * This is the template for the decode as option; it is shared between the
107 * various functions that output the usage for this parameter.
109 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
111 static guint32 cum_bytes;
112 static nstime_t first_ts;
113 static nstime_t prev_dis_ts;
114 static nstime_t prev_cap_ts;
116 static gboolean print_packet_info; /* TRUE if we're to print packet information */
118 static gboolean perform_two_pass_analysis;
121 * The way the packet decode is to be written.
124 WRITE_TEXT, /* summary or detail text */
125 WRITE_XML, /* PDML or PSML */
126 WRITE_FIELDS /* User defined list of fields */
127 /* Add CSV and the like here */
130 static output_action_e output_action;
131 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
132 static gboolean verbose;
133 static gboolean print_hex;
134 static gboolean line_buffered;
136 static print_format_e print_format = PR_FMT_TEXT;
137 static print_stream_t *print_stream;
139 static output_fields_t* output_fields = NULL;
142 * Standard secondary message for unexpected errors.
144 static const char please_report[] =
145 "Please report this to the Wireshark developers";
149 * TRUE if we're to print packet counts to keep track of captured packets.
151 static gboolean print_packet_counts;
154 static capture_options global_capture_opts;
157 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
158 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
161 static int capture(void);
162 static void report_counts(void);
164 static BOOL WINAPI capture_cleanup(DWORD);
166 static void capture_cleanup(int);
168 static void report_counts_siginfo(int);
171 #endif /* HAVE_LIBPCAP */
173 static int load_cap_file(capture_file *, char *, int, int, gint64);
174 static gboolean process_packet(capture_file *cf, gint64 offset,
175 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
176 const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
177 static void show_capture_file_io_error(const char *, int, gboolean);
178 static void show_print_file_io_error(int err);
179 static gboolean write_preamble(capture_file *cf);
180 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
181 static gboolean write_finale(void);
182 static const char *cf_open_error_message(int err, gchar *err_info,
183 gboolean for_writing, int file_type);
185 static void open_failure_message(const char *filename, int err,
186 gboolean for_writing);
187 static void failure_message(const char *msg_format, va_list ap);
188 static void read_failure_message(const char *filename, int err);
189 static void write_failure_message(const char *filename, int err);
194 cf_mark_frame(capture_file *cf _U_, frame_data *frame _U_)
196 g_assert_not_reached();
199 static void list_capture_types(void) {
202 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
203 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
204 if (wtap_dump_can_open(i))
205 fprintf(stderr, " %s - %s\n",
206 wtap_file_type_short_string(i), wtap_file_type_string(i));
211 print_usage(gboolean print_ver)
218 "TShark " VERSION "%s\n"
219 "Dump and analyze network traffic.\n"
220 "See http://www.wireshark.org for more information.\n"
223 wireshark_svnversion, get_copyright_info());
227 fprintf(output, "\n");
228 fprintf(output, "Usage: tshark [options] ...\n");
229 fprintf(output, "\n");
232 fprintf(output, "Capture interface:\n");
233 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
234 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
235 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
236 fprintf(output, " -p don't capture in promiscuous mode\n");
237 #ifdef HAVE_PCAP_CREATE
238 fprintf(output, " -I capture in monitor mode, if available\n");
240 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
241 fprintf(output, " -B <buffer size> size of kernel buffer (def: platform-dependent)\n");
243 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
244 fprintf(output, " -D print list of interfaces and exit\n");
245 fprintf(output, " -L print list of link-layer types of iface and exit\n");
246 fprintf(output, "\n");
247 fprintf(output, "Capture stop conditions:\n");
248 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
249 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
250 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
251 fprintf(output, " files:NUM - stop after NUM files\n");
252 /*fprintf(output, "\n");*/
253 fprintf(output, "Capture output:\n");
254 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
255 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
256 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
257 #endif /* HAVE_LIBPCAP */
259 /*fprintf(output, "\n");*/
260 fprintf(output, "Input file:\n");
261 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
263 fprintf(output, "\n");
264 fprintf(output, "Processing:\n");
265 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
266 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
267 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
268 fprintf(output, " -d %s ...\n", decode_as_arg_template);
269 fprintf(output, " \"Decode As\", see the man page for details\n");
270 fprintf(output, " Example: tcp.port==8888,http\n");
272 /*fprintf(output, "\n");*/
273 fprintf(output, "Output:\n");
274 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
275 fprintf(output, " (or to the standard output for \"-\")\n");
276 fprintf(output, " -C <config profile> start with specified configuration profile\n");
277 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
278 fprintf(output, " an empty \"-F\" option will list the file types\n");
279 fprintf(output, " -V add output of packet tree (Packet Details)\n");
280 fprintf(output, " -S display packets even when writing to a file\n");
281 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
282 fprintf(output, " -T pdml|ps|psml|text|fields\n");
283 fprintf(output, " format of text output (def: text)\n");
284 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
285 fprintf(output, " this option can be repeated to print multiple fields\n");
286 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
287 fprintf(output, " header=y|n switch headers on and off\n");
288 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
289 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
290 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
291 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
292 fprintf(output, " -l flush standard output after each packet\n");
293 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
294 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
295 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
297 fprintf(output, "\n");
298 fprintf(output, "Miscellaneous:\n");
299 fprintf(output, " -h display this help and exit\n");
300 fprintf(output, " -v display version info and exit\n");
301 fprintf(output, " -o <name>:<value> ... override preference setting\n");
302 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
306 * For a dissector table, print on the stream described by output,
307 * its short name (which is what's used in the "-d" option) and its
311 display_dissector_table_names(const char *table_name, const char *ui_name,
314 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
318 * For a dissector handle, print on the stream described by output,
319 * the filter name (which is what's used in the "-d" option) and the full
320 * name for the protocol that corresponds to this handle.
323 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
326 const gchar* proto_filter_name;
327 const gchar* proto_ui_name;
329 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
331 if (proto_id != -1) {
332 proto_filter_name = proto_get_protocol_filter_name(proto_id);
333 proto_ui_name = proto_get_protocol_name(proto_id);
334 g_assert(proto_filter_name != NULL);
335 g_assert(proto_ui_name != NULL);
337 fprintf((FILE *)output, "\t%s (%s)\n",
344 * The protocol_name_search structure is used by find_protocol_name_func()
345 * to pass parameters and store results
347 struct protocol_name_search{
348 gchar *searched_name; /* Protocol filter name we are looking for */
349 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
350 guint nb_match; /* How many dissectors matched searched_name */
352 typedef struct protocol_name_search *protocol_name_search_t;
355 * This function parses all dissectors associated with a table to find the
356 * one whose protocol has the specified filter name. It is called
357 * as a reference function in a call to dissector_table_foreach_handle.
358 * The name we are looking for, as well as the results, are stored in the
359 * protocol_name_search struct pointed to by user_data.
360 * If called using dissector_table_foreach_handle, we actually parse the
361 * whole list of dissectors.
364 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
368 const gchar *protocol_filter_name;
369 protocol_name_search_t search_info;
373 search_info = (protocol_name_search_t)user_data;
375 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
376 if (proto_id != -1) {
377 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
378 g_assert(protocol_filter_name != NULL);
379 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
381 if (search_info->nb_match == 0) {
382 /* Record this handle only if this is the first match */
383 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
385 search_info->nb_match++;
391 * Print all layer type names supported.
392 * We send the output to the stream described by the handle output.
396 fprint_all_layer_types(FILE *output)
399 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
403 * Print all protocol names supported for a specific layer type.
404 * table_name contains the layer type name in which the search is performed.
405 * We send the output to the stream described by the handle output.
409 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
412 dissector_table_foreach_handle(table_name,
413 display_dissector_names,
418 * The function below parses the command-line parameters for the decode as
419 * feature (a string pointer by cl_param).
420 * It checks the format of the command-line, searches for a matching table
421 * and dissector. If a table/dissector match is not found, we display a
422 * summary of the available tables/dissectors (on stderr) and return FALSE.
423 * If everything is fine, we get the "Decode as" preference activated,
424 * then we return TRUE.
427 add_decode_as(const gchar *cl_param)
431 gchar *decoded_param;
432 gchar *remaining_param;
434 gchar *dissector_str;
435 dissector_handle_t dissector_matching;
436 dissector_table_t table_matching;
437 ftenum_t dissector_table_selector_type;
438 struct protocol_name_search user_protocol_name;
440 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
443 decoded_param = g_strdup(cl_param);
444 g_assert(decoded_param);
447 /* The lines below will parse this string (modifying it) to extract all
448 necessary information. Note that decoded_param is still needed since
449 strings are not copied - we just save pointers. */
451 /* This section extracts a layer type (table_name) from decoded_param */
452 table_name = decoded_param; /* Layer type string starts from beginning */
454 remaining_param = strchr(table_name, '=');
455 if (remaining_param == NULL) {
456 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
457 /* If the argument does not follow the template, carry on anyway to check
458 if the table name is at least correct. If remaining_param is NULL,
459 we'll exit anyway further down */
462 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
465 /* Remove leading and trailing spaces from the table name */
466 while ( table_name[0] == ' ' )
468 while ( table_name[strlen(table_name) - 1] == ' ' )
469 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
471 /* The following part searches a table matching with the layer type specified */
472 table_matching = NULL;
474 /* Look for the requested table */
475 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
476 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
479 table_matching = find_dissector_table(table_name);
480 if (!table_matching) {
481 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
485 if (!table_matching) {
486 /* Display a list of supported layer types to help the user, if the
487 specified layer type was not found */
488 cmdarg_err("Valid layer types are:");
489 fprint_all_layer_types(stderr);
491 if (remaining_param == NULL || !table_matching) {
492 /* Exit if the layer type was not found, or if no '=' separator was found
494 g_free(decoded_param);
498 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
499 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
502 remaining_param++; /* Move to the second '=' */
503 *remaining_param = '\0'; /* Remove the second '=' */
505 remaining_param++; /* Position after the layer type string */
507 /* This section extracts a selector value (selector_str) from decoded_param */
509 selector_str = remaining_param; /* Next part starts with the selector number */
511 remaining_param = strchr(selector_str, ',');
512 if (remaining_param == NULL) {
513 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
514 /* If the argument does not follow the template, carry on anyway to check
515 if the selector value is at least correct. If remaining_param is NULL,
516 we'll exit anyway further down */
519 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
522 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
524 switch (dissector_table_selector_type) {
530 /* The selector for this table is an unsigned number. Parse it as such.
531 There's no need to remove leading and trailing spaces from the
532 selector number string, because sscanf will do that for us. */
533 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
534 cmdarg_err("Invalid selector number \"%s\"", selector_str);
535 g_free(decoded_param);
543 /* The selector for this table is a string. */
547 /* There are currently no dissector tables with any types other
548 than the ones listed above. */
549 g_assert_not_reached();
552 if (remaining_param == NULL) {
553 /* Exit if no ',' separator was found (see above) */
554 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
555 fprint_all_protocols_for_layer_types(stderr, table_name);
556 g_free(decoded_param);
560 remaining_param++; /* Position after the selector number string */
562 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
564 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
566 /* Remove leading and trailing spaces from the dissector name */
567 while ( dissector_str[0] == ' ' )
569 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
570 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
572 dissector_matching = NULL;
574 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
575 if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
576 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
579 user_protocol_name.nb_match = 0;
580 user_protocol_name.searched_name = dissector_str;
581 user_protocol_name.matched_handle = NULL;
583 dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
585 if (user_protocol_name.nb_match != 0) {
586 dissector_matching = user_protocol_name.matched_handle;
587 if (user_protocol_name.nb_match > 1) {
588 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
592 /* OK, check whether the problem is that there isn't any such
593 protocol, or that there is but it's not specified as a protocol
594 that's valid for that dissector table.
595 Note, we don't exit here, but dissector_matching will remain NULL,
597 if (proto_get_id_by_filter_name(dissector_str) == -1) {
598 /* No such protocol */
599 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
601 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
602 dissector_str, table_name);
607 if (!dissector_matching) {
608 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
609 fprint_all_protocols_for_layer_types(stderr, table_name);
610 g_free(decoded_param);
614 /* This is the end of the code that parses the command-line options.
615 All information is now stored in the variables:
619 The above variables that are strings are still pointing to areas within
620 decoded_parm. decoded_parm thus still needs to be kept allocated in
621 until we stop needing these variables
622 decoded_param will be deallocated at each exit point of this function */
625 /* We now have a pointer to the handle for the requested dissector
626 (requested protocol) inside the variable dissector_matching */
627 switch (dissector_table_selector_type) {
633 /* The selector for this table is an unsigned number. */
634 dissector_change(table_name, selector, dissector_matching);
640 /* The selector for this table is a string. */
641 dissector_change_string(table_name, selector_str, dissector_matching);
645 /* There are currently no dissector tables with any types other
646 than the ones listed above. */
647 g_assert_not_reached();
649 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
654 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
655 const gchar *message, gpointer user_data)
657 /* ignore log message, if log_level isn't interesting based
658 upon the console log preferences.
659 If the preferences haven't been loaded loaded yet, display the
662 The default console_log_level preference value is such that only
663 ERROR, CRITICAL and WARNING level messages are processed;
664 MESSAGE, INFO and DEBUG level messages are ignored.
666 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
667 ERROR and CRITICAL level messages so the current code is a behavioral
668 change. The current behavior is the same as in Wireshark.
670 if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
671 prefs.console_log_level != 0) {
675 g_log_default_handler(log_domain, log_level, message, user_data);
680 output_file_description(const char *fname)
682 char *save_file_string;
684 /* Get a string that describes what we're writing to */
685 if (strcmp(fname, "-") == 0) {
686 /* We're writing to the standard output */
687 save_file_string = g_strdup("standard output");
689 /* We're writing to a file with the name in save_file */
690 save_file_string = g_strdup_printf("file \"%s\"", fname);
692 return save_file_string;
696 print_current_user(void) {
697 gchar *cur_user, *cur_group;
698 if (started_with_special_privs()) {
699 cur_user = get_cur_username();
700 cur_group = get_cur_groupname();
701 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
702 cur_user, cur_group);
705 if (running_with_special_privs()) {
706 fprintf(stderr, " This could be dangerous.");
708 fprintf(stderr, "\n");
713 check_capture_privs(void) {
716 /* Warn the user if npf.sys isn't loaded. */
717 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
718 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
719 "capturing or\nlisting interfaces.\n");
725 show_version(GString *comp_info_str, GString *runtime_info_str)
727 printf("TShark " VERSION "%s\n"
734 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
735 runtime_info_str->str);
739 main(int argc, char *argv[])
741 char *init_progfile_dir_error;
743 gboolean arg_error = FALSE;
749 char *gpf_path, *pf_path;
750 char *gdp_path, *dp_path;
751 int gpf_open_errno, gpf_read_errno;
752 int pf_open_errno, pf_read_errno;
753 int gdp_open_errno, gdp_read_errno;
754 int dp_open_errno, dp_read_errno;
757 gboolean list_link_layer_types = FALSE;
758 gboolean start_capture = FALSE;
761 gboolean capture_option_specified = FALSE;
763 gboolean quiet = FALSE;
764 int out_file_type = WTAP_FILE_PCAP;
765 gchar *cf_name = NULL, *rfilter = NULL;
766 #ifdef HAVE_PCAP_OPEN_DEAD
767 struct bpf_program fcode;
769 dfilter_t *rfcode = NULL;
772 GLogLevelFlags log_flags;
776 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
777 #define OPTSTRING_B "B:"
779 #define OPTSTRING_B ""
780 #endif /* _WIN32 or HAVE_PCAP_CREATE */
781 #else /* HAVE_LIBPCAP */
782 #define OPTSTRING_B ""
783 #endif /* HAVE_LIBPCAP */
785 #ifdef HAVE_PCAP_CREATE
786 #define OPTSTRING_I "I"
788 #define OPTSTRING_I ""
791 #define OPTSTRING "a:b:" OPTSTRING_B "c:C:d:De:E:f:F:G:hi:" OPTSTRING_I "K:lLnN:o:pPqr:R:s:St:T:u:vVw:xX:y:z:"
793 static const char optstring[] = OPTSTRING;
796 * Get credential information for later use.
798 get_credential_info();
801 * Attempt to get the pathname of the executable file.
803 init_progfile_dir_error = init_progfile_dir(argv[0], main);
804 if (init_progfile_dir_error != NULL) {
805 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
806 init_progfile_dir_error);
810 * In order to have the -X opts assigned before the wslua machine starts
811 * we need to call getopts before epan_init() gets called.
814 optind_initial = optind;
816 while ((opt = getopt(argc, argv, optstring)) != -1) {
818 case 'C': /* Configuration Profile */
819 if (profile_exists (optarg)) {
820 set_profile_name (optarg);
822 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
834 optind = optind_initial;
839 /** Send All g_log messages to our own handler **/
843 G_LOG_LEVEL_CRITICAL|
848 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
850 g_log_set_handler(NULL,
852 tshark_log_handler, NULL /* user_data */);
853 g_log_set_handler(LOG_DOMAIN_MAIN,
855 tshark_log_handler, NULL /* user_data */);
858 g_log_set_handler(LOG_DOMAIN_CAPTURE,
860 tshark_log_handler, NULL /* user_data */);
861 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
863 tshark_log_handler, NULL /* user_data */);
866 initialize_funnel_ops();
869 capture_opts_init(&global_capture_opts, &cfile);
872 timestamp_set_type(TS_RELATIVE);
873 timestamp_set_precision(TS_PREC_AUTO);
874 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
876 /* Register all dissectors; we must do this before checking for the
877 "-G" flag, as the "-G" flag dumps information registered by the
878 dissectors, and we must do it before we read the preferences, in
879 case any dissectors register preferences. */
880 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
881 failure_message, open_failure_message, read_failure_message,
882 write_failure_message);
884 /* Register all tap listeners; we do this before we parse the arguments,
885 as the "-z" argument can specify a registered tap. */
887 /* we register the plugin taps before the other taps because
888 stats_tree taps plugins will be registered as tap listeners
889 by stats_tree_stat.c and need to registered before that */
891 register_all_plugin_tap_listeners();
893 register_all_tap_listeners();
895 /* Now register the preferences for any non-dissector modules.
896 We must do that before we read the preferences as well. */
897 prefs_register_modules();
899 /* If invoked with the "-G" flag, we dump out information based on
900 the argument to the "-G" flag; if no argument is specified,
901 for backwards compatibility we dump out a glossary of display
904 XXX - we do this here, for now, to support "-G" with no arguments.
905 If none of our build or other processes uses "-G" with no arguments,
906 we can just process it with the other arguments. */
907 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
908 proto_initialize_all_prefixes();
911 proto_registrar_dump_fields(1);
913 if (strcmp(argv[2], "fields") == 0)
914 proto_registrar_dump_fields(1);
915 else if (strcmp(argv[2], "fields2") == 0)
916 proto_registrar_dump_fields(2);
917 else if (strcmp(argv[2], "fields3") == 0)
918 proto_registrar_dump_fields(3);
919 else if (strcmp(argv[2], "protocols") == 0)
920 proto_registrar_dump_protocols();
921 else if (strcmp(argv[2], "values") == 0)
922 proto_registrar_dump_values();
923 else if (strcmp(argv[2], "decodes") == 0)
924 dissector_dump_decodes();
925 else if (strcmp(argv[2], "defaultprefs") == 0)
927 else if (strcmp(argv[2], "currentprefs") == 0) {
928 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
929 &pf_open_errno, &pf_read_errno, &pf_path);
932 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
939 /* Set the C-language locale to the native environment. */
940 setlocale(LC_ALL, "");
942 prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
943 &pf_open_errno, &pf_read_errno, &pf_path);
944 if (gpf_path != NULL) {
945 if (gpf_open_errno != 0) {
946 cmdarg_err("Can't open global preferences file \"%s\": %s.",
947 pf_path, strerror(gpf_open_errno));
949 if (gpf_read_errno != 0) {
950 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
951 pf_path, strerror(gpf_read_errno));
954 if (pf_path != NULL) {
955 if (pf_open_errno != 0) {
956 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
957 strerror(pf_open_errno));
959 if (pf_read_errno != 0) {
960 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
961 pf_path, strerror(pf_read_errno));
967 /* Set the name resolution code's flags from the preferences. */
968 g_resolv_flags = prefs_p->name_resolve;
970 /* Read the disabled protocols file. */
971 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
972 &dp_path, &dp_open_errno, &dp_read_errno);
973 if (gdp_path != NULL) {
974 if (gdp_open_errno != 0) {
975 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
976 gdp_path, strerror(gdp_open_errno));
978 if (gdp_read_errno != 0) {
979 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
980 gdp_path, strerror(gdp_read_errno));
984 if (dp_path != NULL) {
985 if (dp_open_errno != 0) {
987 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
988 strerror(dp_open_errno));
990 if (dp_read_errno != 0) {
992 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
993 strerror(dp_read_errno));
998 check_capture_privs();
1000 cap_file_init(&cfile);
1002 /* Print format defaults to this. */
1003 print_format = PR_FMT_TEXT;
1005 output_fields = output_fields_new();
1007 /* Now get our args */
1008 while ((opt = getopt(argc, argv, optstring)) != -1) {
1010 case 'a': /* autostop criteria */
1011 case 'b': /* Ringbuffer option */
1012 case 'c': /* Capture x packets */
1013 case 'f': /* capture filter */
1014 case 'i': /* Use interface x */
1015 case 'p': /* Don't capture in promiscuous mode */
1016 #ifdef HAVE_PCAP_CREATE
1017 case 'I': /* Capture in monitor mode, if available */
1019 case 's': /* Set the snapshot (capture) length */
1020 case 'w': /* Write to capture file x */
1021 case 'y': /* Set the pcap data link type */
1022 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1023 case 'B': /* Buffer size */
1024 #endif /* _WIN32 or HAVE_PCAP_CREATE */
1026 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1031 capture_option_specified = TRUE;
1036 /* Configuration profile settings were already processed just ignore them this time*/
1038 case 'd': /* Decode as rule */
1039 if (!add_decode_as(optarg))
1042 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1043 case 'K': /* Kerberos keytab file */
1044 read_keytab_file(optarg);
1047 case 'D': /* Print a list of capture devices and exit */
1049 status = capture_opts_list_interfaces(FALSE);
1052 capture_option_specified = TRUE;
1058 output_fields_add(output_fields, optarg);
1062 if(!output_fields_set_option(output_fields, optarg)) {
1063 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1064 output_fields_list_options(stderr);
1069 out_file_type = wtap_short_string_to_file_type(optarg);
1070 if (out_file_type < 0) {
1071 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1072 list_capture_types();
1076 case 'h': /* Print help and exit */
1080 case 'l': /* "Line-buffer" standard output */
1081 /* This isn't line-buffering, strictly speaking, it's just
1082 flushing the standard output after the information for
1083 each packet is printed; however, that should be good
1084 enough for all the purposes to which "-l" is put (and
1085 is probably actually better for "-V", as it does fewer
1088 See the comment in "process_packet()" for an explanation of
1089 why we do that, and why we don't just use "setvbuf()" to
1090 make the standard output line-buffered (short version: in
1091 Windows, "line-buffered" is the same as "fully-buffered",
1092 and the output buffer is only flushed when it fills up). */
1093 line_buffered = TRUE;
1095 case 'L': /* Print list of link-layer types and exit */
1097 list_link_layer_types = TRUE;
1099 capture_option_specified = TRUE;
1103 #if GLIB_CHECK_VERSION(2,10,0)
1104 case 'P': /* Perform two pass analysis */
1105 perform_two_pass_analysis = TRUE;
1108 case 'n': /* No name resolution */
1109 g_resolv_flags = RESOLV_NONE;
1111 case 'N': /* Select what types of addresses/port #s to resolve */
1112 if (g_resolv_flags == RESOLV_ALL)
1113 g_resolv_flags = RESOLV_NONE;
1114 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1115 if (badopt != '\0') {
1116 cmdarg_err("-N specifies unknown resolving option '%c';",
1118 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1122 case 'o': /* Override preference from command line */
1123 switch (prefs_set_pref(optarg)) {
1128 case PREFS_SET_SYNTAX_ERR:
1129 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1133 case PREFS_SET_NO_SUCH_PREF:
1134 case PREFS_SET_OBSOLETE:
1135 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1140 case 'q': /* Quiet */
1143 case 'r': /* Read capture file x */
1144 cf_name = g_strdup(optarg);
1146 case 'R': /* Read file filter */
1149 case 'S': /* show packets in real time */
1150 print_packet_info = TRUE;
1152 case 't': /* Time stamp type */
1153 if (strcmp(optarg, "r") == 0)
1154 timestamp_set_type(TS_RELATIVE);
1155 else if (strcmp(optarg, "a") == 0)
1156 timestamp_set_type(TS_ABSOLUTE);
1157 else if (strcmp(optarg, "ad") == 0)
1158 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1159 else if (strcmp(optarg, "d") == 0)
1160 timestamp_set_type(TS_DELTA);
1161 else if (strcmp(optarg, "dd") == 0)
1162 timestamp_set_type(TS_DELTA_DIS);
1163 else if (strcmp(optarg, "e") == 0)
1164 timestamp_set_type(TS_EPOCH);
1166 cmdarg_err("Invalid time stamp type \"%s\"",
1168 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1169 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1173 case 'T': /* printing Type */
1174 if (strcmp(optarg, "text") == 0) {
1175 output_action = WRITE_TEXT;
1176 print_format = PR_FMT_TEXT;
1177 } else if (strcmp(optarg, "ps") == 0) {
1178 output_action = WRITE_TEXT;
1179 print_format = PR_FMT_PS;
1180 } else if (strcmp(optarg, "pdml") == 0) {
1181 output_action = WRITE_XML;
1183 } else if (strcmp(optarg, "psml") == 0) {
1184 output_action = WRITE_XML;
1186 } else if(strcmp(optarg, "fields") == 0) {
1187 output_action = WRITE_FIELDS;
1188 verbose = TRUE; /* Need full tree info */
1190 cmdarg_err("Invalid -T parameter.");
1191 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1195 case 'u': /* Seconds type */
1196 if (strcmp(optarg, "s") == 0)
1197 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1198 else if (strcmp(optarg, "hms") == 0)
1199 timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1201 cmdarg_err("Invalid seconds type \"%s\"", optarg);
1202 cmdarg_err_cont("It must be \"s\" for seconds or \"hms\" for hours, minutes and seconds.");
1206 case 'v': /* Show version and exit */
1208 GString *comp_info_str;
1209 GString *runtime_info_str;
1210 /* Assemble the compile-time version information string */
1211 comp_info_str = g_string_new("Compiled ");
1212 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
1214 /* Assemble the run-time version information string */
1215 runtime_info_str = g_string_new("Running ");
1216 get_runtime_version_info(runtime_info_str, NULL);
1217 show_version(comp_info_str, runtime_info_str);
1218 g_string_free(comp_info_str, TRUE);
1219 g_string_free(runtime_info_str, TRUE);
1223 case 'V': /* Verbose */
1225 /* The user asked for a verbose output, so let's ensure they get it,
1226 * even if they're writing to a file.
1228 print_packet_info = TRUE;
1230 case 'x': /* Print packet data in hex (and ASCII) */
1232 /* The user asked for hex output, so let's ensure they get it,
1233 * even if they're writing to a file.
1235 print_packet_info = TRUE;
1240 /* We won't call the init function for the stat this soon
1241 as it would disallow MATE's fields (which are registered
1242 by the preferences set callback) from being used as
1243 part of a tap filter. Instead, we just add the argument
1244 to a list of stat arguments. */
1245 if (!process_stat_cmd_arg(optarg)) {
1246 cmdarg_err("invalid -z argument.");
1247 cmdarg_err_cont(" -z argument must be one of :");
1248 list_stat_cmd_args();
1253 case '?': /* Bad flag - print usage message */
1256 list_capture_types();
1266 /* If we specified output fields, but not the output field type... */
1267 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1268 cmdarg_err("Output fields were specified with \"-e\", "
1269 "but \"-Tfields\" was not specified.");
1271 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1272 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1273 "specified with \"-e\".");
1278 /* If no capture filter or read filter has been specified, and there are
1279 still command-line arguments, treat them as the tokens of a capture
1280 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1281 flag was specified. */
1282 if (optind < argc) {
1283 if (cf_name != NULL) {
1284 if (rfilter != NULL) {
1285 cmdarg_err("Read filters were specified both with \"-R\" "
1286 "and with additional command-line arguments");
1289 rfilter = get_args_as_string(argc, argv, optind);
1292 if (global_capture_opts.has_cfilter) {
1293 cmdarg_err("Capture filters were specified both with \"-f\""
1294 " and with additional command-line arguments");
1297 global_capture_opts.has_cfilter = TRUE;
1298 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1300 capture_option_specified = TRUE;
1306 if (!global_capture_opts.saving_to_file) {
1307 /* We're not saving the capture to a file; if "-q" wasn't specified,
1308 we should print packet information */
1310 print_packet_info = TRUE;
1312 /* We're saving to a file; if we're writing to the standard output.
1313 and we'll also be writing dissected packets to the standard
1314 output, reject the request. At best, we could redirect that
1315 to the standard error; we *can't* write both to the standard
1316 output and have either of them be useful. */
1317 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1318 cmdarg_err("You can't write both raw packet data and dissected packets"
1319 " to the standard output.");
1324 /* We're not saving the capture to a file; if "-q" wasn't specified,
1325 we should print packet information */
1327 print_packet_info = TRUE;
1330 #ifndef HAVE_LIBPCAP
1331 if (capture_option_specified)
1332 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1339 /* We don't support capture filters when reading from a capture file
1340 (the BPF compiler doesn't support all link-layer types that we
1341 support in capture files we read). */
1343 if (cf_name != NULL) {
1344 if (global_capture_opts.has_cfilter) {
1345 cmdarg_err("Only read filters, not capture filters, "
1346 "can be specified when reading a capture file.");
1353 if (output_action != WRITE_TEXT) {
1354 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1360 if (list_link_layer_types) {
1361 /* We're supposed to list the link-layer types for an interface;
1362 did the user also specify a capture file to be read? */
1364 /* Yes - that's bogus. */
1365 cmdarg_err("You can't specify -L and a capture file to be read.");
1368 /* No - did they specify a ring buffer option? */
1369 if (global_capture_opts.multi_files_on) {
1370 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1376 * "-r" was specified, so we're reading a capture file.
1377 * Capture options don't apply here.
1379 if (global_capture_opts.multi_files_on) {
1380 cmdarg_err("Multiple capture files requested, but "
1381 "a capture isn't being done.");
1384 if (global_capture_opts.has_file_duration) {
1385 cmdarg_err("Switching capture files after a time interval was specified, but "
1386 "a capture isn't being done.");
1389 if (global_capture_opts.has_ring_num_files) {
1390 cmdarg_err("A ring buffer of capture files was specified, but "
1391 "a capture isn't being done.");
1394 if (global_capture_opts.has_autostop_files) {
1395 cmdarg_err("A maximum number of capture files was specified, but "
1396 "a capture isn't being done.");
1400 /* Note: TShark now allows the restriction of a _read_ file by packet count
1401 * and byte count as well as a write file. Other autostop options remain valid
1402 * only for a write file.
1404 if (global_capture_opts.has_autostop_duration) {
1405 cmdarg_err("A maximum capture time was specified, but "
1406 "a capture isn't being done.");
1411 * "-r" wasn't specified, so we're doing a live capture.
1413 if (global_capture_opts.saving_to_file) {
1414 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1416 /* When capturing, we only support writing libpcap format. */
1417 if (out_file_type != WTAP_FILE_PCAP) {
1418 cmdarg_err("Live captures can only be saved in libpcap format.");
1421 if (global_capture_opts.multi_files_on) {
1422 /* Multiple-file mode doesn't work under certain conditions:
1423 a) it doesn't work if you're writing to the standard output;
1424 b) it doesn't work if you're writing to a pipe;
1426 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1427 cmdarg_err("Multiple capture files requested, but "
1428 "the capture is being written to the standard output.");
1431 if (global_capture_opts.output_to_pipe) {
1432 cmdarg_err("Multiple capture files requested, but "
1433 "the capture file is a pipe.");
1436 if (!global_capture_opts.has_autostop_filesize &&
1437 !global_capture_opts.has_file_duration) {
1438 cmdarg_err("Multiple capture files requested, but "
1439 "no maximum capture file size or duration was specified.");
1444 /* They didn't specify a "-w" flag, so we won't be saving to a
1445 capture file. Check for options that only make sense if
1446 we're saving to a file. */
1447 if (global_capture_opts.has_autostop_filesize) {
1448 cmdarg_err("Maximum capture file size specified, but "
1449 "capture isn't being saved to a file.");
1452 if (global_capture_opts.multi_files_on) {
1453 cmdarg_err("Multiple capture files requested, but "
1454 "the capture isn't being saved to a file.");
1463 /* Start windows sockets */
1464 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1467 /* Notify all registered modules that have had any of their preferences
1468 changed either from one of the preferences file or from the command
1469 line that their preferences have changed. */
1472 /* At this point MATE will have registered its field array so we can
1473 have a tap filter with one of MATE's late-registered fields as part
1474 of the filter. We can now process all the "-z" arguments. */
1475 start_requested_stats();
1477 /* disabled protocols as per configuration file */
1478 if (gdp_path == NULL && dp_path == NULL) {
1479 set_disabled_protos_list();
1482 /* Build the column format array */
1483 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1486 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1487 capture_opts_trim_ring_num_files(&global_capture_opts);
1490 if (rfilter != NULL) {
1491 if (!dfilter_compile(rfilter, &rfcode)) {
1492 cmdarg_err("%s", dfilter_error_msg);
1494 #ifdef HAVE_PCAP_OPEN_DEAD
1498 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1500 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1502 " Note: That display filter code looks like a valid capture filter;");
1504 " maybe you mixed them up?");
1513 cfile.rfcode = rfcode;
1515 if (print_packet_info) {
1516 /* If we're printing as text or PostScript, we have
1517 to create a print stream. */
1518 if (output_action == WRITE_TEXT) {
1519 switch (print_format) {
1522 print_stream = print_stream_text_stdio_new(stdout);
1526 print_stream = print_stream_ps_stdio_new(stdout);
1530 g_assert_not_reached();
1535 /* We have to dissect each packet if:
1537 we're printing information about each packet;
1539 we're using a read filter on the packets;
1541 we're using any taps. */
1542 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1546 * We're reading a capture file.
1550 * Immediately relinquish any special privileges we have; we must not
1551 * be allowed to read any capture files the user running TShark
1554 relinquish_special_privs_perm();
1555 print_current_user();
1557 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1562 /* Set timestamp precision; there should arguably be a command-line
1563 option to let the user set this. */
1564 switch(wtap_file_tsprecision(cfile.wth)) {
1565 case(WTAP_FILE_TSPREC_SEC):
1566 timestamp_set_precision(TS_PREC_AUTO_SEC);
1568 case(WTAP_FILE_TSPREC_DSEC):
1569 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1571 case(WTAP_FILE_TSPREC_CSEC):
1572 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1574 case(WTAP_FILE_TSPREC_MSEC):
1575 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1577 case(WTAP_FILE_TSPREC_USEC):
1578 timestamp_set_precision(TS_PREC_AUTO_USEC);
1580 case(WTAP_FILE_TSPREC_NSEC):
1581 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1584 g_assert_not_reached();
1587 /* Process the packets in the file */
1589 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1590 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1591 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1593 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1600 /* No capture file specified, so we're supposed to do a live capture
1601 (or get a list of link-layer types for a live capture device);
1602 do we have support for live captures? */
1609 cmdarg_err("WinPcap couldn't be found.");
1610 detailed_err = cant_load_winpcap_err("TShark");
1611 cmdarg_err_cont("%s", detailed_err);
1612 g_free(detailed_err);
1617 /* trim the interface name and exit if that failed */
1618 if (!capture_opts_trim_iface(&global_capture_opts,
1619 (prefs_p->capture_device) ? get_if_name(prefs_p->capture_device) : NULL)) {
1623 /* if requested, list the link layer types and exit */
1624 if (list_link_layer_types) {
1625 /* Get the list of link-layer types for the capture device. */
1629 lt_list = capture_pcap_linktype_list(global_capture_opts.iface, &err_str);
1630 if (lt_list == NULL) {
1631 if (err_str != NULL) {
1632 cmdarg_err("The list of data link types for the capture device \"%s\" could not be obtained (%s)."
1633 "Please check to make sure you have sufficient permissions, and that\n"
1634 "you have the proper interface or pipe specified.\n", global_capture_opts.iface, err_str);
1637 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
1640 capture_opts_print_link_layer_types(lt_list);
1641 free_pcap_linktype_list(lt_list);
1645 if (print_packet_info) {
1646 if (!write_preamble(NULL)) {
1648 show_print_file_io_error(err);
1651 } else if (!quiet) {
1653 * We're not printing information for each packet, and the user
1654 * didn't ask us not to print a count of packets as they arrive,
1655 * so print that count so the user knows that packets are arriving.
1657 * XXX - what if the user wants to do a live capture, doesn't want
1658 * to save it to a file, doesn't want information printed for each
1659 * packet, does want some "-z" statistic, and wants packet counts
1660 * so they know whether they're seeing any packets?
1662 print_packet_counts = TRUE;
1665 /* For now, assume libpcap gives microsecond precision. */
1666 timestamp_set_precision(TS_PREC_AUTO_USEC);
1670 if (print_packet_info) {
1671 if (!write_finale()) {
1673 show_print_file_io_error(err);
1677 /* No - complain. */
1678 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1685 #if GLIB_CHECK_VERSION(2,10,0)
1686 if (cfile.plist_start != NULL)
1687 g_slice_free_chain(frame_data, cfile.plist_start, next);
1690 draw_tap_listeners(TRUE);
1691 funnel_dump_all_text_windows();
1694 output_fields_free(output_fields);
1695 output_fields = NULL;
1700 /*#define USE_BROKEN_G_MAIN_LOOP*/
1702 #ifdef USE_BROKEN_G_MAIN_LOOP
1705 gboolean loop_running = FALSE;
1707 guint32 packet_count = 0;
1710 /* XXX - move to the right position / file */
1711 /* read from a pipe (callback) */
1712 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1714 typedef struct pipe_input_tag {
1718 pipe_input_cb_t input_cb;
1719 guint pipe_input_id;
1721 GStaticMutex callback_running;
1725 static pipe_input_t pipe_input;
1728 /* The timer has expired, see if there's stuff to read from the pipe,
1729 if so, do the callback */
1731 pipe_timer_cb(gpointer data)
1735 gboolean result, result1;
1737 pipe_input_t *pipe_input = data;
1738 gint iterations = 0;
1741 g_static_mutex_lock (&pipe_input->callback_running);
1743 /* try to read data from the pipe only 5 times, to avoid blocking */
1744 while(iterations < 5) {
1745 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1747 /* Oddly enough although Named pipes don't work on win9x,
1748 PeekNamedPipe does !!! */
1749 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1750 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1752 /* Get the child process exit status */
1753 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1756 /* If the Peek returned an error, or there are bytes to be read
1757 or the childwatcher thread has terminated then call the normal
1759 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1761 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1763 /* And call the real handler */
1764 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1765 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1766 /* pipe closed, return false so that the timer is stopped */
1767 g_static_mutex_unlock (&pipe_input->callback_running);
1772 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1773 /* No data, stop now */
1780 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1782 g_static_mutex_unlock (&pipe_input->callback_running);
1784 /* we didn't stopped the timer, so let it run */
1791 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1794 pipe_input.source = source;
1795 pipe_input.child_process = child_process;
1796 pipe_input.user_data = user_data;
1797 pipe_input.input_cb = input_cb;
1800 g_static_mutex_init(&pipe_input.callback_running);
1801 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1802 do this but that doesn't cover all win32 platforms. GTK can do
1803 this but doesn't seem to work over processes. Attempt to do
1804 something similar here, start a timer and check for data on every
1806 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1807 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1817 #ifdef USE_TSHARK_SELECT
1821 struct sigaction action, oldaction;
1825 * XXX - dropping privileges is still required, until code cleanup is done
1827 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1828 * when it's done, we don't need special privileges to run tshark at all,
1829 * therefore we don't need to drop these privileges
1830 * The only thing we might want to keep is a warning if tshark is run as root,
1831 * as it's no longer necessary and potentially dangerous.
1833 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1834 * We've opened the capture device, so we shouldn't need any special
1835 * privileges any more; relinquish those privileges.
1837 * XXX - if we have saved set-user-ID support, we should give up those
1838 * privileges immediately, and then reclaim them long enough to get
1839 * a list of network interfaces and to open one, and then give them
1840 * up again, so that stuff we do while processing the argument list,
1841 * reading the user's preferences, loading and starting plugins
1842 * (especially *user* plugins), etc. is done with the user's privileges,
1843 * not special privileges.
1845 relinquish_special_privs_perm();
1846 print_current_user();
1848 /* Cleanup all data structures used for dissection. */
1849 cleanup_dissection();
1850 /* Initialize all data structures used for dissection. */
1854 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1855 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1857 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1859 action.sa_handler = capture_cleanup;
1860 action.sa_flags = 0;
1861 sigemptyset(&action.sa_mask);
1862 sigaction(SIGTERM, &action, NULL);
1863 sigaction(SIGINT, &action, NULL);
1864 sigaction(SIGHUP, NULL, &oldaction);
1865 if (oldaction.sa_handler == SIG_DFL)
1866 sigaction(SIGHUP, &action, NULL);
1869 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1870 quiet mode, report the number of packets we've captured. */
1871 action.sa_handler = report_counts_siginfo;
1872 action.sa_flags = 0;
1873 sigemptyset(&action.sa_mask);
1874 sigaction(SIGINFO, &action, NULL);
1875 #endif /* SIGINFO */
1878 global_capture_opts.state = CAPTURE_PREPARING;
1880 /* Let the user know what interface was chosen. */
1881 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1882 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1884 ret = sync_pipe_start(&global_capture_opts);
1889 /* the actual capture loop
1891 * XXX - glib doesn't seem to provide any event based loop handling.
1893 * XXX - for whatever reason,
1894 * calling g_main_loop_new() ends up in 100% cpu load.
1896 * But that doesn't matter: in UNIX we can use select() to find an input
1897 * source with something to do.
1899 * But that doesn't matter because we're in a CLI (that doesn't need to
1900 * update a GUI or something at the same time) so it's OK if we block
1901 * trying to read from the pipe.
1903 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1904 * wrong (but I leave it there in case I am...).
1907 #ifdef USE_TSHARK_SELECT
1909 FD_SET(pipe_input.source, &readfds);
1912 loop_running = TRUE;
1914 while (loop_running)
1916 #ifdef USE_TSHARK_SELECT
1917 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1923 } else if (ret == 1) {
1925 /* Call the real handler */
1926 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1927 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1930 #ifdef USE_TSHARK_SELECT
1939 /* XXX - move the call to main_window_update() out of capture_sync.c */
1940 /* dummy for capture_sync.c to make linker happy */
1941 void main_window_update(void)
1945 /* capture child detected an error */
1947 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1949 cmdarg_err("%s", error_msg);
1950 cmdarg_err_cont("%s", secondary_error_msg);
1954 /* capture child detected an capture filter related error */
1956 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1958 dfilter_t *rfcode = NULL;
1961 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1963 "Invalid capture filter: \"%s\"!\n"
1965 "That string looks like a valid display filter; however, it isn't a valid\n"
1966 "capture filter (%s).\n"
1968 "Note that display filters and capture filters don't have the same syntax,\n"
1969 "so you can't use most display filter expressions as capture filters.\n"
1971 "See the User's Guide for a description of the capture filter syntax.",
1972 capture_opts->cfilter, error_message);
1973 dfilter_free(rfcode);
1976 "Invalid capture filter: \"%s\"!\n"
1978 "That string isn't a valid capture filter (%s).\n"
1979 "See the User's Guide for a description of the capture filter syntax.",
1980 capture_opts->cfilter, error_message);
1985 /* capture child tells us we have a new (or the first) capture file */
1987 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1989 gboolean is_tempfile;
1993 if(capture_opts->state == CAPTURE_PREPARING) {
1994 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1996 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1998 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
2000 /* free the old filename */
2001 if (capture_opts->save_file != NULL) {
2003 /* we start a new capture file, close the old one (if we had one before) */
2004 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
2005 if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
2006 wtap_close(((capture_file *) capture_opts->cf)->wth);
2008 ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
2011 g_free(capture_opts->save_file);
2012 is_tempfile = FALSE;
2014 /* we didn't had a save_file before, must be a tempfile */
2018 /* save the new filename */
2019 capture_opts->save_file = g_strdup(new_file);
2021 /* if we are in real-time mode, open the new file now */
2023 /* Attempt to open the capture file and set up to read from it. */
2024 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
2028 /* Don't unlink (delete) the save file - leave it around,
2029 for debugging purposes. */
2030 g_free(capture_opts->save_file);
2031 capture_opts->save_file = NULL;
2036 capture_opts->state = CAPTURE_RUNNING;
2042 /* capture child tells us we have new packets to read */
2044 capture_input_new_packets(capture_options *capture_opts, int to_read)
2050 capture_file *cf = capture_opts->cf;
2051 gboolean filtering_tap_listeners;
2056 * Prevent a SIGINFO handler from writing to stdout while we're
2057 * doing so; instead, have it just set a flag telling us to print
2058 * that information when we're done.
2061 #endif /* SIGINFO */
2063 /* Do we have any tap listeners with filters? */
2064 filtering_tap_listeners = have_filtering_tap_listeners();
2066 /* Get the union of the flags for all tap listeners. */
2067 tap_flags = union_of_tap_listener_flags();
2070 while (to_read-- && cf->wth) {
2071 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2073 /* read from file failed, tell the capture child to stop */
2074 sync_pipe_stop(capture_opts);
2075 wtap_close(cf->wth);
2078 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2079 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2080 filtering_tap_listeners, tap_flags);
2083 /* packet sucessfully read and gone through the "Read Filter" */
2089 * Dumpcap's doing all the work; we're not doing any dissection.
2090 * Count all the packets it wrote.
2092 packet_count += to_read;
2095 if (print_packet_counts) {
2096 /* We're printing packet counts. */
2097 if (packet_count != 0) {
2098 fprintf(stderr, "\r%u ", packet_count);
2099 /* stderr could be line buffered */
2106 * Allow SIGINFO handlers to write.
2111 * If a SIGINFO handler asked us to write out capture counts, do so.
2115 #endif /* SIGINFO */
2121 if (!print_packet_counts) {
2122 /* Report the count only if we aren't printing a packet count
2123 as packets arrive. */
2124 fprintf(stderr, "%u packet%s captured\n", packet_count,
2125 plurality(packet_count, "", "s"));
2128 infoprint = FALSE; /* we just reported it */
2129 #endif /* SIGINFO */
2134 report_counts_siginfo(int signum _U_)
2136 int sav_errno = errno;
2137 /* If we've been told to delay printing, just set a flag asking
2138 that we print counts (if we're supposed to), otherwise print
2139 the count of packets captured (if we're supposed to). */
2146 #endif /* SIGINFO */
2149 /* capture child detected any packet drops? */
2151 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2153 if (print_packet_counts) {
2154 /* We're printing packet counts to stderr.
2155 Send a newline so that we move to the line after the packet count. */
2156 fprintf(stderr, "\n");
2160 /* We're printing packet counts to stderr.
2161 Send a newline so that we move to the line after the packet count. */
2162 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2167 /* capture child closed its side of the pipe, do the required cleanup */
2169 capture_input_closed(capture_options *capture_opts)
2173 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2174 wtap_close(((capture_file *) capture_opts->cf)->wth);
2176 #ifdef USE_BROKEN_G_MAIN_LOOP
2177 /*g_main_loop_quit(loop);*/
2180 loop_running = FALSE;
2189 capture_cleanup(DWORD ctrltype _U_)
2191 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2192 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2193 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2194 like SIGTERM at least when the machine's shutting down.
2196 For now, we handle them all as indications that we should clean up
2197 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2200 However, as handlers run in a new thread, we can't just longjmp
2201 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2202 no other handler - such as one that would terminate the process -
2205 XXX - for some reason, typing ^C to TShark, if you run this in
2206 a Cygwin console window in at least some versions of Cygwin,
2207 causes TShark to terminate immediately; this routine gets
2208 called, but the main loop doesn't get a chance to run and
2209 exit cleanly, at least if this is compiled with Microsoft Visual
2210 C++ (i.e., it's a property of the Cygwin console window or Bash;
2211 it happens if TShark is not built with Cygwin - for all I know,
2212 building it with Cygwin may make the problem go away). */
2214 /* tell the capture child to stop */
2215 sync_pipe_stop(&global_capture_opts);
2217 /* don't stop our own loop already here, otherwise status messages and
2218 * cleanup wouldn't be done properly. The child will indicate the stop of
2219 * everything by calling capture_input_closed() later */
2225 capture_cleanup(int signum _U_)
2227 /* tell the capture child to stop */
2228 sync_pipe_stop(&global_capture_opts);
2231 #endif /* HAVE_LIBPCAP */
2233 #if GLIB_CHECK_VERSION(2,10,0)
2235 process_packet_first_pass(capture_file *cf,
2236 gint64 offset, const struct wtap_pkthdr *whdr,
2237 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2239 frame_data *fdata = g_slice_new(frame_data);
2243 /* Count this packet. */
2246 /* If we're not running a display filter and we're not printing any
2247 packet information, we don't need to do a dissection. This means
2248 that all packets can be marked as 'passed'. */
2251 frame_data_init(fdata, cf->count, whdr, offset, cum_bytes);
2253 /* If we're going to print packet information, or we're going to
2254 run a read filter, or we're going to process taps, set up to
2255 do a dissection and do so. */
2256 if (do_dissection) {
2258 /* Grab any resolved addresses */
2259 host_name_lookup_process(NULL);
2261 /* The protocol tree will be "visible", i.e., printed, only if we're
2262 printing packet details, which is true if we're printing stuff
2263 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2265 epan_dissect_init(&edt, FALSE, FALSE);
2267 /* If we're running a read filter, prime the epan_dissect_t with that
2270 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2272 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2273 &first_ts, &prev_dis_ts, &prev_cap_ts);
2275 epan_dissect_run(&edt, pseudo_header, pd, fdata, NULL);
2277 /* Run the read filter if we have one. */
2279 passed = dfilter_apply_edt(cf->rfcode, &edt);
2283 frame_data_set_after_dissect(fdata, &cum_bytes, &prev_dis_ts);
2284 cap_file_add_fdata(cf, fdata);
2287 g_slice_free(frame_data, fdata);
2290 epan_dissect_cleanup(&edt);
2296 process_packet_second_pass(capture_file *cf, frame_data *fdata,
2297 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2298 gboolean filtering_tap_listeners, guint tap_flags)
2300 gboolean create_proto_tree;
2305 /* If we're not running a display filter and we're not printing any
2306 packet information, we don't need to do a dissection. This means
2307 that all packets can be marked as 'passed'. */
2310 /* If we're going to print packet information, or we're going to
2311 run a read filter, or we're going to process taps, set up to
2312 do a dissection and do so. */
2313 if (do_dissection) {
2315 /* Grab any resolved addresses */
2316 host_name_lookup_process(NULL);
2318 if (cf->rfcode || verbose || filtering_tap_listeners ||
2319 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2320 create_proto_tree = TRUE;
2322 create_proto_tree = FALSE;
2324 /* The protocol tree will be "visible", i.e., printed, only if we're
2325 printing packet details, which is true if we're printing stuff
2326 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2328 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2330 /* If we're running a read filter, prime the epan_dissect_t with that
2333 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2335 col_custom_prime_edt(&edt, &cf->cinfo);
2337 tap_queue_init(&edt);
2339 /* We only need the columns if either
2341 1) some tap needs the columns
2345 2) we're printing packet info but we're *not* verbose; in verbose
2346 mode, we print the protocol tree, not the protocol summary. */
2347 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2352 epan_dissect_run(&edt, pseudo_header, pd, fdata, cinfo);
2354 tap_push_tapped_queue(&edt);
2356 /* Run the read filter if we have one. */
2358 passed = dfilter_apply_edt(cf->rfcode, &edt);
2362 /* Process this packet. */
2363 if (print_packet_info) {
2364 /* We're printing packet information; print the information for
2367 print_packet(cf, &edt);
2369 print_packet(cf, NULL);
2371 /* The ANSI C standard does not appear to *require* that a line-buffered
2372 stream be flushed to the host environment whenever a newline is
2373 written, it just says that, on such a stream, characters "are
2374 intended to be transmitted to or from the host environment as a
2375 block when a new-line character is encountered".
2377 The Visual C++ 6.0 C implementation doesn't do what is intended;
2378 even if you set a stream to be line-buffered, it still doesn't
2379 flush the buffer at the end of every line.
2381 So, if the "-l" flag was specified, we flush the standard output
2382 at the end of a packet. This will do the right thing if we're
2383 printing packet summary lines, and, as we print the entire protocol
2384 tree for a single packet without waiting for anything to happen,
2385 it should be as good as line-buffered mode if we're printing
2386 protocol trees. (The whole reason for the "-l" flag in either
2387 tcpdump or TShark is to allow the output of a live capture to
2388 be piped to a program or script and to have that script see the
2389 information for the packet as soon as it's printed, rather than
2390 having to wait until a standard I/O buffer fills up. */
2394 if (ferror(stdout)) {
2395 show_print_file_io_error(errno);
2401 if (do_dissection) {
2402 epan_dissect_cleanup(&edt);
2409 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2410 int max_packet_count, gint64 max_byte_count)
2413 int snapshot_length;
2418 char *save_file_string = NULL;
2419 gboolean filtering_tap_listeners;
2422 linktype = wtap_file_encap(cf->wth);
2423 if (save_file != NULL) {
2424 /* Get a string that describes what we're writing to */
2425 save_file_string = output_file_description(save_file);
2427 /* Set up to write to the capture file. */
2428 snapshot_length = wtap_snapshot_length(cf->wth);
2429 if (snapshot_length == 0) {
2430 /* Snapshot length of input file not known. */
2431 snapshot_length = WTAP_MAX_PACKET_SIZE;
2433 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2434 FALSE /* compressed */, &err);
2437 /* We couldn't set up to write to the capture file. */
2440 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2441 cmdarg_err("Capture files can't be written in that format.");
2444 case WTAP_ERR_UNSUPPORTED_ENCAP:
2445 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2446 cmdarg_err("The capture file being read can't be written in "
2450 case WTAP_ERR_CANT_OPEN:
2451 cmdarg_err("The %s couldn't be created for some "
2452 "unknown reason.", save_file_string);
2455 case WTAP_ERR_SHORT_WRITE:
2456 cmdarg_err("A full header couldn't be written to the %s.",
2461 cmdarg_err("The %s could not be created: %s.", save_file_string,
2462 wtap_strerror(err));
2468 if (print_packet_info) {
2469 if (!write_preamble(cf)) {
2471 show_print_file_io_error(err);
2478 /* Do we have any tap listeners with filters? */
2479 filtering_tap_listeners = have_filtering_tap_listeners();
2481 /* Get the union of the flags for all tap listeners. */
2482 tap_flags = union_of_tap_listener_flags();
2484 if (perform_two_pass_analysis) {
2485 #if GLIB_CHECK_VERSION(2,10,0)
2487 int old_max_packet_count = max_packet_count;
2489 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2490 if (process_packet_first_pass(cf, data_offset, wtap_phdr(cf->wth),
2491 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2492 /* Stop reading if we have the maximum number of packets;
2493 * When the -c option has not been used, max_packet_count
2494 * starts at 0, which practically means, never stop reading.
2495 * (unless we roll over max_packet_count ?)
2497 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2498 err = 0; /* This is not an error */
2504 /* Close the sequential I/O side, to free up memory it requires. */
2505 wtap_sequential_close(cf->wth);
2507 /* Allow the protocol dissectors to free up memory that they
2508 * don't need after the sequential run-through of the packets. */
2509 postseq_cleanup_all_protocols();
2511 max_packet_count = old_max_packet_count;
2513 for (fdata = cf->plist_start; err == 0 && fdata != NULL; fdata = fdata->next) {
2514 if (wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2515 cf->pd, fdata->cap_len, &err, &err_info)) {
2516 if (process_packet_second_pass(cf, fdata,
2517 &cf->pseudo_header, cf->pd,
2518 filtering_tap_listeners, tap_flags)) {
2519 /* Either there's no read filtering or this packet passed the
2520 filter, so, if we're writing to a capture file, write
2523 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2524 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2526 /* Error writing to a capture file */
2527 show_capture_file_io_error(save_file, err, FALSE);
2528 wtap_dump_close(pdh, &err);
2532 /* Stop reading if we have the maximum number of packets;
2533 * When the -c option has not been used, max_packet_count
2534 * starts at 0, which practically means, never stop reading.
2535 * (unless we roll over max_packet_count ?)
2537 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2538 err = 0; /* This is not an error */
2547 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2548 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2549 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2550 filtering_tap_listeners, tap_flags)) {
2551 /* Either there's no read filtering or this packet passed the
2552 filter, so, if we're writing to a capture file, write
2555 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2556 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2558 /* Error writing to a capture file */
2559 show_capture_file_io_error(save_file, err, FALSE);
2560 wtap_dump_close(pdh, &err);
2564 /* Stop reading if we have the maximum number of packets;
2565 * When the -c option has not been used, max_packet_count
2566 * starts at 0, which practically means, never stop reading.
2567 * (unless we roll over max_packet_count ?)
2569 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2570 err = 0; /* This is not an error */
2578 /* Print a message noting that the read failed somewhere along the line. */
2581 case WTAP_ERR_UNSUPPORTED_ENCAP:
2582 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2583 cf->filename, err_info);
2587 case WTAP_ERR_CANT_READ:
2588 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2592 case WTAP_ERR_SHORT_READ:
2593 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2597 case WTAP_ERR_BAD_RECORD:
2598 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2599 cf->filename, err_info);
2604 cmdarg_err("An error occurred while reading \"%s\": %s.",
2605 cf->filename, wtap_strerror(err));
2608 if (save_file != NULL) {
2609 /* Now close the capture file. */
2610 if (!wtap_dump_close(pdh, &err))
2611 show_capture_file_io_error(save_file, err, TRUE);
2614 if (save_file != NULL) {
2615 /* Now close the capture file. */
2616 if (!wtap_dump_close(pdh, &err))
2617 show_capture_file_io_error(save_file, err, TRUE);
2619 if (print_packet_info) {
2620 if (!write_finale()) {
2622 show_print_file_io_error(err);
2629 wtap_close(cf->wth);
2632 g_free(save_file_string);
2638 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2639 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2640 gboolean filtering_tap_listeners, guint tap_flags)
2643 gboolean create_proto_tree;
2648 /* Count this packet. */
2651 /* If we're not running a display filter and we're not printing any
2652 packet information, we don't need to do a dissection. This means
2653 that all packets can be marked as 'passed'. */
2656 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
2658 /* If we're going to print packet information, or we're going to
2659 run a read filter, or we're going to process taps, set up to
2660 do a dissection and do so. */
2661 if (do_dissection) {
2662 if (print_packet_info && g_resolv_flags)
2663 /* Grab any resolved addresses */
2664 host_name_lookup_process(NULL);
2666 if (cf->rfcode || verbose || filtering_tap_listeners ||
2667 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2668 create_proto_tree = TRUE;
2670 create_proto_tree = FALSE;
2672 /* The protocol tree will be "visible", i.e., printed, only if we're
2673 printing packet details, which is true if we're printing stuff
2674 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2676 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2678 /* If we're running a read filter, prime the epan_dissect_t with that
2681 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2683 col_custom_prime_edt(&edt, &cf->cinfo);
2685 tap_queue_init(&edt);
2687 /* We only need the columns if either
2689 1) some tap needs the columns
2693 2) we're printing packet info but we're *not* verbose; in verbose
2694 mode, we print the protocol tree, not the protocol summary. */
2695 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2700 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
2701 &first_ts, &prev_dis_ts, &prev_cap_ts);
2703 epan_dissect_run(&edt, pseudo_header, pd, &fdata, cinfo);
2705 tap_push_tapped_queue(&edt);
2707 /* Run the read filter if we have one. */
2709 passed = dfilter_apply_edt(cf->rfcode, &edt);
2713 frame_data_set_after_dissect(&fdata, &cum_bytes, &prev_dis_ts);
2715 /* Process this packet. */
2716 if (print_packet_info) {
2717 /* We're printing packet information; print the information for
2720 print_packet(cf, &edt);
2722 print_packet(cf, NULL);
2724 /* The ANSI C standard does not appear to *require* that a line-buffered
2725 stream be flushed to the host environment whenever a newline is
2726 written, it just says that, on such a stream, characters "are
2727 intended to be transmitted to or from the host environment as a
2728 block when a new-line character is encountered".
2730 The Visual C++ 6.0 C implementation doesn't do what is intended;
2731 even if you set a stream to be line-buffered, it still doesn't
2732 flush the buffer at the end of every line.
2734 So, if the "-l" flag was specified, we flush the standard output
2735 at the end of a packet. This will do the right thing if we're
2736 printing packet summary lines, and, as we print the entire protocol
2737 tree for a single packet without waiting for anything to happen,
2738 it should be as good as line-buffered mode if we're printing
2739 protocol trees. (The whole reason for the "-l" flag in either
2740 tcpdump or TShark is to allow the output of a live capture to
2741 be piped to a program or script and to have that script see the
2742 information for the packet as soon as it's printed, rather than
2743 having to wait until a standard I/O buffer fills up. */
2747 if (ferror(stdout)) {
2748 show_print_file_io_error(errno);
2754 if (do_dissection) {
2755 epan_dissect_cleanup(&edt);
2756 frame_data_cleanup(&fdata);
2762 write_preamble(capture_file *cf)
2764 switch (output_action) {
2767 return print_preamble(print_stream, cf ? cf->filename : NULL);
2771 write_pdml_preamble(stdout);
2773 write_psml_preamble(stdout);
2774 return !ferror(stdout);
2777 write_fields_preamble(output_fields, stdout);
2778 return !ferror(stdout);
2781 g_assert_not_reached();
2787 get_line_buf(size_t len)
2789 static char *line_bufp = NULL;
2790 static size_t line_buf_len = 256;
2791 size_t new_line_buf_len;
2793 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2794 new_line_buf_len *= 2)
2796 if (line_bufp == NULL) {
2797 line_buf_len = new_line_buf_len;
2798 line_bufp = g_malloc(line_buf_len + 1);
2800 if (new_line_buf_len > line_buf_len) {
2801 line_buf_len = new_line_buf_len;
2802 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2809 print_columns(capture_file *cf)
2816 line_bufp = get_line_buf(256);
2819 for (i = 0; i < cf->cinfo.num_cols; i++) {
2820 switch (cf->cinfo.col_fmt[i]) {
2824 * Don't print this if we're doing a live capture from a network
2825 * interface - if we're doing a live capture, you won't be
2826 * able to look at the capture in the future (it's not being
2827 * saved anywhere), so the frame numbers are unlikely to be
2830 * (XXX - it might be nice to be able to save and print at
2831 * the same time, sort of like an "Update list of packets
2832 * in real time" capture in Wireshark.)
2834 if (global_capture_opts.iface != NULL)
2837 column_len = strlen(cf->cinfo.col_data[i]);
2840 line_bufp = get_line_buf(buf_offset + column_len);
2841 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2847 case COL_ABS_DATE_TIME: /* XXX - wider */
2848 column_len = strlen(cf->cinfo.col_data[i]);
2849 if (column_len < 10)
2851 line_bufp = get_line_buf(buf_offset + column_len);
2852 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2858 case COL_DEF_DL_SRC:
2859 case COL_RES_DL_SRC:
2860 case COL_UNRES_DL_SRC:
2861 case COL_DEF_NET_SRC:
2862 case COL_RES_NET_SRC:
2863 case COL_UNRES_NET_SRC:
2864 column_len = strlen(cf->cinfo.col_data[i]);
2865 if (column_len < 12)
2867 line_bufp = get_line_buf(buf_offset + column_len);
2868 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2874 case COL_DEF_DL_DST:
2875 case COL_RES_DL_DST:
2876 case COL_UNRES_DL_DST:
2877 case COL_DEF_NET_DST:
2878 case COL_RES_NET_DST:
2879 case COL_UNRES_NET_DST:
2880 column_len = strlen(cf->cinfo.col_data[i]);
2881 if (column_len < 12)
2883 line_bufp = get_line_buf(buf_offset + column_len);
2884 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2888 column_len = strlen(cf->cinfo.col_data[i]);
2889 line_bufp = get_line_buf(buf_offset + column_len);
2890 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2893 buf_offset += column_len;
2894 if (i != cf->cinfo.num_cols - 1) {
2896 * This isn't the last column, so we need to print a
2897 * separator between this column and the next.
2899 * If we printed a network source and are printing a
2900 * network destination of the same type next, separate
2901 * them with "->"; if we printed a network destination
2902 * and are printing a network source of the same type
2903 * next, separate them with "<-"; otherwise separate them
2906 * We add enough space to the buffer for " <- " or " -> ",
2907 * even if we're only adding " ".
2909 line_bufp = get_line_buf(buf_offset + 4);
2910 switch (cf->cinfo.col_fmt[i]) {
2915 switch (cf->cinfo.col_fmt[i + 1]) {
2920 strcat(line_bufp + buf_offset, " -> ");
2925 strcat(line_bufp + buf_offset, " ");
2931 case COL_DEF_DL_SRC:
2932 case COL_RES_DL_SRC:
2933 case COL_UNRES_DL_SRC:
2934 switch (cf->cinfo.col_fmt[i + 1]) {
2936 case COL_DEF_DL_DST:
2937 case COL_RES_DL_DST:
2938 case COL_UNRES_DL_DST:
2939 strcat(line_bufp + buf_offset, " -> ");
2944 strcat(line_bufp + buf_offset, " ");
2950 case COL_DEF_NET_SRC:
2951 case COL_RES_NET_SRC:
2952 case COL_UNRES_NET_SRC:
2953 switch (cf->cinfo.col_fmt[i + 1]) {
2955 case COL_DEF_NET_DST:
2956 case COL_RES_NET_DST:
2957 case COL_UNRES_NET_DST:
2958 strcat(line_bufp + buf_offset, " -> ");
2963 strcat(line_bufp + buf_offset, " ");
2972 switch (cf->cinfo.col_fmt[i + 1]) {
2977 strcat(line_bufp + buf_offset, " <- ");
2982 strcat(line_bufp + buf_offset, " ");
2988 case COL_DEF_DL_DST:
2989 case COL_RES_DL_DST:
2990 case COL_UNRES_DL_DST:
2991 switch (cf->cinfo.col_fmt[i + 1]) {
2993 case COL_DEF_DL_SRC:
2994 case COL_RES_DL_SRC:
2995 case COL_UNRES_DL_SRC:
2996 strcat(line_bufp + buf_offset, " <- ");
3001 strcat(line_bufp + buf_offset, " ");
3007 case COL_DEF_NET_DST:
3008 case COL_RES_NET_DST:
3009 case COL_UNRES_NET_DST:
3010 switch (cf->cinfo.col_fmt[i + 1]) {
3012 case COL_DEF_NET_SRC:
3013 case COL_RES_NET_SRC:
3014 case COL_UNRES_NET_SRC:
3015 strcat(line_bufp + buf_offset, " <- ");
3020 strcat(line_bufp + buf_offset, " ");
3027 strcat(line_bufp + buf_offset, " ");
3033 return print_line(print_stream, 0, line_bufp);
3037 print_packet(capture_file *cf, epan_dissect_t *edt)
3039 print_args_t print_args;
3042 /* Print the information in the protocol tree. */
3043 switch (output_action) {
3046 print_args.to_file = TRUE;
3047 print_args.format = print_format;
3048 print_args.print_summary = !verbose;
3049 print_args.print_hex = verbose && print_hex;
3050 print_args.print_formfeed = FALSE;
3051 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
3053 /* init the packet range */
3054 packet_range_init(&print_args.range);
3056 if (!proto_tree_print(&print_args, edt, print_stream))
3059 /* "print_hex_data()" will put out a leading blank line, as well
3060 as a trailing one; print one here, to separate the packets,
3061 only if "print_hex_data()" won't be called. */
3062 if (!print_line(print_stream, 0, ""))
3068 proto_tree_write_pdml(edt, stdout);
3070 return !ferror(stdout);
3072 proto_tree_write_fields(output_fields, edt, stdout);
3074 return !ferror(stdout);
3077 /* Just fill in the columns. */
3078 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3080 /* Now print them. */
3081 switch (output_action) {
3084 if (!print_columns(cf))
3089 proto_tree_write_psml(edt, stdout);
3090 return !ferror(stdout);
3091 case WRITE_FIELDS: /*No non-verbose "fields" format */
3092 g_assert_not_reached();
3097 if (!print_hex_data(print_stream, edt))
3099 if (!print_line(print_stream, 0, ""))
3108 switch (output_action) {
3111 return print_finale(print_stream);
3115 write_pdml_finale(stdout);
3117 write_psml_finale(stdout);
3118 return !ferror(stdout);
3121 write_fields_finale(output_fields, stdout);
3122 return !ferror(stdout);
3125 g_assert_not_reached();
3131 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3135 char err_msg[2048+1];
3137 wth = wtap_open_offline(fname, err, &err_info, perform_two_pass_analysis);
3141 /* The open succeeded. Fill in the information for this file. */
3143 /* Cleanup all data structures used for dissection. */
3144 cleanup_dissection();
3145 /* Initialize all data structures used for dissection. */
3149 cf->f_datalen = 0; /* not used, but set it anyway */
3151 /* Set the file name because we need it to set the follow stream filter.
3152 XXX - is that still true? We need it for other reasons, though,
3154 cf->filename = g_strdup(fname);
3156 /* Indicate whether it's a permanent or temporary file. */
3157 cf->is_tempfile = is_tempfile;
3159 /* If it's a temporary capture buffer file, mark it as not saved. */
3160 cf->user_saved = !is_tempfile;
3162 cf->cd_t = wtap_file_type(cf->wth);
3164 cf->drops_known = FALSE;
3166 cf->snap = wtap_snapshot_length(cf->wth);
3167 if (cf->snap == 0) {
3168 /* Snapshot length not known. */
3169 cf->has_snap = FALSE;
3170 cf->snap = WTAP_MAX_PACKET_SIZE;
3172 cf->has_snap = TRUE;
3173 nstime_set_zero(&cf->elapsed_time);
3174 nstime_set_unset(&first_ts);
3175 nstime_set_unset(&prev_dis_ts);
3176 nstime_set_unset(&prev_cap_ts);
3178 cf->state = FILE_READ_IN_PROGRESS;
3183 g_snprintf(err_msg, sizeof err_msg,
3184 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3185 cmdarg_err("%s", err_msg);
3190 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3192 char *save_file_string;
3194 save_file_string = output_file_description(fname);
3199 cmdarg_err("Not all the packets could be written to the %s because there is "
3200 "no space left on the file system.",
3206 cmdarg_err("Not all the packets could be written to the %s because you are "
3207 "too close to, or over your disk quota.",
3212 case WTAP_ERR_CANT_CLOSE:
3213 cmdarg_err("The %s couldn't be closed for some unknown reason.",
3217 case WTAP_ERR_SHORT_WRITE:
3218 cmdarg_err("Not all the packets could be written to the %s.",
3224 cmdarg_err("The %s could not be closed: %s.", save_file_string,
3225 wtap_strerror(err));
3227 cmdarg_err("An error occurred while writing to the %s: %s.",
3228 save_file_string, wtap_strerror(err));
3232 g_free(save_file_string);
3236 show_print_file_io_error(int err)
3241 cmdarg_err("Not all the packets could be printed because there is "
3242 "no space left on the file system.");
3247 cmdarg_err("Not all the packets could be printed because you are "
3248 "too close to, or over your disk quota.");
3253 cmdarg_err("An error occurred while printing packets: %s.",
3260 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3264 static char errmsg_errno[1024+1];
3267 /* Wiretap error. */
3270 case WTAP_ERR_NOT_REGULAR_FILE:
3271 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3274 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3275 /* Seen only when opening a capture file for reading. */
3276 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3279 case WTAP_ERR_UNSUPPORTED:
3280 /* Seen only when opening a capture file for reading. */
3281 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3282 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3285 errmsg = errmsg_errno;
3288 case WTAP_ERR_CANT_WRITE_TO_PIPE:
3289 /* Seen only when opening a capture file for writing. */
3290 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3291 "The file \"%%s\" is a pipe, and %s capture files can't be "
3292 "written to a pipe.", wtap_file_type_string(file_type));
3293 errmsg = errmsg_errno;
3296 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3297 /* Seen only when opening a capture file for writing. */
3298 errmsg = "TShark doesn't support writing capture files in that format.";
3301 case WTAP_ERR_UNSUPPORTED_ENCAP:
3303 errmsg = "TShark can't save this capture in that format.";
3305 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3306 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3309 errmsg = errmsg_errno;
3313 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3315 errmsg = "TShark can't save this capture in that format.";
3317 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3320 case WTAP_ERR_BAD_RECORD:
3321 /* Seen only when opening a capture file for reading. */
3322 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3323 "The file \"%%s\" appears to be damaged or corrupt.\n"
3326 errmsg = errmsg_errno;
3329 case WTAP_ERR_CANT_OPEN:
3331 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3333 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3336 case WTAP_ERR_SHORT_READ:
3337 errmsg = "The file \"%s\" appears to have been cut short"
3338 " in the middle of a packet or other data.";
3341 case WTAP_ERR_SHORT_WRITE:
3342 errmsg = "A full header couldn't be written to the file \"%s\".";
3346 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3347 "The file \"%%s\" could not be %s: %s.",
3348 for_writing ? "created" : "opened",
3349 wtap_strerror(err));
3350 errmsg = errmsg_errno;
3354 errmsg = file_open_error_message(err, for_writing);
3359 * Open/create errors are reported with an console message in TShark.
3362 open_failure_message(const char *filename, int err, gboolean for_writing)
3364 fprintf(stderr, "tshark: ");
3365 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3366 fprintf(stderr, "\n");
3371 * General errors are reported with an console message in TShark.
3374 failure_message(const char *msg_format, va_list ap)
3376 fprintf(stderr, "tshark: ");
3377 vfprintf(stderr, msg_format, ap);
3378 fprintf(stderr, "\n");
3382 * Read errors are reported with an console message in TShark.
3385 read_failure_message(const char *filename, int err)
3387 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3388 filename, strerror(err));
3392 * Write errors are reported with an console message in TShark.
3395 write_failure_message(const char *filename, int err)
3397 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3398 filename, strerror(err));
3402 * Print to the standard error. This is a command-line tool, so there's
3403 * no need to pop up a console.
3406 vfprintf_stderr(const char *fmt, va_list ap)
3408 vfprintf(stderr, fmt, ap);
3412 fprintf_stderr(const char *fmt, ...)
3417 vfprintf_stderr(fmt, ap);
3422 * Report an error in command-line arguments.
3425 cmdarg_err(const char *fmt, ...)
3430 failure_message(fmt, ap);
3435 * Report additional information for an error in command-line arguments.
3438 cmdarg_err_cont(const char *fmt, ...)
3443 vfprintf(stderr, fmt, ap);
3444 fprintf(stderr, "\n");