5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10 * and Guy Harris <guy@alum.mit.edu>.
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
63 #include <epan/epan.h>
64 #include <epan/filesystem.h>
65 #include <epan/privileges.h>
66 #include <wiretap/file_util.h>
69 #include <epan/timestamp.h>
70 #include <epan/packet.h>
72 #include "disabled_protos.h"
73 #include <epan/prefs.h>
74 #include <epan/column.h>
76 #include <epan/addr_resolv.h>
78 #include "clopts_common.h"
79 #include "cmdarg_err.h"
80 #include "version_info.h"
81 #include <epan/conversation.h>
82 #include <epan/plugins.h>
84 #include "conditions.h"
85 #include "capture_stop_conditions.h"
86 #include "ringbuffer.h"
87 #include "capture_ui_utils.h"
88 #include <epan/epan_dissect.h>
90 #include <epan/stat_cmd_args.h>
91 #include <epan/timestamp.h>
92 #include <epan/ex-opt.h>
97 #include "capture-pcap-util.h"
99 #include <wiretap/wtap-capture.h>
101 #include "capture-wpcap.h"
102 #include "capture_errs.h"
105 #include "capture_loop.h"
106 #include "capture_sync.h"
107 #endif /* HAVE_LIBPCAP */
108 #include "epan/emem.h"
110 #include <epan/funnel.h>
113 * This is the template for the decode as option; it is shared between the
114 * various functions that output the usage for this parameter.
116 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
118 static nstime_t first_ts;
119 static nstime_t prev_ts;
120 static GString *comp_info_str, *runtime_info_str;
122 static gboolean print_packet_info; /* TRUE if we're to print packet information */
124 * The way the packet decode is to be written.
127 WRITE_TEXT, /* summary or detail text */
128 WRITE_XML /* PDML or PSML */
129 /* Add CSV and the like here */
131 static output_action_e output_action;
132 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
133 static gboolean verbose;
134 static gboolean print_hex;
135 static gboolean line_buffered;
136 static guint32 cum_bytes = 0;
137 static print_format_e print_format = PR_FMT_TEXT;
138 static print_stream_t *print_stream;
141 * Standard secondary message for unexpected errors.
143 static const char please_report[] =
144 "Please report this to the Wireshark developers";
148 * TRUE if we're to print packet counts to keep track of captured packets.
150 static gboolean print_packet_counts;
156 static capture_options capture_opts;
160 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
161 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
163 #endif /* HAVE_LIBPCAP */
166 static int capture(void);
167 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
169 static void report_counts(void);
171 static BOOL WINAPI capture_cleanup(DWORD);
173 static void capture_cleanup(int);
175 static void report_counts_siginfo(int);
178 #endif /* HAVE_LIBPCAP */
180 static int load_cap_file(capture_file *, char *, int);
181 static gboolean process_packet(capture_file *cf, gint64 offset,
182 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
184 static void show_capture_file_io_error(const char *, int, gboolean);
185 static void show_print_file_io_error(int err);
186 static gboolean write_preamble(capture_file *cf);
187 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
188 static gboolean write_finale(void);
189 static const char *cf_open_error_message(int err, gchar *err_info,
190 gboolean for_writing, int file_type);
192 static void open_failure_message(const char *filename, int err,
193 gboolean for_writing);
194 static void failure_message(const char *msg_format, va_list ap);
195 static void read_failure_message(const char *filename, int err);
200 static void list_capture_types(void) {
203 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
204 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
205 if (wtap_dump_can_open(i))
206 fprintf(stderr, " %s - %s\n",
207 wtap_file_type_short_string(i), wtap_file_type_string(i));
212 print_usage(gboolean print_ver)
219 "TShark " VERSION "%s\n"
220 "Dump and analyze network traffic.\n"
221 "See http://www.wireshark.org for more information.\n"
224 svnversion, get_copyright_info());
228 fprintf(output, "\n");
229 fprintf(output, "Usage: tshark [options] ...\n");
230 fprintf(output, "\n");
233 fprintf(output, "Capture interface:\n");
234 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
235 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
236 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
237 fprintf(output, " -p don't capture in promiscuous mode\n");
239 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
241 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
242 fprintf(output, " -D print list of interfaces and exit\n");
243 fprintf(output, " -L print list of link-layer types of iface and exit\n");
244 fprintf(output, "\n");
245 fprintf(output, "Capture stop conditions:\n");
246 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
247 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
248 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
249 fprintf(output, " files:NUM - stop after NUM files\n");
250 /*fprintf(output, "\n");*/
251 fprintf(output, "Capture output:\n");
252 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
253 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
254 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
255 #endif /* HAVE_LIBPCAP */
257 /*fprintf(output, "\n");*/
258 fprintf(output, "Input file:\n");
259 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
261 fprintf(output, "\n");
262 fprintf(output, "Processing:\n");
263 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
264 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
265 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
266 fprintf(output, " -d %s ...\n", decode_as_arg_template);
267 fprintf(output, " \"Decode As\", see the man page for details\n");
268 fprintf(output, " Example: tcp.port==8888,http\n");
270 /*fprintf(output, "\n");*/
271 fprintf(output, "Output:\n");
272 fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
273 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
274 fprintf(output, " an empty \"-F\" option will list the file types\n");
275 fprintf(output, " -V add output of packet tree (Packet Details)\n");
276 fprintf(output, " -S display packets even when writing to a file\n");
277 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
278 fprintf(output, " -T pdml|ps|psml|text output format of text output (def: text)\n");
279 fprintf(output, " -t ad|a|r|d|e output format of time stamps (def: r: rel. to first)\n");
280 fprintf(output, " -l flush output after each packet\n");
281 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
282 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
283 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
285 fprintf(output, "\n");
286 fprintf(output, "Miscellaneous:\n");
287 fprintf(output, " -h display this help and exit\n");
288 fprintf(output, " -v display version info and exit\n");
289 fprintf(output, " -o <name>:<value> ... override preference setting\n");
293 * For a dissector table, print on the stream described by output,
294 * its short name (which is what's used in the "-d" option) and its
298 display_dissector_table_names(char *table_name, const char *ui_name,
301 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
305 * For a dissector handle, print on the stream described by output,
306 * the filter name (which is what's used in the "-d" option) and the full
307 * name for the protocol that corresponds to this handle.
310 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
313 const gchar* proto_filter_name;
314 const gchar* proto_ui_name;
316 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
318 if (proto_id != -1) {
319 proto_filter_name = proto_get_protocol_filter_name(proto_id);
320 proto_ui_name = proto_get_protocol_name(proto_id);
321 g_assert(proto_filter_name != NULL);
322 g_assert(proto_ui_name != NULL);
324 fprintf((FILE *)output, "\t%s (%s)\n",
331 * The protocol_name_search structure is used by find_protocol_name_func()
332 * to pass parameters and store results
334 struct protocol_name_search{
335 gchar *searched_name; /* Protocol filter name we are looking for */
336 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
337 guint nb_match; /* How many dissectors matched searched_name */
339 typedef struct protocol_name_search *protocol_name_search_t;
342 * This function parses all dissectors associated with a table to find the
343 * one whose protocol has the specified filter name. It is called
344 * as a reference function in a call to dissector_table_foreach_handle.
345 * The name we are looking for, as well as the results, are stored in the
346 * protocol_name_search struct pointed to by user_data.
347 * If called using dissector_table_foreach_handle, we actually parse the
348 * whole list of dissectors.
351 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
355 const gchar *protocol_filter_name;
356 protocol_name_search_t search_info;
360 search_info = (protocol_name_search_t)user_data;
362 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
363 if (proto_id != -1) {
364 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
365 g_assert(protocol_filter_name != NULL);
366 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
368 if (search_info->nb_match == 0) {
369 /* Record this handle only if this is the first match */
370 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
372 search_info->nb_match++;
378 * Print all layer type names supported.
379 * We send the output to the stream described by the handle output.
383 fprint_all_layer_types(FILE *output)
386 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
390 * Print all protocol names supported for a specific layer type.
391 * table_name contains the layer type name in which the search is performed.
392 * We send the output to the stream described by the handle output.
396 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
399 dissector_table_foreach_handle(table_name,
400 display_dissector_names,
405 * The function below parses the command-line parameters for the decode as
406 * feature (a string pointer by cl_param).
407 * It checks the format of the command-line, searches for a matching table
408 * and dissector. If a table/dissector match is not found, we display a
409 * summary of the available tables/dissectors (on stderr) and return FALSE.
410 * If everything is fine, we get the "Decode as" preference activated,
411 * then we return TRUE.
414 add_decode_as(const gchar *cl_param)
418 gchar *decoded_param;
419 gchar *remaining_param;
421 gchar *dissector_str;
422 dissector_handle_t dissector_matching;
423 dissector_table_t table_matching;
424 ftenum_t dissector_table_selector_type;
425 struct protocol_name_search user_protocol_name;
427 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
430 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
431 g_assert(decoded_param);
432 strcpy(decoded_param, cl_param);
435 /* The lines below will parse this string (modifying it) to extract all
436 necessary information. Note that decoded_param is still needed since
437 strings are not copied - we just save pointers. */
439 /* This section extracts a layer type (table_name) from decoded_param */
440 table_name = decoded_param; /* Layer type string starts from beginning */
442 remaining_param = strchr(table_name, '=');
443 if (remaining_param == NULL) {
444 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
445 /* If the argument does not follow the template, carry on anyway to check
446 if the table name is at least correct. If remaining_param is NULL,
447 we'll exit anyway further down */
450 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
453 /* Remove leading and trailing spaces from the table name */
454 while ( table_name[0] == ' ' )
456 while ( table_name[strlen(table_name) - 1] == ' ' )
457 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
459 /* The following part searches a table matching with the layer type specified */
460 table_matching = NULL;
462 /* Look for the requested table */
463 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
464 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
467 table_matching = find_dissector_table(table_name);
468 if (!table_matching) {
469 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
473 if (!table_matching) {
474 /* Display a list of supported layer types to help the user, if the
475 specified layer type was not found */
476 cmdarg_err("Valid layer types are:");
477 fprint_all_layer_types(stderr);
479 if (remaining_param == NULL || !table_matching) {
480 /* Exit if the layer type was not found, or if no '=' separator was found
482 g_free(decoded_param);
486 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
487 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
490 remaining_param++; /* Move to the second '=' */
491 *remaining_param = '\0'; /* Remove the second '=' */
493 remaining_param++; /* Position after the layer type string */
495 /* This section extracts a selector value (selector_str) from decoded_param */
497 selector_str = remaining_param; /* Next part starts with the selector number */
499 remaining_param = strchr(selector_str, ',');
500 if (remaining_param == NULL) {
501 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
502 /* If the argument does not follow the template, carry on anyway to check
503 if the selector value is at least correct. If remaining_param is NULL,
504 we'll exit anyway further down */
507 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
510 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
512 switch (dissector_table_selector_type) {
518 /* The selector for this table is an unsigned number. Parse it as such.
519 There's no need to remove leading and trailing spaces from the
520 selector number string, because sscanf will do that for us. */
521 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
522 cmdarg_err("Invalid selector number \"%s\"", selector_str);
523 g_free(decoded_param);
530 /* The selector for this table is a string. */
534 /* There are currently no dissector tables with any types other
535 than the ones listed above. */
536 g_assert_not_reached();
539 if (remaining_param == NULL) {
540 /* Exit if no ',' separator was found (see above) */
541 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
542 fprint_all_protocols_for_layer_types(stderr, table_name);
543 g_free(decoded_param);
547 remaining_param++; /* Position after the selector number string */
549 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
551 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
553 /* Remove leading and trailing spaces from the dissector name */
554 while ( dissector_str[0] == ' ' )
556 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
557 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
559 dissector_matching = NULL;
561 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
562 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 */
563 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
566 user_protocol_name.nb_match = 0;
567 user_protocol_name.searched_name = dissector_str;
568 user_protocol_name.matched_handle = NULL;
570 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 */
572 if (user_protocol_name.nb_match != 0) {
573 dissector_matching = user_protocol_name.matched_handle;
574 if (user_protocol_name.nb_match > 1) {
575 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
579 /* OK, check whether the problem is that there isn't any such
580 protocol, or that there is but it's not specified as a protocol
581 that's valid for that dissector table.
582 Note, we don't exit here, but dissector_matching will remain NULL,
584 if (proto_get_id_by_filter_name(dissector_str) == -1) {
585 /* No such protocol */
586 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
588 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
589 dissector_str, table_name);
594 if (!dissector_matching) {
595 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
596 fprint_all_protocols_for_layer_types(stderr, table_name);
597 g_free(decoded_param);
601 /* This is the end of the code that parses the command-line options.
602 All information is now stored in the variables:
606 The above variables that are strings are still pointing to areas within
607 decoded_parm. decoded_parm thus still needs to be kept allocated in
608 until we stop needing these variables
609 decoded_param will be deallocated at each exit point of this function */
612 /* We now have a pointer to the handle for the requested dissector
613 (requested protocol) inside the variable dissector_matching */
614 switch (dissector_table_selector_type) {
620 /* The selector for this table is an unsigned number. */
621 dissector_change(table_name, selector, dissector_matching);
626 /* The selector for this table is a string. */
627 dissector_change_string(table_name, selector_str, dissector_matching);
631 /* There are currently no dissector tables with any types other
632 than the ones listed above. */
633 g_assert_not_reached();
635 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
640 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
641 const gchar *message _U_, gpointer user_data _U_)
646 output_file_description(const char *fname)
648 char *save_file_string;
650 /* Get a string that describes what we're writing to */
651 if (strcmp(fname, "-") == 0) {
652 /* We're writing to the standard output */
653 save_file_string = g_strdup("standard output");
655 /* We're writing to a file with the name in save_file */
656 save_file_string = g_strdup_printf("file \"%s\"", fname);
658 return save_file_string;
662 main(int argc, char *argv[])
664 char *init_progfile_dir_error;
667 gboolean arg_error = FALSE;
673 char *gpf_path, *pf_path;
674 char *gdp_path, *dp_path;
675 int gpf_open_errno, gpf_read_errno;
676 int pf_open_errno, pf_read_errno;
677 int gdp_open_errno, gdp_read_errno;
678 int dp_open_errno, dp_read_errno;
681 gboolean list_link_layer_types = FALSE;
682 gboolean start_capture = FALSE;
684 gboolean capture_option_specified = FALSE;
686 gboolean quiet = FALSE;
687 int out_file_type = WTAP_FILE_PCAP;
688 gchar *cf_name = NULL, *rfilter = NULL;
689 #ifdef HAVE_PCAP_OPEN_DEAD
690 struct bpf_program fcode;
692 dfilter_t *rfcode = NULL;
695 GLogLevelFlags log_flags;
699 #define OPTSTRING_INIT "a:b:c:d:Df:F:G:hi:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
702 #define OPTSTRING_WIN32 "B:"
704 #define OPTSTRING_WIN32 ""
707 #define OPTSTRING_WIN32 ""
708 #endif /* HAVE_LIBPCAP */
710 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
713 * Attempt to get the pathname of the executable file.
715 init_progfile_dir_error = init_progfile_dir(argv[0]);
716 if (init_progfile_dir_error != NULL) {
717 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
718 init_progfile_dir_error);
722 * Get credential information for later use.
724 get_credential_info();
727 * in order to have the -X otps assigned before the wslua machine starts
728 * we need to getopts before epan_init() gets called
731 optind_initial = optind;
733 while ((opt = getopt(argc, argv, optstring)) != -1) {
743 optind = optind_initial;
746 /* nothing more than the standard GLib handler, but without a warning */
749 G_LOG_LEVEL_CRITICAL|
754 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
756 g_log_set_handler(NULL,
758 log_func_ignore, NULL /* user_data */);
759 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
761 log_func_ignore, NULL /* user_data */);
763 initialize_funnel_ops();
766 capture_opts_init(&capture_opts, NULL /* cfile */);
769 timestamp_set_type(TS_RELATIVE);
770 timestamp_set_precision(TS_PREC_AUTO);
772 /* Register all dissectors; we must do this before checking for the
773 "-G" flag, as the "-G" flag dumps information registered by the
774 dissectors, and we must do it before we read the preferences, in
775 case any dissectors register preferences. */
776 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
777 failure_message,open_failure_message,read_failure_message);
779 /* Register all tap listeners; we do this before we parse the arguments,
780 as the "-z" argument can specify a registered tap. */
782 /* we register the plugin taps before the other taps because
783 stats_tree taps plugins will be registered as tap listeners
784 by stats_tree_stat.c and need to registered before that */
786 register_all_plugin_tap_listeners();
788 register_all_tap_listeners();
790 /* Now register the preferences for any non-dissector modules.
791 We must do that before we read the preferences as well. */
792 prefs_register_modules();
794 /* If invoked with the "-G" flag, we dump out information based on
795 the argument to the "-G" flag; if no argument is specified,
796 for backwards compatibility we dump out a glossary of display
799 XXX - we do this here, for now, to support "-G" with no arguments.
800 If none of our build or other processes uses "-G" with no arguments,
801 we can just process it with the other arguments. */
802 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
804 proto_registrar_dump_fields(1);
806 if (strcmp(argv[2], "fields") == 0)
807 proto_registrar_dump_fields(1);
808 else if (strcmp(argv[2], "fields2") == 0)
809 proto_registrar_dump_fields(2);
810 else if (strcmp(argv[2], "fields3") == 0)
811 proto_registrar_dump_fields(3);
812 else if (strcmp(argv[2], "protocols") == 0)
813 proto_registrar_dump_protocols();
814 else if (strcmp(argv[2], "values") == 0)
815 proto_registrar_dump_values();
816 else if (strcmp(argv[2], "decodes") == 0)
817 dissector_dump_decodes();
818 else if (strcmp(argv[2], "defaultprefs") == 0)
820 else if (strcmp(argv[2], "currentprefs") == 0) {
821 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
822 &pf_open_errno, &pf_read_errno, &pf_path);
825 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
832 /* Set the C-language locale to the native environment. */
833 setlocale(LC_ALL, "");
835 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
836 &pf_open_errno, &pf_read_errno, &pf_path);
837 if (gpf_path != NULL) {
838 if (gpf_open_errno != 0) {
839 cmdarg_err("Can't open global preferences file \"%s\": %s.",
840 pf_path, strerror(gpf_open_errno));
842 if (gpf_read_errno != 0) {
843 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
844 pf_path, strerror(gpf_read_errno));
847 if (pf_path != NULL) {
848 if (pf_open_errno != 0) {
849 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
850 strerror(pf_open_errno));
852 if (pf_read_errno != 0) {
853 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
854 pf_path, strerror(pf_read_errno));
860 /* Set the name resolution code's flags from the preferences. */
861 g_resolv_flags = prefs->name_resolve;
863 /* Read the disabled protocols file. */
864 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
865 &dp_path, &dp_open_errno, &dp_read_errno);
866 if (gdp_path != NULL) {
867 if (gdp_open_errno != 0) {
868 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
869 gdp_path, strerror(gdp_open_errno));
871 if (gdp_read_errno != 0) {
872 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
873 gdp_path, strerror(gdp_read_errno));
877 if (dp_path != NULL) {
878 if (dp_open_errno != 0) {
880 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
881 strerror(dp_open_errno));
883 if (dp_read_errno != 0) {
885 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
886 strerror(dp_read_errno));
892 /* Load Wpcap, if possible */
896 init_cap_file(&cfile);
898 /* Assemble the compile-time version information string */
899 comp_info_str = g_string_new("Compiled ");
900 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
902 /* Assemble the run-time version information string */
903 runtime_info_str = g_string_new("Running ");
904 get_runtime_version_info(runtime_info_str, NULL);
906 /* Print format defaults to this. */
907 print_format = PR_FMT_TEXT;
909 /* Now get our args */
910 while ((opt = getopt(argc, argv, optstring)) != -1) {
912 case 'a': /* autostop criteria */
913 case 'b': /* Ringbuffer option */
914 case 'c': /* Capture xxx packets */
915 case 'f': /* capture filter */
916 case 'i': /* Use interface xxx */
917 case 'p': /* Don't capture in promiscuous mode */
918 case 's': /* Set the snapshot (capture) length */
919 case 'w': /* Write to capture file xxx */
920 case 'y': /* Set the pcap data link type */
922 case 'B': /* Buffer size */
925 status = capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
930 capture_option_specified = TRUE;
934 case 'd': /* Decode as rule */
935 if (!add_decode_as(optarg))
938 case 'D': /* Print a list of capture devices and exit */
940 status = capture_opts_list_interfaces();
943 capture_option_specified = TRUE;
948 out_file_type = wtap_short_string_to_file_type(optarg);
949 if (out_file_type < 0) {
950 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
951 list_capture_types();
955 case 'h': /* Print help and exit */
959 case 'l': /* "Line-buffer" standard output */
960 /* This isn't line-buffering, strictly speaking, it's just
961 flushing the standard output after the information for
962 each packet is printed; however, that should be good
963 enough for all the purposes to which "-l" is put (and
964 is probably actually better for "-V", as it does fewer
967 See the comment in "process_packet()" for an explanation of
968 why we do that, and why we don't just use "setvbuf()" to
969 make the standard output line-buffered (short version: in
970 Windows, "line-buffered" is the same as "fully-buffered",
971 and the output buffer is only flushed when it fills up). */
972 line_buffered = TRUE;
974 case 'L': /* Print list of link-layer types and exit */
976 list_link_layer_types = TRUE;
979 capture_option_specified = TRUE;
983 case 'n': /* No name resolution */
984 g_resolv_flags = RESOLV_NONE;
986 case 'N': /* Select what types of addresses/port #s to resolve */
987 if (g_resolv_flags == RESOLV_ALL)
988 g_resolv_flags = RESOLV_NONE;
989 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
990 if (badopt != '\0') {
991 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
996 case 'o': /* Override preference from command line */
997 switch (prefs_set_pref(optarg)) {
1002 case PREFS_SET_SYNTAX_ERR:
1003 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1007 case PREFS_SET_NO_SUCH_PREF:
1008 case PREFS_SET_OBSOLETE:
1009 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1014 case 'q': /* Quiet */
1017 case 'r': /* Read capture file xxx */
1018 cf_name = g_strdup(optarg);
1020 case 'R': /* Read file filter */
1023 case 'S': /* show packets in real time */
1024 print_packet_info = TRUE;
1026 case 't': /* Time stamp type */
1027 if (strcmp(optarg, "r") == 0)
1028 timestamp_set_type(TS_RELATIVE);
1029 else if (strcmp(optarg, "a") == 0)
1030 timestamp_set_type(TS_ABSOLUTE);
1031 else if (strcmp(optarg, "ad") == 0)
1032 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1033 else if (strcmp(optarg, "d") == 0)
1034 timestamp_set_type(TS_DELTA);
1035 else if (strcmp(optarg, "e") == 0)
1036 timestamp_set_type(TS_EPOCH);
1038 cmdarg_err("Invalid time stamp type \"%s\"",
1040 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1041 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1045 case 'T': /* printing Type */
1046 if (strcmp(optarg, "text") == 0) {
1047 output_action = WRITE_TEXT;
1048 print_format = PR_FMT_TEXT;
1049 } else if (strcmp(optarg, "ps") == 0) {
1050 output_action = WRITE_TEXT;
1051 print_format = PR_FMT_PS;
1052 } else if (strcmp(optarg, "pdml") == 0) {
1053 output_action = WRITE_XML;
1055 } else if (strcmp(optarg, "psml") == 0) {
1056 output_action = WRITE_XML;
1059 cmdarg_err("Invalid -T parameter.");
1060 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
1064 case 'v': /* Show version and exit */
1065 printf("TShark " VERSION "%s\n"
1072 svnversion, get_copyright_info(), comp_info_str->str,
1073 runtime_info_str->str);
1076 case 'V': /* Verbose */
1079 case 'x': /* Print packet data in hex (and ASCII) */
1085 /* We won't call the init function for the stat this soon
1086 as it would disallow MATE's fields (which are registered
1087 by the preferences set callback) from being used as
1088 part of a tap filter. Instead, we just add the argument
1089 to a list of stat arguments. */
1090 if (!process_stat_cmd_arg(optarg)) {
1091 cmdarg_err("invalid -z argument.");
1092 cmdarg_err_cont(" -z argument must be one of :");
1093 list_stat_cmd_args();
1098 case '?': /* Bad flag - print usage message */
1101 list_capture_types();
1111 /* If no capture filter or read filter has been specified, and there are
1112 still command-line arguments, treat them as the tokens of a capture
1113 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1114 flag was specified. */
1115 if (optind < argc) {
1116 if (cf_name != NULL) {
1117 if (rfilter != NULL) {
1118 cmdarg_err("Read filters were specified both with \"-R\" "
1119 "and with additional command-line arguments");
1122 rfilter = get_args_as_string(argc, argv, optind);
1125 if (capture_opts.has_cfilter) {
1126 cmdarg_err("Capture filters were specified both with \"-f\""
1127 " and with additional command-line arguments");
1130 capture_opts.has_cfilter = TRUE;
1131 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1133 capture_option_specified = TRUE;
1138 if (!capture_opts.saving_to_file) {
1139 /* We're not saving the capture to a file; if "-q" wasn't specified,
1140 we should print packet information */
1142 print_packet_info = TRUE;
1144 /* We're saving to a file; if we're writing to the standard output.
1145 and we'll also be writing dissected packets to the standard
1146 output, reject the request. At best, we could redirect that
1147 to the standard error; we *can't* write both to the standard
1148 output and have either of them be useful. */
1149 if (strcmp(capture_opts.save_file, "-") == 0 && print_packet_info) {
1150 cmdarg_err("You can't write both raw packet data and dissected packets"
1151 " to the standard output.");
1156 #ifndef HAVE_LIBPCAP
1157 if (capture_option_specified)
1158 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1165 /* We don't support capture filters when reading from a capture file
1166 (the BPF compiler doesn't support all link-layer types that we
1167 support in capture files we read). */
1169 if (cf_name != NULL) {
1170 if (capture_opts.has_cfilter) {
1171 cmdarg_err("Only read filters, not capture filters, "
1172 "can be specified when reading a capture file.");
1179 if (output_action != WRITE_TEXT) {
1180 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1186 if (list_link_layer_types) {
1187 /* We're supposed to list the link-layer types for an interface;
1188 did the user also specify a capture file to be read? */
1190 /* Yes - that's bogus. */
1191 cmdarg_err("You can't specify -L and a capture file to be read.");
1194 /* No - did they specify a ring buffer option? */
1195 if (capture_opts.multi_files_on) {
1196 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1200 /* If they didn't specify a "-w" flag, but specified a maximum capture
1201 file size, tell them that this doesn't work, and exit. */
1202 if (capture_opts.has_autostop_filesize && capture_opts.save_file == NULL) {
1203 cmdarg_err("Maximum capture file size specified, but "
1204 "capture isn't being saved to a file.");
1210 * "-r" was specified, so we're reading a capture file.
1211 * Capture options don't apply here.
1213 if (capture_opts.multi_files_on) {
1214 cmdarg_err("Multiple capture files requested, but "
1215 "a capture isn't being done.");
1218 if (capture_opts.has_file_duration) {
1219 cmdarg_err("Switching capture files after a time interval was specified, but "
1220 "a capture isn't being done.");
1223 if (capture_opts.has_ring_num_files) {
1224 cmdarg_err("A ring buffer of capture files was specified, but "
1225 "a capture isn't being done.");
1228 if (capture_opts.has_autostop_files) {
1229 cmdarg_err("A maximum number of capture files was specified, but "
1230 "a capture isn't being done.");
1233 if (capture_opts.has_autostop_packets) {
1234 cmdarg_err("A maximum number of captured packets was specified, but "
1235 "a capture isn't being done.");
1238 if (capture_opts.has_autostop_filesize) {
1239 cmdarg_err("A maximum capture file size was specified, but "
1240 "a capture isn't being done.");
1243 if (capture_opts.has_autostop_duration) {
1244 cmdarg_err("A maximum capture time was specified, but "
1245 "a capture isn't being done.");
1250 * "-r" wasn't specified, so we're doing a live capture.
1252 if (capture_opts.saving_to_file) {
1253 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1255 /* When capturing, we only support writing libpcap format. */
1256 if (out_file_type != WTAP_FILE_PCAP) {
1257 cmdarg_err("Live captures can only be saved in libpcap format.");
1260 if (capture_opts.multi_files_on) {
1261 /* Multiple-file mode works only under certain conditions:
1262 a) it doesn't work if you're writing to the standard output;
1263 b) it doesn't work if you're writing to a pipe;
1264 c) it makes no sense if the maximum file size is set to "infinite"
1265 (XXX - shouldn't that be "if there is no stop criterion",
1266 as you might want to switch files based on a packet count
1268 if (strcmp(capture_opts.save_file, "-") == 0) {
1269 cmdarg_err("Multiple capture files requested, but "
1270 "the capture is being written to the standard output.");
1273 if (capture_opts.output_to_pipe) {
1274 cmdarg_err("Multiple capture files requested, but "
1275 "the capture file is a pipe.");
1278 if (!capture_opts.has_autostop_filesize) {
1279 cmdarg_err("Multiple capture files requested, but "
1280 "no maximum capture file size was specified.");
1285 /* They didn't specify a "-w" flag, so we won't be saving to a
1286 capture file. Check for options that only make sense if
1287 we're saving to a file. */
1288 if (capture_opts.has_autostop_filesize) {
1289 cmdarg_err("Maximum capture file size specified, but "
1290 "capture isn't being saved to a file.");
1293 if (capture_opts.multi_files_on) {
1294 cmdarg_err("Multiple capture files requested, but "
1295 "the capture isn't being saved to a file.");
1304 /* Start windows sockets */
1305 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1308 /* Notify all registered modules that have had any of their preferences
1309 changed either from one of the preferences file or from the command
1310 line that their preferences have changed. */
1313 /* At this point MATE will have registered its field array so we can
1314 have a tap filter with one of MATE's late-registered fields as part
1315 of the filter. We can now process all the "-z" arguments. */
1316 start_requested_stats();
1318 /* disabled protocols as per configuration file */
1319 if (gdp_path == NULL && dp_path == NULL) {
1320 set_disabled_protos_list();
1323 /* Build the column format array */
1324 col_setup(&cfile.cinfo, prefs->num_cols);
1325 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1326 cfile.cinfo.col_fmt[i] = get_column_format(i);
1327 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1328 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1330 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1331 cfile.cinfo.col_data[i] = NULL;
1332 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1333 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1335 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1336 cfile.cinfo.col_fence[i] = 0;
1337 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1338 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1341 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1344 for (j = 0; j < NUM_COL_FMTS; j++) {
1345 if (!cfile.cinfo.fmt_matx[i][j])
1348 if (cfile.cinfo.col_first[j] == -1)
1349 cfile.cinfo.col_first[j] = i;
1350 cfile.cinfo.col_last[j] = i;
1355 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1356 capture_opts_trim_ring_num_files(&capture_opts);
1359 if (rfilter != NULL) {
1360 if (!dfilter_compile(rfilter, &rfcode)) {
1361 cmdarg_err("%s", dfilter_error_msg);
1363 #ifdef HAVE_PCAP_OPEN_DEAD
1367 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1369 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1371 " Note: That display filter code looks like a valid capture filter;");
1373 " maybe you mixed them up?");
1382 cfile.rfcode = rfcode;
1384 if (print_packet_info) {
1385 /* If we're printing as text or PostScript, we have
1386 to create a print stream. */
1387 if (output_action == WRITE_TEXT) {
1388 switch (print_format) {
1391 print_stream = print_stream_text_stdio_new(stdout);
1395 print_stream = print_stream_ps_stdio_new(stdout);
1399 g_assert_not_reached();
1404 /* We have to dissect each packet if:
1406 we're printing information about each packet;
1408 we're using a read filter on the packets;
1410 we're using any taps. */
1411 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1415 * We're reading a capture file.
1419 * Immediately relinquish any special privileges we have; we must not
1420 * be allowed to read any capture files the user running TShark
1423 relinquish_special_privs_perm();
1425 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1430 /* Set timestamp precision; there should arguably be a command-line
1431 option to let the user set this. */
1432 switch(wtap_file_tsprecision(cfile.wth)) {
1433 case(WTAP_FILE_TSPREC_SEC):
1434 timestamp_set_precision(TS_PREC_AUTO_SEC);
1436 case(WTAP_FILE_TSPREC_DSEC):
1437 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1439 case(WTAP_FILE_TSPREC_CSEC):
1440 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1442 case(WTAP_FILE_TSPREC_MSEC):
1443 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1445 case(WTAP_FILE_TSPREC_USEC):
1446 timestamp_set_precision(TS_PREC_AUTO_USEC);
1448 case(WTAP_FILE_TSPREC_NSEC):
1449 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1452 g_assert_not_reached();
1455 /* Process the packets in the file */
1456 err = load_cap_file(&cfile, capture_opts.save_file, out_file_type);
1463 /* No capture file specified, so we're supposed to do a live capture
1464 (or get a list of link-layer types for a live capture device);
1465 do we have support for live captures? */
1472 cmdarg_err("WinPcap couldn't be found.");
1473 detailed_err = cant_load_winpcap_err("TShark");
1474 cmdarg_err_cont("%s", detailed_err);
1475 g_free(detailed_err);
1480 /* trim the interface name and exit if that failed */
1481 if (!capture_opts_trim_iface(&capture_opts,
1482 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1486 /* if requested, list the link layer types and exit */
1487 if (list_link_layer_types) {
1488 status = capture_opts_list_link_layer_types(&capture_opts);
1492 if (!print_packet_info && !quiet) {
1494 * We're not printing information for each packet, and the user
1495 * didn't ask us not to print a count of packets as they arrive,
1496 * so print that count so the user knows that packets are arriving.
1498 * XXX - what if the user wants to do a live capture, doesn't want
1499 * to save it to a file, doesn't want information printed for each
1500 * packet, does want some "-z" statistic, and wants packet counts
1501 * so they know whether they're seeing any packets?
1503 print_packet_counts = TRUE;
1506 /* For now, assume libpcap gives microsecond precision. */
1507 timestamp_set_precision(TS_PREC_AUTO_USEC);
1511 if (capture_opts.multi_files_on) {
1515 /* No - complain. */
1516 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1521 draw_tap_listeners(TRUE);
1522 funnel_dump_all_text_windows();
1529 /* Do the low-level work of a capture.
1530 Returns TRUE if it succeeds, FALSE otherwise. */
1532 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1538 int volatile volatile_err = 0;
1539 int volatile inpkts = 0;
1541 condition *volatile cnd_autostop_size = NULL;
1542 condition *volatile cnd_autostop_duration = NULL;
1545 void (*oldhandler)(int);
1547 struct pcap_stat stats;
1550 gboolean cfilter_error = FALSE;
1551 char errmsg[1024+1];
1552 char secondary_errmsg[4096+1];
1555 /* Initialize all data structures used for dissection. */
1558 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1560 ld.packet_cb = capture_pcap_cb;
1563 /* open the "input file" from network interface or capture pipe */
1564 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg),
1565 secondary_errmsg, sizeof(secondary_errmsg))) {
1570 * We've opened the capture device, so we shouldn't need any special
1571 * privileges any more; relinquish those privileges.
1573 * XXX - if we have saved set-user-ID support, we should give up those
1574 * privileges immediately, and then reclaim them long enough to get
1575 * a list of network interfaces and to open one, and then give them
1576 * up again, so that stuff we do while processing the argument list,
1577 * reading the user's preferences, loading and starting plugins
1578 * (especially *user* plugins), etc. is done with the user's privileges,
1579 * not special privileges.
1581 relinquish_special_privs_perm();
1583 /* init the input filter from the network interface (capture pipe will do nothing) */
1584 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts.iface, capture_opts.cfilter)) {
1586 case INITFILTER_NO_ERROR:
1589 case INITFILTER_BAD_FILTER:
1590 cfilter_error = TRUE;
1591 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1592 *secondary_errmsg = '\0';
1595 case INITFILTER_OTHER_ERROR:
1596 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1597 pcap_geterr(ld.pcap_h));
1598 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1602 if (capture_opts.saving_to_file) {
1603 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1604 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1605 *secondary_errmsg = '\0';
1609 /* set up to write to the already-opened capture output file/files */
1610 if(!capture_loop_init_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg)) {
1611 *secondary_errmsg = '\0';
1615 /* Save the capture file name. */
1616 ld.save_file = capture_opts.save_file;
1619 ld.wtap_linktype = wtap_pcap_encap_to_wtap_encap(ld.linktype);
1622 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1623 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1625 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1627 XXX - deal with signal semantics on various UNIX platforms. Or just
1628 use "sigaction()" and be done with it? */
1629 signal(SIGTERM, capture_cleanup);
1630 signal(SIGINT, capture_cleanup);
1631 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1632 signal(SIGHUP, oldhandler);
1635 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1636 quiet mode, report the number of packets we've captured. */
1637 signal(SIGINFO, report_counts_siginfo);
1638 #endif /* SIGINFO */
1641 /* Let the user know what interface was chosen. */
1642 descr = get_interface_descriptive_name(capture_opts.iface);
1643 fprintf(stderr, "Capturing on %s\n", descr);
1646 /* initialize capture stop conditions */
1647 init_capture_stop_conditions();
1648 /* create stop conditions */
1649 if (capture_opts.has_autostop_filesize)
1650 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1651 (long)capture_opts.autostop_filesize * 1024);
1652 if (capture_opts.has_autostop_duration)
1653 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1654 (gint32)capture_opts.autostop_duration);
1656 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1657 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT, capture_opts.file_duration);
1659 if (!setjmp(ld.stopenv)) {
1661 ld.packet_count = 0;
1666 /* We need to be careful with automatic variables defined in the
1667 outer scope which are changed inside the loop. Most compilers
1668 don't try to roll them back to their original values after the
1669 longjmp which causes the loop to finish, but all that the
1670 standards say is that their values are indeterminate. If we
1671 don't want them to be rolled back, we should define them with the
1672 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1673 Programming in the UNIX Environment, p. 178).
1675 The "err" variable causes a particular problem. If we give it
1676 the volatile attribute, then when we pass a reference to it (as
1677 in "&err") to a function, GCC warns: "passing arg <n> of
1678 <function> discards qualifiers from pointer target type".
1679 Therefore within the loop and just beyond we don't use "err".
1680 Within the loop we define "loop_err", and assign its value to
1681 "volatile_err", which is in the outer scope and is checked when
1684 We also define "packet_count_prev" here to keep things tidy,
1685 since it's used only inside the loop. If it were defined in the
1686 outer scope, GCC would give a warning (unnecessary in this case)
1687 that it might be clobbered, and we'd need to give it the volatile
1688 attribute to suppress the warning. */
1691 int packet_count_prev = 0;
1693 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1694 /* We're not stopping at a particular capture file size, and we're
1695 not stopping after some particular amount of time has expired,
1696 so either we have no stop condition or the only stop condition
1697 is a maximum packet count.
1699 If there's no maximum packet count, pass it -1, meaning "until
1700 you run out of packets in the bufferful you read". Otherwise,
1701 pass it the number of packets we have left to capture.
1703 We don't call "pcap_loop()" as, if we're saving to a file that's
1704 a FIFO, we want to flush the FIFO after we're done processing
1705 this libpcap bufferful of packets, so that the program
1706 reading the FIFO sees the packets immediately and doesn't get
1707 any partial packet, forcing it to block in the middle of reading
1709 if (capture_opts.autostop_packets == 0)
1712 if (ld.packet_count >= capture_opts.autostop_packets) {
1713 /* XXX do we need this test here? */
1714 /* It appears there's nothing more to capture. */
1717 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1720 /* We need to check the capture file size or the timeout after
1725 inpkts = capture_loop_dispatch(NULL, &ld, errmsg, sizeof errmsg);
1727 /* Error from "pcap_dispatch()", or error or "no more packets" from
1728 "cap_pipe_dispatch(). */
1730 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1731 /* The specified capture time has elapsed; stop the capture. */
1733 } else if (inpkts > 0) {
1734 if (capture_opts.autostop_packets != 0 &&
1735 ld.packet_count >= capture_opts.autostop_packets) {
1736 /* The specified number of packets have been captured and have
1737 passed both any capture filter in effect and any read filter
1740 } else if (cnd_autostop_size != NULL &&
1741 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)) {
1742 /* We're saving the capture to a file, and the capture file reached
1743 its maximum size. */
1744 if (capture_opts.multi_files_on) {
1745 /* Switch to the next ringbuffer file */
1746 if (ringbuf_switch_file(&ld.pdh, &capture_opts.save_file,
1747 &save_file_fd, &ld.bytes_written,
1749 /* File switch succeeded: reset the condition */
1750 cnd_reset(cnd_autostop_size);
1751 if (cnd_file_duration) {
1752 cnd_reset(cnd_file_duration);
1755 /* File switch failed: stop here */
1756 volatile_err = loop_err;
1760 /* No ringbuffer - just stop. */
1764 if (capture_opts.output_to_pipe) {
1765 if (ld.packet_count > packet_count_prev) {
1766 libpcap_dump_flush(ld.pdh, NULL);
1767 packet_count_prev = ld.packet_count;
1771 } /* while (ld.go) */
1773 /* delete stop conditions */
1774 if (cnd_autostop_size != NULL)
1775 cnd_delete(cnd_autostop_size);
1776 if (cnd_autostop_duration != NULL)
1777 cnd_delete(cnd_autostop_duration);
1778 if (cnd_file_duration != NULL)
1779 cnd_delete(cnd_file_duration);
1781 if (print_packet_counts) {
1782 /* We're printing packet counts to stderr.
1783 Send a newline so that we move to the line after the packet count. */
1784 fprintf(stderr, "\n");
1787 /* If we got an error while capturing, report it. */
1789 if (ld.from_cap_pipe) {
1790 if (ld.cap_pipe_err == PIPERR) {
1791 cmdarg_err("Error while capturing packets: %s", errmsg);
1794 cmdarg_err("Error while capturing packets: %s", pcap_geterr(ld.pcap_h));
1798 if (volatile_err == 0)
1801 show_capture_file_io_error(capture_opts.save_file, volatile_err, FALSE);
1805 if (capture_opts.save_file != NULL) {
1806 /* We're saving to a file or files; close all files. */
1807 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1809 /* If we've displayed a message about a write error, there's no point
1810 in displaying another message about an error on close. */
1811 if (!close_ok && write_ok)
1812 show_capture_file_io_error(capture_opts.save_file, err, TRUE);
1815 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1816 eth_close(ld.cap_pipe_fd);
1818 /* Get the capture statistics, and, if any packets were dropped, report
1820 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1821 if (stats.ps_drop != 0) {
1822 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1825 cmdarg_err("Can't get packet-drop statistics: %s", pcap_geterr(ld.pcap_h));
1827 pcap_close(ld.pcap_h);
1830 /* Report the number of captured packets if not reported during capture
1831 and we are saving to a file. */
1837 if (capture_opts.multi_files_on) {
1838 ringbuf_error_cleanup();
1840 g_free(capture_opts.save_file);
1841 capture_opts.save_file = NULL;
1842 if (cfilter_error) {
1843 dfilter_t *rfcode = NULL;
1844 if (dfilter_compile(capture_opts.cfilter, &rfcode) && rfcode != NULL) {
1846 "Invalid capture filter: \"%s\"!\n"
1848 "That string looks like a valid display filter; however, it isn't a valid\n"
1849 "capture filter (%s).\n"
1851 "Note that display filters and capture filters don't have the same syntax,\n"
1852 "so you can't use most display filter expressions as capture filters.\n"
1854 "See the User's Guide for a description of the capture filter syntax.",
1855 capture_opts.cfilter, errmsg);
1856 dfilter_free(rfcode);
1859 "Invalid capture filter: \"%s\"!\n"
1861 "That string isn't a valid capture filter (%s).\n"
1862 "See the User's Guide for a description of the capture filter syntax.",
1863 capture_opts.cfilter, errmsg);
1866 cmdarg_err("%s", errmsg);
1867 if (*secondary_errmsg != '\0') {
1868 fprintf(stderr, "\n");
1869 cmdarg_err_cont("%s", secondary_errmsg);
1872 if (ld.from_cap_pipe) {
1873 if (ld.cap_pipe_fd >= 0)
1874 eth_close(ld.cap_pipe_fd);
1876 if (ld.pcap_h != NULL)
1877 pcap_close(ld.pcap_h);
1884 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1887 struct wtap_pkthdr whdr;
1888 union wtap_pseudo_header pseudo_header;
1889 const guchar *wtap_pd;
1890 loop_data *ld = (loop_data *) user;
1894 gboolean packet_accepted;
1898 * Prevent a SIGINFO handler from writing to stdout while we're
1899 * doing so; instead, have it just set a flag telling us to print
1900 * that information when we're done.
1903 #endif /* SIGINFO */
1905 /* The current packet may have arrived after a very long silence,
1906 * way past the time to switch files. In order not to have
1907 * the first packet of a new series of events as the last
1908 * [or only] packet in the file, switch before writing!
1910 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1911 /* time elapsed for this ring file, switch to the next */
1912 if (ringbuf_switch_file(&ld->pdh, &ld->save_file, &save_file_fd,
1913 &ld->bytes_written, &loop_err)) {
1914 /* File switch succeeded: reset the condition */
1915 cnd_reset(cnd_file_duration);
1917 /* File switch failed: stop here */
1918 /* XXX - we should do something with "loop_err" */
1923 if (do_dissection) {
1924 /* We're goint to print packet information, run a read filter, or
1925 process taps. Use process_packet() to handle that; in order
1926 to do that, we need to convert from libpcap to Wiretap format.
1927 If that fails, ignore the packet (wtap_process_pcap_packet has
1928 written an error message). */
1929 wtap_pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd,
1930 &pseudo_header, &whdr, &err);
1931 if (wtap_pd == NULL)
1934 packet_accepted = process_packet(&cfile, 0, &whdr, &pseudo_header, wtap_pd);
1936 /* We're just writing out packets. */
1937 packet_accepted = TRUE;
1940 if (packet_accepted) {
1941 /* Count this packet. */
1946 if (ld->pdh != NULL) {
1947 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
1948 /* Error writing to a capture file */
1949 if (print_packet_counts) {
1950 /* We're printing counts of packets captured; move to the line after
1952 fprintf(stderr, "\n");
1954 show_capture_file_io_error(ld->save_file, err, FALSE);
1955 pcap_close(ld->pcap_h);
1956 libpcap_dump_close(ld->pdh, &err);
1960 if (print_packet_counts) {
1961 /* We're printing packet counts. */
1962 if (ld->packet_count != 0) {
1963 fprintf(stderr, "\r%u ", ld->packet_count);
1964 /* stderr could be line buffered */
1972 * Allow SIGINFO handlers to write.
1977 * If a SIGINFO handler asked us to write out capture counts, do so.
1981 #endif /* SIGINFO */
1986 capture_cleanup(DWORD ctrltype _U_)
1988 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1989 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1990 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1991 like SIGTERM at least when the machine's shutting down.
1993 For now, we handle them all as indications that we should clean up
1994 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1997 However, as handlers run in a new thread, we can't just longjmp
1998 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1999 no other handler - such as one that would terminate the process -
2002 XXX - for some reason, typing ^C to TShark, if you run this in
2003 a Cygwin console window in at least some versions of Cygwin,
2004 causes TShark to terminate immediately; this routine gets
2005 called, but the main loop doesn't get a chance to run and
2006 exit cleanly, at least if this is compiled with Microsoft Visual
2007 C++ (i.e., it's a property of the Cygwin console window or Bash;
2008 it happens if TShark is not built with Cygwin - for all I know,
2009 building it with Cygwin may make the problem go away). */
2015 capture_cleanup(int signum _U_)
2017 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2018 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2019 "ld.go" to FALSE and return, we won't break out of it and quit
2021 longjmp(ld.stopenv, 1);
2029 /* XXX - if we use sigaction, this doesn't have to be done.
2030 (Yes, this isn't necessary on BSD, but just in case a system
2031 where "signal()" has AT&T semantics adopts SIGINFO....) */
2032 signal(SIGINFO, report_counts_siginfo);
2033 #endif /* SIGINFO */
2035 if (!print_packet_counts) {
2036 /* Report the count only if we aren't printing a packet count
2037 as packets arrive. */
2038 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2041 infoprint = FALSE; /* we just reported it */
2042 #endif /* SIGINFO */
2047 report_counts_siginfo(int signum _U_)
2049 int sav_errno = errno;
2050 /* If we've been told to delay printing, just set a flag asking
2051 that we print counts (if we're supposed to), otherwise print
2052 the count of packets captured (if we're supposed to). */
2059 #endif /* SIGINFO */
2060 #endif /* HAVE_LIBPCAP */
2063 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
2066 int snapshot_length;
2071 char *save_file_string = NULL;
2073 linktype = wtap_file_encap(cf->wth);
2074 if (save_file != NULL) {
2075 /* Get a string that describes what we're writing to */
2076 save_file_string = output_file_description(save_file);
2078 /* Set up to write to the capture file. */
2079 snapshot_length = wtap_snapshot_length(cf->wth);
2080 if (snapshot_length == 0) {
2081 /* Snapshot length of input file not known. */
2082 snapshot_length = WTAP_MAX_PACKET_SIZE;
2084 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2085 FALSE /* compressed */, &err);
2088 /* We couldn't set up to write to the capture file. */
2091 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2092 cmdarg_err("Capture files can't be written in that format.");
2095 case WTAP_ERR_UNSUPPORTED_ENCAP:
2096 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2097 cmdarg_err("The capture file being read can't be written in "
2101 case WTAP_ERR_CANT_OPEN:
2102 cmdarg_err("The %s couldn't be created for some "
2103 "unknown reason.", save_file_string);
2106 case WTAP_ERR_SHORT_WRITE:
2107 cmdarg_err("A full header couldn't be written to the %s.",
2112 cmdarg_err("The %s could not be created: %s.", save_file_string,
2113 wtap_strerror(err));
2119 if (print_packet_info) {
2120 if (!write_preamble(cf)) {
2122 show_print_file_io_error(err);
2128 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2129 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2130 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2131 /* Either there's no read filtering or this packet passed the
2132 filter, so, if we're writing to a capture file, write
2135 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2136 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2138 /* Error writing to a capture file */
2139 show_capture_file_io_error(save_file, err, FALSE);
2140 wtap_dump_close(pdh, &err);
2147 /* Print a message noting that the read failed somewhere along the line. */
2150 case WTAP_ERR_UNSUPPORTED_ENCAP:
2151 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2152 cf->filename, err_info);
2155 case WTAP_ERR_CANT_READ:
2156 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2160 case WTAP_ERR_SHORT_READ:
2161 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2165 case WTAP_ERR_BAD_RECORD:
2166 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2167 cf->filename, err_info);
2171 cmdarg_err("An error occurred while reading \"%s\": %s.",
2172 cf->filename, wtap_strerror(err));
2175 if (save_file != NULL) {
2176 /* Now close the capture file. */
2177 if (!wtap_dump_close(pdh, &err))
2178 show_capture_file_io_error(save_file, err, TRUE);
2181 if (save_file != NULL) {
2182 /* Now close the capture file. */
2183 if (!wtap_dump_close(pdh, &err))
2184 show_capture_file_io_error(save_file, err, TRUE);
2186 if (print_packet_info) {
2187 if (!write_finale()) {
2189 show_print_file_io_error(err);
2196 wtap_close(cf->wth);
2199 if (save_file_string != NULL)
2200 g_free(save_file_string);
2206 fill_in_fdata(frame_data *fdata, capture_file *cf,
2207 const struct wtap_pkthdr *phdr, gint64 offset)
2212 fdata->num = cf->count;
2213 fdata->pkt_len = phdr->len;
2214 cum_bytes += phdr->len;
2215 fdata->cum_bytes = cum_bytes;
2216 fdata->cap_len = phdr->caplen;
2217 fdata->file_off = offset;
2218 fdata->lnk_t = phdr->pkt_encap;
2219 fdata->abs_ts = *((nstime_t *) &phdr->ts);
2220 fdata->flags.passed_dfilter = 0;
2221 fdata->flags.encoding = CHAR_ASCII;
2222 fdata->flags.visited = 0;
2223 fdata->flags.marked = 0;
2224 fdata->flags.ref_time = 0;
2225 fdata->color_filter = NULL;
2227 /* If we don't have the time stamp of the first packet in the
2228 capture, it's because this is the first packet. Save the time
2229 stamp of this packet as the time stamp of the first packet. */
2230 if (nstime_is_zero(&first_ts)) {
2231 first_ts = fdata->abs_ts;
2234 /* If we don't have the time stamp of the previous displayed packet,
2235 it's because this is the first displayed packet. Save the time
2236 stamp of this packet as the time stamp of the previous displayed
2238 if (nstime_is_zero(&prev_ts)) {
2239 prev_ts = fdata->abs_ts;
2242 /* Get the time elapsed between the first packet and this packet. */
2243 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2245 /* If it's greater than the current elapsed time, set the elapsed time
2246 to it (we check for "greater than" so as not to be confused by
2247 time moving backwards). */
2248 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2249 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2250 cf->elapsed_time = fdata->rel_ts;
2253 /* Get the time elapsed between the previous displayed packet and
2255 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2256 prev_ts = fdata->abs_ts;
2259 /* Free up all data attached to a "frame_data" structure. */
2261 clear_fdata(frame_data *fdata)
2264 g_slist_free(fdata->pfd);
2268 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2269 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2272 gboolean create_proto_tree;
2273 epan_dissect_t *edt;
2276 /* Count this packet. */
2279 /* If we're going to print packet information, or we're going to
2280 run a read filter, or we're going to process taps, set up to
2281 do a dissection and do so. */
2282 if (do_dissection) {
2283 fill_in_fdata(&fdata, cf, whdr, offset);
2285 if (print_packet_info) {
2286 /* Grab any resolved addresses */
2288 if (g_resolv_flags) {
2289 host_name_lookup_process(NULL);
2294 if (cf->rfcode || verbose || num_tap_filters!=0)
2295 create_proto_tree = TRUE;
2297 create_proto_tree = FALSE;
2298 /* The protocol tree will be "visible", i.e., printed, only if we're
2299 printing packet details, which is true if we're printing stuff
2300 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2302 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2304 /* If we're running a read filter, prime the epan_dissect_t with that
2307 epan_dissect_prime_dfilter(edt, cf->rfcode);
2309 tap_queue_init(edt);
2311 /* We only need the columns if we're printing packet info but we're
2312 *not* verbose; in verbose mode, we print the protocol tree, not
2313 the protocol summary. */
2314 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2315 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2317 tap_push_tapped_queue(edt);
2319 /* Run the read filter if we have one. */
2321 passed = dfilter_apply_edt(cf->rfcode, edt);
2325 /* We're not running a display filter and we're not printing any
2326 packet information, so we don't need to do a dissection, and all
2327 packets are processed. */
2333 /* Process this packet. */
2334 if (print_packet_info) {
2335 /* We're printing packet information; print the information for
2337 print_packet(cf, edt);
2339 /* The ANSI C standard does not appear to *require* that a line-buffered
2340 stream be flushed to the host environment whenever a newline is
2341 written, it just says that, on such a stream, characters "are
2342 intended to be transmitted to or from the host environment as a
2343 block when a new-line character is encountered".
2345 The Visual C++ 6.0 C implementation doesn't do what is intended;
2346 even if you set a stream to be line-buffered, it still doesn't
2347 flush the buffer at the end of every line.
2349 So, if the "-l" flag was specified, we flush the standard output
2350 at the end of a packet. This will do the right thing if we're
2351 printing packet summary lines, and, as we print the entire protocol
2352 tree for a single packet without waiting for anything to happen,
2353 it should be as good as line-buffered mode if we're printing
2354 protocol trees. (The whole reason for the "-l" flag in either
2355 tcpdump or TShark is to allow the output of a live capture to
2356 be piped to a program or script and to have that script see the
2357 information for the packet as soon as it's printed, rather than
2358 having to wait until a standard I/O buffer fills up. */
2362 if (ferror(stdout)) {
2363 show_print_file_io_error(errno);
2369 if (do_dissection) {
2370 epan_dissect_free(edt);
2371 clear_fdata(&fdata);
2377 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2379 char *save_file_string;
2381 save_file_string = output_file_description(fname);
2386 cmdarg_err("Not all the packets could be written to the %s because there is "
2387 "no space left on the file system.",
2393 cmdarg_err("Not all the packets could be written to the %s because you are "
2394 "too close to, or over your disk quota.",
2399 case WTAP_ERR_CANT_CLOSE:
2400 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2404 case WTAP_ERR_SHORT_WRITE:
2405 cmdarg_err("Not all the packets could be written to the %s.",
2411 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2412 wtap_strerror(err));
2414 cmdarg_err("An error occurred while writing to the %s: %s.",
2415 save_file_string, wtap_strerror(err));
2419 g_free(save_file_string);
2423 write_preamble(capture_file *cf)
2425 switch (output_action) {
2428 return print_preamble(print_stream, cf->filename);
2433 write_pdml_preamble(stdout);
2435 write_psml_preamble(stdout);
2436 return !ferror(stdout);
2439 g_assert_not_reached();
2445 get_line_buf(size_t len)
2447 static char *line_bufp = NULL;
2448 static size_t line_buf_len = 256;
2449 size_t new_line_buf_len;
2451 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2452 new_line_buf_len *= 2)
2454 if (line_bufp == NULL) {
2455 line_buf_len = new_line_buf_len;
2456 line_bufp = g_malloc(line_buf_len + 1);
2458 if (new_line_buf_len > line_buf_len) {
2459 line_buf_len = new_line_buf_len;
2460 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2467 print_columns(capture_file *cf)
2474 line_bufp = get_line_buf(256);
2477 for (i = 0; i < cf->cinfo.num_cols; i++) {
2478 switch (cf->cinfo.col_fmt[i]) {
2482 * Don't print this if we're doing a live capture from a network
2483 * interface - if we're doing a live capture, you won't be
2484 * able to look at the capture in the future (it's not being
2485 * saved anywhere), so the frame numbers are unlikely to be
2488 * (XXX - it might be nice to be able to save and print at
2489 * the same time, sort of like an "Update list of packets
2490 * in real time" capture in Wireshark.)
2492 if (capture_opts.iface != NULL)
2495 column_len = strlen(cf->cinfo.col_data[i]);
2498 line_bufp = get_line_buf(buf_offset + column_len);
2499 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2505 case COL_ABS_DATE_TIME: /* XXX - wider */
2506 column_len = strlen(cf->cinfo.col_data[i]);
2507 if (column_len < 10)
2509 line_bufp = get_line_buf(buf_offset + column_len);
2510 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2516 case COL_DEF_DL_SRC:
2517 case COL_RES_DL_SRC:
2518 case COL_UNRES_DL_SRC:
2519 case COL_DEF_NET_SRC:
2520 case COL_RES_NET_SRC:
2521 case COL_UNRES_NET_SRC:
2522 column_len = strlen(cf->cinfo.col_data[i]);
2523 if (column_len < 12)
2525 line_bufp = get_line_buf(buf_offset + column_len);
2526 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2532 case COL_DEF_DL_DST:
2533 case COL_RES_DL_DST:
2534 case COL_UNRES_DL_DST:
2535 case COL_DEF_NET_DST:
2536 case COL_RES_NET_DST:
2537 case COL_UNRES_NET_DST:
2538 column_len = strlen(cf->cinfo.col_data[i]);
2539 if (column_len < 12)
2541 line_bufp = get_line_buf(buf_offset + column_len);
2542 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2546 column_len = strlen(cf->cinfo.col_data[i]);
2547 line_bufp = get_line_buf(buf_offset + column_len);
2548 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2551 buf_offset += column_len;
2552 if (i != cf->cinfo.num_cols - 1) {
2554 * This isn't the last column, so we need to print a
2555 * separator between this column and the next.
2557 * If we printed a network source and are printing a
2558 * network destination of the same type next, separate
2559 * them with "->"; if we printed a network destination
2560 * and are printing a network source of the same type
2561 * next, separate them with "<-"; otherwise separate them
2564 * We add enough space to the buffer for " <- " or " -> ",
2565 * even if we're only adding " ".
2567 line_bufp = get_line_buf(buf_offset + 4);
2568 switch (cf->cinfo.col_fmt[i]) {
2573 switch (cf->cinfo.col_fmt[i + 1]) {
2578 strcat(line_bufp + buf_offset, " -> ");
2583 strcat(line_bufp + buf_offset, " ");
2589 case COL_DEF_DL_SRC:
2590 case COL_RES_DL_SRC:
2591 case COL_UNRES_DL_SRC:
2592 switch (cf->cinfo.col_fmt[i + 1]) {
2594 case COL_DEF_DL_DST:
2595 case COL_RES_DL_DST:
2596 case COL_UNRES_DL_DST:
2597 strcat(line_bufp + buf_offset, " -> ");
2602 strcat(line_bufp + buf_offset, " ");
2608 case COL_DEF_NET_SRC:
2609 case COL_RES_NET_SRC:
2610 case COL_UNRES_NET_SRC:
2611 switch (cf->cinfo.col_fmt[i + 1]) {
2613 case COL_DEF_NET_DST:
2614 case COL_RES_NET_DST:
2615 case COL_UNRES_NET_DST:
2616 strcat(line_bufp + buf_offset, " -> ");
2621 strcat(line_bufp + buf_offset, " ");
2630 switch (cf->cinfo.col_fmt[i + 1]) {
2635 strcat(line_bufp + buf_offset, " <- ");
2640 strcat(line_bufp + buf_offset, " ");
2646 case COL_DEF_DL_DST:
2647 case COL_RES_DL_DST:
2648 case COL_UNRES_DL_DST:
2649 switch (cf->cinfo.col_fmt[i + 1]) {
2651 case COL_DEF_DL_SRC:
2652 case COL_RES_DL_SRC:
2653 case COL_UNRES_DL_SRC:
2654 strcat(line_bufp + buf_offset, " <- ");
2659 strcat(line_bufp + buf_offset, " ");
2665 case COL_DEF_NET_DST:
2666 case COL_RES_NET_DST:
2667 case COL_UNRES_NET_DST:
2668 switch (cf->cinfo.col_fmt[i + 1]) {
2670 case COL_DEF_NET_SRC:
2671 case COL_RES_NET_SRC:
2672 case COL_UNRES_NET_SRC:
2673 strcat(line_bufp + buf_offset, " <- ");
2678 strcat(line_bufp + buf_offset, " ");
2685 strcat(line_bufp + buf_offset, " ");
2691 return print_line(print_stream, 0, line_bufp);
2695 print_packet(capture_file *cf, epan_dissect_t *edt)
2697 print_args_t print_args;
2700 /* Print the information in the protocol tree. */
2701 switch (output_action) {
2704 print_args.to_file = TRUE;
2705 print_args.format = print_format;
2706 print_args.print_summary = !verbose;
2707 print_args.print_hex = verbose && print_hex;
2708 print_args.print_formfeed = FALSE;
2709 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2711 /* init the packet range */
2712 packet_range_init(&print_args.range);
2714 if (!proto_tree_print(&print_args, edt, print_stream))
2717 /* "print_hex_data()" will put out a leading blank line, as well
2718 as a trailing one; print one here, to separate the packets,
2719 only if "print_hex_data()" won't be called. */
2720 if (!print_line(print_stream, 0, ""))
2726 proto_tree_write_pdml(edt, stdout);
2728 return !ferror(stdout);
2731 /* Just fill in the columns. */
2732 epan_dissect_fill_in_columns(edt);
2734 /* Now print them. */
2735 switch (output_action) {
2738 if (!print_columns(cf))
2743 proto_tree_write_psml(edt, stdout);
2744 return !ferror(stdout);
2748 if (!print_hex_data(print_stream, edt))
2750 if (!print_line(print_stream, 0, ""))
2759 switch (output_action) {
2762 return print_finale(print_stream);
2767 write_pdml_finale(stdout);
2769 write_psml_finale(stdout);
2770 return !ferror(stdout);
2773 g_assert_not_reached();
2779 show_print_file_io_error(int err)
2784 cmdarg_err("Not all the packets could be printed because there is "
2785 "no space left on the file system.");
2790 cmdarg_err("Not all the packets could be printed because you are "
2791 "too close to, or over your disk quota.");
2796 cmdarg_err("An error occurred while printing packets: %s.",
2803 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2807 static char errmsg_errno[1024+1];
2810 /* Wiretap error. */
2813 case WTAP_ERR_NOT_REGULAR_FILE:
2814 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2817 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2818 /* Seen only when opening a capture file for reading. */
2819 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2822 case WTAP_ERR_UNSUPPORTED:
2823 /* Seen only when opening a capture file for reading. */
2824 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2825 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2828 errmsg = errmsg_errno;
2831 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2832 /* Seen only when opening a capture file for writing. */
2833 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2834 "The file \"%%s\" is a pipe, and %s capture files can't be "
2835 "written to a pipe.", wtap_file_type_string(file_type));
2836 errmsg = errmsg_errno;
2839 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2840 /* Seen only when opening a capture file for writing. */
2841 errmsg = "TShark doesn't support writing capture files in that format.";
2844 case WTAP_ERR_UNSUPPORTED_ENCAP:
2846 errmsg = "TShark can't save this capture in that format.";
2848 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2849 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
2852 errmsg = errmsg_errno;
2856 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2858 errmsg = "TShark can't save this capture in that format.";
2860 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
2863 case WTAP_ERR_BAD_RECORD:
2864 /* Seen only when opening a capture file for reading. */
2865 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2866 "The file \"%%s\" appears to be damaged or corrupt.\n"
2869 errmsg = errmsg_errno;
2872 case WTAP_ERR_CANT_OPEN:
2874 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2876 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2879 case WTAP_ERR_SHORT_READ:
2880 errmsg = "The file \"%s\" appears to have been cut short"
2881 " in the middle of a packet or other data.";
2884 case WTAP_ERR_SHORT_WRITE:
2885 errmsg = "A full header couldn't be written to the file \"%s\".";
2889 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2890 "The file \"%%s\" could not be %s: %s.",
2891 for_writing ? "created" : "opened",
2892 wtap_strerror(err));
2893 errmsg = errmsg_errno;
2897 errmsg = file_open_error_message(err, for_writing);
2902 * Open/create errors are reported with an console message in TShark.
2905 open_failure_message(const char *filename, int err, gboolean for_writing)
2907 fprintf(stderr, "tshark: ");
2908 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2909 fprintf(stderr, "\n");
2913 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2917 char err_msg[2048+1];
2919 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2923 /* The open succeeded. Fill in the information for this file. */
2925 /* Initialize all data structures used for dissection. */
2929 cf->f_datalen = 0; /* not used, but set it anyway */
2931 /* Set the file name because we need it to set the follow stream filter.
2932 XXX - is that still true? We need it for other reasons, though,
2934 cf->filename = g_strdup(fname);
2936 /* Indicate whether it's a permanent or temporary file. */
2937 cf->is_tempfile = is_tempfile;
2939 /* If it's a temporary capture buffer file, mark it as not saved. */
2940 cf->user_saved = !is_tempfile;
2942 cf->cd_t = wtap_file_type(cf->wth);
2944 cf->drops_known = FALSE;
2946 cf->snap = wtap_snapshot_length(cf->wth);
2947 if (cf->snap == 0) {
2948 /* Snapshot length not known. */
2949 cf->has_snap = FALSE;
2950 cf->snap = WTAP_MAX_PACKET_SIZE;
2952 cf->has_snap = TRUE;
2953 nstime_set_zero(&cf->elapsed_time);
2954 nstime_set_zero(&first_ts);
2955 nstime_set_zero(&prev_ts);
2960 g_snprintf(err_msg, sizeof err_msg,
2961 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
2962 cmdarg_err("%s", err_msg);
2968 * General errors are reported with an console message in TShark.
2971 failure_message(const char *msg_format, va_list ap)
2973 fprintf(stderr, "tshark: ");
2974 vfprintf(stderr, msg_format, ap);
2975 fprintf(stderr, "\n");
2979 * Read errors are reported with an console message in TShark.
2982 read_failure_message(const char *filename, int err)
2984 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2985 filename, strerror(err));
2989 * Report an error in command-line arguments.
2992 cmdarg_err(const char *fmt, ...)
2997 fprintf(stderr, "tshark: ");
2998 vfprintf(stderr, fmt, ap);
2999 fprintf(stderr, "\n");
3004 * Report additional information for an error in command-line arguments.
3007 cmdarg_err_cont(const char *fmt, ...)
3012 vfprintf(stderr, fmt, ap);
3013 fprintf(stderr, "\n");
3018 /****************************************************************************************************************/
3019 /* indication report "dummies", needed for capture_loop.c */
3023 /** Report a new capture file having been opened. */
3025 report_new_capture_file(const char *filename)
3027 /* shouldn't happen */
3028 g_assert_not_reached();
3031 /** Report a number of new packets captured. */
3033 report_packet_count(int packet_count)
3035 /* shouldn't happen */
3036 g_assert_not_reached();
3039 /** Report the packet drops once the capture finishes. */
3041 report_packet_drops(int drops)
3043 /* shouldn't happen */
3044 g_assert_not_reached();
3047 /** Report an error in the capture. */
3049 report_capture_error(const char *errmsg, const char *secondary_error_msg)
3052 cmdarg_err_cont(secondary_error_msg);
3055 /** Report an error with a capture filter. */
3057 report_cfilter_error(const char *cfilter, const char *errmsg)
3061 "Invalid capture filter: \"%s\"!\n"
3063 "That string isn't a valid capture filter (%s).\n"
3064 "See the User's Guide for a description of the capture filter syntax.",
3068 #endif /* HAVE_LIBPCAP */
3071 /****************************************************************************************************************/
3072 /* signal pipe "dummies", needed for capture_loop.c */
3078 signal_pipe_check_running(void)
3080 /* currently, no check required */
3085 #endif /* HAVE_LIBPCAP */