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_dis_ts;
120 static nstime_t prev_cap_ts;
121 static GString *comp_info_str, *runtime_info_str;
123 static gboolean print_packet_info; /* TRUE if we're to print packet information */
125 * The way the packet decode is to be written.
128 WRITE_TEXT, /* summary or detail text */
129 WRITE_XML, /* PDML or PSML */
130 WRITE_FIELDS /* User defined list of fields */
131 /* Add CSV and the like here */
133 static output_action_e output_action;
134 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
135 static gboolean verbose;
136 static gboolean print_hex;
137 static gboolean line_buffered;
138 static guint32 cum_bytes = 0;
139 static print_format_e print_format = PR_FMT_TEXT;
140 static print_stream_t *print_stream;
142 static output_fields_t* output_fields = NULL;
145 * Standard secondary message for unexpected errors.
147 static const char please_report[] =
148 "Please report this to the Wireshark developers";
152 * TRUE if we're to print packet counts to keep track of captured packets.
154 static gboolean print_packet_counts;
160 static capture_options capture_opts;
164 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
165 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
167 #endif /* HAVE_LIBPCAP */
170 static int capture(void);
171 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
173 static void report_counts(void);
175 static BOOL WINAPI capture_cleanup(DWORD);
177 static void capture_cleanup(int);
179 static void report_counts_siginfo(int);
182 #endif /* HAVE_LIBPCAP */
184 static int load_cap_file(capture_file *, char *, int, int, gint64);
185 static gboolean process_packet(capture_file *cf, gint64 offset,
186 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
188 static void show_capture_file_io_error(const char *, int, gboolean);
189 static void show_print_file_io_error(int err);
190 static gboolean write_preamble(capture_file *cf);
191 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
192 static gboolean write_finale(void);
193 static const char *cf_open_error_message(int err, gchar *err_info,
194 gboolean for_writing, int file_type);
196 static void open_failure_message(const char *filename, int err,
197 gboolean for_writing);
198 static void failure_message(const char *msg_format, va_list ap);
199 static void read_failure_message(const char *filename, int err);
204 static void list_capture_types(void) {
207 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
208 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
209 if (wtap_dump_can_open(i))
210 fprintf(stderr, " %s - %s\n",
211 wtap_file_type_short_string(i), wtap_file_type_string(i));
216 print_usage(gboolean print_ver)
223 "TShark " VERSION "%s\n"
224 "Dump and analyze network traffic.\n"
225 "See http://www.wireshark.org for more information.\n"
228 wireshark_svnversion, get_copyright_info());
232 fprintf(output, "\n");
233 fprintf(output, "Usage: tshark [options] ...\n");
234 fprintf(output, "\n");
237 fprintf(output, "Capture interface:\n");
238 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
239 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
240 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
241 fprintf(output, " -p don't capture in promiscuous mode\n");
243 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
245 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
246 fprintf(output, " -D print list of interfaces and exit\n");
247 fprintf(output, " -L print list of link-layer types of iface and exit\n");
248 fprintf(output, "\n");
249 fprintf(output, "Capture stop conditions:\n");
250 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
251 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
252 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
253 fprintf(output, " files:NUM - stop after NUM files\n");
254 /*fprintf(output, "\n");*/
255 fprintf(output, "Capture output:\n");
256 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
257 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
258 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
259 #endif /* HAVE_LIBPCAP */
261 /*fprintf(output, "\n");*/
262 fprintf(output, "Input file:\n");
263 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
265 fprintf(output, "\n");
266 fprintf(output, "Processing:\n");
267 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
268 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
269 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
270 fprintf(output, " -d %s ...\n", decode_as_arg_template);
271 fprintf(output, " \"Decode As\", see the man page for details\n");
272 fprintf(output, " Example: tcp.port==8888,http\n");
274 /*fprintf(output, "\n");*/
275 fprintf(output, "Output:\n");
276 fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\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, " -l flush output after each packet\n");
292 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
293 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
294 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
296 fprintf(output, "\n");
297 fprintf(output, "Miscellaneous:\n");
298 fprintf(output, " -h display this help and exit\n");
299 fprintf(output, " -v display version info and exit\n");
300 fprintf(output, " -o <name>:<value> ... override preference setting\n");
304 * For a dissector table, print on the stream described by output,
305 * its short name (which is what's used in the "-d" option) and its
309 display_dissector_table_names(const char *table_name, const char *ui_name,
312 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
316 * For a dissector handle, print on the stream described by output,
317 * the filter name (which is what's used in the "-d" option) and the full
318 * name for the protocol that corresponds to this handle.
321 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
324 const gchar* proto_filter_name;
325 const gchar* proto_ui_name;
327 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
329 if (proto_id != -1) {
330 proto_filter_name = proto_get_protocol_filter_name(proto_id);
331 proto_ui_name = proto_get_protocol_name(proto_id);
332 g_assert(proto_filter_name != NULL);
333 g_assert(proto_ui_name != NULL);
335 fprintf((FILE *)output, "\t%s (%s)\n",
342 * The protocol_name_search structure is used by find_protocol_name_func()
343 * to pass parameters and store results
345 struct protocol_name_search{
346 gchar *searched_name; /* Protocol filter name we are looking for */
347 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
348 guint nb_match; /* How many dissectors matched searched_name */
350 typedef struct protocol_name_search *protocol_name_search_t;
353 * This function parses all dissectors associated with a table to find the
354 * one whose protocol has the specified filter name. It is called
355 * as a reference function in a call to dissector_table_foreach_handle.
356 * The name we are looking for, as well as the results, are stored in the
357 * protocol_name_search struct pointed to by user_data.
358 * If called using dissector_table_foreach_handle, we actually parse the
359 * whole list of dissectors.
362 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
366 const gchar *protocol_filter_name;
367 protocol_name_search_t search_info;
371 search_info = (protocol_name_search_t)user_data;
373 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
374 if (proto_id != -1) {
375 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
376 g_assert(protocol_filter_name != NULL);
377 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
379 if (search_info->nb_match == 0) {
380 /* Record this handle only if this is the first match */
381 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
383 search_info->nb_match++;
389 * Print all layer type names supported.
390 * We send the output to the stream described by the handle output.
394 fprint_all_layer_types(FILE *output)
397 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
401 * Print all protocol names supported for a specific layer type.
402 * table_name contains the layer type name in which the search is performed.
403 * We send the output to the stream described by the handle output.
407 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
410 dissector_table_foreach_handle(table_name,
411 display_dissector_names,
416 * The function below parses the command-line parameters for the decode as
417 * feature (a string pointer by cl_param).
418 * It checks the format of the command-line, searches for a matching table
419 * and dissector. If a table/dissector match is not found, we display a
420 * summary of the available tables/dissectors (on stderr) and return FALSE.
421 * If everything is fine, we get the "Decode as" preference activated,
422 * then we return TRUE.
425 add_decode_as(const gchar *cl_param)
429 gchar *decoded_param;
430 gchar *remaining_param;
432 gchar *dissector_str;
433 dissector_handle_t dissector_matching;
434 dissector_table_t table_matching;
435 ftenum_t dissector_table_selector_type;
436 struct protocol_name_search user_protocol_name;
438 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
441 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
442 g_assert(decoded_param);
443 strcpy(decoded_param, cl_param);
446 /* The lines below will parse this string (modifying it) to extract all
447 necessary information. Note that decoded_param is still needed since
448 strings are not copied - we just save pointers. */
450 /* This section extracts a layer type (table_name) from decoded_param */
451 table_name = decoded_param; /* Layer type string starts from beginning */
453 remaining_param = strchr(table_name, '=');
454 if (remaining_param == NULL) {
455 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
456 /* If the argument does not follow the template, carry on anyway to check
457 if the table name is at least correct. If remaining_param is NULL,
458 we'll exit anyway further down */
461 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
464 /* Remove leading and trailing spaces from the table name */
465 while ( table_name[0] == ' ' )
467 while ( table_name[strlen(table_name) - 1] == ' ' )
468 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
470 /* The following part searches a table matching with the layer type specified */
471 table_matching = NULL;
473 /* Look for the requested table */
474 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
475 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
478 table_matching = find_dissector_table(table_name);
479 if (!table_matching) {
480 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
484 if (!table_matching) {
485 /* Display a list of supported layer types to help the user, if the
486 specified layer type was not found */
487 cmdarg_err("Valid layer types are:");
488 fprint_all_layer_types(stderr);
490 if (remaining_param == NULL || !table_matching) {
491 /* Exit if the layer type was not found, or if no '=' separator was found
493 g_free(decoded_param);
497 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
498 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
501 remaining_param++; /* Move to the second '=' */
502 *remaining_param = '\0'; /* Remove the second '=' */
504 remaining_param++; /* Position after the layer type string */
506 /* This section extracts a selector value (selector_str) from decoded_param */
508 selector_str = remaining_param; /* Next part starts with the selector number */
510 remaining_param = strchr(selector_str, ',');
511 if (remaining_param == NULL) {
512 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
513 /* If the argument does not follow the template, carry on anyway to check
514 if the selector value is at least correct. If remaining_param is NULL,
515 we'll exit anyway further down */
518 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
521 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
523 switch (dissector_table_selector_type) {
529 /* The selector for this table is an unsigned number. Parse it as such.
530 There's no need to remove leading and trailing spaces from the
531 selector number string, because sscanf will do that for us. */
532 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
533 cmdarg_err("Invalid selector number \"%s\"", selector_str);
534 g_free(decoded_param);
541 /* The selector for this table is a string. */
545 /* There are currently no dissector tables with any types other
546 than the ones listed above. */
547 g_assert_not_reached();
550 if (remaining_param == NULL) {
551 /* Exit if no ',' separator was found (see above) */
552 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
553 fprint_all_protocols_for_layer_types(stderr, table_name);
554 g_free(decoded_param);
558 remaining_param++; /* Position after the selector number string */
560 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
562 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
564 /* Remove leading and trailing spaces from the dissector name */
565 while ( dissector_str[0] == ' ' )
567 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
568 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
570 dissector_matching = NULL;
572 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
573 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 */
574 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
577 user_protocol_name.nb_match = 0;
578 user_protocol_name.searched_name = dissector_str;
579 user_protocol_name.matched_handle = NULL;
581 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 */
583 if (user_protocol_name.nb_match != 0) {
584 dissector_matching = user_protocol_name.matched_handle;
585 if (user_protocol_name.nb_match > 1) {
586 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
590 /* OK, check whether the problem is that there isn't any such
591 protocol, or that there is but it's not specified as a protocol
592 that's valid for that dissector table.
593 Note, we don't exit here, but dissector_matching will remain NULL,
595 if (proto_get_id_by_filter_name(dissector_str) == -1) {
596 /* No such protocol */
597 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
599 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
600 dissector_str, table_name);
605 if (!dissector_matching) {
606 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
607 fprint_all_protocols_for_layer_types(stderr, table_name);
608 g_free(decoded_param);
612 /* This is the end of the code that parses the command-line options.
613 All information is now stored in the variables:
617 The above variables that are strings are still pointing to areas within
618 decoded_parm. decoded_parm thus still needs to be kept allocated in
619 until we stop needing these variables
620 decoded_param will be deallocated at each exit point of this function */
623 /* We now have a pointer to the handle for the requested dissector
624 (requested protocol) inside the variable dissector_matching */
625 switch (dissector_table_selector_type) {
631 /* The selector for this table is an unsigned number. */
632 dissector_change(table_name, selector, dissector_matching);
637 /* The selector for this table is a string. */
638 dissector_change_string(table_name, selector_str, dissector_matching);
642 /* There are currently no dissector tables with any types other
643 than the ones listed above. */
644 g_assert_not_reached();
646 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
651 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
652 const gchar *message _U_, gpointer user_data _U_)
657 output_file_description(const char *fname)
659 char *save_file_string;
661 /* Get a string that describes what we're writing to */
662 if (strcmp(fname, "-") == 0) {
663 /* We're writing to the standard output */
664 save_file_string = g_strdup("standard output");
666 /* We're writing to a file with the name in save_file */
667 save_file_string = g_strdup_printf("file \"%s\"", fname);
669 return save_file_string;
673 main(int argc, char *argv[])
675 char *init_progfile_dir_error;
678 gboolean arg_error = FALSE;
684 char *gpf_path, *pf_path;
685 char *gdp_path, *dp_path;
686 int gpf_open_errno, gpf_read_errno;
687 int pf_open_errno, pf_read_errno;
688 int gdp_open_errno, gdp_read_errno;
689 int dp_open_errno, dp_read_errno;
692 gboolean list_link_layer_types = FALSE;
693 gboolean start_capture = FALSE;
695 gboolean capture_option_specified = FALSE;
697 gboolean quiet = FALSE;
698 int out_file_type = WTAP_FILE_PCAP;
699 gchar *cf_name = NULL, *rfilter = NULL;
700 #ifdef HAVE_PCAP_OPEN_DEAD
701 struct bpf_program fcode;
703 dfilter_t *rfcode = NULL;
706 GLogLevelFlags log_flags;
710 #define OPTSTRING_INIT "a:b:c:d:De:E:f:F:G:hi:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
713 #define OPTSTRING_WIN32 "B:"
715 #define OPTSTRING_WIN32 ""
718 #define OPTSTRING_WIN32 ""
719 #endif /* HAVE_LIBPCAP */
721 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
724 * Attempt to get the pathname of the executable file.
726 init_progfile_dir_error = init_progfile_dir(argv[0]);
727 if (init_progfile_dir_error != NULL) {
728 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
729 init_progfile_dir_error);
733 * Get credential information for later use.
735 get_credential_info();
738 * Now attempt to get the pathname of the plugins.
743 * In order to have the -X opts assigned before the wslua machine starts
744 * we need to call getopts before epan_init() gets called.
747 optind_initial = optind;
749 while ((opt = getopt(argc, argv, optstring)) != -1) {
759 optind = optind_initial;
762 /* nothing more than the standard GLib handler, but without a warning */
769 g_log_set_handler(NULL,
771 log_func_ignore, NULL /* user_data */);
772 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
774 log_func_ignore, NULL /* user_data */);
776 initialize_funnel_ops();
779 capture_opts_init(&capture_opts, NULL /* cfile */);
782 timestamp_set_type(TS_RELATIVE);
783 timestamp_set_precision(TS_PREC_AUTO);
785 /* Register all dissectors; we must do this before checking for the
786 "-G" flag, as the "-G" flag dumps information registered by the
787 dissectors, and we must do it before we read the preferences, in
788 case any dissectors register preferences. */
789 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
790 failure_message, open_failure_message, read_failure_message);
792 /* Register all tap listeners; we do this before we parse the arguments,
793 as the "-z" argument can specify a registered tap. */
795 /* we register the plugin taps before the other taps because
796 stats_tree taps plugins will be registered as tap listeners
797 by stats_tree_stat.c and need to registered before that */
799 register_all_plugin_tap_listeners();
801 register_all_tap_listeners();
803 /* Now register the preferences for any non-dissector modules.
804 We must do that before we read the preferences as well. */
805 prefs_register_modules();
807 /* If invoked with the "-G" flag, we dump out information based on
808 the argument to the "-G" flag; if no argument is specified,
809 for backwards compatibility we dump out a glossary of display
812 XXX - we do this here, for now, to support "-G" with no arguments.
813 If none of our build or other processes uses "-G" with no arguments,
814 we can just process it with the other arguments. */
815 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
817 proto_registrar_dump_fields(1);
819 if (strcmp(argv[2], "fields") == 0)
820 proto_registrar_dump_fields(1);
821 else if (strcmp(argv[2], "fields2") == 0)
822 proto_registrar_dump_fields(2);
823 else if (strcmp(argv[2], "fields3") == 0)
824 proto_registrar_dump_fields(3);
825 else if (strcmp(argv[2], "protocols") == 0)
826 proto_registrar_dump_protocols();
827 else if (strcmp(argv[2], "values") == 0)
828 proto_registrar_dump_values();
829 else if (strcmp(argv[2], "decodes") == 0)
830 dissector_dump_decodes();
831 else if (strcmp(argv[2], "defaultprefs") == 0)
833 else if (strcmp(argv[2], "currentprefs") == 0) {
834 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
835 &pf_open_errno, &pf_read_errno, &pf_path);
838 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
845 /* Set the C-language locale to the native environment. */
846 setlocale(LC_ALL, "");
848 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
849 &pf_open_errno, &pf_read_errno, &pf_path);
850 if (gpf_path != NULL) {
851 if (gpf_open_errno != 0) {
852 cmdarg_err("Can't open global preferences file \"%s\": %s.",
853 pf_path, strerror(gpf_open_errno));
855 if (gpf_read_errno != 0) {
856 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
857 pf_path, strerror(gpf_read_errno));
860 if (pf_path != NULL) {
861 if (pf_open_errno != 0) {
862 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
863 strerror(pf_open_errno));
865 if (pf_read_errno != 0) {
866 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
867 pf_path, strerror(pf_read_errno));
873 /* Set the name resolution code's flags from the preferences. */
874 g_resolv_flags = prefs->name_resolve;
876 /* Read the disabled protocols file. */
877 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
878 &dp_path, &dp_open_errno, &dp_read_errno);
879 if (gdp_path != NULL) {
880 if (gdp_open_errno != 0) {
881 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
882 gdp_path, strerror(gdp_open_errno));
884 if (gdp_read_errno != 0) {
885 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
886 gdp_path, strerror(gdp_read_errno));
890 if (dp_path != NULL) {
891 if (dp_open_errno != 0) {
893 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
894 strerror(dp_open_errno));
896 if (dp_read_errno != 0) {
898 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
899 strerror(dp_read_errno));
905 /* Load Wpcap, if possible */
909 init_cap_file(&cfile);
911 /* Assemble the compile-time version information string */
912 comp_info_str = g_string_new("Compiled ");
913 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
915 /* Assemble the run-time version information string */
916 runtime_info_str = g_string_new("Running ");
917 get_runtime_version_info(runtime_info_str, NULL);
919 /* Print format defaults to this. */
920 print_format = PR_FMT_TEXT;
922 output_fields = output_fields_new();
924 /* Now get our args */
925 while ((opt = getopt(argc, argv, optstring)) != -1) {
927 case 'a': /* autostop criteria */
928 case 'b': /* Ringbuffer option */
929 case 'c': /* Capture xxx packets */
930 case 'f': /* capture filter */
931 case 'i': /* Use interface xxx */
932 case 'p': /* Don't capture in promiscuous mode */
933 case 's': /* Set the snapshot (capture) length */
934 case 'w': /* Write to capture file xxx */
935 case 'y': /* Set the pcap data link type */
937 case 'B': /* Buffer size */
940 status = capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
945 capture_option_specified = TRUE;
949 case 'd': /* Decode as rule */
950 if (!add_decode_as(optarg))
953 case 'D': /* Print a list of capture devices and exit */
955 status = capture_opts_list_interfaces();
958 capture_option_specified = TRUE;
964 output_fields_add(output_fields, optarg);
968 if(!output_fields_set_option(output_fields, optarg)) {
969 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
970 output_fields_list_options(stderr);
975 out_file_type = wtap_short_string_to_file_type(optarg);
976 if (out_file_type < 0) {
977 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
978 list_capture_types();
982 case 'h': /* Print help and exit */
986 case 'l': /* "Line-buffer" standard output */
987 /* This isn't line-buffering, strictly speaking, it's just
988 flushing the standard output after the information for
989 each packet is printed; however, that should be good
990 enough for all the purposes to which "-l" is put (and
991 is probably actually better for "-V", as it does fewer
994 See the comment in "process_packet()" for an explanation of
995 why we do that, and why we don't just use "setvbuf()" to
996 make the standard output line-buffered (short version: in
997 Windows, "line-buffered" is the same as "fully-buffered",
998 and the output buffer is only flushed when it fills up). */
999 line_buffered = TRUE;
1001 case 'L': /* Print list of link-layer types and exit */
1003 list_link_layer_types = TRUE;
1006 capture_option_specified = TRUE;
1010 case 'n': /* No name resolution */
1011 g_resolv_flags = RESOLV_NONE;
1013 case 'N': /* Select what types of addresses/port #s to resolve */
1014 if (g_resolv_flags == RESOLV_ALL)
1015 g_resolv_flags = RESOLV_NONE;
1016 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1017 if (badopt != '\0') {
1018 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
1023 case 'o': /* Override preference from command line */
1024 switch (prefs_set_pref(optarg)) {
1029 case PREFS_SET_SYNTAX_ERR:
1030 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1034 case PREFS_SET_NO_SUCH_PREF:
1035 case PREFS_SET_OBSOLETE:
1036 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1041 case 'q': /* Quiet */
1044 case 'r': /* Read capture file xxx */
1045 cf_name = g_strdup(optarg);
1047 case 'R': /* Read file filter */
1050 case 'S': /* show packets in real time */
1051 print_packet_info = TRUE;
1053 case 't': /* Time stamp type */
1054 if (strcmp(optarg, "r") == 0)
1055 timestamp_set_type(TS_RELATIVE);
1056 else if (strcmp(optarg, "a") == 0)
1057 timestamp_set_type(TS_ABSOLUTE);
1058 else if (strcmp(optarg, "ad") == 0)
1059 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1060 else if (strcmp(optarg, "d") == 0)
1061 timestamp_set_type(TS_DELTA);
1062 else if (strcmp(optarg, "dd") == 0)
1063 timestamp_set_type(TS_DELTA_DIS);
1064 else if (strcmp(optarg, "e") == 0)
1065 timestamp_set_type(TS_EPOCH);
1067 cmdarg_err("Invalid time stamp type \"%s\"",
1069 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1070 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1074 case 'T': /* printing Type */
1075 if (strcmp(optarg, "text") == 0) {
1076 output_action = WRITE_TEXT;
1077 print_format = PR_FMT_TEXT;
1078 } else if (strcmp(optarg, "ps") == 0) {
1079 output_action = WRITE_TEXT;
1080 print_format = PR_FMT_PS;
1081 } else if (strcmp(optarg, "pdml") == 0) {
1082 output_action = WRITE_XML;
1084 } else if (strcmp(optarg, "psml") == 0) {
1085 output_action = WRITE_XML;
1087 } else if(strcmp(optarg, "fields") == 0) {
1088 output_action = WRITE_FIELDS;
1089 verbose = TRUE; /* Need full tree info */
1091 cmdarg_err("Invalid -T parameter.");
1092 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1096 case 'v': /* Show version and exit */
1097 printf("TShark " VERSION "%s\n"
1104 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1105 runtime_info_str->str);
1108 case 'V': /* Verbose */
1111 case 'x': /* Print packet data in hex (and ASCII) */
1117 /* We won't call the init function for the stat this soon
1118 as it would disallow MATE's fields (which are registered
1119 by the preferences set callback) from being used as
1120 part of a tap filter. Instead, we just add the argument
1121 to a list of stat arguments. */
1122 if (!process_stat_cmd_arg(optarg)) {
1123 cmdarg_err("invalid -z argument.");
1124 cmdarg_err_cont(" -z argument must be one of :");
1125 list_stat_cmd_args();
1130 case '?': /* Bad flag - print usage message */
1133 list_capture_types();
1143 /* If we specified output fields, but not the output field type... */
1144 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1145 cmdarg_err("Output fields were specified with \"-e\", "
1146 "but \"-Tfields\" was not specified.");
1148 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1149 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1150 "specified with \"-e\".");
1155 /* If no capture filter or read filter has been specified, and there are
1156 still command-line arguments, treat them as the tokens of a capture
1157 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1158 flag was specified. */
1159 if (optind < argc) {
1160 if (cf_name != NULL) {
1161 if (rfilter != NULL) {
1162 cmdarg_err("Read filters were specified both with \"-R\" "
1163 "and with additional command-line arguments");
1166 rfilter = get_args_as_string(argc, argv, optind);
1169 if (capture_opts.has_cfilter) {
1170 cmdarg_err("Capture filters were specified both with \"-f\""
1171 " and with additional command-line arguments");
1174 capture_opts.has_cfilter = TRUE;
1175 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1177 capture_option_specified = TRUE;
1183 if (!capture_opts.saving_to_file) {
1184 /* We're not saving the capture to a file; if "-q" wasn't specified,
1185 we should print packet information */
1187 print_packet_info = TRUE;
1189 /* We're saving to a file; if we're writing to the standard output.
1190 and we'll also be writing dissected packets to the standard
1191 output, reject the request. At best, we could redirect that
1192 to the standard error; we *can't* write both to the standard
1193 output and have either of them be useful. */
1194 if (strcmp(capture_opts.save_file, "-") == 0 && print_packet_info) {
1195 cmdarg_err("You can't write both raw packet data and dissected packets"
1196 " to the standard output.");
1201 /* We're not saving the capture to a file; if "-q" wasn't specified,
1202 we should print packet information */
1204 print_packet_info = TRUE;
1207 #ifndef HAVE_LIBPCAP
1208 if (capture_option_specified)
1209 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1216 /* We don't support capture filters when reading from a capture file
1217 (the BPF compiler doesn't support all link-layer types that we
1218 support in capture files we read). */
1220 if (cf_name != NULL) {
1221 if (capture_opts.has_cfilter) {
1222 cmdarg_err("Only read filters, not capture filters, "
1223 "can be specified when reading a capture file.");
1230 if (output_action != WRITE_TEXT) {
1231 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1237 if (list_link_layer_types) {
1238 /* We're supposed to list the link-layer types for an interface;
1239 did the user also specify a capture file to be read? */
1241 /* Yes - that's bogus. */
1242 cmdarg_err("You can't specify -L and a capture file to be read.");
1245 /* No - did they specify a ring buffer option? */
1246 if (capture_opts.multi_files_on) {
1247 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1253 * "-r" was specified, so we're reading a capture file.
1254 * Capture options don't apply here.
1256 if (capture_opts.multi_files_on) {
1257 cmdarg_err("Multiple capture files requested, but "
1258 "a capture isn't being done.");
1261 if (capture_opts.has_file_duration) {
1262 cmdarg_err("Switching capture files after a time interval was specified, but "
1263 "a capture isn't being done.");
1266 if (capture_opts.has_ring_num_files) {
1267 cmdarg_err("A ring buffer of capture files was specified, but "
1268 "a capture isn't being done.");
1271 if (capture_opts.has_autostop_files) {
1272 cmdarg_err("A maximum number of capture files was specified, but "
1273 "a capture isn't being done.");
1277 /* Note: TShark now allows the restriction of a _read_ file by packet count
1278 * and byte count as well as a write file. Other autostop options remain valid
1279 * only for a write file.
1281 if (capture_opts.has_autostop_duration) {
1282 cmdarg_err("A maximum capture time was specified, but "
1283 "a capture isn't being done.");
1288 * "-r" wasn't specified, so we're doing a live capture.
1290 if (capture_opts.saving_to_file) {
1291 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1293 /* When capturing, we only support writing libpcap format. */
1294 if (out_file_type != WTAP_FILE_PCAP) {
1295 cmdarg_err("Live captures can only be saved in libpcap format.");
1298 if (capture_opts.multi_files_on) {
1299 /* Multiple-file mode doesn't work under certain conditions:
1300 a) it doesn't work if you're writing to the standard output;
1301 b) it doesn't work if you're writing to a pipe;
1303 if (strcmp(capture_opts.save_file, "-") == 0) {
1304 cmdarg_err("Multiple capture files requested, but "
1305 "the capture is being written to the standard output.");
1308 if (capture_opts.output_to_pipe) {
1309 cmdarg_err("Multiple capture files requested, but "
1310 "the capture file is a pipe.");
1313 if (!capture_opts.has_autostop_filesize &&
1314 !capture_opts.has_file_duration) {
1315 cmdarg_err("Multiple capture files requested, but "
1316 "no maximum capture file size or duration was specified.");
1321 /* They didn't specify a "-w" flag, so we won't be saving to a
1322 capture file. Check for options that only make sense if
1323 we're saving to a file. */
1324 if (capture_opts.has_autostop_filesize) {
1325 cmdarg_err("Maximum capture file size specified, but "
1326 "capture isn't being saved to a file.");
1329 if (capture_opts.multi_files_on) {
1330 cmdarg_err("Multiple capture files requested, but "
1331 "the capture isn't being saved to a file.");
1340 /* Start windows sockets */
1341 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1344 /* Notify all registered modules that have had any of their preferences
1345 changed either from one of the preferences file or from the command
1346 line that their preferences have changed. */
1349 /* At this point MATE will have registered its field array so we can
1350 have a tap filter with one of MATE's late-registered fields as part
1351 of the filter. We can now process all the "-z" arguments. */
1352 start_requested_stats();
1354 /* disabled protocols as per configuration file */
1355 if (gdp_path == NULL && dp_path == NULL) {
1356 set_disabled_protos_list();
1359 /* Build the column format array */
1360 col_setup(&cfile.cinfo, prefs->num_cols);
1361 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1362 cfile.cinfo.col_fmt[i] = get_column_format(i);
1363 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1364 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1366 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1367 cfile.cinfo.col_data[i] = NULL;
1368 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1369 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1371 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1372 cfile.cinfo.col_fence[i] = 0;
1373 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1374 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1377 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1380 for (j = 0; j < NUM_COL_FMTS; j++) {
1381 if (!cfile.cinfo.fmt_matx[i][j])
1384 if (cfile.cinfo.col_first[j] == -1)
1385 cfile.cinfo.col_first[j] = i;
1386 cfile.cinfo.col_last[j] = i;
1391 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1392 capture_opts_trim_ring_num_files(&capture_opts);
1395 if (rfilter != NULL) {
1396 if (!dfilter_compile(rfilter, &rfcode)) {
1397 cmdarg_err("%s", dfilter_error_msg);
1399 #ifdef HAVE_PCAP_OPEN_DEAD
1403 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1405 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1407 " Note: That display filter code looks like a valid capture filter;");
1409 " maybe you mixed them up?");
1418 cfile.rfcode = rfcode;
1420 if (print_packet_info) {
1421 /* If we're printing as text or PostScript, we have
1422 to create a print stream. */
1423 if (output_action == WRITE_TEXT) {
1424 switch (print_format) {
1427 print_stream = print_stream_text_stdio_new(stdout);
1431 print_stream = print_stream_ps_stdio_new(stdout);
1435 g_assert_not_reached();
1440 /* We have to dissect each packet if:
1442 we're printing information about each packet;
1444 we're using a read filter on the packets;
1446 we're using any taps. */
1447 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1451 * We're reading a capture file.
1455 * Immediately relinquish any special privileges we have; we must not
1456 * be allowed to read any capture files the user running TShark
1459 relinquish_special_privs_perm();
1461 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1466 /* Set timestamp precision; there should arguably be a command-line
1467 option to let the user set this. */
1468 switch(wtap_file_tsprecision(cfile.wth)) {
1469 case(WTAP_FILE_TSPREC_SEC):
1470 timestamp_set_precision(TS_PREC_AUTO_SEC);
1472 case(WTAP_FILE_TSPREC_DSEC):
1473 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1475 case(WTAP_FILE_TSPREC_CSEC):
1476 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1478 case(WTAP_FILE_TSPREC_MSEC):
1479 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1481 case(WTAP_FILE_TSPREC_USEC):
1482 timestamp_set_precision(TS_PREC_AUTO_USEC);
1484 case(WTAP_FILE_TSPREC_NSEC):
1485 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1488 g_assert_not_reached();
1491 /* Process the packets in the file */
1493 err = load_cap_file(&cfile, capture_opts.save_file, out_file_type,
1494 capture_opts.has_autostop_packets ? capture_opts.autostop_packets : 0,
1495 capture_opts.has_autostop_filesize ? capture_opts.autostop_filesize : 0);
1497 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1505 /* No capture file specified, so we're supposed to do a live capture
1506 (or get a list of link-layer types for a live capture device);
1507 do we have support for live captures? */
1514 cmdarg_err("WinPcap couldn't be found.");
1515 detailed_err = cant_load_winpcap_err("TShark");
1516 cmdarg_err_cont("%s", detailed_err);
1517 g_free(detailed_err);
1522 /* trim the interface name and exit if that failed */
1523 if (!capture_opts_trim_iface(&capture_opts,
1524 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1528 /* if requested, list the link layer types and exit */
1529 if (list_link_layer_types) {
1530 status = capture_opts_list_link_layer_types(&capture_opts);
1534 if (!print_packet_info && !quiet) {
1536 * We're not printing information for each packet, and the user
1537 * didn't ask us not to print a count of packets as they arrive,
1538 * so print that count so the user knows that packets are arriving.
1540 * XXX - what if the user wants to do a live capture, doesn't want
1541 * to save it to a file, doesn't want information printed for each
1542 * packet, does want some "-z" statistic, and wants packet counts
1543 * so they know whether they're seeing any packets?
1545 print_packet_counts = TRUE;
1548 /* For now, assume libpcap gives microsecond precision. */
1549 timestamp_set_precision(TS_PREC_AUTO_USEC);
1553 if (capture_opts.multi_files_on) {
1557 /* No - complain. */
1558 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1563 draw_tap_listeners(TRUE);
1564 funnel_dump_all_text_windows();
1567 output_fields_free(output_fields);
1568 output_fields = NULL;
1574 /* Do the low-level work of a capture.
1575 Returns TRUE if it succeeds, FALSE otherwise. */
1577 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1583 int volatile volatile_err = 0;
1584 int volatile inpkts = 0;
1586 condition *volatile cnd_autostop_size = NULL;
1587 condition *volatile cnd_autostop_duration = NULL;
1590 void (*oldhandler)(int);
1592 struct pcap_stat stats;
1595 gboolean cfilter_error = FALSE;
1596 char errmsg[1024+1];
1597 char secondary_errmsg[4096+1];
1600 /* Initialize all data structures used for dissection. */
1603 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1605 ld.packet_cb = capture_pcap_cb;
1608 /* open the "input file" from network interface or capture pipe */
1609 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg),
1610 secondary_errmsg, sizeof(secondary_errmsg))) {
1615 * We've opened the capture device, so we shouldn't need any special
1616 * privileges any more; relinquish those privileges.
1618 * XXX - if we have saved set-user-ID support, we should give up those
1619 * privileges immediately, and then reclaim them long enough to get
1620 * a list of network interfaces and to open one, and then give them
1621 * up again, so that stuff we do while processing the argument list,
1622 * reading the user's preferences, loading and starting plugins
1623 * (especially *user* plugins), etc. is done with the user's privileges,
1624 * not special privileges.
1626 relinquish_special_privs_perm();
1628 /* init the input filter from the network interface (capture pipe will do nothing) */
1629 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts.iface, capture_opts.cfilter)) {
1631 case INITFILTER_NO_ERROR:
1634 case INITFILTER_BAD_FILTER:
1635 cfilter_error = TRUE;
1636 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1637 *secondary_errmsg = '\0';
1640 case INITFILTER_OTHER_ERROR:
1641 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1642 pcap_geterr(ld.pcap_h));
1643 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1647 if (capture_opts.saving_to_file) {
1648 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1649 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1650 *secondary_errmsg = '\0';
1654 /* set up to write to the already-opened capture output file/files */
1655 if(!capture_loop_init_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg)) {
1656 *secondary_errmsg = '\0';
1660 /* Save the capture file name. */
1661 ld.save_file = capture_opts.save_file;
1664 ld.wtap_linktype = wtap_pcap_encap_to_wtap_encap(ld.linktype);
1667 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1668 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1670 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1672 XXX - deal with signal semantics on various UNIX platforms. Or just
1673 use "sigaction()" and be done with it? */
1674 signal(SIGTERM, capture_cleanup);
1675 signal(SIGINT, capture_cleanup);
1676 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1677 signal(SIGHUP, oldhandler);
1680 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1681 quiet mode, report the number of packets we've captured. */
1682 signal(SIGINFO, report_counts_siginfo);
1683 #endif /* SIGINFO */
1686 /* Let the user know what interface was chosen. */
1687 descr = get_interface_descriptive_name(capture_opts.iface);
1688 fprintf(stderr, "Capturing on %s\n", descr);
1691 /* initialize capture stop conditions */
1692 init_capture_stop_conditions();
1693 /* create stop conditions */
1694 if (capture_opts.has_autostop_filesize)
1695 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1696 (long)capture_opts.autostop_filesize * 1024);
1697 if (capture_opts.has_autostop_duration)
1698 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1699 (gint32)capture_opts.autostop_duration);
1701 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1702 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT, capture_opts.file_duration);
1704 if (!setjmp(ld.stopenv)) {
1706 ld.packet_count = 0;
1711 /* We need to be careful with automatic variables defined in the
1712 outer scope which are changed inside the loop. Most compilers
1713 don't try to roll them back to their original values after the
1714 longjmp which causes the loop to finish, but all that the
1715 standards say is that their values are indeterminate. If we
1716 don't want them to be rolled back, we should define them with the
1717 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1718 Programming in the UNIX Environment, p. 178).
1720 The "err" variable causes a particular problem. If we give it
1721 the volatile attribute, then when we pass a reference to it (as
1722 in "&err") to a function, GCC warns: "passing arg <n> of
1723 <function> discards qualifiers from pointer target type".
1724 Therefore within the loop and just beyond we don't use "err".
1725 Within the loop we define "loop_err", and assign its value to
1726 "volatile_err", which is in the outer scope and is checked when
1729 We also define "packet_count_prev" here to keep things tidy,
1730 since it's used only inside the loop. If it were defined in the
1731 outer scope, GCC would give a warning (unnecessary in this case)
1732 that it might be clobbered, and we'd need to give it the volatile
1733 attribute to suppress the warning. */
1736 int packet_count_prev = 0;
1738 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1739 /* We're not stopping at a particular capture file size, and we're
1740 not stopping after some particular amount of time has expired,
1741 so either we have no stop condition or the only stop condition
1742 is a maximum packet count.
1744 If there's no maximum packet count, pass it -1, meaning "until
1745 you run out of packets in the bufferful you read". Otherwise,
1746 pass it the number of packets we have left to capture.
1748 We don't call "pcap_loop()" as, if we're saving to a file that's
1749 a FIFO, we want to flush the FIFO after we're done processing
1750 this libpcap bufferful of packets, so that the program
1751 reading the FIFO sees the packets immediately and doesn't get
1752 any partial packet, forcing it to block in the middle of reading
1754 if (capture_opts.autostop_packets == 0)
1757 if (ld.packet_count >= capture_opts.autostop_packets) {
1758 /* XXX do we need this test here? */
1759 /* It appears there's nothing more to capture. */
1762 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1765 /* We need to check the capture file size or the timeout after
1770 inpkts = capture_loop_dispatch(NULL, &ld, errmsg, sizeof errmsg);
1772 /* Error from "pcap_dispatch()", or error or "no more packets" from
1773 "cap_pipe_dispatch(). */
1775 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1776 /* The specified capture time has elapsed; stop the capture. */
1778 } else if (inpkts > 0) {
1779 if (capture_opts.autostop_packets != 0 &&
1780 ld.packet_count >= capture_opts.autostop_packets) {
1781 /* The specified number of packets have been captured and have
1782 passed both any capture filter in effect and any read filter
1785 } else if (cnd_autostop_size != NULL &&
1786 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)) {
1787 /* We're saving the capture to a file, and the capture file reached
1788 its maximum size. */
1789 if (capture_opts.multi_files_on) {
1790 /* Switch to the next ringbuffer file */
1791 if (ringbuf_switch_file(&ld.pdh, &capture_opts.save_file,
1792 &save_file_fd, &ld.bytes_written,
1794 /* File switch succeeded: reset the condition */
1795 cnd_reset(cnd_autostop_size);
1796 if (cnd_file_duration) {
1797 cnd_reset(cnd_file_duration);
1800 /* File switch failed: stop here */
1801 volatile_err = loop_err;
1805 /* No ringbuffer - just stop. */
1809 if (capture_opts.output_to_pipe) {
1810 if (ld.packet_count > packet_count_prev) {
1811 libpcap_dump_flush(ld.pdh, NULL);
1812 packet_count_prev = ld.packet_count;
1816 } /* while (ld.go) */
1818 /* delete stop conditions */
1819 if (cnd_autostop_size != NULL)
1820 cnd_delete(cnd_autostop_size);
1821 if (cnd_autostop_duration != NULL)
1822 cnd_delete(cnd_autostop_duration);
1823 if (cnd_file_duration != NULL)
1824 cnd_delete(cnd_file_duration);
1826 if (print_packet_counts) {
1827 /* We're printing packet counts to stderr.
1828 Send a newline so that we move to the line after the packet count. */
1829 fprintf(stderr, "\n");
1832 /* If we got an error while capturing, report it. */
1834 if (ld.from_cap_pipe) {
1835 if (ld.cap_pipe_err == PIPERR) {
1836 cmdarg_err("Error while capturing packets: %s", errmsg);
1839 cmdarg_err("Error while capturing packets: %s", pcap_geterr(ld.pcap_h));
1843 if (volatile_err == 0)
1846 show_capture_file_io_error(capture_opts.save_file, volatile_err, FALSE);
1850 if (capture_opts.save_file != NULL) {
1851 /* We're saving to a file or files; close all files. */
1852 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1854 /* If we've displayed a message about a write error, there's no point
1855 in displaying another message about an error on close. */
1856 if (!close_ok && write_ok)
1857 show_capture_file_io_error(capture_opts.save_file, err, TRUE);
1860 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1861 eth_close(ld.cap_pipe_fd);
1863 /* Get the capture statistics, and, if any packets were dropped, report
1865 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1866 if (stats.ps_drop != 0) {
1867 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1870 cmdarg_err("Can't get packet-drop statistics: %s", pcap_geterr(ld.pcap_h));
1872 pcap_close(ld.pcap_h);
1875 /* Report the number of captured packets if not reported during capture
1876 and we are saving to a file. */
1882 if (capture_opts.multi_files_on) {
1883 ringbuf_error_cleanup();
1885 g_free(capture_opts.save_file);
1886 capture_opts.save_file = NULL;
1887 if (cfilter_error) {
1888 dfilter_t *rfcode = NULL;
1889 if (dfilter_compile(capture_opts.cfilter, &rfcode) && rfcode != NULL) {
1891 "Invalid capture filter: \"%s\"!\n"
1893 "That string looks like a valid display filter; however, it isn't a valid\n"
1894 "capture filter (%s).\n"
1896 "Note that display filters and capture filters don't have the same syntax,\n"
1897 "so you can't use most display filter expressions as capture filters.\n"
1899 "See the User's Guide for a description of the capture filter syntax.",
1900 capture_opts.cfilter, errmsg);
1901 dfilter_free(rfcode);
1904 "Invalid capture filter: \"%s\"!\n"
1906 "That string isn't a valid capture filter (%s).\n"
1907 "See the User's Guide for a description of the capture filter syntax.",
1908 capture_opts.cfilter, errmsg);
1911 cmdarg_err("%s", errmsg);
1912 if (*secondary_errmsg != '\0') {
1913 fprintf(stderr, "\n");
1914 cmdarg_err_cont("%s", secondary_errmsg);
1917 if (ld.from_cap_pipe) {
1918 if (ld.cap_pipe_fd >= 0)
1919 eth_close(ld.cap_pipe_fd);
1921 if (ld.pcap_h != NULL)
1922 pcap_close(ld.pcap_h);
1929 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1932 struct wtap_pkthdr whdr;
1933 union wtap_pseudo_header pseudo_header;
1934 const guchar *wtap_pd;
1935 loop_data *ld = (loop_data *) user;
1939 gboolean packet_accepted;
1943 * Prevent a SIGINFO handler from writing to stdout while we're
1944 * doing so; instead, have it just set a flag telling us to print
1945 * that information when we're done.
1948 #endif /* SIGINFO */
1950 /* The current packet may have arrived after a very long silence,
1951 * way past the time to switch files. In order not to have
1952 * the first packet of a new series of events as the last
1953 * [or only] packet in the file, switch before writing!
1955 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1956 /* time elapsed for this ring file, switch to the next */
1957 if (ringbuf_switch_file(&ld->pdh, &ld->save_file, &save_file_fd,
1958 &ld->bytes_written, &loop_err)) {
1959 /* File switch succeeded: reset the condition */
1960 cnd_reset(cnd_file_duration);
1962 /* File switch failed: stop here */
1963 /* XXX - we should do something with "loop_err" */
1968 if (do_dissection) {
1969 /* We're goint to print packet information, run a read filter, or
1970 process taps. Use process_packet() to handle that; in order
1971 to do that, we need to convert from libpcap to Wiretap format.
1972 If that fails, ignore the packet (wtap_process_pcap_packet has
1973 written an error message). */
1974 wtap_pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd,
1975 &pseudo_header, &whdr, &err);
1976 if (wtap_pd == NULL)
1979 packet_accepted = process_packet(&cfile, 0, &whdr, &pseudo_header, wtap_pd);
1981 /* We're just writing out packets. */
1982 packet_accepted = TRUE;
1985 if (packet_accepted) {
1986 /* Count this packet. */
1991 if (ld->pdh != NULL) {
1992 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
1993 /* Error writing to a capture file */
1994 if (print_packet_counts) {
1995 /* We're printing counts of packets captured; move to the line after
1997 fprintf(stderr, "\n");
1999 show_capture_file_io_error(ld->save_file, err, FALSE);
2000 pcap_close(ld->pcap_h);
2001 libpcap_dump_close(ld->pdh, &err);
2005 if (print_packet_counts) {
2006 /* We're printing packet counts. */
2007 if (ld->packet_count != 0) {
2008 fprintf(stderr, "\r%u ", ld->packet_count);
2009 /* stderr could be line buffered */
2017 * Allow SIGINFO handlers to write.
2022 * If a SIGINFO handler asked us to write out capture counts, do so.
2026 #endif /* SIGINFO */
2031 capture_cleanup(DWORD ctrltype _U_)
2033 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2034 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2035 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2036 like SIGTERM at least when the machine's shutting down.
2038 For now, we handle them all as indications that we should clean up
2039 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2042 However, as handlers run in a new thread, we can't just longjmp
2043 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2044 no other handler - such as one that would terminate the process -
2047 XXX - for some reason, typing ^C to TShark, if you run this in
2048 a Cygwin console window in at least some versions of Cygwin,
2049 causes TShark to terminate immediately; this routine gets
2050 called, but the main loop doesn't get a chance to run and
2051 exit cleanly, at least if this is compiled with Microsoft Visual
2052 C++ (i.e., it's a property of the Cygwin console window or Bash;
2053 it happens if TShark is not built with Cygwin - for all I know,
2054 building it with Cygwin may make the problem go away). */
2060 capture_cleanup(int signum _U_)
2062 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2063 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2064 "ld.go" to FALSE and return, we won't break out of it and quit
2066 longjmp(ld.stopenv, 1);
2074 /* XXX - if we use sigaction, this doesn't have to be done.
2075 (Yes, this isn't necessary on BSD, but just in case a system
2076 where "signal()" has AT&T semantics adopts SIGINFO....) */
2077 signal(SIGINFO, report_counts_siginfo);
2078 #endif /* SIGINFO */
2080 if (!print_packet_counts) {
2081 /* Report the count only if we aren't printing a packet count
2082 as packets arrive. */
2083 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2086 infoprint = FALSE; /* we just reported it */
2087 #endif /* SIGINFO */
2092 report_counts_siginfo(int signum _U_)
2094 int sav_errno = errno;
2095 /* If we've been told to delay printing, just set a flag asking
2096 that we print counts (if we're supposed to), otherwise print
2097 the count of packets captured (if we're supposed to). */
2104 #endif /* SIGINFO */
2105 #endif /* HAVE_LIBPCAP */
2108 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2109 int max_packet_count, gint64 max_byte_count)
2112 int snapshot_length;
2117 char *save_file_string = NULL;
2119 linktype = wtap_file_encap(cf->wth);
2120 if (save_file != NULL) {
2121 /* Get a string that describes what we're writing to */
2122 save_file_string = output_file_description(save_file);
2124 /* Set up to write to the capture file. */
2125 snapshot_length = wtap_snapshot_length(cf->wth);
2126 if (snapshot_length == 0) {
2127 /* Snapshot length of input file not known. */
2128 snapshot_length = WTAP_MAX_PACKET_SIZE;
2130 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2131 FALSE /* compressed */, &err);
2134 /* We couldn't set up to write to the capture file. */
2137 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2138 cmdarg_err("Capture files can't be written in that format.");
2141 case WTAP_ERR_UNSUPPORTED_ENCAP:
2142 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2143 cmdarg_err("The capture file being read can't be written in "
2147 case WTAP_ERR_CANT_OPEN:
2148 cmdarg_err("The %s couldn't be created for some "
2149 "unknown reason.", save_file_string);
2152 case WTAP_ERR_SHORT_WRITE:
2153 cmdarg_err("A full header couldn't be written to the %s.",
2158 cmdarg_err("The %s could not be created: %s.", save_file_string,
2159 wtap_strerror(err));
2165 if (print_packet_info) {
2166 if (!write_preamble(cf)) {
2168 show_print_file_io_error(err);
2174 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2175 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2176 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2177 /* Either there's no read filtering or this packet passed the
2178 filter, so, if we're writing to a capture file, write
2181 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2182 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2184 /* Error writing to a capture file */
2185 show_capture_file_io_error(save_file, err, FALSE);
2186 wtap_dump_close(pdh, &err);
2190 /* Stop reading if we have the maximum number of packets;
2191 * note that a zero max_packet_count will never be matched
2192 * (unless we roll over the packet number?)
2194 if(max_packet_count == cf->count || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2195 err = 0; /* This is not an error */
2201 /* Print a message noting that the read failed somewhere along the line. */
2204 case WTAP_ERR_UNSUPPORTED_ENCAP:
2205 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2206 cf->filename, err_info);
2209 case WTAP_ERR_CANT_READ:
2210 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2214 case WTAP_ERR_SHORT_READ:
2215 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2219 case WTAP_ERR_BAD_RECORD:
2220 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2221 cf->filename, err_info);
2225 cmdarg_err("An error occurred while reading \"%s\": %s.",
2226 cf->filename, wtap_strerror(err));
2229 if (save_file != NULL) {
2230 /* Now close the capture file. */
2231 if (!wtap_dump_close(pdh, &err))
2232 show_capture_file_io_error(save_file, err, TRUE);
2235 if (save_file != NULL) {
2236 /* Now close the capture file. */
2237 if (!wtap_dump_close(pdh, &err))
2238 show_capture_file_io_error(save_file, err, TRUE);
2240 if (print_packet_info) {
2241 if (!write_finale()) {
2243 show_print_file_io_error(err);
2250 wtap_close(cf->wth);
2253 if (save_file_string != NULL)
2254 g_free(save_file_string);
2260 fill_in_fdata(frame_data *fdata, capture_file *cf,
2261 const struct wtap_pkthdr *phdr, gint64 offset)
2266 fdata->num = cf->count;
2267 fdata->pkt_len = phdr->len;
2268 cum_bytes += phdr->len;
2269 fdata->cum_bytes = cum_bytes;
2270 fdata->cap_len = phdr->caplen;
2271 fdata->file_off = offset;
2272 fdata->lnk_t = phdr->pkt_encap;
2273 fdata->abs_ts.secs = phdr->ts.secs;
2274 fdata->abs_ts.nsecs = phdr->ts.nsecs;
2275 fdata->flags.passed_dfilter = 0;
2276 fdata->flags.encoding = CHAR_ASCII;
2277 fdata->flags.visited = 0;
2278 fdata->flags.marked = 0;
2279 fdata->flags.ref_time = 0;
2280 fdata->color_filter = NULL;
2282 /* If we don't have the time stamp of the first packet in the
2283 capture, it's because this is the first packet. Save the time
2284 stamp of this packet as the time stamp of the first packet. */
2285 if (nstime_is_zero(&first_ts)) {
2286 first_ts = fdata->abs_ts;
2289 /* If we don't have the time stamp of the previous captured packet,
2290 it's because this is the first packet. Save the time
2291 stamp of this packet as the time stamp of the previous captured
2293 if (nstime_is_zero(&prev_cap_ts)) {
2294 prev_cap_ts = fdata->abs_ts;
2297 /* Get the time elapsed between the first packet and this packet. */
2298 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2300 /* If it's greater than the current elapsed time, set the elapsed time
2301 to it (we check for "greater than" so as not to be confused by
2302 time moving backwards). */
2303 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2304 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2305 cf->elapsed_time = fdata->rel_ts;
2308 /* Get the time elapsed between the previous displayed packet and
2310 if (nstime_is_zero(&prev_dis_ts))
2311 nstime_set_zero(&fdata->del_dis_ts);
2313 nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2315 /* Get the time elapsed between the previous captured packet and
2317 nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2318 prev_cap_ts = fdata->abs_ts;
2321 /* Free up all data attached to a "frame_data" structure. */
2323 clear_fdata(frame_data *fdata)
2326 g_slist_free(fdata->pfd);
2330 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2331 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2334 gboolean create_proto_tree;
2335 epan_dissect_t *edt;
2338 /* Count this packet. */
2341 /* If we're going to print packet information, or we're going to
2342 run a read filter, or we're going to process taps, set up to
2343 do a dissection and do so. */
2344 if (do_dissection) {
2345 fill_in_fdata(&fdata, cf, whdr, offset);
2347 if (print_packet_info) {
2348 /* Grab any resolved addresses */
2350 if (g_resolv_flags) {
2351 host_name_lookup_process(NULL);
2356 if (cf->rfcode || verbose || num_tap_filters!=0)
2357 create_proto_tree = TRUE;
2359 create_proto_tree = FALSE;
2360 /* The protocol tree will be "visible", i.e., printed, only if we're
2361 printing packet details, which is true if we're printing stuff
2362 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2364 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2366 /* If we're running a read filter, prime the epan_dissect_t with that
2369 epan_dissect_prime_dfilter(edt, cf->rfcode);
2371 tap_queue_init(edt);
2373 /* We only need the columns if we're printing packet info but we're
2374 *not* verbose; in verbose mode, we print the protocol tree, not
2375 the protocol summary. */
2376 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2377 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2379 tap_push_tapped_queue(edt);
2381 /* Run the read filter if we have one. */
2383 passed = dfilter_apply_edt(cf->rfcode, edt);
2387 /* We're not running a display filter and we're not printing any
2388 packet information, so we don't need to do a dissection, and all
2389 packets are processed. */
2395 /* Keep the time of the current packet if the packet passed
2396 the read filter so that the delta time since last displayed
2397 packet can be calculated */
2398 prev_dis_ts = fdata.abs_ts;
2400 /* Process this packet. */
2401 if (print_packet_info) {
2402 /* We're printing packet information; print the information for
2404 print_packet(cf, edt);
2406 /* The ANSI C standard does not appear to *require* that a line-buffered
2407 stream be flushed to the host environment whenever a newline is
2408 written, it just says that, on such a stream, characters "are
2409 intended to be transmitted to or from the host environment as a
2410 block when a new-line character is encountered".
2412 The Visual C++ 6.0 C implementation doesn't do what is intended;
2413 even if you set a stream to be line-buffered, it still doesn't
2414 flush the buffer at the end of every line.
2416 So, if the "-l" flag was specified, we flush the standard output
2417 at the end of a packet. This will do the right thing if we're
2418 printing packet summary lines, and, as we print the entire protocol
2419 tree for a single packet without waiting for anything to happen,
2420 it should be as good as line-buffered mode if we're printing
2421 protocol trees. (The whole reason for the "-l" flag in either
2422 tcpdump or TShark is to allow the output of a live capture to
2423 be piped to a program or script and to have that script see the
2424 information for the packet as soon as it's printed, rather than
2425 having to wait until a standard I/O buffer fills up. */
2429 if (ferror(stdout)) {
2430 show_print_file_io_error(errno);
2436 if (do_dissection) {
2437 epan_dissect_free(edt);
2438 clear_fdata(&fdata);
2444 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2446 char *save_file_string;
2448 save_file_string = output_file_description(fname);
2453 cmdarg_err("Not all the packets could be written to the %s because there is "
2454 "no space left on the file system.",
2460 cmdarg_err("Not all the packets could be written to the %s because you are "
2461 "too close to, or over your disk quota.",
2466 case WTAP_ERR_CANT_CLOSE:
2467 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2471 case WTAP_ERR_SHORT_WRITE:
2472 cmdarg_err("Not all the packets could be written to the %s.",
2478 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2479 wtap_strerror(err));
2481 cmdarg_err("An error occurred while writing to the %s: %s.",
2482 save_file_string, wtap_strerror(err));
2486 g_free(save_file_string);
2490 write_preamble(capture_file *cf)
2492 switch (output_action) {
2495 return print_preamble(print_stream, cf->filename);
2500 write_pdml_preamble(stdout);
2502 write_psml_preamble(stdout);
2503 return !ferror(stdout);
2506 write_fields_preamble(output_fields, stdout);
2507 return !ferror(stdout);
2510 g_assert_not_reached();
2516 get_line_buf(size_t len)
2518 static char *line_bufp = NULL;
2519 static size_t line_buf_len = 256;
2520 size_t new_line_buf_len;
2522 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2523 new_line_buf_len *= 2)
2525 if (line_bufp == NULL) {
2526 line_buf_len = new_line_buf_len;
2527 line_bufp = g_malloc(line_buf_len + 1);
2529 if (new_line_buf_len > line_buf_len) {
2530 line_buf_len = new_line_buf_len;
2531 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2538 print_columns(capture_file *cf)
2545 line_bufp = get_line_buf(256);
2548 for (i = 0; i < cf->cinfo.num_cols; i++) {
2549 switch (cf->cinfo.col_fmt[i]) {
2553 * Don't print this if we're doing a live capture from a network
2554 * interface - if we're doing a live capture, you won't be
2555 * able to look at the capture in the future (it's not being
2556 * saved anywhere), so the frame numbers are unlikely to be
2559 * (XXX - it might be nice to be able to save and print at
2560 * the same time, sort of like an "Update list of packets
2561 * in real time" capture in Wireshark.)
2563 if (capture_opts.iface != NULL)
2566 column_len = strlen(cf->cinfo.col_data[i]);
2569 line_bufp = get_line_buf(buf_offset + column_len);
2570 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2576 case COL_ABS_DATE_TIME: /* XXX - wider */
2577 column_len = strlen(cf->cinfo.col_data[i]);
2578 if (column_len < 10)
2580 line_bufp = get_line_buf(buf_offset + column_len);
2581 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2587 case COL_DEF_DL_SRC:
2588 case COL_RES_DL_SRC:
2589 case COL_UNRES_DL_SRC:
2590 case COL_DEF_NET_SRC:
2591 case COL_RES_NET_SRC:
2592 case COL_UNRES_NET_SRC:
2593 column_len = strlen(cf->cinfo.col_data[i]);
2594 if (column_len < 12)
2596 line_bufp = get_line_buf(buf_offset + column_len);
2597 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2603 case COL_DEF_DL_DST:
2604 case COL_RES_DL_DST:
2605 case COL_UNRES_DL_DST:
2606 case COL_DEF_NET_DST:
2607 case COL_RES_NET_DST:
2608 case COL_UNRES_NET_DST:
2609 column_len = strlen(cf->cinfo.col_data[i]);
2610 if (column_len < 12)
2612 line_bufp = get_line_buf(buf_offset + column_len);
2613 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2617 column_len = strlen(cf->cinfo.col_data[i]);
2618 line_bufp = get_line_buf(buf_offset + column_len);
2619 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2622 buf_offset += column_len;
2623 if (i != cf->cinfo.num_cols - 1) {
2625 * This isn't the last column, so we need to print a
2626 * separator between this column and the next.
2628 * If we printed a network source and are printing a
2629 * network destination of the same type next, separate
2630 * them with "->"; if we printed a network destination
2631 * and are printing a network source of the same type
2632 * next, separate them with "<-"; otherwise separate them
2635 * We add enough space to the buffer for " <- " or " -> ",
2636 * even if we're only adding " ".
2638 line_bufp = get_line_buf(buf_offset + 4);
2639 switch (cf->cinfo.col_fmt[i]) {
2644 switch (cf->cinfo.col_fmt[i + 1]) {
2649 strcat(line_bufp + buf_offset, " -> ");
2654 strcat(line_bufp + buf_offset, " ");
2660 case COL_DEF_DL_SRC:
2661 case COL_RES_DL_SRC:
2662 case COL_UNRES_DL_SRC:
2663 switch (cf->cinfo.col_fmt[i + 1]) {
2665 case COL_DEF_DL_DST:
2666 case COL_RES_DL_DST:
2667 case COL_UNRES_DL_DST:
2668 strcat(line_bufp + buf_offset, " -> ");
2673 strcat(line_bufp + buf_offset, " ");
2679 case COL_DEF_NET_SRC:
2680 case COL_RES_NET_SRC:
2681 case COL_UNRES_NET_SRC:
2682 switch (cf->cinfo.col_fmt[i + 1]) {
2684 case COL_DEF_NET_DST:
2685 case COL_RES_NET_DST:
2686 case COL_UNRES_NET_DST:
2687 strcat(line_bufp + buf_offset, " -> ");
2692 strcat(line_bufp + buf_offset, " ");
2701 switch (cf->cinfo.col_fmt[i + 1]) {
2706 strcat(line_bufp + buf_offset, " <- ");
2711 strcat(line_bufp + buf_offset, " ");
2717 case COL_DEF_DL_DST:
2718 case COL_RES_DL_DST:
2719 case COL_UNRES_DL_DST:
2720 switch (cf->cinfo.col_fmt[i + 1]) {
2722 case COL_DEF_DL_SRC:
2723 case COL_RES_DL_SRC:
2724 case COL_UNRES_DL_SRC:
2725 strcat(line_bufp + buf_offset, " <- ");
2730 strcat(line_bufp + buf_offset, " ");
2736 case COL_DEF_NET_DST:
2737 case COL_RES_NET_DST:
2738 case COL_UNRES_NET_DST:
2739 switch (cf->cinfo.col_fmt[i + 1]) {
2741 case COL_DEF_NET_SRC:
2742 case COL_RES_NET_SRC:
2743 case COL_UNRES_NET_SRC:
2744 strcat(line_bufp + buf_offset, " <- ");
2749 strcat(line_bufp + buf_offset, " ");
2756 strcat(line_bufp + buf_offset, " ");
2762 return print_line(print_stream, 0, line_bufp);
2766 print_packet(capture_file *cf, epan_dissect_t *edt)
2768 print_args_t print_args;
2771 /* Print the information in the protocol tree. */
2772 switch (output_action) {
2775 print_args.to_file = TRUE;
2776 print_args.format = print_format;
2777 print_args.print_summary = !verbose;
2778 print_args.print_hex = verbose && print_hex;
2779 print_args.print_formfeed = FALSE;
2780 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2782 /* init the packet range */
2783 packet_range_init(&print_args.range);
2785 if (!proto_tree_print(&print_args, edt, print_stream))
2788 /* "print_hex_data()" will put out a leading blank line, as well
2789 as a trailing one; print one here, to separate the packets,
2790 only if "print_hex_data()" won't be called. */
2791 if (!print_line(print_stream, 0, ""))
2797 proto_tree_write_pdml(edt, stdout);
2799 return !ferror(stdout);
2801 proto_tree_write_fields(output_fields, edt, stdout);
2803 return !ferror(stdout);
2806 /* Just fill in the columns. */
2807 epan_dissect_fill_in_columns(edt);
2809 /* Now print them. */
2810 switch (output_action) {
2813 if (!print_columns(cf))
2818 proto_tree_write_psml(edt, stdout);
2819 return !ferror(stdout);
2820 case WRITE_FIELDS: /*No non-verbose "fields" format */
2821 g_assert_not_reached();
2826 if (!print_hex_data(print_stream, edt))
2828 if (!print_line(print_stream, 0, ""))
2837 switch (output_action) {
2840 return print_finale(print_stream);
2845 write_pdml_finale(stdout);
2847 write_psml_finale(stdout);
2848 return !ferror(stdout);
2851 write_fields_finale(output_fields, stdout);
2852 return !ferror(stdout);
2855 g_assert_not_reached();
2861 show_print_file_io_error(int err)
2866 cmdarg_err("Not all the packets could be printed because there is "
2867 "no space left on the file system.");
2872 cmdarg_err("Not all the packets could be printed because you are "
2873 "too close to, or over your disk quota.");
2878 cmdarg_err("An error occurred while printing packets: %s.",
2885 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2889 static char errmsg_errno[1024+1];
2892 /* Wiretap error. */
2895 case WTAP_ERR_NOT_REGULAR_FILE:
2896 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2899 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2900 /* Seen only when opening a capture file for reading. */
2901 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2904 case WTAP_ERR_UNSUPPORTED:
2905 /* Seen only when opening a capture file for reading. */
2906 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2907 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2910 errmsg = errmsg_errno;
2913 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2914 /* Seen only when opening a capture file for writing. */
2915 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2916 "The file \"%%s\" is a pipe, and %s capture files can't be "
2917 "written to a pipe.", wtap_file_type_string(file_type));
2918 errmsg = errmsg_errno;
2921 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2922 /* Seen only when opening a capture file for writing. */
2923 errmsg = "TShark doesn't support writing capture files in that format.";
2926 case WTAP_ERR_UNSUPPORTED_ENCAP:
2928 errmsg = "TShark can't save this capture in that format.";
2930 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2931 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
2934 errmsg = errmsg_errno;
2938 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2940 errmsg = "TShark can't save this capture in that format.";
2942 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
2945 case WTAP_ERR_BAD_RECORD:
2946 /* Seen only when opening a capture file for reading. */
2947 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2948 "The file \"%%s\" appears to be damaged or corrupt.\n"
2951 errmsg = errmsg_errno;
2954 case WTAP_ERR_CANT_OPEN:
2956 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2958 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2961 case WTAP_ERR_SHORT_READ:
2962 errmsg = "The file \"%s\" appears to have been cut short"
2963 " in the middle of a packet or other data.";
2966 case WTAP_ERR_SHORT_WRITE:
2967 errmsg = "A full header couldn't be written to the file \"%s\".";
2971 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2972 "The file \"%%s\" could not be %s: %s.",
2973 for_writing ? "created" : "opened",
2974 wtap_strerror(err));
2975 errmsg = errmsg_errno;
2979 errmsg = file_open_error_message(err, for_writing);
2984 * Open/create errors are reported with an console message in TShark.
2987 open_failure_message(const char *filename, int err, gboolean for_writing)
2989 fprintf(stderr, "tshark: ");
2990 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2991 fprintf(stderr, "\n");
2995 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2999 char err_msg[2048+1];
3001 wth = wtap_open_offline(fname, err, &err_info, FALSE);
3005 /* The open succeeded. Fill in the information for this file. */
3007 /* Initialize all data structures used for dissection. */
3011 cf->f_datalen = 0; /* not used, but set it anyway */
3013 /* Set the file name because we need it to set the follow stream filter.
3014 XXX - is that still true? We need it for other reasons, though,
3016 cf->filename = g_strdup(fname);
3018 /* Indicate whether it's a permanent or temporary file. */
3019 cf->is_tempfile = is_tempfile;
3021 /* If it's a temporary capture buffer file, mark it as not saved. */
3022 cf->user_saved = !is_tempfile;
3024 cf->cd_t = wtap_file_type(cf->wth);
3026 cf->drops_known = FALSE;
3028 cf->snap = wtap_snapshot_length(cf->wth);
3029 if (cf->snap == 0) {
3030 /* Snapshot length not known. */
3031 cf->has_snap = FALSE;
3032 cf->snap = WTAP_MAX_PACKET_SIZE;
3034 cf->has_snap = TRUE;
3035 nstime_set_zero(&cf->elapsed_time);
3036 nstime_set_zero(&first_ts);
3037 nstime_set_zero(&prev_dis_ts);
3038 nstime_set_zero(&prev_cap_ts);
3043 g_snprintf(err_msg, sizeof err_msg,
3044 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3045 cmdarg_err("%s", err_msg);
3051 * General errors are reported with an console message in TShark.
3054 failure_message(const char *msg_format, va_list ap)
3056 fprintf(stderr, "tshark: ");
3057 vfprintf(stderr, msg_format, ap);
3058 fprintf(stderr, "\n");
3062 * Read errors are reported with an console message in TShark.
3065 read_failure_message(const char *filename, int err)
3067 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3068 filename, strerror(err));
3072 * Report an error in command-line arguments.
3075 cmdarg_err(const char *fmt, ...)
3080 fprintf(stderr, "tshark: ");
3081 vfprintf(stderr, fmt, ap);
3082 fprintf(stderr, "\n");
3087 * Report additional information for an error in command-line arguments.
3090 cmdarg_err_cont(const char *fmt, ...)
3095 vfprintf(stderr, fmt, ap);
3096 fprintf(stderr, "\n");
3101 /****************************************************************************************************************/
3102 /* indication report "dummies", needed for capture_loop.c */
3106 /** Report a new capture file having been opened. */
3108 report_new_capture_file(const char *filename _U_)
3110 /* shouldn't happen */
3111 g_assert_not_reached();
3114 /** Report a number of new packets captured. */
3116 report_packet_count(int packet_count _U_)
3118 /* shouldn't happen */
3119 g_assert_not_reached();
3122 /** Report the packet drops once the capture finishes. */
3124 report_packet_drops(int drops _U_)
3126 /* shouldn't happen */
3127 g_assert_not_reached();
3130 /** Report an error in the capture. */
3132 report_capture_error(const char *errmsg, const char *secondary_error_msg)
3135 cmdarg_err_cont(secondary_error_msg);
3138 /** Report an error with a capture filter. */
3140 report_cfilter_error(const char *cfilter, const char *errmsg)
3144 "Invalid capture filter: \"%s\"!\n"
3146 "That string isn't a valid capture filter (%s).\n"
3147 "See the User's Guide for a description of the capture filter syntax.",
3151 #endif /* HAVE_LIBPCAP */
3154 /****************************************************************************************************************/
3155 /* signal pipe "dummies", needed for capture_loop.c */
3161 signal_pipe_check_running(void)
3163 /* currently, no check required */
3168 #endif /* HAVE_LIBPCAP */