5 * Ethereal - Network traffic analyzer
6 * By Gerald Combs <gerald@ethereal.com>
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>
67 #include <epan/timestamp.h>
68 #include <epan/packet.h>
70 #include "disabled_protos.h"
71 #include <epan/prefs.h>
72 #include <epan/column.h>
74 #include <epan/addr_resolv.h>
76 #include "clopts_common.h"
77 #include "version_info.h"
78 #include <epan/conversation.h>
79 #include <epan/plugins.h>
81 #include "conditions.h"
82 #include "capture_stop_conditions.h"
83 #include "ringbuffer.h"
84 #include "capture_ui_utils.h"
85 #include <epan/epan_dissect.h>
87 #include <epan/stat_cmd_args.h>
88 #include <epan/timestamp.h>
93 #include "pcap-util.h"
94 #include <wiretap/wtap-capture.h>
95 #include <wiretap/libpcap.h>
97 #include "capture-wpcap.h"
100 #endif /* HAVE_LIBPCAP */
101 #include "epan/emem.h"
104 * This is the template for the decode as option; it is shared between the
105 * various functions that output the usage for this parameter.
107 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
109 static nstime_t first_ts;
110 static nstime_t prev_ts;
111 static GString *comp_info_str, *runtime_info_str;
113 static gboolean print_packet_info; /* TRUE if we're to print packet information */
115 * The way the packet decode is to be written.
118 WRITE_TEXT, /* summary or detail text */
119 WRITE_XML /* PDML or PSML */
120 /* Add CSV and the like here */
122 static output_action_e output_action;
123 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
124 static gboolean verbose;
125 static gboolean print_hex;
126 static gboolean line_buffered;
127 static guint32 cum_bytes = 0;
128 static print_format_e print_format = PR_FMT_TEXT;
129 static print_stream_t *print_stream;
133 * TRUE if we're to print packet counts to keep track of captured packets.
135 static gboolean print_packet_counts;
137 typedef struct _loop_data {
138 gboolean go; /* TRUE as long as we're supposed to keep capturing */
140 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
142 char *save_file; /* Name of file to which we're writing */
145 gboolean output_to_pipe;
148 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
149 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
150 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
152 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
153 STATE_EXPECT_DATA, STATE_READ_DATA
155 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
162 static capture_options capture_opts;
166 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
167 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
169 #endif /* HAVE_LIBPCAP */
172 static int capture(char *, int);
173 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
175 static void report_counts(void);
177 static BOOL WINAPI capture_cleanup(DWORD);
179 static void capture_cleanup(int);
181 static void report_counts_siginfo(int);
184 #endif /* HAVE_LIBPCAP */
186 static int load_cap_file(capture_file *, char *, int);
187 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
188 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
189 const guchar *pd, int *err);
190 static void show_capture_file_io_error(const char *, int, gboolean);
191 static void show_print_file_io_error(int err);
192 static gboolean write_preamble(capture_file *cf);
193 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
194 static gboolean write_finale(void);
195 static const char *cf_open_error_message(int err, gchar *err_info,
196 gboolean for_writing, int file_type);
199 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
200 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
201 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
202 struct pcaprec_modified_hdr *, guchar *, char *, int);
206 static void open_failure_message(const char *filename, int err,
207 gboolean for_writing);
208 static void failure_message(const char *msg_format, va_list ap);
209 static void read_failure_message(const char *filename, int err);
215 print_usage(gboolean print_ver)
222 fprintf(output, "This is GNU t" PACKAGE " " VERSION "%s"
223 "\n (C) 1998-2005 Gerald Combs <gerald@ethereal.com>"
226 svnversion, comp_info_str->str, runtime_info_str->str);
231 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
233 fprintf(output, "\t[ -b <capture ring buffer option> ] ... [ -c <capture packet count> ]\n");
234 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
235 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <capture interface> ]\n");
236 fprintf(output, "\t[ -N <name resolving flags> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
237 fprintf(output, "\t[ -R <read (display) filter> ] [ -s <capture snaplen> ] [ -t <time stamp format> ]\n");
238 fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -y <capture link type> ]\n");
239 fprintf(output, "\t[ -z <statistics ]\n");
241 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
242 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
243 fprintf(output, "\t[ -F <output file type> ] [ -N <name resolving flags> ]\n");
244 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read (display) filter> ]\n");
245 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ] [ -w <savefile> ]\n");
246 fprintf(output, "\t[ -z <statistics ]\n");
248 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
249 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
250 if (wtap_dump_can_open(i))
251 fprintf(output, "\t%s - %s\n",
252 wtap_file_type_short_string(i), wtap_file_type_string(i));
254 fprintf(output, "\tdefault is libpcap\n");
258 * For a dissector table, print on the stream described by output,
259 * its short name (which is what's used in the "-d" option) and its
263 display_dissector_table_names(char *table_name, const char *ui_name,
266 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
270 * For a dissector handle, print on the stream described by output,
271 * the filter name (which is what's used in the "-d" option) and the full
272 * name for the protocol that corresponds to this handle.
275 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
278 const gchar* proto_filter_name;
279 const gchar* proto_ui_name;
281 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
283 if (proto_id != -1) {
284 proto_filter_name = proto_get_protocol_filter_name(proto_id);
285 proto_ui_name = proto_get_protocol_name(proto_id);
286 g_assert(proto_filter_name != NULL);
287 g_assert(proto_ui_name != NULL);
289 fprintf((FILE *)output, "\t%s (%s)\n",
296 * The protocol_name_search structure is used by find_protocol_name_func()
297 * to pass parameters and store results
299 struct protocol_name_search{
300 gchar *searched_name; /* Protocol filter name we are looking for */
301 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
302 guint nb_match; /* How many dissectors matched searched_name */
304 typedef struct protocol_name_search *protocol_name_search_t;
307 * This function parses all dissectors associated with a table to find the
308 * one whose protocol has the specified filter name. It is called
309 * as a reference function in a call to dissector_table_foreach_handle.
310 * The name we are looking for, as well as the results, are stored in the
311 * protocol_name_search struct pointed to by user_data.
312 * If called using dissector_table_foreach_handle, we actually parse the
313 * whole list of dissectors.
316 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
320 const gchar *protocol_filter_name;
321 protocol_name_search_t search_info;
325 search_info = (protocol_name_search_t)user_data;
327 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
328 if (proto_id != -1) {
329 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
330 g_assert(protocol_filter_name != NULL);
331 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
333 if (search_info->nb_match == 0) {
334 /* Record this handle only if this is the first match */
335 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
337 search_info->nb_match++;
343 * Print all layer type names supported.
344 * We send the output to the stream described by the handle output.
348 fprint_all_layer_types(FILE *output)
351 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
355 * Print all protocol names supported for a specific layer type.
356 * table_name contains the layer type name in which the search is performed.
357 * We send the output to the stream described by the handle output.
361 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
364 dissector_table_foreach_handle(table_name,
365 display_dissector_names,
370 * The function below parses the command-line parameters for the decode as
371 * feature (a string pointer by cl_param).
372 * It checks the format of the command-line, searches for a matching table
373 * and dissector. If a table/dissector match is not found, we display a
374 * summary of the available tables/dissectors (on stderr) and return FALSE.
375 * If everything is fine, we get the "Decode as" preference activated,
376 * then we return TRUE.
379 add_decode_as(const gchar *cl_param)
383 gchar *decoded_param;
384 gchar *remaining_param;
386 gchar *dissector_str;
387 dissector_handle_t dissector_matching;
388 dissector_table_t table_matching;
389 ftenum_t dissector_table_selector_type;
390 struct protocol_name_search user_protocol_name;
392 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
395 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
396 g_assert(decoded_param);
397 strcpy(decoded_param, cl_param);
400 /* The lines below will parse this string (modifying it) to extract all
401 necessary information. Note that decoded_param is still needed since
402 strings are not copied - we just save pointers. */
404 /* This section extracts a layer type (table_name) from decoded_param */
405 table_name = decoded_param; /* Layer type string starts from beginning */
407 remaining_param = strchr(table_name, '=');
408 if (remaining_param == NULL) {
409 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
410 /* If the argument does not follow the template, carry on anyway to check
411 if the table name is at least correct. If remaining_param is NULL,
412 we'll exit anyway further down */
415 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
418 /* Remove leading and trailing spaces from the table name */
419 while ( table_name[0] == ' ' )
421 while ( table_name[strlen(table_name) - 1] == ' ' )
422 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
424 /* The following part searches a table matching with the layer type specified */
425 table_matching = NULL;
427 /* Look for the requested table */
428 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
429 fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
432 table_matching = find_dissector_table(table_name);
433 if (!table_matching) {
434 fprintf(stderr, "tethereal: Unknown layer type -- %s\n", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
438 if (!table_matching) {
439 /* Display a list of supported layer types to help the user, if the
440 specified layer type was not found */
441 fprintf(stderr, "tethereal: Valid layer types are:\n");
442 fprint_all_layer_types(stderr);
444 if (remaining_param == NULL || !table_matching) {
445 /* Exit if the layer type was not found, or if no '=' separator was found
447 g_free(decoded_param);
451 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
452 fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
455 remaining_param++; /* Move to the second '=' */
456 *remaining_param = '\0'; /* Remove the second '=' */
458 remaining_param++; /* Position after the layer type string */
460 /* This section extracts a selector value (selector_str) from decoded_param */
462 selector_str = remaining_param; /* Next part starts with the selector number */
464 remaining_param = strchr(selector_str, ',');
465 if (remaining_param == NULL) {
466 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
467 /* If the argument does not follow the template, carry on anyway to check
468 if the selector value is at least correct. If remaining_param is NULL,
469 we'll exit anyway further down */
472 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
475 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
477 switch (dissector_table_selector_type) {
483 /* The selector for this table is an unsigned number. Parse it as such.
484 There's no need to remove leading and trailing spaces from the
485 selector number string, because sscanf will do that for us. */
486 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
487 fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
488 g_free(decoded_param);
495 /* The selector for this table is a string. */
499 /* There are currently no dissector tables with any types other
500 than the ones listed above. */
501 g_assert_not_reached();
504 if (remaining_param == NULL) {
505 /* Exit if no ',' separator was found (see above) */
506 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
507 fprint_all_protocols_for_layer_types(stderr, table_name);
508 g_free(decoded_param);
512 remaining_param++; /* Position after the selector number string */
514 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
516 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
518 /* Remove leading and trailing spaces from the dissector name */
519 while ( dissector_str[0] == ' ' )
521 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
522 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
524 dissector_matching = NULL;
526 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
527 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 */
528 fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
531 user_protocol_name.nb_match = 0;
532 user_protocol_name.searched_name = dissector_str;
533 user_protocol_name.matched_handle = NULL;
535 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 */
537 if (user_protocol_name.nb_match != 0) {
538 dissector_matching = user_protocol_name.matched_handle;
539 if (user_protocol_name.nb_match > 1) {
540 fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
544 /* OK, check whether the problem is that there isn't any such
545 protocol, or that there is but it's not specified as a protocol
546 that's valid for that dissector table.
547 Note, we don't exit here, but dissector_matching will remain NULL,
549 if (proto_get_id_by_filter_name(dissector_str) == -1) {
550 /* No such protocol */
551 fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
553 fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
554 dissector_str, table_name);
559 if (!dissector_matching) {
560 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
561 fprint_all_protocols_for_layer_types(stderr, table_name);
562 g_free(decoded_param);
566 /* This is the end of the code that parses the command-line options.
567 All information is now stored in the variables:
571 The above variables that are strings are still pointing to areas within
572 decoded_parm. decoded_parm thus still needs to be kept allocated in
573 until we stop needing these variables
574 decoded_param will be deallocated at each exit point of this function */
577 /* We now have a pointer to the handle for the requested dissector
578 (requested protocol) inside the variable dissector_matching */
579 switch (dissector_table_selector_type) {
585 /* The selector for this table is an unsigned number. */
586 dissector_change(table_name, selector, dissector_matching);
591 /* The selector for this table is a string. */
592 dissector_change_string(table_name, selector_str, dissector_matching);
596 /* There are currently no dissector tables with any types other
597 than the ones listed above. */
598 g_assert_not_reached();
600 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
605 main(int argc, char *argv[])
609 gboolean arg_error = FALSE;
615 char *gpf_path, *pf_path;
616 char *gdp_path, *dp_path;
617 int gpf_open_errno, gpf_read_errno;
618 int pf_open_errno, pf_read_errno;
619 int gdp_open_errno, gdp_read_errno;
620 int dp_open_errno, dp_read_errno;
623 gboolean capture_filter_specified = FALSE;
624 GList *if_list, *if_entry;
628 gchar err_str[PCAP_ERRBUF_SIZE];
629 gchar *cant_get_if_list_errstr;
630 gboolean list_link_layer_types = FALSE;
632 gboolean capture_option_specified = FALSE;
634 gboolean quiet = FALSE;
635 gchar *save_file = NULL;
636 int out_file_type = WTAP_FILE_PCAP;
637 gchar *cf_name = NULL, *rfilter = NULL;
639 gboolean start_capture = FALSE;
641 GList *lt_list, *lt_entry;
642 data_link_info_t *data_link_info;
644 #ifdef HAVE_PCAP_OPEN_DEAD
645 struct bpf_program fcode;
647 dfilter_t *rfcode = NULL;
651 /* initialize memory allocation subsystem */
656 capture_opts_init(&capture_opts, NULL /* cfile */);
659 timestamp_set_type(TS_RELATIVE);
660 timestamp_set_precision(TS_PREC_AUTO);
662 /* Register all dissectors; we must do this before checking for the
663 "-G" flag, as the "-G" flag dumps information registered by the
664 dissectors, and we must do it before we read the preferences, in
665 case any dissectors register preferences. */
666 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
667 failure_message,open_failure_message,read_failure_message);
669 /* Register all tap listeners; we do this before we parse the arguments,
670 as the "-z" argument can specify a registered tap. */
672 /* we register the plugin taps before the other taps because
673 stats_tree taps plugins will be registered as tap listeners
674 by stats_tree_stat.c and need to registered before that */
676 register_all_plugin_tap_listeners();
678 register_all_tap_listeners();
680 /* Now register the preferences for any non-dissector modules.
681 We must do that before we read the preferences as well. */
682 prefs_register_modules();
684 /* If invoked with the "-G" flag, we dump out information based on
685 the argument to the "-G" flag; if no argument is specified,
686 for backwards compatibility we dump out a glossary of display
689 We do this here to mirror what happens in the GTK+ version, although
690 it's not necessary here. */
691 handle_dashG_option(argc, argv, "tethereal");
693 /* Set the C-language locale to the native environment. */
694 setlocale(LC_ALL, "");
696 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
697 &pf_open_errno, &pf_read_errno, &pf_path);
698 if (gpf_path != NULL) {
699 if (gpf_open_errno != 0) {
700 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
701 pf_path, strerror(gpf_open_errno));
703 if (gpf_read_errno != 0) {
704 fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
705 pf_path, strerror(gpf_read_errno));
708 if (pf_path != NULL) {
709 if (pf_open_errno != 0) {
710 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
711 strerror(pf_open_errno));
713 if (pf_read_errno != 0) {
714 fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
715 pf_path, strerror(pf_read_errno));
721 /* Set the name resolution code's flags from the preferences. */
722 g_resolv_flags = prefs->name_resolve;
724 /* Read the disabled protocols file. */
725 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
726 &dp_path, &dp_open_errno, &dp_read_errno);
727 if (gdp_path != NULL) {
728 if (gdp_open_errno != 0) {
730 "Could not open global disabled protocols file\n\"%s\": %s.\n",
731 gdp_path, strerror(gdp_open_errno));
733 if (gdp_read_errno != 0) {
735 "I/O error reading global disabled protocols file\n\"%s\": %s.\n",
736 gdp_path, strerror(gdp_read_errno));
740 if (dp_path != NULL) {
741 if (dp_open_errno != 0) {
743 "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
744 strerror(dp_open_errno));
746 if (dp_read_errno != 0) {
748 "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
749 strerror(dp_read_errno));
755 /* Load Wpcap, if possible */
759 init_cap_file(&cfile);
761 /* Assemble the compile-time version information string */
762 comp_info_str = g_string_new("Compiled ");
763 get_compiled_version_info(comp_info_str);
765 /* Assemble the run-time version information string */
766 runtime_info_str = g_string_new("Running ");
767 get_runtime_version_info(runtime_info_str);
769 /* Print format defaults to this. */
770 print_format = PR_FMT_TEXT;
772 /* Now get our args */
773 while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vw:Vxy:z:")) != -1) {
775 case 'a': /* autostop criteria */
776 case 'b': /* Ringbuffer option */
777 case 'c': /* Capture xxx packets */
778 case 'f': /* capture filter */
779 case 'p': /* Don't capture in promiscuous mode */
780 case 's': /* Set the snapshot (capture) length */
781 case 'y': /* Set the pcap data link type */
783 capture_opts_add_opt(&capture_opts, "tethereal", opt, optarg, &start_capture);
785 capture_option_specified = TRUE;
789 case 'd': /* Decode as rule */
790 if (!add_decode_as(optarg))
793 case 'D': /* Print a list of capture devices */
795 if_list = get_interface_list(&err, err_str);
796 if (if_list == NULL) {
799 case CANT_GET_INTERFACE_LIST:
800 cant_get_if_list_errstr =
801 cant_get_if_list_error_message(err_str);
802 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
803 g_free(cant_get_if_list_errstr);
806 case NO_INTERFACES_FOUND:
807 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
812 i = 1; /* Interface id number */
813 for (if_entry = g_list_first(if_list); if_entry != NULL;
814 if_entry = g_list_next(if_entry)) {
815 if_info = if_entry->data;
816 printf("%d. %s", i++, if_info->name);
817 if (if_info->description != NULL)
818 printf(" (%s)", if_info->description);
821 free_interface_list(if_list);
824 capture_option_specified = TRUE;
829 out_file_type = wtap_short_string_to_file_type(optarg);
830 if (out_file_type < 0) {
831 fprintf(stderr, "tethereal: \"%s\" isn't a valid capture file type\n",
836 case 'h': /* Print help and exit */
840 case 'i': /* Use interface xxx */
843 * If the argument is a number, treat it as an index into the list
844 * of adapters, as printed by "tethereal -D".
846 * This should be OK on UNIX systems, as interfaces shouldn't have
847 * names that begin with digits. It can be useful on Windows, where
848 * more than one interface can have the same name.
850 adapter_index = strtol(optarg, &p, 10);
851 if (p != NULL && *p == '\0') {
852 if (adapter_index < 0) {
854 "tethereal: The specified adapter index is a negative number\n");
857 if (adapter_index > INT_MAX) {
859 "tethereal: The specified adapter index is too large (greater than %d)\n",
863 if (adapter_index == 0) {
864 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
867 if_list = get_interface_list(&err, err_str);
868 if (if_list == NULL) {
871 case CANT_GET_INTERFACE_LIST:
872 cant_get_if_list_errstr =
873 cant_get_if_list_error_message(err_str);
874 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
875 g_free(cant_get_if_list_errstr);
878 case NO_INTERFACES_FOUND:
879 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
884 if_info = g_list_nth_data(if_list, adapter_index - 1);
885 if (if_info == NULL) {
886 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
889 capture_opts.iface = g_strdup(if_info->name);
890 free_interface_list(if_list);
892 capture_opts.iface = g_strdup(optarg);
894 capture_option_specified = TRUE;
898 case 'l': /* "Line-buffer" standard output */
899 /* This isn't line-buffering, strictly speaking, it's just
900 flushing the standard output after the information for
901 each packet is printed; however, that should be good
902 enough for all the purposes to which "-l" is put (and
903 is probably actually better for "-V", as it does fewer
906 See the comment in "process_packet()" for an explanation of
907 why we do that, and why we don't just use "setvbuf()" to
908 make the standard output line-buffered (short version: in
909 Windows, "line-buffered" is the same as "fully-buffered",
910 and the output buffer is only flushed when it fills up). */
911 line_buffered = TRUE;
913 case 'L': /* Print list of link-layer types and exit */
915 list_link_layer_types = TRUE;
918 capture_option_specified = TRUE;
922 case 'n': /* No name resolution */
923 g_resolv_flags = RESOLV_NONE;
925 case 'N': /* Select what types of addresses/port #s to resolve */
926 if (g_resolv_flags == RESOLV_ALL)
927 g_resolv_flags = RESOLV_NONE;
928 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
929 if (badopt != '\0') {
930 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
935 case 'o': /* Override preference from command line */
936 switch (prefs_set_pref(optarg)) {
938 case PREFS_SET_SYNTAX_ERR:
939 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
943 case PREFS_SET_NO_SUCH_PREF:
944 case PREFS_SET_OBSOLETE:
945 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
951 case 'q': /* Quiet */
954 case 'r': /* Read capture file xxx */
955 cf_name = g_strdup(optarg);
957 case 'R': /* Read file filter */
960 case 'S': /* show packets in real time */
961 print_packet_info = TRUE;
963 case 't': /* Time stamp type */
964 if (strcmp(optarg, "r") == 0)
965 timestamp_set_type(TS_RELATIVE);
966 else if (strcmp(optarg, "a") == 0)
967 timestamp_set_type(TS_ABSOLUTE);
968 else if (strcmp(optarg, "ad") == 0)
969 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
970 else if (strcmp(optarg, "d") == 0)
971 timestamp_set_type(TS_DELTA);
973 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
975 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
976 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
980 case 'T': /* printing Type */
981 if (strcmp(optarg, "text") == 0) {
982 output_action = WRITE_TEXT;
983 print_format = PR_FMT_TEXT;
984 } else if (strcmp(optarg, "ps") == 0) {
985 output_action = WRITE_TEXT;
986 print_format = PR_FMT_PS;
987 } else if (strcmp(optarg, "pdml") == 0) {
988 output_action = WRITE_XML;
990 } else if (strcmp(optarg, "psml") == 0) {
991 output_action = WRITE_XML;
994 fprintf(stderr, "tethereal: Invalid -T parameter.\n");
995 fprintf(stderr, "It must be \"ps\", \"text\", \"pdml\", or \"psml\".\n");
999 case 'v': /* Show version and exit */
1000 printf("t" PACKAGE " " VERSION "%s\n%s\n%s\n",
1001 svnversion, comp_info_str->str, runtime_info_str->str);
1004 case 'w': /* Write to capture file xxx */
1005 save_file = g_strdup(optarg);
1007 case 'V': /* Verbose */
1010 case 'x': /* Print packet data in hex (and ASCII) */
1014 /* We won't call the init function for the stat this soon
1015 as it would disallow MATE's fields (which are registered
1016 by the preferences set callback) from being used as
1017 part of a tap filter. Instead, we just add the argument
1018 to a list of stat arguments. */
1019 if (!process_stat_cmd_arg(optarg)) {
1020 fprintf(stderr,"tethereal: invalid -z argument.\n");
1021 fprintf(stderr," -z argument must be one of :\n");
1022 list_stat_cmd_args();
1027 case '?': /* Bad flag - print usage message */
1033 /* If no capture filter or read filter has been specified, and there are
1034 still command-line arguments, treat them as the tokens of a capture
1035 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1036 flag was specified. */
1037 if (optind < argc) {
1038 if (cf_name != NULL) {
1039 if (rfilter != NULL) {
1041 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1044 rfilter = get_args_as_string(argc, argv, optind);
1047 if (capture_filter_specified) {
1049 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1052 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1054 capture_option_specified = TRUE;
1059 /* See if we're writing a capture file and the file is a pipe */
1061 ld.output_to_pipe = FALSE;
1063 if (save_file != NULL) {
1064 /* We're writing to a capture file. */
1065 if (strcmp(save_file, "-") == 0) {
1066 /* Write to the standard output. */
1068 save_file = g_strdup("");
1070 /* XXX - should we check whether it's a pipe? It's arguably
1071 silly to do "-w - >output_file" rather than "-w output_file",
1072 but by not checking we might be violating the Principle Of
1073 Least Astonishment. */
1074 ld.output_to_pipe = TRUE;
1079 err = test_for_fifo(save_file);
1082 case ENOENT: /* it doesn't exist, so we'll be creating it,
1083 and it won't be a FIFO */
1084 case 0: /* found it, but it's not a FIFO */
1087 case ESPIPE: /* it is a FIFO */
1088 ld.output_to_pipe = TRUE;
1091 default: /* couldn't stat it */
1093 "tethereal: Error testing whether capture file is a pipe: %s\n",
1100 /* We're not writing to a file, so we should print packet information
1101 unless "-q" was specified. */
1103 print_packet_info = TRUE;
1106 #ifndef HAVE_LIBPCAP
1107 if (capture_option_specified)
1108 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1115 /* We don't support capture filters when reading from a capture file
1116 (the BPF compiler doesn't support all link-layer types that we
1117 support in capture files we read). */
1119 if (cf_name != NULL) {
1120 if (capture_filter_specified) {
1122 "tethereal: Only read filters, not capture filters, can be specified when reading a capture file.\n");
1129 if (output_action != WRITE_TEXT) {
1130 fprintf(stderr, "tethereal: Raw packet hex data can only be printed as text or PostScript\n");
1136 if (list_link_layer_types) {
1137 /* We're supposed to list the link-layer types for an interface;
1138 did the user also specify a capture file to be read? */
1140 /* Yes - that's bogus. */
1141 fprintf(stderr, "tethereal: You can't specify -L and a capture file to be read.\n");
1144 /* No - did they specify a ring buffer option? */
1145 if (capture_opts.multi_files_on) {
1146 fprintf(stderr, "tethereal: Ring buffer requested, but a capture isn't being done.\n");
1150 /* If they didn't specify a "-w" flag, but specified a maximum capture
1151 file size, tell them that this doesn't work, and exit. */
1152 if (capture_opts.has_autostop_filesize && save_file == NULL) {
1153 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1154 "capture isn't being saved to a file.\n");
1158 if (capture_opts.multi_files_on) {
1159 /* Ring buffer works only under certain conditions:
1160 a) ring buffer does not work if you're not saving the capture to
1162 b) ring buffer only works if you're saving in libpcap format;
1163 c) it makes no sense to enable the ring buffer if the maximum
1164 file size is set to "infinite";
1165 d) file must not be a pipe. */
1166 if (save_file == NULL) {
1167 fprintf(stderr, "tethereal: Ring buffer requested, but "
1168 "capture isn't being saved to a file.\n");
1171 if (out_file_type != WTAP_FILE_PCAP) {
1172 fprintf(stderr, "tethereal: Ring buffer requested, but "
1173 "capture isn't being saved in libpcap format.\n");
1176 if (!capture_opts.has_autostop_filesize) {
1177 fprintf(stderr, "tethereal: Ring buffer requested, but "
1178 "no maximum capture file size was specified.\n");
1181 if (ld.output_to_pipe) {
1182 fprintf(stderr, "tethereal: Ring buffer requested, but "
1183 "capture file is a pipe.\n");
1191 /* Start windows sockets */
1192 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1195 /* Notify all registered modules that have had any of their preferences
1196 changed either from one of the preferences file or from the command
1197 line that their preferences have changed. */
1200 /* At this point MATE will have registered its field array so we can
1201 have a tap filter with one of MATE's late-registered fields as part
1202 of the filter. We can now process all the "-z" arguments. */
1203 start_requested_stats();
1205 /* disabled protocols as per configuration file */
1206 if (gdp_path == NULL && dp_path == NULL) {
1207 set_disabled_protos_list();
1210 /* Build the column format array */
1211 col_setup(&cfile.cinfo, prefs->num_cols);
1212 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1213 cfile.cinfo.col_fmt[i] = get_column_format(i);
1214 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1215 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1217 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1218 cfile.cinfo.col_data[i] = NULL;
1219 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1220 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1222 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1223 cfile.cinfo.col_fence[i] = 0;
1224 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1225 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1228 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1231 for (j = 0; j < NUM_COL_FMTS; j++) {
1232 if (!cfile.cinfo.fmt_matx[i][j])
1235 if (cfile.cinfo.col_first[j] == -1)
1236 cfile.cinfo.col_first[j] = i;
1237 cfile.cinfo.col_last[j] = i;
1242 if (capture_opts.snaplen < 1)
1243 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1244 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1245 capture_opts.snaplen = MIN_PACKET_SIZE;
1247 /* Check the value range of the ring_num_files parameter */
1248 if (capture_opts.ring_num_files > RINGBUFFER_MAX_NUM_FILES)
1249 capture_opts.ring_num_files = RINGBUFFER_MAX_NUM_FILES;
1250 #if RINGBUFFER_MIN_NUM_FILES > 0
1251 else if (capture_opts.ring_num_files < RINGBUFFER_MIN_NUM_FILES)
1252 capture_opts.ring_num_files = RINGBUFFER_MIN_NUM_FILES;
1256 if (rfilter != NULL) {
1257 if (!dfilter_compile(rfilter, &rfcode)) {
1258 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1260 #ifdef HAVE_PCAP_OPEN_DEAD
1264 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1266 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1268 " Note: That display filter code looks like a valid capture filter;\n"
1269 " maybe you mixed them up?\n");
1278 cfile.rfcode = rfcode;
1280 if (print_packet_info) {
1281 /* If we're printing as text or PostScript, we have
1282 to create a print stream. */
1283 if (output_action == WRITE_TEXT) {
1284 switch (print_format) {
1287 print_stream = print_stream_text_stdio_new(stdout);
1291 print_stream = print_stream_ps_stdio_new(stdout);
1295 g_assert_not_reached();
1300 /* We have to dissect each packet if:
1302 we're printing information about each packet;
1304 we're using a read filter on the packets;
1306 we're using any taps. */
1307 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1311 * We're reading a capture file.
1316 * Immediately relinquish any set-UID or set-GID privileges we have;
1317 * we must not be allowed to read any capture files the user running
1318 * Tethereal can't open.
1324 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1329 /* Set timestamp precision; there should arguably be a command-line
1330 option to let the user set this. */
1331 switch(wtap_file_tsprecision(cfile.wth)) {
1332 case(WTAP_FILE_TSPREC_SEC):
1333 timestamp_set_precision(TS_PREC_AUTO_SEC);
1335 case(WTAP_FILE_TSPREC_DSEC):
1336 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1338 case(WTAP_FILE_TSPREC_CSEC):
1339 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1341 case(WTAP_FILE_TSPREC_MSEC):
1342 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1344 case(WTAP_FILE_TSPREC_USEC):
1345 timestamp_set_precision(TS_PREC_AUTO_USEC);
1347 case(WTAP_FILE_TSPREC_NSEC):
1348 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1351 g_assert_not_reached();
1354 /* Process the packets in the file */
1355 err = load_cap_file(&cfile, save_file, out_file_type);
1362 /* No capture file specified, so we're supposed to do a live capture
1363 (or get a list of link-layer types for a live capture device);
1364 do we have support for live captures? */
1369 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1374 /* Yes; did the user specify an interface to use? */
1375 if (capture_opts.iface == NULL) {
1376 /* No - is a default specified in the preferences file? */
1377 if (prefs->capture_device != NULL) {
1379 if_text = strrchr(prefs->capture_device, ' ');
1380 if (if_text == NULL) {
1381 capture_opts.iface = g_strdup(prefs->capture_device);
1383 capture_opts.iface = g_strdup(if_text + 1); /* Skip over space */
1386 /* No - pick the first one from the list of interfaces. */
1387 if_list = get_interface_list(&err, err_str);
1388 if (if_list == NULL) {
1391 case CANT_GET_INTERFACE_LIST:
1392 cant_get_if_list_errstr = cant_get_if_list_error_message(err_str);
1393 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1394 g_free(cant_get_if_list_errstr);
1397 case NO_INTERFACES_FOUND:
1398 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1403 if_info = if_list->data; /* first interface */
1404 capture_opts.iface = g_strdup(if_info->name);
1405 free_interface_list(if_list);
1409 if (list_link_layer_types) {
1410 /* We were asked to list the link-layer types for an interface.
1411 Get the list of link-layer types for the capture device. */
1412 lt_list = get_pcap_linktype_list(capture_opts.iface, err_str);
1413 if (lt_list == NULL) {
1414 if (err_str[0] != '\0') {
1415 fprintf(stderr, "tethereal: The list of data link types for the capture device could not be obtained (%s).\n"
1416 "Please check to make sure you have sufficient permissions, and that\n"
1417 "you have the proper interface or pipe specified.\n", err_str);
1419 fprintf(stderr, "tethereal: The capture device has no data link types.\n");
1422 fprintf(stderr, "Data link types (use option -y to set):\n");
1423 for (lt_entry = lt_list; lt_entry != NULL;
1424 lt_entry = g_list_next(lt_entry)) {
1425 data_link_info = lt_entry->data;
1426 fprintf(stderr, " %s", data_link_info->name);
1427 if (data_link_info->description != NULL)
1428 fprintf(stderr, " (%s)", data_link_info->description);
1430 fprintf(stderr, " (not supported)");
1433 free_pcap_linktype_list(lt_list);
1439 * The user didn't ask us not to print a count of packets as
1440 * they arrive, so do so.
1442 print_packet_counts = TRUE;
1445 /* For now, assume libpcap gives microsecond precision. */
1446 timestamp_set_precision(TS_PREC_AUTO_USEC);
1448 capture(save_file, out_file_type);
1450 if (capture_opts.multi_files_on) {
1454 /* No - complain. */
1455 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1460 draw_tap_listeners(TRUE);
1467 /* Do the low-level work of a capture.
1468 Returns TRUE if it succeeds, FALSE otherwise. */
1470 static condition *volatile cnd_ring_timeout = NULL; /* this must be visible in process_packet */
1473 capture(char *save_file, int out_file_type)
1477 gchar open_err_str[PCAP_ERRBUF_SIZE];
1478 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1479 bpf_u_int32 netnum, netmask;
1480 struct bpf_program fcode;
1481 const char *set_linktype_err_str;
1483 int volatile volatile_err = 0;
1484 int volatile inpkts = 0;
1486 char errmsg[1024+1];
1487 condition *volatile cnd_stop_capturesize = NULL;
1488 condition *volatile cnd_stop_timeout = NULL;
1491 void (*oldhandler)(int);
1492 static const char ppamsg[] = "can't find PPA for ";
1493 const char *libpcap_warn;
1494 volatile int pipe_fd = -1;
1495 struct pcap_hdr hdr;
1496 struct pcaprec_modified_hdr rechdr;
1497 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1499 struct pcap_stat stats;
1502 dfilter_t *rfcode = NULL;
1505 /* Initialize all data structures used for dissection. */
1508 ld.linktype = WTAP_ENCAP_UNKNOWN;
1511 /* Open the network interface to capture from it.
1512 Some versions of libpcap may put warnings into the error buffer
1513 if they succeed; to tell if that's happened, we have to clear
1514 the error buffer, and check if it's still a null string. */
1515 open_err_str[0] = '\0';
1516 ld.pch = pcap_open_live(capture_opts.iface, capture_opts.snaplen,
1517 capture_opts.promisc_mode, 1000, open_err_str);
1519 if (ld.pch != NULL) {
1520 /* setting the data link type only works on real interfaces */
1521 if (capture_opts.linktype != -1) {
1522 set_linktype_err_str = set_pcap_linktype(ld.pch, capture_opts.iface,
1523 capture_opts.linktype);
1524 if (set_linktype_err_str != NULL) {
1525 g_snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1526 set_linktype_err_str);
1531 /* We couldn't open "cfile.iface" as a network device. */
1533 /* On Windows, we don't support capturing on pipes, so we give up. */
1535 /* On Win32 OSes, the capture devices are probably available to all
1536 users; don't warn about permissions problems.
1538 Do, however, warn that WAN devices aren't supported. */
1539 g_snprintf(errmsg, sizeof errmsg,
1540 "The capture session could not be initiated (%s).\n"
1541 "Please check that you have the proper interface specified.\n"
1543 "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
1544 "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
1545 "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
1546 "don't support capturing on PPP/WAN interfaces at all.\n",
1550 /* try to open cfile.iface as a pipe */
1551 pipe_fd = pipe_open_live(capture_opts.iface, &hdr, &ld, errmsg,
1554 if (pipe_fd == -1) {
1556 if (ld.pipe_err == PIPNEXIST) {
1557 /* Pipe doesn't exist, so output message for interface */
1559 /* If we got a "can't find PPA for XXX" message, warn the user (who
1560 is running Tethereal on HP-UX) that they don't have a version
1561 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1562 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1563 PPA for XXX" rather than "can't find PPA for XXX"). */
1564 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1567 "You are running Tethereal with a version of the libpcap library\n"
1568 "that doesn't handle HP-UX network devices well; this means that\n"
1569 "Tethereal may not be able to capture packets.\n"
1571 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1572 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1573 "packaged binary form from the Software Porting And Archive Centre\n"
1574 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1575 "at the URL lists a number of mirror sites.";
1578 g_snprintf(errmsg, sizeof errmsg,
1579 "The capture session could not be initiated (%s).\n"
1580 "Please check to make sure you have sufficient permissions, and that\n"
1581 "you have the proper interface or pipe specified.%s", open_err_str,
1585 * Else pipe (or file) does exist and pipe_open_live() has
1590 /* pipe_open_live() succeeded; don't want
1591 error message from pcap_open_live() */
1592 open_err_str[0] = '\0';
1598 * We've opened the capture device, so, if we're set-UID or set-GID,
1599 * relinquish those privileges.
1601 * XXX - if we have saved set-user-ID support, we should give up those
1602 * privileges immediately, and then reclaim them long enough to get
1603 * a list of network interfaces and to open one, and then give them
1604 * up again, so that stuff we do while processing the argument list,
1605 * reading the user's preferences, etc. is done as the real user and
1606 * group, not the effective user and group.
1612 if (capture_opts.cfilter && !ld.from_pipe) {
1613 /* A capture filter was specified; set it up. */
1614 if (pcap_lookupnet(capture_opts.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1616 * Well, we can't get the netmask for this interface; it's used
1617 * only for filters that check for broadcast IP addresses, so
1618 * we just warn the user, and punt and use 0.
1621 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1624 if (pcap_compile(ld.pch, &fcode, capture_opts.cfilter, 1, netmask) < 0) {
1625 if (dfilter_compile(capture_opts.cfilter, &rfcode)) {
1626 g_snprintf(errmsg, sizeof errmsg,
1627 "Unable to parse capture filter string (%s).\n"
1628 " Interestingly enough, this looks like a valid display filter\n"
1629 " Are you sure you didn't mix them up?",
1630 pcap_geterr(ld.pch));
1632 g_snprintf(errmsg, sizeof errmsg,
1633 "Unable to parse capture filter string (%s).",
1634 pcap_geterr(ld.pch));
1638 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1639 g_snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1640 pcap_geterr(ld.pch));
1641 #ifdef HAVE_PCAP_FREECODE
1642 pcap_freecode(&fcode);
1646 #ifdef HAVE_PCAP_FREECODE
1647 pcap_freecode(&fcode);
1651 /* Set up to write to the capture file. */
1654 pcap_encap = hdr.network;
1655 file_snaplen = hdr.snaplen;
1659 pcap_encap = get_pcap_linktype(ld.pch, capture_opts.iface);
1660 file_snaplen = pcap_snapshot(ld.pch);
1662 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1663 if (save_file != NULL) {
1664 /* Set up to write to the capture file. */
1665 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1666 strcpy(errmsg, "The network you're capturing from is of a type"
1667 " that Tethereal doesn't support.");
1670 ld.save_file = save_file;
1671 if (capture_opts.multi_files_on) {
1672 save_file_fd = ringbuf_init(save_file,
1673 capture_opts.ring_num_files);
1674 if (save_file_fd != -1) {
1675 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1676 file_snaplen, &err);
1678 err = errno; /* "ringbuf_init()" failed */
1682 ld.pdh = wtap_dump_open(save_file, out_file_type,
1683 ld.linktype, file_snaplen, &err);
1686 if (ld.pdh == NULL) {
1687 g_snprintf(errmsg, sizeof errmsg,
1688 cf_open_error_message(err, NULL, TRUE, out_file_type),
1689 *save_file == '\0' ? "stdout" : save_file);
1694 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1695 returned a warning; print it, but keep capturing. */
1696 if (open_err_str[0] != '\0')
1697 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1700 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1701 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1703 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1705 XXX - deal with signal semantics on various UNIX platforms. Or just
1706 use "sigaction()" and be done with it? */
1707 signal(SIGTERM, capture_cleanup);
1708 signal(SIGINT, capture_cleanup);
1709 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1710 signal(SIGHUP, oldhandler);
1713 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1714 quiet mode, report the number of packets we've captured. */
1715 signal(SIGINFO, report_counts_siginfo);
1716 #endif /* SIGINFO */
1719 /* Let the user know what interface was chosen. */
1720 descr = get_interface_descriptive_name(capture_opts.iface);
1721 fprintf(stderr, "Capturing on %s\n", descr);
1724 /* initialize capture stop conditions */
1725 init_capture_stop_conditions();
1726 /* create stop conditions */
1727 if (capture_opts.has_autostop_filesize)
1728 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1729 (long)capture_opts.autostop_filesize * 1000);
1730 if (capture_opts.has_autostop_duration)
1731 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1732 (gint32)capture_opts.autostop_duration);
1734 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1735 cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT,
1736 capture_opts.file_duration);
1738 if (!setjmp(ld.stopenv)) {
1740 ld.packet_count = 0;
1744 /* We need to be careful with automatic variables defined in the
1745 outer scope which are changed inside the loop. Most compilers
1746 don't try to roll them back to their original values after the
1747 longjmp which causes the loop to finish, but all that the
1748 standards say is that their values are indeterminate. If we
1749 don't want them to be rolled back, we should define them with the
1750 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1751 Programming in the UNIX Environment, p. 178).
1753 The "err" variable causes a particular problem. If we give it
1754 the volatile attribute, then when we pass a reference to it (as
1755 in "&err") to a function, GCC warns: "passing arg <n> of
1756 <function> discards qualifiers from pointer target type".
1757 Therefore within the loop and just beyond we don't use "err".
1758 Within the loop we define "loop_err", and assign its value to
1759 "volatile_err", which is in the outer scope and is checked when
1762 We also define "packet_count_prev" here to keep things tidy,
1763 since it's used only inside the loop. If it were defined in the
1764 outer scope, GCC would give a warning (unnecessary in this case)
1765 that it might be clobbered, and we'd need to give it the volatile
1766 attribute to suppress the warning. */
1769 int packet_count_prev = 0;
1771 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1772 /* We're not stopping at a particular capture file size, and we're
1773 not stopping after some particular amount of time has expired,
1774 so either we have no stop condition or the only stop condition
1775 is a maximum packet count.
1777 If there's no maximum packet count, pass it -1, meaning "until
1778 you run out of packets in the bufferful you read". Otherwise,
1779 pass it the number of packets we have left to capture.
1781 We don't call "pcap_loop()" as, if we're saving to a file that's
1782 a FIFO, we want to flush the FIFO after we're done processing
1783 this libpcap bufferful of packets, so that the program
1784 reading the FIFO sees the packets immediately and doesn't get
1785 any partial packet, forcing it to block in the middle of reading
1787 if (capture_opts.autostop_packets == 0)
1790 if (ld.packet_count >= capture_opts.autostop_packets) {
1791 /* XXX do we need this test here? */
1792 /* It appears there's nothing more to capture. */
1795 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1798 /* We need to check the capture file size or the timeout after
1804 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1805 errmsg, sizeof errmsg);
1808 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1810 /* Error from "pcap_dispatch()", or error or "no more packets" from
1811 "pipe_dispatch(). */
1813 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1814 /* The specified capture time has elapsed; stop the capture. */
1816 } else if (inpkts > 0) {
1817 if (capture_opts.autostop_packets != 0 &&
1818 ld.packet_count >= capture_opts.autostop_packets) {
1819 /* The specified number of packets have been captured and have
1820 passed both any capture filter in effect and any read filter
1823 } else if (cnd_stop_capturesize != NULL &&
1824 cnd_eval(cnd_stop_capturesize,
1825 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1826 /* We're saving the capture to a file, and the capture file reached
1827 its maximum size. */
1828 if (capture_opts.multi_files_on) {
1829 /* Switch to the next ringbuffer file */
1830 if (ringbuf_switch_file(&ld.pdh, &save_file, &save_file_fd, &loop_err)) {
1831 /* File switch succeeded: reset the condition */
1832 cnd_reset(cnd_stop_capturesize);
1833 if (cnd_ring_timeout) {
1834 cnd_reset(cnd_ring_timeout);
1837 /* File switch failed: stop here */
1838 volatile_err = loop_err;
1842 /* No ringbuffer - just stop. */
1846 if (ld.output_to_pipe) {
1847 if (ld.packet_count > packet_count_prev) {
1848 if (fflush(wtap_dump_file(ld.pdh))) {
1849 volatile_err = errno;
1852 packet_count_prev = ld.packet_count;
1856 } /* while (ld.go) */
1858 /* delete stop conditions */
1859 if (cnd_stop_capturesize != NULL)
1860 cnd_delete(cnd_stop_capturesize);
1861 if (cnd_stop_timeout != NULL)
1862 cnd_delete(cnd_stop_timeout);
1863 if (cnd_ring_timeout != NULL)
1864 cnd_delete(cnd_ring_timeout);
1866 if (print_packet_counts) {
1867 /* We're printing packet counts to stderr.
1868 Send a newline so that we move to the line after the packet count. */
1869 fprintf(stderr, "\n");
1872 /* If we got an error while capturing, report it. */
1876 if (ld.pipe_err == PIPERR) {
1877 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1883 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1884 pcap_geterr(ld.pch));
1888 if (volatile_err == 0)
1891 show_capture_file_io_error(save_file, volatile_err, FALSE);
1895 if (save_file != NULL) {
1896 /* We're saving to a file or files; close all files. */
1897 if (capture_opts.multi_files_on) {
1898 dump_ok = ringbuf_wtap_dump_close(&save_file, &err);
1900 dump_ok = wtap_dump_close(ld.pdh, &err);
1902 /* If we've displayed a message about a write error, there's no point
1903 in displaying another message about an error on close. */
1904 if (!dump_ok && !write_err)
1905 show_capture_file_io_error(save_file, err, TRUE);
1909 if (ld.from_pipe && pipe_fd >= 0)
1914 /* Get the capture statistics, and, if any packets were dropped, report
1916 if (pcap_stats(ld.pch, &stats) >= 0) {
1917 if (stats.ps_drop != 0) {
1918 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1921 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
1922 pcap_geterr(ld.pch));
1927 /* Report the number of captured packets if not reported during capture
1928 and we are saving to a file. */
1934 if (capture_opts.multi_files_on) {
1935 ringbuf_error_cleanup();
1939 fprintf(stderr, "tethereal: %s\n", errmsg);
1955 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
1958 struct wtap_pkthdr whdr;
1959 union wtap_pseudo_header pseudo_header;
1960 loop_data *ldat = (loop_data *) user;
1965 /* Convert from libpcap to Wiretap format.
1966 If that fails, ignore the packet (wtap_process_pcap_packet has
1967 written an error message). */
1968 pd = wtap_process_pcap_packet(ldat->linktype, phdr, pd, &pseudo_header,
1975 * Prevent a SIGINFO handler from writing to stdout while we're
1976 * doing so; instead, have it just set a flag telling us to print
1977 * that information when we're done.
1980 #endif /* SIGINFO */
1982 /* The current packet may have arrived after a very long silence,
1983 * way past the time to switch files. In order not to have
1984 * the first packet of a new series of events as the last
1985 * [or only] packet in the file, switch before writing!
1987 if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
1988 /* time elapsed for this ring file, switch to the next */
1989 if (ringbuf_switch_file(&ldat->pdh, &ldat->save_file, &save_file_fd, &loop_err)) {
1990 /* File switch succeeded: reset the condition */
1991 cnd_reset(cnd_ring_timeout);
1993 /* File switch failed: stop here */
1994 /* XXX - we should do something with "loop_err" */
1999 if (!process_packet(&cfile, ldat->pdh, 0, &whdr, &pseudo_header, pd, &err)) {
2000 /* Error writing to a capture file */
2001 if (print_packet_counts) {
2002 /* We're printing counts of packets captured; move to the line after
2004 fprintf(stderr, "\n");
2006 show_capture_file_io_error(ldat->save_file, err, FALSE);
2007 pcap_close(ldat->pch);
2008 wtap_dump_close(ldat->pdh, &err);
2014 * Allow SIGINFO handlers to write.
2019 * If a SIGINFO handler asked us to write out capture counts, do so.
2023 #endif /* SIGINFO */
2028 capture_cleanup(DWORD ctrltype _U_)
2030 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2031 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2032 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2033 like SIGTERM at least when the machine's shutting down.
2035 For now, we handle them all as indications that we should clean up
2036 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2039 However, as handlers run in a new thread, we can't just longjmp
2040 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2041 no other handler - such as one that would terminate the process -
2044 XXX - for some reason, typing ^C to Tethereal, if you run this in
2045 a Cygwin console window in at least some versions of Cygwin,
2046 causes Tethereal to terminate immediately; this routine gets
2047 called, but the main loop doesn't get a chance to run and
2048 exit cleanly, at least if this is compiled with Microsoft Visual
2049 C++ (i.e., it's a property of the Cygwin console window or Bash;
2050 it happens if Tethereal is not built with Cygwin - for all I know,
2051 building it with Cygwin may make the problem go away). */
2057 capture_cleanup(int signum _U_)
2059 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2060 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2061 "ld.go" to FALSE and return, we won't break out of it and quit
2063 longjmp(ld.stopenv, 1);
2071 /* XXX - if we use sigaction, this doesn't have to be done.
2072 (Yes, this isn't necessary on BSD, but just in case a system
2073 where "signal()" has AT&T semantics adopts SIGINFO....) */
2074 signal(SIGINFO, report_counts_siginfo);
2075 #endif /* SIGINFO */
2077 if (!print_packet_counts) {
2078 /* Report the count only if we aren't printing a packet count
2079 as packets arrive. */
2080 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2083 infoprint = FALSE; /* we just reported it */
2084 #endif /* SIGINFO */
2089 report_counts_siginfo(int signum _U_)
2091 int sav_errno = errno;
2092 /* If we've been told to delay printing, just set a flag asking
2093 that we print counts (if we're supposed to), otherwise print
2094 the count of packets captured (if we're supposed to). */
2101 #endif /* SIGINFO */
2102 #endif /* HAVE_LIBPCAP */
2105 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
2108 int snapshot_length;
2114 linktype = wtap_file_encap(cf->wth);
2115 if (save_file != NULL) {
2116 /* Set up to write to the capture file. */
2117 snapshot_length = wtap_snapshot_length(cf->wth);
2118 if (snapshot_length == 0) {
2119 /* Snapshot length of input file not known. */
2120 snapshot_length = WTAP_MAX_PACKET_SIZE;
2122 pdh = wtap_dump_open(save_file, out_file_type,
2123 linktype, snapshot_length, &err);
2126 /* We couldn't set up to write to the capture file. */
2129 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2131 "tethereal: Capture files can't be written in that format.\n");
2134 case WTAP_ERR_UNSUPPORTED_ENCAP:
2135 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2137 "tethereal: The capture file being read can't be written in "
2141 case WTAP_ERR_CANT_OPEN:
2143 "tethereal: The file \"%s\" couldn't be created for some "
2144 "unknown reason.\n",
2145 *save_file == '\0' ? "stdout" : save_file);
2148 case WTAP_ERR_SHORT_WRITE:
2150 "tethereal: A full header couldn't be written to the file \"%s\".\n",
2151 *save_file == '\0' ? "stdout" : save_file);
2156 "tethereal: The file \"%s\" could not be created: %s\n.",
2157 *save_file == '\0' ? "stdout" : save_file,
2158 wtap_strerror(err));
2164 if (print_packet_info) {
2165 if (!write_preamble(cf)) {
2167 show_print_file_io_error(err);
2173 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2174 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
2175 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2177 /* Error writing to a capture file */
2178 show_capture_file_io_error(save_file, err, FALSE);
2179 wtap_dump_close(pdh, &err);
2184 /* Print a message noting that the read failed somewhere along the line. */
2187 case WTAP_ERR_UNSUPPORTED_ENCAP:
2189 "tethereal: \"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)\n",
2190 cf->filename, err_info);
2193 case WTAP_ERR_CANT_READ:
2195 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2199 case WTAP_ERR_SHORT_READ:
2201 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2205 case WTAP_ERR_BAD_RECORD:
2207 "tethereal: \"%s\" appears to be damaged or corrupt.\n(%s)\n",
2208 cf->filename, err_info);
2213 "tethereal: An error occurred while reading \"%s\": %s.\n",
2214 cf->filename, wtap_strerror(err));
2217 if (save_file != NULL) {
2218 /* Now close the capture file. */
2219 if (!wtap_dump_close(pdh, &err))
2220 show_capture_file_io_error(save_file, err, TRUE);
2223 if (save_file != NULL) {
2224 /* Now close the capture file. */
2225 if (!wtap_dump_close(pdh, &err))
2226 show_capture_file_io_error(save_file, err, TRUE);
2228 if (print_packet_info) {
2229 if (!write_finale()) {
2231 show_print_file_io_error(err);
2238 wtap_close(cf->wth);
2245 fill_in_fdata(frame_data *fdata, capture_file *cf,
2246 const struct wtap_pkthdr *phdr, long offset)
2251 fdata->num = cf->count;
2252 fdata->pkt_len = phdr->len;
2253 cum_bytes += phdr->len;
2254 fdata->cum_bytes = cum_bytes;
2255 fdata->cap_len = phdr->caplen;
2256 fdata->file_off = offset;
2257 fdata->lnk_t = phdr->pkt_encap;
2258 fdata->abs_ts = *((nstime_t *) &phdr->ts);
2259 fdata->flags.passed_dfilter = 0;
2260 fdata->flags.encoding = CHAR_ASCII;
2261 fdata->flags.visited = 0;
2262 fdata->flags.marked = 0;
2263 fdata->flags.ref_time = 0;
2265 /* If we don't have the time stamp of the first packet in the
2266 capture, it's because this is the first packet. Save the time
2267 stamp of this packet as the time stamp of the first packet. */
2268 if (nstime_is_zero(&first_ts)) {
2269 first_ts = fdata->abs_ts;
2272 /* If we don't have the time stamp of the previous displayed packet,
2273 it's because this is the first displayed packet. Save the time
2274 stamp of this packet as the time stamp of the previous displayed
2276 if (nstime_is_zero(&prev_ts)) {
2277 prev_ts = fdata->abs_ts;
2280 /* Get the time elapsed between the first packet and this packet. */
2281 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2283 /* If it's greater than the current elapsed time, set the elapsed time
2284 to it (we check for "greater than" so as not to be confused by
2285 time moving backwards). */
2286 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2287 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2288 cf->elapsed_time = fdata->rel_ts;
2291 /* Get the time elapsed between the previous displayed packet and
2293 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2294 prev_ts = fdata->abs_ts;
2297 /* Free up all data attached to a "frame_data" structure. */
2299 clear_fdata(frame_data *fdata)
2302 g_slist_free(fdata->pfd);
2306 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2307 const struct wtap_pkthdr *whdr,
2308 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2312 gboolean create_proto_tree;
2313 epan_dissect_t *edt;
2316 /* Count this packet. */
2319 /* If we're going to print packet information, or we're going to
2320 run a read filter, or we're going to process taps, set up to
2321 do a dissection and do so. */
2322 if (do_dissection) {
2323 fill_in_fdata(&fdata, cf, whdr, offset);
2325 if (print_packet_info) {
2326 /* Grab any resolved addresses */
2328 if (g_resolv_flags) {
2329 host_name_lookup_process(NULL);
2334 if (cf->rfcode || verbose || num_tap_filters!=0)
2335 create_proto_tree = TRUE;
2337 create_proto_tree = FALSE;
2338 /* The protocol tree will be "visible", i.e., printed, only if we're
2339 printing packet details, which is true if we're printing stuff
2340 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2342 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2344 /* If we're running a read filter, prime the epan_dissect_t with that
2347 epan_dissect_prime_dfilter(edt, cf->rfcode);
2349 tap_queue_init(edt);
2351 /* We only need the columns if we're printing packet info but we're
2352 *not* verbose; in verbose mode, we print the protocol tree, not
2353 the protocol summary. */
2354 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2355 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2357 tap_push_tapped_queue(edt);
2359 /* Run the read filter if we have one. */
2361 passed = dfilter_apply_edt(cf->rfcode, edt);
2365 /* We're not running a display filter and we're not printing any
2366 packet information, so we don't need to do a dissection, and all
2367 packets are processed. */
2373 /* Count this packet. */
2378 /* Process this packet. */
2380 /* We're writing to a capture file; write this packet. */
2381 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2384 if (print_packet_counts) {
2385 /* We're printing packet counts. */
2386 if (ld.packet_count != 0) {
2387 fprintf(stderr, "\r%u ", ld.packet_count);
2388 /* stderr could be line buffered */
2394 if (print_packet_info) {
2395 /* We're printing packet information; print the information for
2397 print_packet(cf, edt);
2399 /* The ANSI C standard does not appear to *require* that a line-buffered
2400 stream be flushed to the host environment whenever a newline is
2401 written, it just says that, on such a stream, characters "are
2402 intended to be transmitted to or from the host environment as a
2403 block when a new-line character is encountered".
2405 The Visual C++ 6.0 C implementation doesn't do what is intended;
2406 even if you set a stream to be line-buffered, it still doesn't
2407 flush the buffer at the end of every line.
2409 So, if the "-l" flag was specified, we flush the standard output
2410 at the end of a packet. This will do the right thing if we're
2411 printing packet summary lines, and, as we print the entire protocol
2412 tree for a single packet without waiting for anything to happen,
2413 it should be as good as line-buffered mode if we're printing
2414 protocol trees. (The whole reason for the "-l" flag in either
2415 tcpdump or Tethereal is to allow the output of a live capture to
2416 be piped to a program or script and to have that script see the
2417 information for the packet as soon as it's printed, rather than
2418 having to wait until a standard I/O buffer fills up. */
2422 if (ferror(stdout)) {
2423 show_print_file_io_error(errno);
2429 if (do_dissection) {
2430 epan_dissect_free(edt);
2431 clear_fdata(&fdata);
2437 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2446 "tethereal: Not all the packets could be written to \"%s\" because there is "
2447 "no space left on the file system.\n",
2454 "tethereal: Not all the packets could be written to \"%s\" because you are "
2455 "too close to, or over your disk quota.\n",
2460 case WTAP_ERR_CANT_CLOSE:
2462 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2466 case WTAP_ERR_SHORT_WRITE:
2468 "tethereal: Not all the packets could be written to \"%s\".\n",
2475 "tethereal: \"%s\" could not be closed: %s.\n",
2476 fname, wtap_strerror(err));
2479 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2480 fname, wtap_strerror(err));
2487 write_preamble(capture_file *cf)
2489 switch (output_action) {
2492 return print_preamble(print_stream, cf->filename);
2497 write_pdml_preamble(stdout);
2499 write_psml_preamble(stdout);
2500 return !ferror(stdout);
2503 g_assert_not_reached();
2509 get_line_buf(size_t len)
2511 static char *line_bufp = NULL;
2512 static size_t line_buf_len = 256;
2513 size_t new_line_buf_len;
2515 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2516 new_line_buf_len *= 2)
2518 if (line_bufp == NULL) {
2519 line_buf_len = new_line_buf_len;
2520 line_bufp = g_malloc(line_buf_len + 1);
2522 if (new_line_buf_len > line_buf_len) {
2523 line_buf_len = new_line_buf_len;
2524 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2531 print_columns(capture_file *cf)
2538 line_bufp = get_line_buf(256);
2541 for (i = 0; i < cf->cinfo.num_cols; i++) {
2542 switch (cf->cinfo.col_fmt[i]) {
2546 * Don't print this if we're doing a live capture from a network
2547 * interface - if we're doing a live capture, you won't be
2548 * able to look at the capture in the future (it's not being
2549 * saved anywhere), so the frame numbers are unlikely to be
2552 * (XXX - it might be nice to be able to save and print at
2553 * the same time, sort of like an "Update list of packets
2554 * in real time" capture in Ethereal.)
2556 if (capture_opts.iface != NULL)
2559 column_len = strlen(cf->cinfo.col_data[i]);
2562 line_bufp = get_line_buf(buf_offset + column_len);
2563 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2569 case COL_ABS_DATE_TIME: /* XXX - wider */
2570 column_len = strlen(cf->cinfo.col_data[i]);
2571 if (column_len < 10)
2573 line_bufp = get_line_buf(buf_offset + column_len);
2574 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2580 case COL_DEF_DL_SRC:
2581 case COL_RES_DL_SRC:
2582 case COL_UNRES_DL_SRC:
2583 case COL_DEF_NET_SRC:
2584 case COL_RES_NET_SRC:
2585 case COL_UNRES_NET_SRC:
2586 column_len = strlen(cf->cinfo.col_data[i]);
2587 if (column_len < 12)
2589 line_bufp = get_line_buf(buf_offset + column_len);
2590 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2596 case COL_DEF_DL_DST:
2597 case COL_RES_DL_DST:
2598 case COL_UNRES_DL_DST:
2599 case COL_DEF_NET_DST:
2600 case COL_RES_NET_DST:
2601 case COL_UNRES_NET_DST:
2602 column_len = strlen(cf->cinfo.col_data[i]);
2603 if (column_len < 12)
2605 line_bufp = get_line_buf(buf_offset + column_len);
2606 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2610 column_len = strlen(cf->cinfo.col_data[i]);
2611 line_bufp = get_line_buf(buf_offset + column_len);
2612 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2615 buf_offset += column_len;
2616 if (i != cf->cinfo.num_cols - 1) {
2618 * This isn't the last column, so we need to print a
2619 * separator between this column and the next.
2621 * If we printed a network source and are printing a
2622 * network destination of the same type next, separate
2623 * them with "->"; if we printed a network destination
2624 * and are printing a network source of the same type
2625 * next, separate them with "<-"; otherwise separate them
2628 * We add enough space to the buffer for " <- " or " -> ",
2629 * even if we're only adding " ".
2631 line_bufp = get_line_buf(buf_offset + 4);
2632 switch (cf->cinfo.col_fmt[i]) {
2637 switch (cf->cinfo.col_fmt[i + 1]) {
2642 strcat(line_bufp + buf_offset, " -> ");
2647 strcat(line_bufp + buf_offset, " ");
2653 case COL_DEF_DL_SRC:
2654 case COL_RES_DL_SRC:
2655 case COL_UNRES_DL_SRC:
2656 switch (cf->cinfo.col_fmt[i + 1]) {
2658 case COL_DEF_DL_DST:
2659 case COL_RES_DL_DST:
2660 case COL_UNRES_DL_DST:
2661 strcat(line_bufp + buf_offset, " -> ");
2666 strcat(line_bufp + buf_offset, " ");
2672 case COL_DEF_NET_SRC:
2673 case COL_RES_NET_SRC:
2674 case COL_UNRES_NET_SRC:
2675 switch (cf->cinfo.col_fmt[i + 1]) {
2677 case COL_DEF_NET_DST:
2678 case COL_RES_NET_DST:
2679 case COL_UNRES_NET_DST:
2680 strcat(line_bufp + buf_offset, " -> ");
2685 strcat(line_bufp + buf_offset, " ");
2694 switch (cf->cinfo.col_fmt[i + 1]) {
2699 strcat(line_bufp + buf_offset, " <- ");
2704 strcat(line_bufp + buf_offset, " ");
2710 case COL_DEF_DL_DST:
2711 case COL_RES_DL_DST:
2712 case COL_UNRES_DL_DST:
2713 switch (cf->cinfo.col_fmt[i + 1]) {
2715 case COL_DEF_DL_SRC:
2716 case COL_RES_DL_SRC:
2717 case COL_UNRES_DL_SRC:
2718 strcat(line_bufp + buf_offset, " <- ");
2723 strcat(line_bufp + buf_offset, " ");
2729 case COL_DEF_NET_DST:
2730 case COL_RES_NET_DST:
2731 case COL_UNRES_NET_DST:
2732 switch (cf->cinfo.col_fmt[i + 1]) {
2734 case COL_DEF_NET_SRC:
2735 case COL_RES_NET_SRC:
2736 case COL_UNRES_NET_SRC:
2737 strcat(line_bufp + buf_offset, " <- ");
2742 strcat(line_bufp + buf_offset, " ");
2749 strcat(line_bufp + buf_offset, " ");
2755 return print_line(print_stream, 0, line_bufp);
2759 print_packet(capture_file *cf, epan_dissect_t *edt)
2761 print_args_t print_args;
2764 /* Print the information in the protocol tree. */
2765 switch (output_action) {
2768 print_args.to_file = TRUE;
2769 print_args.format = print_format;
2770 print_args.print_summary = !verbose;
2771 print_args.print_hex = verbose && print_hex;
2772 print_args.print_formfeed = FALSE;
2773 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2775 /* init the packet range */
2776 packet_range_init(&print_args.range);
2778 if (!proto_tree_print(&print_args, edt, print_stream))
2781 /* "print_hex_data()" will put out a leading blank line, as well
2782 as a trailing one; print one here, to separate the packets,
2783 only if "print_hex_data()" won't be called. */
2784 if (!print_line(print_stream, 0, ""))
2790 proto_tree_write_pdml(edt, stdout);
2792 return !ferror(stdout);
2795 /* Just fill in the columns. */
2796 epan_dissect_fill_in_columns(edt);
2798 /* Now print them. */
2799 switch (output_action) {
2802 if (!print_columns(cf))
2807 proto_tree_write_psml(edt, stdout);
2808 return !ferror(stdout);
2812 if (!print_hex_data(print_stream, edt))
2814 if (!print_line(print_stream, 0, ""))
2823 switch (output_action) {
2826 return print_finale(print_stream);
2831 write_pdml_finale(stdout);
2833 write_psml_finale(stdout);
2834 return !ferror(stdout);
2837 g_assert_not_reached();
2843 show_print_file_io_error(int err)
2849 "tethereal: Not all the packets could be printed because there is "
2850 "no space left on the file system.\n");
2856 "tethereal: Not all the packets could be printed because you are "
2857 "too close to, or over your disk quota.\n");
2863 "tethereal: An error occurred while printing packets: %s.\n",
2870 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2874 static char errmsg_errno[1024+1];
2877 /* Wiretap error. */
2880 case WTAP_ERR_NOT_REGULAR_FILE:
2881 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2884 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2885 /* Seen only when opening a capture file for reading. */
2886 errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2889 case WTAP_ERR_UNSUPPORTED:
2890 /* Seen only when opening a capture file for reading. */
2891 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2892 "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2895 errmsg = errmsg_errno;
2898 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2899 /* Seen only when opening a capture file for writing. */
2900 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2901 "The file \"%%s\" is a pipe, and %s capture files can't be "
2902 "written to a pipe.", wtap_file_type_string(file_type));
2903 errmsg = errmsg_errno;
2906 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2907 /* Seen only when opening a capture file for writing. */
2908 errmsg = "Tethereal doesn't support writing capture files in that format.";
2911 case WTAP_ERR_UNSUPPORTED_ENCAP:
2913 errmsg = "Tethereal can't save this capture in that format.";
2915 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2916 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2919 errmsg = errmsg_errno;
2923 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2925 errmsg = "Tethereal can't save this capture in that format.";
2927 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2930 case WTAP_ERR_BAD_RECORD:
2931 /* Seen only when opening a capture file for reading. */
2932 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2933 "The file \"%%s\" appears to be damaged or corrupt.\n"
2936 errmsg = errmsg_errno;
2939 case WTAP_ERR_CANT_OPEN:
2941 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2943 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2946 case WTAP_ERR_SHORT_READ:
2947 errmsg = "The file \"%s\" appears to have been cut short"
2948 " in the middle of a packet or other data.";
2951 case WTAP_ERR_SHORT_WRITE:
2952 errmsg = "A full header couldn't be written to the file \"%s\".";
2956 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2957 "The file \"%%s\" could not be %s: %s.",
2958 for_writing ? "created" : "opened",
2959 wtap_strerror(err));
2960 errmsg = errmsg_errno;
2964 errmsg = file_open_error_message(err, for_writing);
2969 * Open/create errors are reported with an console message in Tethereal.
2972 open_failure_message(const char *filename, int err, gboolean for_writing)
2974 fprintf(stderr, "tethereal: ");
2975 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2976 fprintf(stderr, "\n");
2980 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2984 char err_msg[2048+1];
2986 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2990 /* The open succeeded. Fill in the information for this file. */
2992 /* Initialize all data structures used for dissection. */
2996 cf->f_datalen = 0; /* not used, but set it anyway */
2998 /* Set the file name because we need it to set the follow stream filter.
2999 XXX - is that still true? We need it for other reasons, though,
3001 cf->filename = g_strdup(fname);
3003 /* Indicate whether it's a permanent or temporary file. */
3004 cf->is_tempfile = is_tempfile;
3006 /* If it's a temporary capture buffer file, mark it as not saved. */
3007 cf->user_saved = !is_tempfile;
3009 cf->cd_t = wtap_file_type(cf->wth);
3011 cf->drops_known = FALSE;
3013 cf->snap = wtap_snapshot_length(cf->wth);
3014 if (cf->snap == 0) {
3015 /* Snapshot length not known. */
3016 cf->has_snap = FALSE;
3017 cf->snap = WTAP_MAX_PACKET_SIZE;
3019 cf->has_snap = TRUE;
3020 nstime_set_zero(&cf->elapsed_time);
3021 nstime_set_zero(&first_ts);
3022 nstime_set_zero(&prev_ts);
3027 g_snprintf(err_msg, sizeof err_msg,
3028 cf_open_error_message(*err, err_info, FALSE, 0), fname);
3029 fprintf(stderr, "tethereal: %s\n", err_msg);
3035 /* Take care of byte order in the libpcap headers read from pipes.
3036 * (function taken from wiretap/libpcap.c) */
3038 adjust_header(loop_data *ldat, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
3040 if (ldat->byte_swapped) {
3041 /* Byte-swap the record header fields. */
3042 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
3043 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
3044 rechdr->incl_len = BSWAP32(rechdr->incl_len);
3045 rechdr->orig_len = BSWAP32(rechdr->orig_len);
3048 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
3049 swapped, in order to match the BPF header layout.
3051 Unfortunately, some files were, according to a comment in the "libpcap"
3052 source, written with version 2.3 in their headers but without the
3053 interchanged fields, so if "incl_len" is greater than "orig_len" - which
3054 would make no sense - we assume that we need to swap them. */
3055 if (hdr->version_major == 2 &&
3056 (hdr->version_minor < 3 ||
3057 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
3060 temp = rechdr->orig_len;
3061 rechdr->orig_len = rechdr->incl_len;
3062 rechdr->incl_len = temp;
3066 /* Mimic pcap_open_live() for pipe captures
3067 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
3069 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
3070 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
3072 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ldat,
3073 char *errmsg, int errmsgl)
3075 struct stat pipe_stat;
3079 unsigned int bytes_read;
3082 * XXX Tethereal blocks until we return
3084 if (strcmp(pipename, "-") == 0)
3085 fd = 0; /* read from stdin */
3087 if (stat(pipename, &pipe_stat) < 0) {
3088 if (errno == ENOENT || errno == ENOTDIR)
3089 ldat->pipe_err = PIPNEXIST;
3091 g_snprintf(errmsg, errmsgl,
3092 "The capture session could not be initiated "
3093 "due to error on pipe: %s", strerror(errno));
3094 ldat->pipe_err = PIPERR;
3098 if (! S_ISFIFO(pipe_stat.st_mode)) {
3099 if (S_ISCHR(pipe_stat.st_mode)) {
3101 * Assume the user specified an interface on a system where
3102 * interfaces are in /dev. Pretend we haven't seen it.
3104 ldat->pipe_err = PIPNEXIST;
3106 g_snprintf(errmsg, errmsgl,
3107 "The capture session could not be initiated because\n"
3108 "\"%s\" is neither an interface nor a pipe", pipename);
3109 ldat->pipe_err = PIPERR;
3113 fd = open(pipename, O_RDONLY);
3115 g_snprintf(errmsg, errmsgl,
3116 "The capture session could not be initiated "
3117 "due to error on pipe open: %s", strerror(errno));
3118 ldat->pipe_err = PIPERR;
3123 ldat->from_pipe = TRUE;
3125 /* read the pcap header */
3127 while (bytes_read < sizeof magic) {
3128 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3131 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
3133 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3142 /* Host that wrote it has our byte order, and was running
3143 a program using either standard or ss990417 libpcap. */
3144 ldat->byte_swapped = FALSE;
3145 ldat->modified = FALSE;
3147 case PCAP_MODIFIED_MAGIC:
3148 /* Host that wrote it has our byte order, but was running
3149 a program using either ss990915 or ss991029 libpcap. */
3150 ldat->byte_swapped = FALSE;
3151 ldat->modified = TRUE;
3153 case PCAP_SWAPPED_MAGIC:
3154 /* Host that wrote it has a byte order opposite to ours,
3155 and was running a program using either standard or
3156 ss990417 libpcap. */
3157 ldat->byte_swapped = TRUE;
3158 ldat->modified = FALSE;
3160 case PCAP_SWAPPED_MODIFIED_MAGIC:
3161 /* Host that wrote it out has a byte order opposite to
3162 ours, and was running a program using either ss990915
3163 or ss991029 libpcap. */
3164 ldat->byte_swapped = TRUE;
3165 ldat->modified = TRUE;
3168 /* Not a "libpcap" type we know about. */
3169 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3173 /* Read the rest of the header */
3175 while (bytes_read < sizeof(struct pcap_hdr)) {
3176 b = read(fd, ((char *)hdr)+bytes_read,
3177 sizeof(struct pcap_hdr) - bytes_read);
3180 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
3182 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3189 if (ldat->byte_swapped) {
3190 /* Byte-swap the header fields about which we care. */
3191 hdr->version_major = BSWAP16(hdr->version_major);
3192 hdr->version_minor = BSWAP16(hdr->version_minor);
3193 hdr->snaplen = BSWAP32(hdr->snaplen);
3194 hdr->network = BSWAP32(hdr->network);
3197 if (hdr->version_major < 2) {
3198 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3202 ldat->pipe_state = STATE_EXPECT_REC_HDR;
3203 ldat->pipe_err = PIPOK;
3207 ldat->pipe_err = PIPERR;
3212 /* We read one record from the pipe, take care of byte order in the record
3213 * header, write the record in the capture file, and update capture statistics. */
3216 pipe_dispatch(int fd, loop_data *ldat, struct pcap_hdr *hdr,
3217 struct pcaprec_modified_hdr *rechdr, guchar *data,
3218 char *errmsg, int errmsgl)
3220 struct pcap_pkthdr phdr;
3222 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3225 switch (ldat->pipe_state) {
3227 case STATE_EXPECT_REC_HDR:
3228 ldat->bytes_to_read = ldat->modified ?
3229 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3230 ldat->bytes_read = 0;
3231 ldat->pipe_state = STATE_READ_REC_HDR;
3234 case STATE_READ_REC_HDR:
3235 b = read(fd, ((char *)rechdr)+ldat->bytes_read,
3236 ldat->bytes_to_read - ldat->bytes_read);
3239 result = PD_PIPE_EOF;
3241 result = PD_PIPE_ERR;
3244 if ((ldat->bytes_read += b) < ldat->bytes_to_read)
3246 result = PD_REC_HDR_READ;
3249 case STATE_EXPECT_DATA:
3250 ldat->bytes_read = 0;
3251 ldat->pipe_state = STATE_READ_DATA;
3254 case STATE_READ_DATA:
3255 b = read(fd, data+ldat->bytes_read, rechdr->hdr.incl_len - ldat->bytes_read);
3258 result = PD_PIPE_EOF;
3260 result = PD_PIPE_ERR;
3263 if ((ldat->bytes_read += b) < rechdr->hdr.incl_len)
3265 result = PD_DATA_READ;
3269 g_snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3272 } /* switch (ldat->pipe_state) */
3275 * We've now read as much data as we were expecting, so process it.
3279 case PD_REC_HDR_READ:
3280 /* We've read the header. Take care of byte order. */
3281 adjust_header(ldat, hdr, &rechdr->hdr);
3282 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3283 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3284 ldat->packet_count+1, rechdr->hdr.incl_len);
3287 ldat->pipe_state = STATE_EXPECT_DATA;
3291 /* Fill in a "struct pcap_pkthdr", and process the packet. */
3292 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3293 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3294 phdr.caplen = rechdr->hdr.incl_len;
3295 phdr.len = rechdr->hdr.orig_len;
3297 capture_pcap_cb((guchar *)ldat, &phdr, data);
3299 ldat->pipe_state = STATE_EXPECT_REC_HDR;
3303 ldat->pipe_err = PIPEOF;
3307 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3314 ldat->pipe_err = PIPERR;
3315 /* Return here rather than inside the switch to prevent GCC warning */
3319 #endif /* HAVE_LIBPCAP */
3322 * General errors are reported with an console message in Tethereal.
3325 failure_message(const char *msg_format, va_list ap)
3327 fprintf(stderr, "tethereal: ");
3328 vfprintf(stderr, msg_format, ap);
3329 fprintf(stderr, "\n");
3333 * Read errors are reported with an console message in Tethereal.
3336 read_failure_message(const char *filename, int err)
3338 fprintf(stderr, "tethereal: An error occurred while reading from the file \"%s\": %s.\n",
3339 filename, strerror(err));