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 * Get credential information for later use.
726 get_credential_info();
729 * Attempt to get the pathname of the executable file.
731 init_progfile_dir_error = init_progfile_dir(argv[0]);
732 if (init_progfile_dir_error != NULL) {
733 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
734 init_progfile_dir_error);
738 * In order to have the -X opts assigned before the wslua machine starts
739 * we need to call getopts before epan_init() gets called.
742 optind_initial = optind;
744 while ((opt = getopt(argc, argv, optstring)) != -1) {
754 optind = optind_initial;
757 /* nothing more than the standard GLib handler, but without a warning */
764 g_log_set_handler(NULL,
766 log_func_ignore, NULL /* user_data */);
767 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
769 log_func_ignore, NULL /* user_data */);
771 initialize_funnel_ops();
774 capture_opts_init(&capture_opts, NULL /* cfile */);
777 timestamp_set_type(TS_RELATIVE);
778 timestamp_set_precision(TS_PREC_AUTO);
780 /* Register all dissectors; we must do this before checking for the
781 "-G" flag, as the "-G" flag dumps information registered by the
782 dissectors, and we must do it before we read the preferences, in
783 case any dissectors register preferences. */
784 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
785 failure_message, open_failure_message, read_failure_message);
787 /* Register all tap listeners; we do this before we parse the arguments,
788 as the "-z" argument can specify a registered tap. */
790 /* we register the plugin taps before the other taps because
791 stats_tree taps plugins will be registered as tap listeners
792 by stats_tree_stat.c and need to registered before that */
794 register_all_plugin_tap_listeners();
796 register_all_tap_listeners();
798 /* Now register the preferences for any non-dissector modules.
799 We must do that before we read the preferences as well. */
800 prefs_register_modules();
802 /* If invoked with the "-G" flag, we dump out information based on
803 the argument to the "-G" flag; if no argument is specified,
804 for backwards compatibility we dump out a glossary of display
807 XXX - we do this here, for now, to support "-G" with no arguments.
808 If none of our build or other processes uses "-G" with no arguments,
809 we can just process it with the other arguments. */
810 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
812 proto_registrar_dump_fields(1);
814 if (strcmp(argv[2], "fields") == 0)
815 proto_registrar_dump_fields(1);
816 else if (strcmp(argv[2], "fields2") == 0)
817 proto_registrar_dump_fields(2);
818 else if (strcmp(argv[2], "fields3") == 0)
819 proto_registrar_dump_fields(3);
820 else if (strcmp(argv[2], "protocols") == 0)
821 proto_registrar_dump_protocols();
822 else if (strcmp(argv[2], "values") == 0)
823 proto_registrar_dump_values();
824 else if (strcmp(argv[2], "decodes") == 0)
825 dissector_dump_decodes();
826 else if (strcmp(argv[2], "defaultprefs") == 0)
828 else if (strcmp(argv[2], "currentprefs") == 0) {
829 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
830 &pf_open_errno, &pf_read_errno, &pf_path);
833 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
840 /* Set the C-language locale to the native environment. */
841 setlocale(LC_ALL, "");
843 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
844 &pf_open_errno, &pf_read_errno, &pf_path);
845 if (gpf_path != NULL) {
846 if (gpf_open_errno != 0) {
847 cmdarg_err("Can't open global preferences file \"%s\": %s.",
848 pf_path, strerror(gpf_open_errno));
850 if (gpf_read_errno != 0) {
851 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
852 pf_path, strerror(gpf_read_errno));
855 if (pf_path != NULL) {
856 if (pf_open_errno != 0) {
857 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
858 strerror(pf_open_errno));
860 if (pf_read_errno != 0) {
861 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
862 pf_path, strerror(pf_read_errno));
868 /* Set the name resolution code's flags from the preferences. */
869 g_resolv_flags = prefs->name_resolve;
871 /* Read the disabled protocols file. */
872 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
873 &dp_path, &dp_open_errno, &dp_read_errno);
874 if (gdp_path != NULL) {
875 if (gdp_open_errno != 0) {
876 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
877 gdp_path, strerror(gdp_open_errno));
879 if (gdp_read_errno != 0) {
880 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
881 gdp_path, strerror(gdp_read_errno));
885 if (dp_path != NULL) {
886 if (dp_open_errno != 0) {
888 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
889 strerror(dp_open_errno));
891 if (dp_read_errno != 0) {
893 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
894 strerror(dp_read_errno));
900 /* Load Wpcap, if possible */
904 init_cap_file(&cfile);
906 /* Assemble the compile-time version information string */
907 comp_info_str = g_string_new("Compiled ");
908 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
910 /* Assemble the run-time version information string */
911 runtime_info_str = g_string_new("Running ");
912 get_runtime_version_info(runtime_info_str, NULL);
914 /* Print format defaults to this. */
915 print_format = PR_FMT_TEXT;
917 output_fields = output_fields_new();
919 /* Now get our args */
920 while ((opt = getopt(argc, argv, optstring)) != -1) {
922 case 'a': /* autostop criteria */
923 case 'b': /* Ringbuffer option */
924 case 'c': /* Capture xxx packets */
925 case 'f': /* capture filter */
926 case 'i': /* Use interface xxx */
927 case 'p': /* Don't capture in promiscuous mode */
928 case 's': /* Set the snapshot (capture) length */
929 case 'w': /* Write to capture file xxx */
930 case 'y': /* Set the pcap data link type */
932 case 'B': /* Buffer size */
935 status = capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
940 capture_option_specified = TRUE;
944 case 'd': /* Decode as rule */
945 if (!add_decode_as(optarg))
948 case 'D': /* Print a list of capture devices and exit */
950 status = capture_opts_list_interfaces(FALSE);
953 capture_option_specified = TRUE;
959 output_fields_add(output_fields, optarg);
963 if(!output_fields_set_option(output_fields, optarg)) {
964 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
965 output_fields_list_options(stderr);
970 out_file_type = wtap_short_string_to_file_type(optarg);
971 if (out_file_type < 0) {
972 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
973 list_capture_types();
977 case 'h': /* Print help and exit */
981 case 'l': /* "Line-buffer" standard output */
982 /* This isn't line-buffering, strictly speaking, it's just
983 flushing the standard output after the information for
984 each packet is printed; however, that should be good
985 enough for all the purposes to which "-l" is put (and
986 is probably actually better for "-V", as it does fewer
989 See the comment in "process_packet()" for an explanation of
990 why we do that, and why we don't just use "setvbuf()" to
991 make the standard output line-buffered (short version: in
992 Windows, "line-buffered" is the same as "fully-buffered",
993 and the output buffer is only flushed when it fills up). */
994 line_buffered = TRUE;
996 case 'L': /* Print list of link-layer types and exit */
998 list_link_layer_types = TRUE;
1001 capture_option_specified = TRUE;
1005 case 'n': /* No name resolution */
1006 g_resolv_flags = RESOLV_NONE;
1008 case 'N': /* Select what types of addresses/port #s to resolve */
1009 if (g_resolv_flags == RESOLV_ALL)
1010 g_resolv_flags = RESOLV_NONE;
1011 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1012 if (badopt != '\0') {
1013 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
1018 case 'o': /* Override preference from command line */
1019 switch (prefs_set_pref(optarg)) {
1024 case PREFS_SET_SYNTAX_ERR:
1025 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1029 case PREFS_SET_NO_SUCH_PREF:
1030 case PREFS_SET_OBSOLETE:
1031 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1036 case 'q': /* Quiet */
1039 case 'r': /* Read capture file xxx */
1040 cf_name = g_strdup(optarg);
1042 case 'R': /* Read file filter */
1045 case 'S': /* show packets in real time */
1046 print_packet_info = TRUE;
1048 case 't': /* Time stamp type */
1049 if (strcmp(optarg, "r") == 0)
1050 timestamp_set_type(TS_RELATIVE);
1051 else if (strcmp(optarg, "a") == 0)
1052 timestamp_set_type(TS_ABSOLUTE);
1053 else if (strcmp(optarg, "ad") == 0)
1054 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1055 else if (strcmp(optarg, "d") == 0)
1056 timestamp_set_type(TS_DELTA);
1057 else if (strcmp(optarg, "dd") == 0)
1058 timestamp_set_type(TS_DELTA_DIS);
1059 else if (strcmp(optarg, "e") == 0)
1060 timestamp_set_type(TS_EPOCH);
1062 cmdarg_err("Invalid time stamp type \"%s\"",
1064 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1065 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1069 case 'T': /* printing Type */
1070 if (strcmp(optarg, "text") == 0) {
1071 output_action = WRITE_TEXT;
1072 print_format = PR_FMT_TEXT;
1073 } else if (strcmp(optarg, "ps") == 0) {
1074 output_action = WRITE_TEXT;
1075 print_format = PR_FMT_PS;
1076 } else if (strcmp(optarg, "pdml") == 0) {
1077 output_action = WRITE_XML;
1079 } else if (strcmp(optarg, "psml") == 0) {
1080 output_action = WRITE_XML;
1082 } else if(strcmp(optarg, "fields") == 0) {
1083 output_action = WRITE_FIELDS;
1084 verbose = TRUE; /* Need full tree info */
1086 cmdarg_err("Invalid -T parameter.");
1087 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1091 case 'v': /* Show version and exit */
1092 printf("TShark " VERSION "%s\n"
1099 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1100 runtime_info_str->str);
1103 case 'V': /* Verbose */
1106 case 'x': /* Print packet data in hex (and ASCII) */
1112 /* We won't call the init function for the stat this soon
1113 as it would disallow MATE's fields (which are registered
1114 by the preferences set callback) from being used as
1115 part of a tap filter. Instead, we just add the argument
1116 to a list of stat arguments. */
1117 if (!process_stat_cmd_arg(optarg)) {
1118 cmdarg_err("invalid -z argument.");
1119 cmdarg_err_cont(" -z argument must be one of :");
1120 list_stat_cmd_args();
1125 case '?': /* Bad flag - print usage message */
1128 list_capture_types();
1138 /* If we specified output fields, but not the output field type... */
1139 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1140 cmdarg_err("Output fields were specified with \"-e\", "
1141 "but \"-Tfields\" was not specified.");
1143 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1144 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1145 "specified with \"-e\".");
1150 /* If no capture filter or read filter has been specified, and there are
1151 still command-line arguments, treat them as the tokens of a capture
1152 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1153 flag was specified. */
1154 if (optind < argc) {
1155 if (cf_name != NULL) {
1156 if (rfilter != NULL) {
1157 cmdarg_err("Read filters were specified both with \"-R\" "
1158 "and with additional command-line arguments");
1161 rfilter = get_args_as_string(argc, argv, optind);
1164 if (capture_opts.has_cfilter) {
1165 cmdarg_err("Capture filters were specified both with \"-f\""
1166 " and with additional command-line arguments");
1169 capture_opts.has_cfilter = TRUE;
1170 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1172 capture_option_specified = TRUE;
1178 if (!capture_opts.saving_to_file) {
1179 /* We're not saving the capture to a file; if "-q" wasn't specified,
1180 we should print packet information */
1182 print_packet_info = TRUE;
1184 /* We're saving to a file; if we're writing to the standard output.
1185 and we'll also be writing dissected packets to the standard
1186 output, reject the request. At best, we could redirect that
1187 to the standard error; we *can't* write both to the standard
1188 output and have either of them be useful. */
1189 if (strcmp(capture_opts.save_file, "-") == 0 && print_packet_info) {
1190 cmdarg_err("You can't write both raw packet data and dissected packets"
1191 " to the standard output.");
1196 /* We're not saving the capture to a file; if "-q" wasn't specified,
1197 we should print packet information */
1199 print_packet_info = TRUE;
1202 #ifndef HAVE_LIBPCAP
1203 if (capture_option_specified)
1204 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1211 /* We don't support capture filters when reading from a capture file
1212 (the BPF compiler doesn't support all link-layer types that we
1213 support in capture files we read). */
1215 if (cf_name != NULL) {
1216 if (capture_opts.has_cfilter) {
1217 cmdarg_err("Only read filters, not capture filters, "
1218 "can be specified when reading a capture file.");
1225 if (output_action != WRITE_TEXT) {
1226 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1232 if (list_link_layer_types) {
1233 /* We're supposed to list the link-layer types for an interface;
1234 did the user also specify a capture file to be read? */
1236 /* Yes - that's bogus. */
1237 cmdarg_err("You can't specify -L and a capture file to be read.");
1240 /* No - did they specify a ring buffer option? */
1241 if (capture_opts.multi_files_on) {
1242 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1248 * "-r" was specified, so we're reading a capture file.
1249 * Capture options don't apply here.
1251 if (capture_opts.multi_files_on) {
1252 cmdarg_err("Multiple capture files requested, but "
1253 "a capture isn't being done.");
1256 if (capture_opts.has_file_duration) {
1257 cmdarg_err("Switching capture files after a time interval was specified, but "
1258 "a capture isn't being done.");
1261 if (capture_opts.has_ring_num_files) {
1262 cmdarg_err("A ring buffer of capture files was specified, but "
1263 "a capture isn't being done.");
1266 if (capture_opts.has_autostop_files) {
1267 cmdarg_err("A maximum number of capture files was specified, but "
1268 "a capture isn't being done.");
1272 /* Note: TShark now allows the restriction of a _read_ file by packet count
1273 * and byte count as well as a write file. Other autostop options remain valid
1274 * only for a write file.
1276 if (capture_opts.has_autostop_duration) {
1277 cmdarg_err("A maximum capture time was specified, but "
1278 "a capture isn't being done.");
1283 * "-r" wasn't specified, so we're doing a live capture.
1285 if (capture_opts.saving_to_file) {
1286 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1288 /* When capturing, we only support writing libpcap format. */
1289 if (out_file_type != WTAP_FILE_PCAP) {
1290 cmdarg_err("Live captures can only be saved in libpcap format.");
1293 if (capture_opts.multi_files_on) {
1294 /* Multiple-file mode doesn't work under certain conditions:
1295 a) it doesn't work if you're writing to the standard output;
1296 b) it doesn't work if you're writing to a pipe;
1298 if (strcmp(capture_opts.save_file, "-") == 0) {
1299 cmdarg_err("Multiple capture files requested, but "
1300 "the capture is being written to the standard output.");
1303 if (capture_opts.output_to_pipe) {
1304 cmdarg_err("Multiple capture files requested, but "
1305 "the capture file is a pipe.");
1308 if (!capture_opts.has_autostop_filesize &&
1309 !capture_opts.has_file_duration) {
1310 cmdarg_err("Multiple capture files requested, but "
1311 "no maximum capture file size or duration was specified.");
1316 /* They didn't specify a "-w" flag, so we won't be saving to a
1317 capture file. Check for options that only make sense if
1318 we're saving to a file. */
1319 if (capture_opts.has_autostop_filesize) {
1320 cmdarg_err("Maximum capture file size specified, but "
1321 "capture isn't being saved to a file.");
1324 if (capture_opts.multi_files_on) {
1325 cmdarg_err("Multiple capture files requested, but "
1326 "the capture isn't being saved to a file.");
1335 /* Start windows sockets */
1336 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1339 /* Notify all registered modules that have had any of their preferences
1340 changed either from one of the preferences file or from the command
1341 line that their preferences have changed. */
1344 /* At this point MATE will have registered its field array so we can
1345 have a tap filter with one of MATE's late-registered fields as part
1346 of the filter. We can now process all the "-z" arguments. */
1347 start_requested_stats();
1349 /* disabled protocols as per configuration file */
1350 if (gdp_path == NULL && dp_path == NULL) {
1351 set_disabled_protos_list();
1354 /* Build the column format array */
1355 col_setup(&cfile.cinfo, prefs->num_cols);
1356 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1357 cfile.cinfo.col_fmt[i] = get_column_format(i);
1358 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1359 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1361 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1362 cfile.cinfo.col_data[i] = NULL;
1363 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1364 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1366 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1367 cfile.cinfo.col_fence[i] = 0;
1368 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1369 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1372 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1375 for (j = 0; j < NUM_COL_FMTS; j++) {
1376 if (!cfile.cinfo.fmt_matx[i][j])
1379 if (cfile.cinfo.col_first[j] == -1)
1380 cfile.cinfo.col_first[j] = i;
1381 cfile.cinfo.col_last[j] = i;
1386 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1387 capture_opts_trim_ring_num_files(&capture_opts);
1390 if (rfilter != NULL) {
1391 if (!dfilter_compile(rfilter, &rfcode)) {
1392 cmdarg_err("%s", dfilter_error_msg);
1394 #ifdef HAVE_PCAP_OPEN_DEAD
1398 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1400 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1402 " Note: That display filter code looks like a valid capture filter;");
1404 " maybe you mixed them up?");
1413 cfile.rfcode = rfcode;
1415 if (print_packet_info) {
1416 /* If we're printing as text or PostScript, we have
1417 to create a print stream. */
1418 if (output_action == WRITE_TEXT) {
1419 switch (print_format) {
1422 print_stream = print_stream_text_stdio_new(stdout);
1426 print_stream = print_stream_ps_stdio_new(stdout);
1430 g_assert_not_reached();
1435 /* We have to dissect each packet if:
1437 we're printing information about each packet;
1439 we're using a read filter on the packets;
1441 we're using any taps. */
1442 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1446 * We're reading a capture file.
1450 * Immediately relinquish any special privileges we have; we must not
1451 * be allowed to read any capture files the user running TShark
1454 relinquish_special_privs_perm();
1456 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1461 /* Set timestamp precision; there should arguably be a command-line
1462 option to let the user set this. */
1463 switch(wtap_file_tsprecision(cfile.wth)) {
1464 case(WTAP_FILE_TSPREC_SEC):
1465 timestamp_set_precision(TS_PREC_AUTO_SEC);
1467 case(WTAP_FILE_TSPREC_DSEC):
1468 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1470 case(WTAP_FILE_TSPREC_CSEC):
1471 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1473 case(WTAP_FILE_TSPREC_MSEC):
1474 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1476 case(WTAP_FILE_TSPREC_USEC):
1477 timestamp_set_precision(TS_PREC_AUTO_USEC);
1479 case(WTAP_FILE_TSPREC_NSEC):
1480 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1483 g_assert_not_reached();
1486 /* Process the packets in the file */
1488 err = load_cap_file(&cfile, capture_opts.save_file, out_file_type,
1489 capture_opts.has_autostop_packets ? capture_opts.autostop_packets : 0,
1490 capture_opts.has_autostop_filesize ? capture_opts.autostop_filesize : 0);
1492 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1500 /* No capture file specified, so we're supposed to do a live capture
1501 (or get a list of link-layer types for a live capture device);
1502 do we have support for live captures? */
1509 cmdarg_err("WinPcap couldn't be found.");
1510 detailed_err = cant_load_winpcap_err("TShark");
1511 cmdarg_err_cont("%s", detailed_err);
1512 g_free(detailed_err);
1517 /* trim the interface name and exit if that failed */
1518 if (!capture_opts_trim_iface(&capture_opts,
1519 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1523 /* if requested, list the link layer types and exit */
1524 if (list_link_layer_types) {
1525 status = capture_opts_list_link_layer_types(&capture_opts, FALSE);
1529 if (print_packet_info) {
1530 if (!write_preamble(NULL)) {
1532 show_print_file_io_error(err);
1535 } else if (!quiet) {
1537 * We're not printing information for each packet, and the user
1538 * didn't ask us not to print a count of packets as they arrive,
1539 * so print that count so the user knows that packets are arriving.
1541 * XXX - what if the user wants to do a live capture, doesn't want
1542 * to save it to a file, doesn't want information printed for each
1543 * packet, does want some "-z" statistic, and wants packet counts
1544 * so they know whether they're seeing any packets?
1546 print_packet_counts = TRUE;
1549 /* For now, assume libpcap gives microsecond precision. */
1550 timestamp_set_precision(TS_PREC_AUTO_USEC);
1554 if (capture_opts.multi_files_on) {
1558 if (print_packet_info) {
1559 if (!write_finale()) {
1561 show_print_file_io_error(err);
1565 /* No - complain. */
1566 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1571 draw_tap_listeners(TRUE);
1572 funnel_dump_all_text_windows();
1575 output_fields_free(output_fields);
1576 output_fields = NULL;
1582 /* Do the low-level work of a capture.
1583 Returns TRUE if it succeeds, FALSE otherwise. */
1585 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1591 int volatile volatile_err = 0;
1592 int volatile inpkts = 0;
1594 condition *volatile cnd_autostop_size = NULL;
1595 condition *volatile cnd_autostop_duration = NULL;
1597 void (*oldhandler)(int);
1599 struct pcap_stat stats;
1602 gboolean cfilter_error = FALSE;
1603 char errmsg[1024+1];
1604 char secondary_errmsg[4096+1];
1607 /* Initialize all data structures used for dissection. */
1610 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1612 ld.packet_cb = capture_pcap_cb;
1615 /* open the "input file" from network interface or capture pipe */
1616 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg),
1617 secondary_errmsg, sizeof(secondary_errmsg))) {
1622 * We've opened the capture device, so we shouldn't need any special
1623 * privileges any more; relinquish those privileges.
1625 * XXX - if we have saved set-user-ID support, we should give up those
1626 * privileges immediately, and then reclaim them long enough to get
1627 * a list of network interfaces and to open one, and then give them
1628 * up again, so that stuff we do while processing the argument list,
1629 * reading the user's preferences, loading and starting plugins
1630 * (especially *user* plugins), etc. is done with the user's privileges,
1631 * not special privileges.
1633 relinquish_special_privs_perm();
1635 /* init the input filter from the network interface (capture pipe will do nothing) */
1636 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts.iface, capture_opts.cfilter)) {
1638 case INITFILTER_NO_ERROR:
1641 case INITFILTER_BAD_FILTER:
1642 cfilter_error = TRUE;
1643 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1644 *secondary_errmsg = '\0';
1647 case INITFILTER_OTHER_ERROR:
1648 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1649 pcap_geterr(ld.pcap_h));
1650 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1654 if (capture_opts.saving_to_file) {
1655 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1656 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1657 *secondary_errmsg = '\0';
1661 /* set up to write to the already-opened capture output file/files */
1662 if(!capture_loop_init_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg)) {
1663 *secondary_errmsg = '\0';
1667 /* Save the capture file name. */
1668 ld.save_file = capture_opts.save_file;
1671 ld.wtap_linktype = wtap_pcap_encap_to_wtap_encap(ld.linktype);
1674 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1675 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1677 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1679 XXX - deal with signal semantics on various UNIX platforms. Or just
1680 use "sigaction()" and be done with it? */
1681 signal(SIGTERM, capture_cleanup);
1682 signal(SIGINT, capture_cleanup);
1683 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1684 signal(SIGHUP, oldhandler);
1687 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1688 quiet mode, report the number of packets we've captured. */
1689 signal(SIGINFO, report_counts_siginfo);
1690 #endif /* SIGINFO */
1693 /* Let the user know what interface was chosen. */
1694 capture_opts.iface_descr = get_interface_descriptive_name(capture_opts.iface);
1695 fprintf(stderr, "Capturing on %s\n", capture_opts.iface_descr);
1697 /* initialize capture stop conditions */
1698 init_capture_stop_conditions();
1699 /* create stop conditions */
1700 if (capture_opts.has_autostop_filesize)
1701 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1702 (long)capture_opts.autostop_filesize * 1024);
1703 if (capture_opts.has_autostop_duration)
1704 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1705 (gint32)capture_opts.autostop_duration);
1707 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1708 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT, capture_opts.file_duration);
1710 if (!setjmp(ld.stopenv)) {
1712 ld.packet_count = 0;
1717 /* We need to be careful with automatic variables defined in the
1718 outer scope which are changed inside the loop. Most compilers
1719 don't try to roll them back to their original values after the
1720 longjmp which causes the loop to finish, but all that the
1721 standards say is that their values are indeterminate. If we
1722 don't want them to be rolled back, we should define them with the
1723 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1724 Programming in the UNIX Environment, p. 178).
1726 The "err" variable causes a particular problem. If we give it
1727 the volatile attribute, then when we pass a reference to it (as
1728 in "&err") to a function, GCC warns: "passing arg <n> of
1729 <function> discards qualifiers from pointer target type".
1730 Therefore within the loop and just beyond we don't use "err".
1731 Within the loop we define "loop_err", and assign its value to
1732 "volatile_err", which is in the outer scope and is checked when
1735 We also define "packet_count_prev" here to keep things tidy,
1736 since it's used only inside the loop. If it were defined in the
1737 outer scope, GCC would give a warning (unnecessary in this case)
1738 that it might be clobbered, and we'd need to give it the volatile
1739 attribute to suppress the warning. */
1742 int packet_count_prev = 0;
1744 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1745 /* We're not stopping at a particular capture file size, and we're
1746 not stopping after some particular amount of time has expired,
1747 so either we have no stop condition or the only stop condition
1748 is a maximum packet count.
1750 If there's no maximum packet count, pass it -1, meaning "until
1751 you run out of packets in the bufferful you read". Otherwise,
1752 pass it the number of packets we have left to capture.
1754 We don't call "pcap_loop()" as, if we're saving to a file that's
1755 a FIFO, we want to flush the FIFO after we're done processing
1756 this libpcap bufferful of packets, so that the program
1757 reading the FIFO sees the packets immediately and doesn't get
1758 any partial packet, forcing it to block in the middle of reading
1760 if (capture_opts.autostop_packets == 0)
1763 if (ld.packet_count >= capture_opts.autostop_packets) {
1764 /* XXX do we need this test here? */
1765 /* It appears there's nothing more to capture. */
1768 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1771 /* We need to check the capture file size or the timeout after
1776 inpkts = capture_loop_dispatch(NULL, &ld, errmsg, sizeof errmsg);
1778 /* Error from "pcap_dispatch()", or error or "no more packets" from
1779 "cap_pipe_dispatch(). */
1781 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1782 /* The specified capture time has elapsed; stop the capture. */
1784 } else if (inpkts > 0) {
1785 if (capture_opts.autostop_packets != 0 &&
1786 ld.packet_count >= capture_opts.autostop_packets) {
1787 /* The specified number of packets have been captured and have
1788 passed both any capture filter in effect and any read filter
1791 } else if (cnd_autostop_size != NULL &&
1792 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)) {
1793 /* We're saving the capture to a file, and the capture file reached
1794 its maximum size. */
1795 if (capture_opts.multi_files_on) {
1796 /* Switch to the next ringbuffer file */
1797 if (ringbuf_switch_file(&ld.pdh, &capture_opts.save_file,
1798 &save_file_fd, &ld.bytes_written,
1800 /* File switch succeeded: reset the condition */
1801 cnd_reset(cnd_autostop_size);
1802 if (cnd_file_duration) {
1803 cnd_reset(cnd_file_duration);
1806 /* File switch failed: stop here */
1807 volatile_err = loop_err;
1811 /* No ringbuffer - just stop. */
1815 if (capture_opts.output_to_pipe) {
1816 if (ld.packet_count > packet_count_prev) {
1817 libpcap_dump_flush(ld.pdh, NULL);
1818 packet_count_prev = ld.packet_count;
1822 } /* while (ld.go) */
1824 /* delete stop conditions */
1825 if (cnd_autostop_size != NULL)
1826 cnd_delete(cnd_autostop_size);
1827 if (cnd_autostop_duration != NULL)
1828 cnd_delete(cnd_autostop_duration);
1829 if (cnd_file_duration != NULL)
1830 cnd_delete(cnd_file_duration);
1832 if (print_packet_counts) {
1833 /* We're printing packet counts to stderr.
1834 Send a newline so that we move to the line after the packet count. */
1835 fprintf(stderr, "\n");
1838 /* If we got an error while capturing, report it. */
1840 if (ld.from_cap_pipe) {
1841 if (ld.cap_pipe_err == PIPERR) {
1842 cmdarg_err("Error while capturing packets: %s", errmsg);
1845 cmdarg_err("Error while capturing packets: %s", pcap_geterr(ld.pcap_h));
1849 if (volatile_err == 0)
1852 show_capture_file_io_error(capture_opts.save_file, volatile_err, FALSE);
1856 if (capture_opts.save_file != NULL) {
1857 /* We're saving to a file or files; close all files. */
1858 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1860 /* If we've displayed a message about a write error, there's no point
1861 in displaying another message about an error on close. */
1862 if (!close_ok && write_ok)
1863 show_capture_file_io_error(capture_opts.save_file, err, TRUE);
1866 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1867 eth_close(ld.cap_pipe_fd);
1869 /* Get the capture statistics, and, if any packets were dropped, report
1871 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1872 if (stats.ps_drop != 0) {
1873 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1876 cmdarg_err("Can't get packet-drop statistics: %s", pcap_geterr(ld.pcap_h));
1878 pcap_close(ld.pcap_h);
1881 /* Report the number of captured packets if not reported during capture
1882 and we are saving to a file. */
1888 if (capture_opts.multi_files_on) {
1889 ringbuf_error_cleanup();
1891 g_free(capture_opts.save_file);
1892 capture_opts.save_file = NULL;
1893 if (cfilter_error) {
1894 dfilter_t *rfcode = NULL;
1895 if (dfilter_compile(capture_opts.cfilter, &rfcode) && rfcode != NULL) {
1897 "Invalid capture filter: \"%s\"!\n"
1899 "That string looks like a valid display filter; however, it isn't a valid\n"
1900 "capture filter (%s).\n"
1902 "Note that display filters and capture filters don't have the same syntax,\n"
1903 "so you can't use most display filter expressions as capture filters.\n"
1905 "See the User's Guide for a description of the capture filter syntax.",
1906 capture_opts.cfilter, errmsg);
1907 dfilter_free(rfcode);
1910 "Invalid capture filter: \"%s\"!\n"
1912 "That string isn't a valid capture filter (%s).\n"
1913 "See the User's Guide for a description of the capture filter syntax.",
1914 capture_opts.cfilter, errmsg);
1917 cmdarg_err("%s", errmsg);
1918 if (*secondary_errmsg != '\0') {
1919 fprintf(stderr, "\n");
1920 cmdarg_err_cont("%s", secondary_errmsg);
1923 if (ld.from_cap_pipe) {
1924 if (ld.cap_pipe_fd >= 0)
1925 eth_close(ld.cap_pipe_fd);
1927 if (ld.pcap_h != NULL)
1928 pcap_close(ld.pcap_h);
1935 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1938 struct wtap_pkthdr whdr;
1939 union wtap_pseudo_header pseudo_header;
1940 const guchar *wtap_pd;
1941 loop_data *ld = (void *) user;
1945 gboolean packet_accepted;
1949 * Prevent a SIGINFO handler from writing to stdout while we're
1950 * doing so; instead, have it just set a flag telling us to print
1951 * that information when we're done.
1954 #endif /* SIGINFO */
1956 /* The current packet may have arrived after a very long silence,
1957 * way past the time to switch files. In order not to have
1958 * the first packet of a new series of events as the last
1959 * [or only] packet in the file, switch before writing!
1961 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1962 /* time elapsed for this ring file, switch to the next */
1963 if (ringbuf_switch_file(&ld->pdh, &ld->save_file, &save_file_fd,
1964 &ld->bytes_written, &loop_err)) {
1965 /* File switch succeeded: reset the condition */
1966 cnd_reset(cnd_file_duration);
1968 /* File switch failed: stop here */
1969 /* XXX - we should do something with "loop_err" */
1974 if (do_dissection) {
1975 /* We're goint to print packet information, run a read filter, or
1976 process taps. Use process_packet() to handle that; in order
1977 to do that, we need to convert from libpcap to Wiretap format.
1978 If that fails, ignore the packet (wtap_process_pcap_packet has
1979 written an error message). */
1980 wtap_pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd,
1981 &pseudo_header, &whdr, &err);
1982 if (wtap_pd == NULL)
1985 packet_accepted = process_packet(&cfile, 0, &whdr, &pseudo_header, wtap_pd);
1987 /* We're just writing out packets. */
1988 packet_accepted = TRUE;
1991 if (packet_accepted) {
1992 /* Count this packet. */
1997 if (ld->pdh != NULL) {
1998 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
1999 /* Error writing to a capture file */
2000 if (print_packet_counts) {
2001 /* We're printing counts of packets captured; move to the line after
2003 fprintf(stderr, "\n");
2005 show_capture_file_io_error(ld->save_file, err, FALSE);
2006 pcap_close(ld->pcap_h);
2007 libpcap_dump_close(ld->pdh, &err);
2011 if (print_packet_counts) {
2012 /* We're printing packet counts. */
2013 if (ld->packet_count != 0) {
2014 fprintf(stderr, "\r%u ", ld->packet_count);
2015 /* stderr could be line buffered */
2023 * Allow SIGINFO handlers to write.
2028 * If a SIGINFO handler asked us to write out capture counts, do so.
2032 #endif /* SIGINFO */
2037 capture_cleanup(DWORD ctrltype _U_)
2039 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2040 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2041 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2042 like SIGTERM at least when the machine's shutting down.
2044 For now, we handle them all as indications that we should clean up
2045 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2048 However, as handlers run in a new thread, we can't just longjmp
2049 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2050 no other handler - such as one that would terminate the process -
2053 XXX - for some reason, typing ^C to TShark, if you run this in
2054 a Cygwin console window in at least some versions of Cygwin,
2055 causes TShark to terminate immediately; this routine gets
2056 called, but the main loop doesn't get a chance to run and
2057 exit cleanly, at least if this is compiled with Microsoft Visual
2058 C++ (i.e., it's a property of the Cygwin console window or Bash;
2059 it happens if TShark is not built with Cygwin - for all I know,
2060 building it with Cygwin may make the problem go away). */
2066 capture_cleanup(int signum _U_)
2068 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2069 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2070 "ld.go" to FALSE and return, we won't break out of it and quit
2072 longjmp(ld.stopenv, 1);
2080 /* XXX - if we use sigaction, this doesn't have to be done.
2081 (Yes, this isn't necessary on BSD, but just in case a system
2082 where "signal()" has AT&T semantics adopts SIGINFO....) */
2083 signal(SIGINFO, report_counts_siginfo);
2084 #endif /* SIGINFO */
2086 if (!print_packet_counts) {
2087 /* Report the count only if we aren't printing a packet count
2088 as packets arrive. */
2089 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2092 infoprint = FALSE; /* we just reported it */
2093 #endif /* SIGINFO */
2098 report_counts_siginfo(int signum _U_)
2100 int sav_errno = errno;
2101 /* If we've been told to delay printing, just set a flag asking
2102 that we print counts (if we're supposed to), otherwise print
2103 the count of packets captured (if we're supposed to). */
2110 #endif /* SIGINFO */
2111 #endif /* HAVE_LIBPCAP */
2114 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2115 int max_packet_count, gint64 max_byte_count)
2118 int snapshot_length;
2123 char *save_file_string = NULL;
2125 linktype = wtap_file_encap(cf->wth);
2126 if (save_file != NULL) {
2127 /* Get a string that describes what we're writing to */
2128 save_file_string = output_file_description(save_file);
2130 /* Set up to write to the capture file. */
2131 snapshot_length = wtap_snapshot_length(cf->wth);
2132 if (snapshot_length == 0) {
2133 /* Snapshot length of input file not known. */
2134 snapshot_length = WTAP_MAX_PACKET_SIZE;
2136 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2137 FALSE /* compressed */, &err);
2140 /* We couldn't set up to write to the capture file. */
2143 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2144 cmdarg_err("Capture files can't be written in that format.");
2147 case WTAP_ERR_UNSUPPORTED_ENCAP:
2148 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2149 cmdarg_err("The capture file being read can't be written in "
2153 case WTAP_ERR_CANT_OPEN:
2154 cmdarg_err("The %s couldn't be created for some "
2155 "unknown reason.", save_file_string);
2158 case WTAP_ERR_SHORT_WRITE:
2159 cmdarg_err("A full header couldn't be written to the %s.",
2164 cmdarg_err("The %s could not be created: %s.", save_file_string,
2165 wtap_strerror(err));
2171 if (print_packet_info) {
2172 if (!write_preamble(cf)) {
2174 show_print_file_io_error(err);
2180 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2181 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2182 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2183 /* Either there's no read filtering or this packet passed the
2184 filter, so, if we're writing to a capture file, write
2187 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2188 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2190 /* Error writing to a capture file */
2191 show_capture_file_io_error(save_file, err, FALSE);
2192 wtap_dump_close(pdh, &err);
2196 /* Stop reading if we have the maximum number of packets;
2197 * note that a zero max_packet_count will never be matched
2198 * (unless we roll over the packet number?)
2200 if(max_packet_count == cf->count || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2201 err = 0; /* This is not an error */
2207 /* Print a message noting that the read failed somewhere along the line. */
2210 case WTAP_ERR_UNSUPPORTED_ENCAP:
2211 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2212 cf->filename, err_info);
2215 case WTAP_ERR_CANT_READ:
2216 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2220 case WTAP_ERR_SHORT_READ:
2221 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2225 case WTAP_ERR_BAD_RECORD:
2226 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2227 cf->filename, err_info);
2231 cmdarg_err("An error occurred while reading \"%s\": %s.",
2232 cf->filename, wtap_strerror(err));
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);
2241 if (save_file != NULL) {
2242 /* Now close the capture file. */
2243 if (!wtap_dump_close(pdh, &err))
2244 show_capture_file_io_error(save_file, err, TRUE);
2246 if (print_packet_info) {
2247 if (!write_finale()) {
2249 show_print_file_io_error(err);
2256 wtap_close(cf->wth);
2259 if (save_file_string != NULL)
2260 g_free(save_file_string);
2266 fill_in_fdata(frame_data *fdata, capture_file *cf,
2267 const struct wtap_pkthdr *phdr, gint64 offset)
2272 fdata->num = cf->count;
2273 fdata->pkt_len = phdr->len;
2274 cum_bytes += phdr->len;
2275 fdata->cum_bytes = cum_bytes;
2276 fdata->cap_len = phdr->caplen;
2277 fdata->file_off = offset;
2278 fdata->lnk_t = phdr->pkt_encap;
2279 fdata->abs_ts.secs = phdr->ts.secs;
2280 fdata->abs_ts.nsecs = phdr->ts.nsecs;
2281 fdata->flags.passed_dfilter = 0;
2282 fdata->flags.encoding = CHAR_ASCII;
2283 fdata->flags.visited = 0;
2284 fdata->flags.marked = 0;
2285 fdata->flags.ref_time = 0;
2286 fdata->color_filter = NULL;
2288 /* If we don't have the time stamp of the first packet in the
2289 capture, it's because this is the first packet. Save the time
2290 stamp of this packet as the time stamp of the first packet. */
2291 if (nstime_is_unset(&first_ts)) {
2292 first_ts = fdata->abs_ts;
2295 /* If we don't have the time stamp of the previous captured packet,
2296 it's because this is the first packet. Save the time
2297 stamp of this packet as the time stamp of the previous captured
2299 if (nstime_is_unset(&prev_cap_ts)) {
2300 prev_cap_ts = fdata->abs_ts;
2303 /* Get the time elapsed between the first packet and this packet. */
2304 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2306 /* If it's greater than the current elapsed time, set the elapsed time
2307 to it (we check for "greater than" so as not to be confused by
2308 time moving backwards). */
2309 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2310 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2311 cf->elapsed_time = fdata->rel_ts;
2314 /* Get the time elapsed between the previous displayed packet and
2316 if (nstime_is_unset(&prev_dis_ts))
2317 nstime_set_zero(&fdata->del_dis_ts);
2319 nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2321 /* Get the time elapsed between the previous captured packet and
2323 nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2324 prev_cap_ts = fdata->abs_ts;
2327 /* Free up all data attached to a "frame_data" structure. */
2329 clear_fdata(frame_data *fdata)
2332 g_slist_free(fdata->pfd);
2336 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2337 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2340 gboolean create_proto_tree;
2341 epan_dissect_t *edt;
2344 /* Count this packet. */
2347 /* If we're going to print packet information, or we're going to
2348 run a read filter, or we're going to process taps, set up to
2349 do a dissection and do so. */
2350 if (do_dissection) {
2351 fill_in_fdata(&fdata, cf, whdr, offset);
2353 if (print_packet_info) {
2354 /* Grab any resolved addresses */
2356 if (g_resolv_flags) {
2357 host_name_lookup_process(NULL);
2362 if (cf->rfcode || verbose || num_tap_filters!=0)
2363 create_proto_tree = TRUE;
2365 create_proto_tree = FALSE;
2366 /* The protocol tree will be "visible", i.e., printed, only if we're
2367 printing packet details, which is true if we're printing stuff
2368 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2370 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2372 /* If we're running a read filter, prime the epan_dissect_t with that
2375 epan_dissect_prime_dfilter(edt, cf->rfcode);
2377 tap_queue_init(edt);
2379 /* We only need the columns if we're printing packet info but we're
2380 *not* verbose; in verbose mode, we print the protocol tree, not
2381 the protocol summary. */
2382 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2383 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2385 tap_push_tapped_queue(edt);
2387 /* Run the read filter if we have one. */
2389 passed = dfilter_apply_edt(cf->rfcode, edt);
2393 /* We're not running a display filter and we're not printing any
2394 packet information, so we don't need to do a dissection, and all
2395 packets are processed. */
2401 /* Keep the time of the current packet if the packet passed
2402 the read filter so that the delta time since last displayed
2403 packet can be calculated */
2404 prev_dis_ts = fdata.abs_ts;
2406 /* Process this packet. */
2407 if (print_packet_info) {
2408 /* We're printing packet information; print the information for
2410 print_packet(cf, edt);
2412 /* The ANSI C standard does not appear to *require* that a line-buffered
2413 stream be flushed to the host environment whenever a newline is
2414 written, it just says that, on such a stream, characters "are
2415 intended to be transmitted to or from the host environment as a
2416 block when a new-line character is encountered".
2418 The Visual C++ 6.0 C implementation doesn't do what is intended;
2419 even if you set a stream to be line-buffered, it still doesn't
2420 flush the buffer at the end of every line.
2422 So, if the "-l" flag was specified, we flush the standard output
2423 at the end of a packet. This will do the right thing if we're
2424 printing packet summary lines, and, as we print the entire protocol
2425 tree for a single packet without waiting for anything to happen,
2426 it should be as good as line-buffered mode if we're printing
2427 protocol trees. (The whole reason for the "-l" flag in either
2428 tcpdump or TShark is to allow the output of a live capture to
2429 be piped to a program or script and to have that script see the
2430 information for the packet as soon as it's printed, rather than
2431 having to wait until a standard I/O buffer fills up. */
2435 if (ferror(stdout)) {
2436 show_print_file_io_error(errno);
2442 if (do_dissection) {
2443 epan_dissect_free(edt);
2444 clear_fdata(&fdata);
2450 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2452 char *save_file_string;
2454 save_file_string = output_file_description(fname);
2459 cmdarg_err("Not all the packets could be written to the %s because there is "
2460 "no space left on the file system.",
2466 cmdarg_err("Not all the packets could be written to the %s because you are "
2467 "too close to, or over your disk quota.",
2472 case WTAP_ERR_CANT_CLOSE:
2473 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2477 case WTAP_ERR_SHORT_WRITE:
2478 cmdarg_err("Not all the packets could be written to the %s.",
2484 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2485 wtap_strerror(err));
2487 cmdarg_err("An error occurred while writing to the %s: %s.",
2488 save_file_string, wtap_strerror(err));
2492 g_free(save_file_string);
2496 write_preamble(capture_file *cf)
2498 switch (output_action) {
2501 return print_preamble(print_stream, cf ? cf->filename : NULL);
2506 write_pdml_preamble(stdout);
2508 write_psml_preamble(stdout);
2509 return !ferror(stdout);
2512 write_fields_preamble(output_fields, stdout);
2513 return !ferror(stdout);
2516 g_assert_not_reached();
2522 get_line_buf(size_t len)
2524 static char *line_bufp = NULL;
2525 static size_t line_buf_len = 256;
2526 size_t new_line_buf_len;
2528 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2529 new_line_buf_len *= 2)
2531 if (line_bufp == NULL) {
2532 line_buf_len = new_line_buf_len;
2533 line_bufp = g_malloc(line_buf_len + 1);
2535 if (new_line_buf_len > line_buf_len) {
2536 line_buf_len = new_line_buf_len;
2537 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2544 print_columns(capture_file *cf)
2551 line_bufp = get_line_buf(256);
2554 for (i = 0; i < cf->cinfo.num_cols; i++) {
2555 switch (cf->cinfo.col_fmt[i]) {
2559 * Don't print this if we're doing a live capture from a network
2560 * interface - if we're doing a live capture, you won't be
2561 * able to look at the capture in the future (it's not being
2562 * saved anywhere), so the frame numbers are unlikely to be
2565 * (XXX - it might be nice to be able to save and print at
2566 * the same time, sort of like an "Update list of packets
2567 * in real time" capture in Wireshark.)
2569 if (capture_opts.iface != NULL)
2572 column_len = strlen(cf->cinfo.col_data[i]);
2575 line_bufp = get_line_buf(buf_offset + column_len);
2576 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2582 case COL_ABS_DATE_TIME: /* XXX - wider */
2583 column_len = strlen(cf->cinfo.col_data[i]);
2584 if (column_len < 10)
2586 line_bufp = get_line_buf(buf_offset + column_len);
2587 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2593 case COL_DEF_DL_SRC:
2594 case COL_RES_DL_SRC:
2595 case COL_UNRES_DL_SRC:
2596 case COL_DEF_NET_SRC:
2597 case COL_RES_NET_SRC:
2598 case COL_UNRES_NET_SRC:
2599 column_len = strlen(cf->cinfo.col_data[i]);
2600 if (column_len < 12)
2602 line_bufp = get_line_buf(buf_offset + column_len);
2603 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2609 case COL_DEF_DL_DST:
2610 case COL_RES_DL_DST:
2611 case COL_UNRES_DL_DST:
2612 case COL_DEF_NET_DST:
2613 case COL_RES_NET_DST:
2614 case COL_UNRES_NET_DST:
2615 column_len = strlen(cf->cinfo.col_data[i]);
2616 if (column_len < 12)
2618 line_bufp = get_line_buf(buf_offset + column_len);
2619 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2623 column_len = strlen(cf->cinfo.col_data[i]);
2624 line_bufp = get_line_buf(buf_offset + column_len);
2625 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2628 buf_offset += column_len;
2629 if (i != cf->cinfo.num_cols - 1) {
2631 * This isn't the last column, so we need to print a
2632 * separator between this column and the next.
2634 * If we printed a network source and are printing a
2635 * network destination of the same type next, separate
2636 * them with "->"; if we printed a network destination
2637 * and are printing a network source of the same type
2638 * next, separate them with "<-"; otherwise separate them
2641 * We add enough space to the buffer for " <- " or " -> ",
2642 * even if we're only adding " ".
2644 line_bufp = get_line_buf(buf_offset + 4);
2645 switch (cf->cinfo.col_fmt[i]) {
2650 switch (cf->cinfo.col_fmt[i + 1]) {
2655 strcat(line_bufp + buf_offset, " -> ");
2660 strcat(line_bufp + buf_offset, " ");
2666 case COL_DEF_DL_SRC:
2667 case COL_RES_DL_SRC:
2668 case COL_UNRES_DL_SRC:
2669 switch (cf->cinfo.col_fmt[i + 1]) {
2671 case COL_DEF_DL_DST:
2672 case COL_RES_DL_DST:
2673 case COL_UNRES_DL_DST:
2674 strcat(line_bufp + buf_offset, " -> ");
2679 strcat(line_bufp + buf_offset, " ");
2685 case COL_DEF_NET_SRC:
2686 case COL_RES_NET_SRC:
2687 case COL_UNRES_NET_SRC:
2688 switch (cf->cinfo.col_fmt[i + 1]) {
2690 case COL_DEF_NET_DST:
2691 case COL_RES_NET_DST:
2692 case COL_UNRES_NET_DST:
2693 strcat(line_bufp + buf_offset, " -> ");
2698 strcat(line_bufp + buf_offset, " ");
2707 switch (cf->cinfo.col_fmt[i + 1]) {
2712 strcat(line_bufp + buf_offset, " <- ");
2717 strcat(line_bufp + buf_offset, " ");
2723 case COL_DEF_DL_DST:
2724 case COL_RES_DL_DST:
2725 case COL_UNRES_DL_DST:
2726 switch (cf->cinfo.col_fmt[i + 1]) {
2728 case COL_DEF_DL_SRC:
2729 case COL_RES_DL_SRC:
2730 case COL_UNRES_DL_SRC:
2731 strcat(line_bufp + buf_offset, " <- ");
2736 strcat(line_bufp + buf_offset, " ");
2742 case COL_DEF_NET_DST:
2743 case COL_RES_NET_DST:
2744 case COL_UNRES_NET_DST:
2745 switch (cf->cinfo.col_fmt[i + 1]) {
2747 case COL_DEF_NET_SRC:
2748 case COL_RES_NET_SRC:
2749 case COL_UNRES_NET_SRC:
2750 strcat(line_bufp + buf_offset, " <- ");
2755 strcat(line_bufp + buf_offset, " ");
2762 strcat(line_bufp + buf_offset, " ");
2768 return print_line(print_stream, 0, line_bufp);
2772 print_packet(capture_file *cf, epan_dissect_t *edt)
2774 print_args_t print_args;
2777 /* Print the information in the protocol tree. */
2778 switch (output_action) {
2781 print_args.to_file = TRUE;
2782 print_args.format = print_format;
2783 print_args.print_summary = !verbose;
2784 print_args.print_hex = verbose && print_hex;
2785 print_args.print_formfeed = FALSE;
2786 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2788 /* init the packet range */
2789 packet_range_init(&print_args.range);
2791 if (!proto_tree_print(&print_args, edt, print_stream))
2794 /* "print_hex_data()" will put out a leading blank line, as well
2795 as a trailing one; print one here, to separate the packets,
2796 only if "print_hex_data()" won't be called. */
2797 if (!print_line(print_stream, 0, ""))
2803 proto_tree_write_pdml(edt, stdout);
2805 return !ferror(stdout);
2807 proto_tree_write_fields(output_fields, edt, stdout);
2809 return !ferror(stdout);
2812 /* Just fill in the columns. */
2813 epan_dissect_fill_in_columns(edt);
2815 /* Now print them. */
2816 switch (output_action) {
2819 if (!print_columns(cf))
2824 proto_tree_write_psml(edt, stdout);
2825 return !ferror(stdout);
2826 case WRITE_FIELDS: /*No non-verbose "fields" format */
2827 g_assert_not_reached();
2832 if (!print_hex_data(print_stream, edt))
2834 if (!print_line(print_stream, 0, ""))
2843 switch (output_action) {
2846 return print_finale(print_stream);
2851 write_pdml_finale(stdout);
2853 write_psml_finale(stdout);
2854 return !ferror(stdout);
2857 write_fields_finale(output_fields, stdout);
2858 return !ferror(stdout);
2861 g_assert_not_reached();
2867 show_print_file_io_error(int err)
2872 cmdarg_err("Not all the packets could be printed because there is "
2873 "no space left on the file system.");
2878 cmdarg_err("Not all the packets could be printed because you are "
2879 "too close to, or over your disk quota.");
2884 cmdarg_err("An error occurred while printing packets: %s.",
2891 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2895 static char errmsg_errno[1024+1];
2898 /* Wiretap error. */
2901 case WTAP_ERR_NOT_REGULAR_FILE:
2902 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2905 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2906 /* Seen only when opening a capture file for reading. */
2907 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2910 case WTAP_ERR_UNSUPPORTED:
2911 /* Seen only when opening a capture file for reading. */
2912 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2913 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2916 errmsg = errmsg_errno;
2919 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2920 /* Seen only when opening a capture file for writing. */
2921 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2922 "The file \"%%s\" is a pipe, and %s capture files can't be "
2923 "written to a pipe.", wtap_file_type_string(file_type));
2924 errmsg = errmsg_errno;
2927 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2928 /* Seen only when opening a capture file for writing. */
2929 errmsg = "TShark doesn't support writing capture files in that format.";
2932 case WTAP_ERR_UNSUPPORTED_ENCAP:
2934 errmsg = "TShark can't save this capture in that format.";
2936 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2937 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
2940 errmsg = errmsg_errno;
2944 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2946 errmsg = "TShark can't save this capture in that format.";
2948 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
2951 case WTAP_ERR_BAD_RECORD:
2952 /* Seen only when opening a capture file for reading. */
2953 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2954 "The file \"%%s\" appears to be damaged or corrupt.\n"
2957 errmsg = errmsg_errno;
2960 case WTAP_ERR_CANT_OPEN:
2962 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2964 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2967 case WTAP_ERR_SHORT_READ:
2968 errmsg = "The file \"%s\" appears to have been cut short"
2969 " in the middle of a packet or other data.";
2972 case WTAP_ERR_SHORT_WRITE:
2973 errmsg = "A full header couldn't be written to the file \"%s\".";
2977 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2978 "The file \"%%s\" could not be %s: %s.",
2979 for_writing ? "created" : "opened",
2980 wtap_strerror(err));
2981 errmsg = errmsg_errno;
2985 errmsg = file_open_error_message(err, for_writing);
2990 * Open/create errors are reported with an console message in TShark.
2993 open_failure_message(const char *filename, int err, gboolean for_writing)
2995 fprintf(stderr, "tshark: ");
2996 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2997 fprintf(stderr, "\n");
3001 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3005 char err_msg[2048+1];
3007 wth = wtap_open_offline(fname, err, &err_info, FALSE);
3011 /* The open succeeded. Fill in the information for this file. */
3013 /* Initialize all data structures used for dissection. */
3017 cf->f_datalen = 0; /* not used, but set it anyway */
3019 /* Set the file name because we need it to set the follow stream filter.
3020 XXX - is that still true? We need it for other reasons, though,
3022 cf->filename = g_strdup(fname);
3024 /* Indicate whether it's a permanent or temporary file. */
3025 cf->is_tempfile = is_tempfile;
3027 /* If it's a temporary capture buffer file, mark it as not saved. */
3028 cf->user_saved = !is_tempfile;
3030 cf->cd_t = wtap_file_type(cf->wth);
3032 cf->drops_known = FALSE;
3034 cf->snap = wtap_snapshot_length(cf->wth);
3035 if (cf->snap == 0) {
3036 /* Snapshot length not known. */
3037 cf->has_snap = FALSE;
3038 cf->snap = WTAP_MAX_PACKET_SIZE;
3040 cf->has_snap = TRUE;
3041 nstime_set_zero(&cf->elapsed_time);
3042 nstime_set_unset(&first_ts);
3043 nstime_set_unset(&prev_dis_ts);
3044 nstime_set_unset(&prev_cap_ts);
3049 g_snprintf(err_msg, sizeof err_msg,
3050 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3051 cmdarg_err("%s", err_msg);
3057 * General errors are reported with an console message in TShark.
3060 failure_message(const char *msg_format, va_list ap)
3062 fprintf(stderr, "tshark: ");
3063 vfprintf(stderr, msg_format, ap);
3064 fprintf(stderr, "\n");
3068 * Read errors are reported with an console message in TShark.
3071 read_failure_message(const char *filename, int err)
3073 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3074 filename, strerror(err));
3078 * Report an error in command-line arguments.
3081 cmdarg_err(const char *fmt, ...)
3086 fprintf(stderr, "tshark: ");
3087 vfprintf(stderr, fmt, ap);
3088 fprintf(stderr, "\n");
3093 * Report additional information for an error in command-line arguments.
3096 cmdarg_err_cont(const char *fmt, ...)
3101 vfprintf(stderr, fmt, ap);
3102 fprintf(stderr, "\n");
3107 /****************************************************************************************************************/
3108 /* indication report "dummies", needed for capture_loop.c */
3112 /** Report a new capture file having been opened. */
3114 report_new_capture_file(const char *filename _U_)
3116 /* shouldn't happen */
3117 g_assert_not_reached();
3120 /** Report a number of new packets captured. */
3122 report_packet_count(int packet_count _U_)
3124 /* shouldn't happen */
3125 g_assert_not_reached();
3128 /** Report the packet drops once the capture finishes. */
3130 report_packet_drops(int drops _U_)
3132 /* shouldn't happen */
3133 g_assert_not_reached();
3136 /** Report an error in the capture. */
3138 report_capture_error(const char *errmsg, const char *secondary_error_msg)
3141 cmdarg_err_cont(secondary_error_msg);
3144 /** Report an error with a capture filter. */
3146 report_cfilter_error(const char *cfilter, const char *errmsg)
3150 "Invalid capture filter: \"%s\"!\n"
3152 "That string isn't a valid capture filter (%s).\n"
3153 "See the User's Guide for a description of the capture filter syntax.",
3157 #endif /* HAVE_LIBPCAP */
3160 /****************************************************************************************************************/
3161 /* signal pipe "dummies", needed for capture_loop.c */
3167 signal_pipe_check_running(void)
3169 /* currently, no check required */
3174 #endif /* HAVE_LIBPCAP */