3 * $Id: tethereal.c,v 1.235 2004/04/16 23:16:28 guy Exp $
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.
55 #ifdef HAVE_SYS_STAT_H
56 # include <sys/stat.h>
59 #ifdef NEED_SNPRINTF_H
60 # include "snprintf.h"
63 #ifdef NEED_STRERROR_H
71 #include "cvsversion.h"
74 #include <epan/epan.h>
75 #include <epan/filesystem.h>
78 #include <epan/timestamp.h>
79 #include <epan/packet.h>
81 #include "disabled_protos.h"
85 #include <epan/resolv.h>
87 #include "version_info.h"
89 #include "pcap-util.h"
91 #include <epan/conversation.h>
92 #include <epan/plugins.h>
94 #include "conditions.h"
95 #include "capture_stop_conditions.h"
96 #include "ringbuffer.h"
97 #include <epan/epan_dissect.h>
99 #include <epan/timestamp.h>
102 #include <wiretap/wtap-capture.h>
103 #include <wiretap/libpcap.h>
107 #include "capture-wpcap.h"
111 * This is the template for the decode as option; it is shared between the
112 * various functions that output the usage for this parameter.
114 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
115 static guint32 firstsec, firstusec;
116 static guint32 prevsec, prevusec;
117 static GString *comp_info_str, *runtime_info_str;
118 static gboolean quiet;
119 static gboolean decode;
120 static gboolean verbose;
121 static gboolean print_hex;
122 static gboolean line_buffered;
123 static guint32 cum_bytes = 0;
124 static int print_format;
127 typedef struct _loop_data {
128 gboolean go; /* TRUE as long as we're supposed to keep capturing */
130 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
134 gboolean output_to_pipe;
137 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
138 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
139 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
141 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
142 STATE_EXPECT_DATA, STATE_READ_DATA
145 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
151 static int capture(int);
152 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
154 static void report_counts(void);
156 static BOOL WINAPI capture_cleanup(DWORD);
158 static void capture_cleanup(int);
160 static void report_counts_siginfo(int);
163 #endif /* HAVE_LIBPCAP */
170 static int load_cap_file(capture_file *, int);
171 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
172 union wtap_pseudo_header *, const guchar *);
173 static void show_capture_file_io_error(const char *, int, gboolean);
174 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
175 union wtap_pseudo_header *, const guchar *);
176 static void show_print_file_io_error(int err);
177 static char *cf_open_error_message(int err, gchar *err_info,
178 gboolean for_writing, int file_type);
181 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
182 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
183 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
184 struct pcaprec_modified_hdr *, guchar *, char *, int);
188 static void open_failure_message(const char *filename, int err,
189 gboolean for_writing);
190 static void failure_message(const char *msg_format, va_list ap);
191 static void read_failure_message(const char *filename, int err);
196 int snaplen; /* Maximum captured packet length */
197 int promisc_mode; /* Capture in promiscuous mode */
198 int autostop_count; /* Maximum packet count */
199 gboolean has_autostop_duration; /* TRUE if maximum capture duration
201 gint32 autostop_duration; /* Maximum capture duration */
202 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
204 gint32 autostop_filesize; /* Maximum capture file size */
205 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
206 guint32 ringbuffer_num_files; /* Number of ring buffer files */
207 gboolean has_ring_duration; /* TRUE if ring duration specified */
208 gint32 ringbuffer_duration; /* Switch file after n seconds */
209 int linktype; /* Data link type to use, or -1 for
213 static capture_options capture_opts = {
214 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
215 infinite, in effect */
216 TRUE, /* promiscuous mode is the default */
217 0, /* max packet count - default is 0,
219 FALSE, /* maximum capture duration not
220 specified by default */
221 0, /* maximum capture duration */
222 FALSE, /* maximum capture file size not
223 specified by default */
224 0, /* maximum capture file size */
225 FALSE, /* ring buffer off by default */
226 RINGBUFFER_MIN_NUM_FILES, /* default number of ring buffer
228 FALSE, /* Switch ring file after some */
229 0, /* specified time is off by default */
230 -1 /* Default to not change link type */
233 static gboolean list_link_layer_types;
236 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
237 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
239 #endif /* HAVE_LIBPCAP */
242 print_usage(gboolean print_ver)
249 fprintf(output, "This is GNU t" PACKAGE " " VERSION
253 "\n (C) 1998-2004 Gerald Combs <gerald@ethereal.com>"
256 comp_info_str->str, runtime_info_str->str);
261 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
263 fprintf(output, "\t[ -b <number of ring buffer files>[:<duration>] ] [ -c <count> ]\n");
264 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
265 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <interface> ]\n");
266 fprintf(output, "\t[ -N <resolving> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
267 fprintf(output, "\t[ -R <read filter> ] [ -s <snaplen> ] [ -t <time stamp format> ]\n");
268 fprintf(output, "\t[ -T pdml|ps|text ] [ -w <savefile> ] [ -y <link type> ]\n");
269 fprintf(output, "\t[ -z <statistics string> ]\n");
271 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
272 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
273 fprintf(output, "\t[ -F <output file type> ] [ -N <resolving> ]\n");
274 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
275 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|text ] [ -w <savefile> ]\n");
276 fprintf(output, "\t[ -z <statistics string> ]\n");
278 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
279 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
280 if (wtap_dump_can_open(i))
281 fprintf(output, "\t%s - %s\n",
282 wtap_file_type_short_string(i), wtap_file_type_string(i));
284 fprintf(output, "\tdefault is libpcap\n");
289 get_natural_int(const char *string, const char *name)
294 number = strtol(string, &p, 10);
295 if (p == string || *p != '\0') {
296 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
301 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
305 if (number > INT_MAX) {
306 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
314 get_positive_int(const char *string, const char *name)
318 number = get_natural_int(string, name);
321 fprintf(stderr, "tethereal: The specified %s is zero\n",
330 * Given a string of the form "<autostop criterion>:<value>", as might appear
331 * as an argument to a "-a" option, parse it and set the criterion in
332 * question. Return an indication of whether it succeeded or failed
336 set_autostop_criterion(const char *autostoparg)
340 colonp = strchr(autostoparg, ':');
348 * Skip over any white space (there probably won't be any, but
349 * as we allow it in the preferences file, we might as well
356 * Put the colon back, so if our caller uses, in an
357 * error message, the string they passed us, the message
363 if (strcmp(autostoparg,"duration") == 0) {
364 capture_opts.has_autostop_duration = TRUE;
365 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
366 } else if (strcmp(autostoparg,"filesize") == 0) {
367 capture_opts.has_autostop_filesize = TRUE;
368 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
372 *colonp = ':'; /* put the colon back */
377 * Given a string of the form "<ring buffer file>:<duration>", as might appear
378 * as an argument to a "-b" option, parse it and set the arguments in
379 * question. Return an indication of whether it succeeded or failed
383 get_ring_arguments(const char *arg)
385 guchar *p = NULL, *colonp;
387 colonp = strchr(arg, ':');
389 if (colonp != NULL) {
394 capture_opts.ringbuffer_num_files =
395 get_natural_int(arg, "number of ring buffer files");
401 * Skip over any white space (there probably won't be any, but
402 * as we allow it in the preferences file, we might as well
409 * Put the colon back, so if our caller uses, in an
410 * error message, the string they passed us, the message
417 capture_opts.has_ring_duration = TRUE;
418 capture_opts.ringbuffer_duration = get_positive_int(p,
419 "ring buffer duration");
421 *colonp = ':'; /* put the colon back */
426 /* structure to keep track of what tap listeners have been registered.
428 typedef struct _ethereal_tap_list {
429 struct _ethereal_tap_list *next;
431 void (*func)(char *arg);
433 static ethereal_tap_list *tap_list=NULL;
436 register_ethereal_tap(char *cmd, void (*func)(char *arg))
438 ethereal_tap_list *newtl;
440 newtl=malloc(sizeof(ethereal_tap_list));
441 newtl->next=tap_list;
449 * For a dissector table, print on the stream described by output,
450 * its short name (which is what's used in the "-d" option) and its
454 display_dissector_table_names(char *table_name, char *ui_name, gpointer output)
456 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
460 * For a dissector handle, print on the stream described by output,
461 * the filter name (which is what's used in the "-d" option) and the full
462 * name for the protocol that corresponds to this handle.
465 display_dissector_names(gchar *table _U_, gpointer handle, gpointer output)
468 const gchar* proto_filter_name;
469 const gchar* proto_ui_name;
471 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
473 if (proto_id != -1) {
474 proto_filter_name = proto_get_protocol_filter_name(proto_id);
475 proto_ui_name = proto_get_protocol_name(proto_id);
476 g_assert(proto_filter_name != NULL);
477 g_assert(proto_ui_name != NULL);
479 fprintf((FILE *)output, "\t%s (%s)\n",
486 * The protocol_name_search structure is used by find_protocol_name_func()
487 * to pass parameters and store results
489 struct protocol_name_search{
490 gchar *searched_name; /* Protocol filter name we are looking for */
491 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
492 guint nb_match; /* How many dissectors matched searched_name */
494 typedef struct protocol_name_search *protocol_name_search_t;
497 * This function parses all dissectors associated with a table to find the
498 * one whose protocol has the specified filter name. It is called
499 * as a reference function in a call to dissector_table_foreach_handle.
500 * The name we are looking for, as well as the results, are stored in the
501 * protocol_name_search struct pointed to by user_data.
502 * If called using dissector_table_foreach_handle, we actually parse the
503 * whole list of dissectors.
506 find_protocol_name_func(gchar *table _U_, gpointer handle, gpointer user_data)
510 const gchar *protocol_filter_name;
511 protocol_name_search_t search_info;
515 search_info = (protocol_name_search_t)user_data;
517 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
518 if (proto_id != -1) {
519 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
520 g_assert(protocol_filter_name != NULL);
521 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
523 if (search_info->nb_match == 0) {
524 /* Record this handle only if this is the first match */
525 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
527 search_info->nb_match++;
533 * Print all layer type names supported.
534 * We send the output to the stream described by the handle output.
538 fprint_all_layer_types(FILE *output)
541 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
545 * Print all protocol names supported for a specific layer type.
546 * table_name contains the layer type name in which the search is performed.
547 * We send the output to the stream described by the handle output.
551 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
554 dissector_table_foreach_handle(table_name,
555 display_dissector_names,
560 * The function below parses the command-line parameters for the decode as
561 * feature (a string pointer by cl_param).
562 * It checks the format of the command-line, searches for a matching table
563 * and dissector. If a table/dissector match is not found, we display a
564 * summary of the available tables/dissectors (on stderr) and return FALSE.
565 * If everything is fine, we get the "Decode as" preference activated,
566 * then we return TRUE.
569 add_decode_as(const gchar *cl_param)
573 gchar *decoded_param;
574 gchar *remaining_param;
576 gchar *dissector_str;
577 dissector_handle_t dissector_matching;
578 dissector_table_t table_matching;
579 ftenum_t dissector_table_selector_type;
580 struct protocol_name_search user_protocol_name;
582 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
585 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
586 g_assert(decoded_param);
587 strcpy(decoded_param, cl_param);
590 /* The lines below will parse this string (modifying it) to extract all
591 necessary information. Note that decoded_param is still needed since
592 strings are not copied - we just save pointers. */
594 /* This section extracts a layer type (table_name) from decoded_param */
595 table_name = decoded_param; /* Layer type string starts from beginning */
597 remaining_param = strchr(table_name, '=');
598 if (remaining_param == NULL) {
599 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
600 /* If the argument does not follow the template, carry on anyway to check
601 if the table name is at least correct. If remaining_param is NULL,
602 we'll exit anyway further down */
605 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
608 /* Remove leading and trailing spaces from the table name */
609 while ( table_name[0] == ' ' )
611 while ( table_name[strlen(table_name) - 1] == ' ' )
612 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
614 /* The following part searches a table matching with the layer type specified */
615 table_matching = NULL;
617 /* Look for the requested table */
618 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
619 fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
622 table_matching = find_dissector_table(table_name);
623 if (!table_matching) {
624 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 */
628 if (!table_matching) {
629 /* Display a list of supported layer types to help the user, if the
630 specified layer type was not found */
631 fprintf(stderr, "tethereal: Valid layer types are:\n");
632 fprint_all_layer_types(stderr);
634 if (remaining_param == NULL || !table_matching) {
635 /* Exit if the layer type was not found, or if no '=' separator was found
637 g_free(decoded_param);
641 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
642 fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
645 remaining_param++; /* Move to the second '=' */
646 *remaining_param = '\0'; /* Remove the second '=' */
648 remaining_param++; /* Position after the layer type string */
650 /* This section extracts a selector value (selector_str) from decoded_param */
652 selector_str = remaining_param; /* Next part starts with the selector number */
654 remaining_param = strchr(selector_str, ',');
655 if (remaining_param == NULL) {
656 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
657 /* If the argument does not follow the template, carry on anyway to check
658 if the selector value is at least correct. If remaining_param is NULL,
659 we'll exit anyway further down */
662 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
665 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
667 switch (dissector_table_selector_type) {
673 /* The selector for this table is an unsigned number. Parse it as such.
674 There's no need to remove leading and trailing spaces from the
675 selector number string, because sscanf will do that for us. */
676 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
677 fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
678 g_free(decoded_param);
685 /* The selector for this table is a string. */
689 /* There are currently no dissector tables with any types other
690 than the ones listed above. */
691 g_assert_not_reached();
694 if (remaining_param == NULL) {
695 /* Exit if no ',' separator was found (see above) */
696 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
697 fprint_all_protocols_for_layer_types(stderr, table_name);
698 g_free(decoded_param);
702 remaining_param++; /* Position after the selector number string */
704 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
706 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
708 /* Remove leading and trailing spaces from the dissector name */
709 while ( dissector_str[0] == ' ' )
711 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
712 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
714 dissector_matching = NULL;
716 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
717 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 */
718 fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
721 user_protocol_name.nb_match = 0;
722 user_protocol_name.searched_name = dissector_str;
723 user_protocol_name.matched_handle = NULL;
725 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 */
727 if (user_protocol_name.nb_match != 0) {
728 dissector_matching = user_protocol_name.matched_handle;
729 if (user_protocol_name.nb_match > 1) {
730 fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
734 /* OK, check whether the problem is that there isn't any such
735 protocol, or that there is but it's not specified as a protocol
736 that's valid for that dissector table.
737 Note, we don't exit here, but dissector_matching will remain NULL,
739 if (proto_get_id_by_filter_name(dissector_str) == -1) {
740 /* No such protocol */
741 fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
743 fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
744 dissector_str, table_name);
749 if (!dissector_matching) {
750 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
751 fprint_all_protocols_for_layer_types(stderr, table_name);
752 g_free(decoded_param);
756 /* This is the end of the code that parses the command-line options.
757 All information is now stored in the variables:
761 The above variables that are strings are still pointing to areas within
762 decoded_parm. decoded_parm thus still needs to be kept allocated in
763 until we stop needing these variables
764 decoded_param will be deallocated at each exit point of this function */
767 /* We now have a pointer to the handle for the requested dissector
768 (requested protocol) inside the variable dissector_matching */
769 switch (dissector_table_selector_type) {
775 /* The selector for this table is an unsigned number. */
776 dissector_change(table_name, selector, dissector_matching);
781 /* The selector for this table is a string. */
782 dissector_change_string(table_name, selector_str, dissector_matching);
786 /* There are currently no dissector tables with any types other
787 than the ones listed above. */
788 g_assert_not_reached();
790 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
795 main(int argc, char *argv[])
799 gboolean arg_error = FALSE;
805 char *gpf_path, *pf_path;
806 char *gdp_path, *dp_path;
807 int gpf_open_errno, gpf_read_errno;
808 int pf_open_errno, pf_read_errno;
809 int gdp_open_errno, gdp_read_errno;
810 int dp_open_errno, dp_read_errno;
813 gboolean capture_filter_specified = FALSE;
814 GList *if_list, *if_entry;
818 gchar err_str[PCAP_ERRBUF_SIZE];
820 gboolean capture_option_specified = FALSE;
822 int out_file_type = WTAP_FILE_PCAP;
823 gchar *cf_name = NULL, *rfilter = NULL;
826 GList *lt_list, *lt_entry;
827 data_link_info_t *data_link_info;
829 #ifdef HAVE_PCAP_OPEN_DEAD
830 struct bpf_program fcode;
832 dfilter_t *rfcode = NULL;
835 ethereal_tap_list *tli;
837 set_timestamp_setting(TS_RELATIVE);
839 /* Register all dissectors; we must do this before checking for the
840 "-G" flag, as the "-G" flag dumps information registered by the
841 dissectors, and we must do it before we read the preferences, in
842 case any dissectors register preferences. */
843 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
844 failure_message,open_failure_message,read_failure_message);
846 /* Register all tap listeners; we do this before we parse the arguments,
847 as the "-z" argument can specify a registered tap. */
848 register_all_tap_listeners();
850 /* Now register the preferences for any non-dissector modules.
851 We must do that before we read the preferences as well. */
852 prefs_register_modules();
854 /* If invoked with the "-G" flag, we dump out information based on
855 the argument to the "-G" flag; if no argument is specified,
856 for backwards compatibility we dump out a glossary of display
859 We do this here to mirror what happens in the GTK+ version, although
860 it's not necessary here. */
861 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
863 proto_registrar_dump_fields();
865 if (strcmp(argv[2], "fields") == 0)
866 proto_registrar_dump_fields();
867 else if (strcmp(argv[2], "protocols") == 0)
868 proto_registrar_dump_protocols();
870 fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
878 /* Set the C-language locale to the native environment. */
879 setlocale(LC_ALL, "");
881 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
882 &pf_open_errno, &pf_read_errno, &pf_path);
883 if (gpf_path != NULL) {
884 if (gpf_open_errno != 0) {
885 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
886 pf_path, strerror(gpf_open_errno));
888 if (gpf_read_errno != 0) {
889 fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
890 pf_path, strerror(gpf_read_errno));
893 if (pf_path != NULL) {
894 if (pf_open_errno != 0) {
895 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
896 strerror(pf_open_errno));
898 if (pf_read_errno != 0) {
899 fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
900 pf_path, strerror(pf_read_errno));
906 /* Set the name resolution code's flags from the preferences. */
907 g_resolv_flags = prefs->name_resolve;
909 /* Read the disabled protocols file. */
910 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
911 &dp_path, &dp_open_errno, &dp_read_errno);
912 if (gdp_path != NULL) {
913 if (gdp_open_errno != 0) {
915 "Could not open global disabled protocols file\n\"%s\": %s.\n",
916 gdp_path, strerror(gdp_open_errno));
918 if (gdp_read_errno != 0) {
920 "I/O error reading global disabled protocols file\n\"%s\": %s.\n",
921 gdp_path, strerror(gdp_read_errno));
925 if (dp_path != NULL) {
926 if (dp_open_errno != 0) {
928 "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
929 strerror(dp_open_errno));
931 if (dp_read_errno != 0) {
933 "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
934 strerror(dp_read_errno));
940 /* Load Wpcap, if possible */
944 init_cap_file(&cfile);
946 /* Assemble the compile-time version information string */
947 comp_info_str = g_string_new("Compiled ");
948 get_compiled_version_info(comp_info_str);
950 /* Assemble the run-time version information string */
951 runtime_info_str = g_string_new("Running ");
952 get_runtime_version_info(runtime_info_str);
954 /* Print format defaults to this. */
955 print_format = PR_FMT_TEXT;
957 /* Now get our args */
958 while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vw:Vxy:z:")) != -1) {
960 case 'a': /* autostop criteria */
962 if (set_autostop_criterion(optarg) == FALSE) {
963 fprintf(stderr, "tethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
967 capture_option_specified = TRUE;
971 case 'b': /* Ringbuffer option */
973 capture_opts.ringbuffer_on = TRUE;
974 if (get_ring_arguments(optarg) == FALSE) {
975 fprintf(stderr, "tethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
979 capture_option_specified = TRUE;
983 case 'c': /* Capture xxx packets */
985 capture_opts.autostop_count =
986 get_positive_int(optarg, "packet count");
988 capture_option_specified = TRUE;
992 case 'd': /* Decode as rule */
993 if (!add_decode_as(optarg))
996 case 'D': /* Print a list of capture devices */
998 if_list = get_interface_list(&err, err_str);
999 if (if_list == NULL) {
1002 case CANT_GET_INTERFACE_LIST:
1003 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1007 case NO_INTERFACES_FOUND:
1008 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1013 i = 1; /* Interface id number */
1014 for (if_entry = g_list_first(if_list); if_entry != NULL;
1015 if_entry = g_list_next(if_entry)) {
1016 if_info = if_entry->data;
1017 printf("%d. %s", i++, if_info->name);
1018 if (if_info->description != NULL)
1019 printf(" (%s)", if_info->description);
1022 free_interface_list(if_list);
1025 capture_option_specified = TRUE;
1031 capture_filter_specified = TRUE;
1033 g_free(cfile.cfilter);
1034 cfile.cfilter = g_strdup(optarg);
1036 capture_option_specified = TRUE;
1041 out_file_type = wtap_short_string_to_file_type(optarg);
1042 if (out_file_type < 0) {
1043 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
1048 case 'h': /* Print help and exit */
1052 case 'i': /* Use interface xxx */
1055 * If the argument is a number, treat it as an index into the list
1056 * of adapters, as printed by "tethereal -D".
1058 * This should be OK on UNIX systems, as interfaces shouldn't have
1059 * names that begin with digits. It can be useful on Windows, where
1060 * more than one interface can have the same name.
1062 adapter_index = strtol(optarg, &p, 10);
1063 if (p != NULL && *p == '\0') {
1064 if (adapter_index < 0) {
1066 "tethereal: The specified adapter index is a negative number\n");
1069 if (adapter_index > INT_MAX) {
1071 "tethereal: The specified adapter index is too large (greater than %d)\n",
1075 if (adapter_index == 0) {
1076 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1079 if_list = get_interface_list(&err, err_str);
1080 if (if_list == NULL) {
1083 case CANT_GET_INTERFACE_LIST:
1084 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1088 case NO_INTERFACES_FOUND:
1089 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1094 if_info = g_list_nth_data(if_list, adapter_index - 1);
1095 if (if_info == NULL) {
1096 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1099 cfile.iface = g_strdup(if_info->name);
1100 free_interface_list(if_list);
1102 cfile.iface = g_strdup(optarg);
1104 capture_option_specified = TRUE;
1108 case 'l': /* "Line-buffer" standard output */
1109 /* This isn't line-buffering, strictly speaking, it's just
1110 flushing the standard output after the information for
1111 each packet is printed; however, that should be good
1112 enough for all the purposes to which "-l" is put (and
1113 is probably actually better for "-V", as it does fewer
1116 See the comment in "wtap_dispatch_cb_print()" for an
1117 explanation of why we do that, and why we don't just
1118 use "setvbuf()" to make the standard output line-buffered
1119 (short version: in Windows, "line-buffered" is the same
1120 as "fully-buffered", and the output buffer is only flushed
1121 when it fills up). */
1122 line_buffered = TRUE;
1124 case 'L': /* Print list of link-layer types and exit */
1126 list_link_layer_types = TRUE;
1129 capture_option_specified = TRUE;
1133 case 'n': /* No name resolution */
1134 g_resolv_flags = RESOLV_NONE;
1136 case 'N': /* Select what types of addresses/port #s to resolve */
1137 if (g_resolv_flags == RESOLV_ALL)
1138 g_resolv_flags = RESOLV_NONE;
1139 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1140 if (badopt != '\0') {
1141 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
1146 case 'o': /* Override preference from command line */
1147 switch (prefs_set_pref(optarg)) {
1149 case PREFS_SET_SYNTAX_ERR:
1150 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
1154 case PREFS_SET_NO_SUCH_PREF:
1155 case PREFS_SET_OBSOLETE:
1156 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
1162 case 'p': /* Don't capture in promiscuous mode */
1164 capture_opts.promisc_mode = FALSE;
1166 capture_option_specified = TRUE;
1170 case 'q': /* Quiet */
1173 case 'r': /* Read capture file xxx */
1174 cf_name = g_strdup(optarg);
1176 case 'R': /* Read file filter */
1179 case 's': /* Set the snapshot (capture) length */
1181 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
1183 capture_option_specified = TRUE;
1187 case 'S': /* show packets in real time */
1190 case 't': /* Time stamp type */
1191 if (strcmp(optarg, "r") == 0)
1192 set_timestamp_setting(TS_RELATIVE);
1193 else if (strcmp(optarg, "a") == 0)
1194 set_timestamp_setting(TS_ABSOLUTE);
1195 else if (strcmp(optarg, "ad") == 0)
1196 set_timestamp_setting(TS_ABSOLUTE_WITH_DATE);
1197 else if (strcmp(optarg, "d") == 0)
1198 set_timestamp_setting(TS_DELTA);
1200 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
1202 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
1203 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
1207 case 'T': /* printing Type */
1208 if (strcmp(optarg, "text") == 0)
1209 print_format = PR_FMT_TEXT;
1210 else if (strcmp(optarg, "pdml") == 0)
1211 print_format = PR_FMT_PDML;
1212 else if (strcmp(optarg, "ps") == 0)
1213 print_format = PR_FMT_PS;
1215 fprintf(stderr, "tethereal: Invalid -T parameter.\n");
1216 fprintf(stderr, "It must be \"ps\", \"text\" or \"pdml\".\n");
1220 case 'v': /* Show version and exit */
1221 printf("t" PACKAGE " " VERSION
1226 comp_info_str->str, runtime_info_str->str);
1229 case 'w': /* Write to capture file xxx */
1230 cfile.save_file = g_strdup(optarg);
1232 case 'V': /* Verbose */
1235 case 'x': /* Print packet data in hex (and ASCII) */
1238 case 'y': /* Set the pcap data link type */
1240 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
1241 capture_opts.linktype = pcap_datalink_name_to_val(optarg);
1242 if (capture_opts.linktype == -1) {
1243 fprintf(stderr, "tethereal: The specified data link type \"%s\" is not valid\n",
1247 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1248 /* XXX - just treat it as a number */
1249 capture_opts.linktype = get_natural_int(optarg, "data link type");
1250 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1252 capture_option_specified = TRUE;
1257 for(tli=tap_list;tli;tli=tli->next){
1258 if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
1259 (*tli->func)(optarg);
1264 fprintf(stderr,"tethereal: invalid -z argument.\n");
1265 fprintf(stderr," -z argument must be one of :\n");
1266 for(tli=tap_list;tli;tli=tli->next){
1267 fprintf(stderr," %s\n",tli->cmd);
1273 case '?': /* Bad flag - print usage message */
1279 /* If printing PDML or PS, force -V */
1280 if (print_format == PR_FMT_PDML || print_format == PR_FMT_PS)
1283 /* If no capture filter or read filter has been specified, and there are
1284 still command-line arguments, treat them as the tokens of a capture
1285 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1286 flag was specified. */
1287 if (optind < argc) {
1288 if (cf_name != NULL) {
1289 if (rfilter != NULL) {
1291 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1294 rfilter = get_args_as_string(argc, argv, optind);
1297 if (capture_filter_specified) {
1299 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1302 cfile.cfilter = get_args_as_string(argc, argv, optind);
1304 capture_option_specified = TRUE;
1309 /* See if we're writing a capture file and the file is a pipe */
1311 ld.output_to_pipe = FALSE;
1313 if (cfile.save_file != NULL) {
1314 if (strcmp(cfile.save_file, "-") == 0) {
1316 g_free(cfile.save_file);
1317 cfile.save_file = g_strdup("");
1319 ld.output_to_pipe = TRUE;
1324 err = test_for_fifo(cfile.save_file);
1327 case ENOENT: /* it doesn't exist, so we'll be creating it,
1328 and it won't be a FIFO */
1329 case 0: /* found it, but it's not a FIFO */
1332 case ESPIPE: /* it is a FIFO */
1333 ld.output_to_pipe = TRUE;
1336 default: /* couldn't stat it */
1338 "tethereal: Error testing whether capture file is a pipe: %s\n",
1346 #ifndef HAVE_LIBPCAP
1347 if (capture_option_specified)
1348 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1356 if (list_link_layer_types) {
1357 /* We're supposed to list the link-layer types for an interface;
1358 did the user also specify a capture file to be read? */
1360 /* Yes - that's bogus. */
1361 fprintf(stderr, "tethereal: You cannot specify -L and a capture file to be read.\n");
1364 /* No - did they specify a ring buffer option? */
1365 if (capture_opts.ringbuffer_on) {
1366 fprintf(stderr, "tethereal: Ring buffer requested, but a capture is not being done.\n");
1370 /* If they didn't specify a "-w" flag, but specified a maximum capture
1371 file size, tell them that this doesn't work, and exit. */
1372 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
1373 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1374 "capture isn't being saved to a file.\n");
1378 if (capture_opts.ringbuffer_on) {
1379 /* Ring buffer works only under certain conditions:
1380 a) ring buffer does not work if you're not saving the capture to
1382 b) ring buffer only works if you're saving in libpcap format;
1383 c) it makes no sense to enable the ring buffer if the maximum
1384 file size is set to "infinite";
1385 d) file must not be a pipe. */
1386 if (cfile.save_file == NULL) {
1387 fprintf(stderr, "tethereal: Ring buffer requested, but "
1388 "capture isn't being saved to a file.\n");
1391 if (out_file_type != WTAP_FILE_PCAP) {
1392 fprintf(stderr, "tethereal: Ring buffer requested, but "
1393 "capture isn't being saved in libpcap format.\n");
1396 if (!capture_opts.has_autostop_filesize) {
1397 fprintf(stderr, "tethereal: Ring buffer requested, but "
1398 "no maximum capture file size was specified.\n");
1401 if (ld.output_to_pipe) {
1402 fprintf(stderr, "tethereal: Ring buffer requested, but "
1403 "capture file is a pipe.\n");
1411 /* Start windows sockets */
1412 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1415 /* Notify all registered modules that have had any of their preferences
1416 changed either from one of the preferences file or from the command
1417 line that their preferences have changed. */
1420 /* disabled protocols as per configuration file */
1421 if (gdp_path == NULL && dp_path == NULL) {
1422 set_disabled_protos_list();
1425 /* Build the column format array */
1426 col_setup(&cfile.cinfo, prefs->num_cols);
1427 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1428 cfile.cinfo.col_fmt[i] = get_column_format(i);
1429 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1430 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1432 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1433 cfile.cinfo.col_data[i] = NULL;
1434 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1435 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1437 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1438 cfile.cinfo.col_fence[i] = 0;
1439 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1440 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1443 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1446 for (j = 0; j < NUM_COL_FMTS; j++) {
1447 if (!cfile.cinfo.fmt_matx[i][j])
1450 if (cfile.cinfo.col_first[j] == -1)
1451 cfile.cinfo.col_first[j] = i;
1452 cfile.cinfo.col_last[j] = i;
1457 if (capture_opts.snaplen < 1)
1458 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1459 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1460 capture_opts.snaplen = MIN_PACKET_SIZE;
1462 /* Check the value range of the ringbuffer_num_files parameter */
1463 if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
1464 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
1465 #if RINGBUFFER_MIN_NUM_FILES > 0
1466 else if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
1467 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
1471 if (rfilter != NULL) {
1472 if (!dfilter_compile(rfilter, &rfcode)) {
1473 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1475 #ifdef HAVE_PCAP_OPEN_DEAD
1479 p = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1481 if (pcap_compile(p, &fcode, rfilter, 0, 0) != -1) {
1483 " Note: That display filter code looks like a valid capture filter;\n"
1484 " maybe you mixed them up?\n");
1493 cfile.rfcode = rfcode;
1496 * We're reading a capture file.
1501 * Immediately relinquish any set-UID or set-GID privileges we have;
1502 * we must not be allowed to read any capture files the user running
1503 * Tethereal can't open.
1509 err = cf_open(cf_name, FALSE, &cfile);
1514 err = load_cap_file(&cfile, out_file_type);
1521 /* No capture file specified, so we're supposed to do a live capture
1522 (or get a list of link-layer types for a live capture device);
1523 do we have support for live captures? */
1528 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1533 /* Yes; did the user specify an interface to use? */
1534 if (cfile.iface == NULL) {
1535 /* No - is a default specified in the preferences file? */
1536 if (prefs->capture_device != NULL) {
1538 if_text = strrchr(prefs->capture_device, ' ');
1539 if (if_text == NULL) {
1540 cfile.iface = g_strdup(prefs->capture_device);
1542 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1545 /* No - pick the first one from the list of interfaces. */
1546 if_list = get_interface_list(&err, err_str);
1547 if (if_list == NULL) {
1550 case CANT_GET_INTERFACE_LIST:
1551 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1555 case NO_INTERFACES_FOUND:
1556 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1561 if_info = if_list->data; /* first interface */
1562 cfile.iface = g_strdup(if_info->name);
1563 free_interface_list(if_list);
1567 if (list_link_layer_types) {
1568 /* We were asked to list the link-layer types for an interface.
1569 Get the list of link-layer types for the capture device. */
1570 lt_list = get_pcap_linktype_list(cfile.iface, err_str);
1571 if (lt_list == NULL) {
1572 if (err_str[0] != '\0') {
1573 fprintf(stderr, "tethereal: The list of data link types for the capture device could not be obtained (%s).\n"
1574 "Please check to make sure you have sufficient permissions, and that\n"
1575 "you have the proper interface or pipe specified.\n", err_str);
1577 fprintf(stderr, "tethereal: The capture device has no data link types.\n");
1580 fprintf(stderr, "Data link types (use option -y to set):\n");
1581 for (lt_entry = lt_list; lt_entry != NULL;
1582 lt_entry = g_list_next(lt_entry)) {
1583 data_link_info = lt_entry->data;
1584 fprintf(stderr, " %s", data_link_info->name);
1585 if (data_link_info->description != NULL)
1586 fprintf(stderr, " (%s)", data_link_info->description);
1588 fprintf(stderr, " (not supported)");
1591 free_pcap_linktype_list(lt_list);
1595 capture(out_file_type);
1597 if (capture_opts.ringbuffer_on) {
1601 /* No - complain. */
1602 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1607 draw_tap_listeners(TRUE);
1614 /* Do the low-level work of a capture.
1615 Returns TRUE if it succeeds, FALSE otherwise. */
1617 static condition *volatile cnd_ring_timeout = NULL; /* this must be visible in wtap_dispatch_cb_write */
1620 capture(int out_file_type)
1624 gchar open_err_str[PCAP_ERRBUF_SIZE];
1625 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1626 bpf_u_int32 netnum, netmask;
1627 struct bpf_program fcode;
1628 const char *set_linktype_err_str;
1630 int volatile volatile_err = 0;
1631 int volatile inpkts = 0;
1633 char errmsg[1024+1];
1634 condition *volatile cnd_stop_capturesize = NULL;
1635 condition *volatile cnd_stop_timeout = NULL;
1637 void (*oldhandler)(int);
1638 static const char ppamsg[] = "can't find PPA for ";
1640 volatile int pipe_fd = -1;
1641 struct pcap_hdr hdr;
1642 struct pcaprec_modified_hdr rechdr;
1643 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1645 struct pcap_stat stats;
1648 dfilter_t *rfcode = NULL;
1650 /* Initialize all data structures used for dissection. */
1653 ld.linktype = WTAP_ENCAP_UNKNOWN;
1656 /* Open the network interface to capture from it.
1657 Some versions of libpcap may put warnings into the error buffer
1658 if they succeed; to tell if that's happened, we have to clear
1659 the error buffer, and check if it's still a null string. */
1660 open_err_str[0] = '\0';
1661 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1662 capture_opts.promisc_mode, 1000, open_err_str);
1664 if (ld.pch != NULL) {
1665 /* setting the data link type only works on real interfaces */
1666 if (capture_opts.linktype != -1) {
1667 set_linktype_err_str = set_pcap_linktype(ld.pch, cfile.iface,
1668 capture_opts.linktype);
1669 if (set_linktype_err_str != NULL) {
1670 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1671 set_linktype_err_str);
1676 /* We couldn't open "cfile.iface" as a network device. */
1678 /* On Windows, we don't support capturing on pipes, so we give up. */
1680 /* On Win32 OSes, the capture devices are probably available to all
1681 users; don't warn about permissions problems.
1683 Do, however, warn that WAN devices aren't supported. */
1684 snprintf(errmsg, sizeof errmsg,
1685 "The capture session could not be initiated (%s).\n"
1686 "Please check that you have the proper interface specified.\n"
1688 "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
1689 "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
1690 "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
1691 "don't support capturing on PPP/WAN interfaces at all.\n",
1695 /* try to open cfile.iface as a pipe */
1696 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1698 if (pipe_fd == -1) {
1700 if (ld.pipe_err == PIPNEXIST) {
1701 /* Pipe doesn't exist, so output message for interface */
1703 /* If we got a "can't find PPA for XXX" message, warn the user (who
1704 is running Tethereal on HP-UX) that they don't have a version
1705 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1706 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1707 PPA for XXX" rather than "can't find PPA for XXX"). */
1708 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1711 "You are running Tethereal with a version of the libpcap library\n"
1712 "that doesn't handle HP-UX network devices well; this means that\n"
1713 "Tethereal may not be able to capture packets.\n"
1715 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1716 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1717 "packaged binary form from the Software Porting And Archive Centre\n"
1718 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1719 "at the URL lists a number of mirror sites.";
1722 snprintf(errmsg, sizeof errmsg,
1723 "The capture session could not be initiated (%s).\n"
1724 "Please check to make sure you have sufficient permissions, and that\n"
1725 "you have the proper interface or pipe specified.%s", open_err_str,
1729 * Else pipe (or file) does exist and pipe_open_live() has
1734 /* pipe_open_live() succeeded; don't want
1735 error message from pcap_open_live() */
1736 open_err_str[0] = '\0';
1742 * We've opened the capture device, so, if we're set-UID or set-GID,
1743 * relinquish those privileges.
1745 * XXX - if we have saved set-user-ID support, we should give up those
1746 * privileges immediately, and then reclaim them long enough to get
1747 * a list of network interfaces and to open one, and then give them
1748 * up again, so that stuff we do while processing the argument list,
1749 * reading the user's preferences, etc. is done as the real user and
1750 * group, not the effective user and group.
1756 if (cfile.cfilter && !ld.from_pipe) {
1757 /* A capture filter was specified; set it up. */
1758 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1760 * Well, we can't get the netmask for this interface; it's used
1761 * only for filters that check for broadcast IP addresses, so
1762 * we just warn the user, and punt and use 0.
1765 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1768 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1769 if (dfilter_compile(cfile.cfilter, &rfcode)) {
1770 snprintf(errmsg, sizeof errmsg,
1771 "Unable to parse capture filter string (%s).\n"
1772 " Interestingly enough, this looks like a valid display filter\n"
1773 " Are you sure you didn't mix them up?",
1774 pcap_geterr(ld.pch));
1776 snprintf(errmsg, sizeof errmsg,
1777 "Unable to parse capture filter string (%s).",
1778 pcap_geterr(ld.pch));
1782 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1783 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1784 pcap_geterr(ld.pch));
1789 /* Set up to write to the capture file. */
1792 pcap_encap = hdr.network;
1793 file_snaplen = hdr.snaplen;
1797 pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1798 file_snaplen = pcap_snapshot(ld.pch);
1800 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1801 if (cfile.save_file != NULL) {
1802 /* Set up to write to the capture file. */
1803 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1804 strcpy(errmsg, "The network you're capturing from is of a type"
1805 " that Tethereal doesn't support.");
1808 if (capture_opts.ringbuffer_on) {
1809 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1810 capture_opts.ringbuffer_num_files);
1811 if (cfile.save_file_fd != -1) {
1812 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1813 pcap_snapshot(ld.pch), &err);
1815 err = errno; /* "ringbuf_init()" failed */
1819 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1820 ld.linktype, pcap_snapshot(ld.pch), &err);
1823 if (ld.pdh == NULL) {
1824 snprintf(errmsg, sizeof errmsg,
1825 cf_open_error_message(err, NULL, TRUE, out_file_type),
1826 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1831 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1832 returned a warning; print it, but keep capturing. */
1833 if (open_err_str[0] != '\0')
1834 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1837 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1838 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1840 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1842 XXX - deal with signal semantics on various UNIX platforms. Or just
1843 use "sigaction()" and be done with it? */
1844 signal(SIGTERM, capture_cleanup);
1845 signal(SIGINT, capture_cleanup);
1846 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1847 signal(SIGHUP, oldhandler);
1850 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1851 quiet mode, report the number of packets we've captured. */
1852 signal(SIGINFO, report_counts_siginfo);
1853 #endif /* SIGINFO */
1856 /* Let the user know what interface was chosen. */
1857 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1859 /* initialize capture stop conditions */
1860 init_capture_stop_conditions();
1861 /* create stop conditions */
1862 if (capture_opts.has_autostop_filesize)
1863 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1864 (long)capture_opts.autostop_filesize * 1000);
1865 if (capture_opts.has_autostop_duration)
1866 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1867 (gint32)capture_opts.autostop_duration);
1869 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1870 cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT,
1871 capture_opts.ringbuffer_duration);
1873 if (!setjmp(ld.stopenv)) {
1875 ld.packet_count = 0;
1879 /* We need to be careful with automatic variables defined in the
1880 outer scope which are changed inside the loop. Most compilers
1881 don't try to roll them back to their original values after the
1882 longjmp which causes the loop to finish, but all that the
1883 standards say is that their values are indeterminate. If we
1884 don't want them to be rolled back, we should define them with the
1885 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1886 Programming in the UNIX Environment, p. 178).
1888 The "err" variable causes a particular problem. If we give it
1889 the volatile attribute, then when we pass a reference to it (as
1890 in "&err") to a function, GCC warns: "passing arg <n> of
1891 <function> discards qualifiers from pointer target type".
1892 Therefore within the loop and just beyond we don't use "err".
1893 Within the loop we define "loop_err", and assign its value to
1894 "volatile_err", which is in the outer scope and is checked when
1897 We also define "packet_count_prev" here to keep things tidy,
1898 since it's used only inside the loop. If it were defined in the
1899 outer scope, GCC would give a warning (unnecessary in this case)
1900 that it might be clobbered, and we'd need to give it the volatile
1901 attribute to suppress the warning. */
1904 int packet_count_prev = 0;
1906 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1907 /* We're not stopping at a particular capture file size, and we're
1908 not stopping after some particular amount of time has expired,
1909 so either we have no stop condition or the only stop condition
1910 is a maximum packet count.
1912 If there's no maximum packet count, pass it -1, meaning "until
1913 you run out of packets in the bufferful you read". Otherwise,
1914 pass it the number of packets we have left to capture.
1916 We don't call "pcap_loop()" as, if we're saving to a file that's
1917 a FIFO, we want to flush the FIFO after we're done processing
1918 this libpcap bufferful of packets, so that the program
1919 reading the FIFO sees the packets immediately and doesn't get
1920 any partial packet, forcing it to block in the middle of reading
1922 if (capture_opts.autostop_count == 0)
1925 if (ld.packet_count >= capture_opts.autostop_count) {
1926 /* XXX do we need this test here? */
1927 /* It appears there's nothing more to capture. */
1930 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1933 /* We need to check the capture file size or the timeout after
1939 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1940 errmsg, sizeof errmsg);
1943 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1945 /* Error from "pcap_dispatch()", or error or "no more packets" from
1946 "pipe_dispatch(). */
1948 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1949 /* The specified capture time has elapsed; stop the capture. */
1951 } else if (inpkts > 0) {
1952 if (capture_opts.autostop_count != 0 &&
1953 ld.packet_count >= capture_opts.autostop_count) {
1954 /* The specified number of packets have been captured and have
1955 passed both any capture filter in effect and any read filter
1958 } else if (cnd_stop_capturesize != NULL &&
1959 cnd_eval(cnd_stop_capturesize,
1960 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1961 /* We're saving the capture to a file, and the capture file reached
1962 its maximum size. */
1963 if (capture_opts.ringbuffer_on) {
1964 /* Switch to the next ringbuffer file */
1965 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1966 /* File switch succeeded: reset the condition */
1967 cnd_reset(cnd_stop_capturesize);
1968 if (cnd_ring_timeout) {
1969 cnd_reset(cnd_ring_timeout);
1972 /* File switch failed: stop here */
1973 volatile_err = loop_err;
1977 /* No ringbuffer - just stop. */
1981 if (ld.output_to_pipe) {
1982 if (ld.packet_count > packet_count_prev) {
1983 if (fflush(wtap_dump_file(ld.pdh))) {
1984 volatile_err = errno;
1987 packet_count_prev = ld.packet_count;
1991 } /* while (ld.go) */
1993 /* delete stop conditions */
1994 if (cnd_stop_capturesize != NULL)
1995 cnd_delete(cnd_stop_capturesize);
1996 if (cnd_stop_timeout != NULL)
1997 cnd_delete(cnd_stop_timeout);
1998 if (cnd_ring_timeout != NULL)
1999 cnd_delete(cnd_ring_timeout);
2001 if ((cfile.save_file != NULL) && !quiet) {
2002 /* We're saving to a file, which means we're printing packet counts
2003 to stderr if we are not running silent and deep.
2004 Send a newline so that we move to the line after the packet count. */
2005 fprintf(stderr, "\n");
2008 /* If we got an error while capturing, report it. */
2012 if (ld.pipe_err == PIPERR) {
2013 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2019 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2020 pcap_geterr(ld.pch));
2024 if (volatile_err == 0)
2027 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
2031 if (cfile.save_file != NULL) {
2032 /* We're saving to a file or files; close all files. */
2033 if (capture_opts.ringbuffer_on) {
2034 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
2036 dump_ok = wtap_dump_close(ld.pdh, &err);
2038 /* If we've displayed a message about a write error, there's no point
2039 in displaying another message about an error on close. */
2040 if (!dump_ok && !write_err)
2041 show_capture_file_io_error(cfile.save_file, err, TRUE);
2045 if (ld.from_pipe && pipe_fd >= 0)
2050 /* Get the capture statistics, and, if any packets were dropped, report
2052 if (pcap_stats(ld.pch, &stats) >= 0) {
2053 if (stats.ps_drop != 0) {
2054 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
2057 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
2058 pcap_geterr(ld.pch));
2063 /* Report the number of captured packets if not reported during capture
2064 and we are saving to a file. */
2070 if (capture_opts.ringbuffer_on) {
2071 ringbuf_error_cleanup();
2073 g_free(cfile.save_file);
2074 cfile.save_file = NULL;
2075 fprintf(stderr, "tethereal: %s\n", errmsg);
2091 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2094 struct wtap_pkthdr whdr;
2095 union wtap_pseudo_header pseudo_header;
2096 loop_data *ld = (loop_data *) user;
2100 /* Convert from libpcap to Wiretap format.
2101 If that fails, ignore the packet (wtap_process_pcap_packet has
2102 written an error message). */
2103 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2112 wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
2113 /* Report packet capture count if not quiet */
2116 if (ld->packet_count != 0) {
2117 fprintf(stderr, "\r%u ", ld->packet_count);
2118 /* stderr could be line buffered */
2122 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
2123 &pseudo_header, pd);
2127 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
2133 capture_cleanup(DWORD ctrltype _U_)
2135 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2136 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2137 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2138 like SIGTERM at least when the machine's shutting down.
2140 For now, we handle them all as indications that we should clean up
2141 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2144 However, as handlers run in a new thread, we can't just longjmp
2145 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2146 no other handler - such as one that would terminate the process -
2149 XXX - for some reason, typing ^C to Tethereal, if you run this in
2150 a Cygwin console window in at least some versions of Cygwin,
2151 causes Tethereal to terminate immediately; this routine gets
2152 called, but the main loop doesn't get a chance to run and
2153 exit cleanly, at least if this is compiled with Microsoft Visual
2154 C++ (i.e., it's a property of the Cygwin console window or Bash;
2155 it happens if Tethereal is not built with Cygwin - for all I know,
2156 building it with Cygwin may make the problem go away). */
2162 capture_cleanup(int signum _U_)
2164 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2165 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2166 "ld.go" to FALSE and return, we won't break out of it and quit
2168 longjmp(ld.stopenv, 1);
2176 /* XXX - if we use sigaction, this doesn't have to be done.
2177 (Yes, this isn't necessary on BSD, but just in case a system
2178 where "signal()" has AT&T semantics adopts SIGINFO....) */
2179 signal(SIGINFO, report_counts_siginfo);
2180 #endif /* SIGINFO */
2182 if (cfile.save_file != NULL && quiet) {
2183 /* Report the count only if we're capturing to a file (rather
2184 than printing captured packet information out) and aren't
2185 updating a count as packets arrive. */
2186 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2189 infoprint = FALSE; /* we just reported it */
2190 #endif /* SIGINFO */
2195 report_counts_siginfo(int signum _U_)
2197 int sav_errno = errno;
2198 /* If we've been told to delay printing, just set a flag asking
2199 that we print counts (if we're supposed to), otherwise print
2200 the count of packets captured (if we're supposed to). */
2207 #endif /* SIGINFO */
2208 #endif /* HAVE_LIBPCAP */
2211 load_cap_file(capture_file *cf, int out_file_type)
2214 int snapshot_length;
2221 linktype = wtap_file_encap(cf->wth);
2222 if (cf->save_file != NULL) {
2223 /* Set up to write to the capture file. */
2224 snapshot_length = wtap_snapshot_length(cf->wth);
2225 if (snapshot_length == 0) {
2226 /* Snapshot length of input file not known. */
2227 snapshot_length = WTAP_MAX_PACKET_SIZE;
2229 pdh = wtap_dump_open(cf->save_file, out_file_type,
2230 linktype, snapshot_length, &err);
2233 /* We couldn't set up to write to the capture file. */
2236 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2238 "tethereal: Capture files can't be written in that format.\n");
2241 case WTAP_ERR_UNSUPPORTED_ENCAP:
2242 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2244 "tethereal: The capture file being read cannot be written in "
2248 case WTAP_ERR_CANT_OPEN:
2250 "tethereal: The file \"%s\" couldn't be created for some "
2251 "unknown reason.\n",
2252 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2255 case WTAP_ERR_SHORT_WRITE:
2257 "tethereal: A full header couldn't be written to the file \"%s\".\n",
2258 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2263 "tethereal: The file \"%s\" could not be created: %s\n.",
2264 *cf->save_file == '\0' ? "stdout" : cf->save_file,
2265 wtap_strerror(err));
2272 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
2275 print_preamble(stdout, print_format);
2276 if (ferror(stdout)) {
2278 show_print_file_io_error(err);
2283 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
2287 if (cf->save_file != NULL) {
2288 /* Now close the capture file. */
2289 if (!wtap_dump_close(args.pdh, &err))
2290 show_capture_file_io_error(cfile.save_file, err, TRUE);
2292 print_finale(stdout, print_format);
2293 if (ferror(stdout)) {
2295 show_print_file_io_error(err);
2299 /* Print a message noting that the read failed somewhere along the line. */
2302 case WTAP_ERR_UNSUPPORTED_ENCAP:
2304 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n(%s)\n",
2305 cf->filename, err_info);
2308 case WTAP_ERR_CANT_READ:
2310 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2314 case WTAP_ERR_SHORT_READ:
2316 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2320 case WTAP_ERR_BAD_RECORD:
2322 "tethereal: \"%s\" appears to be damaged or corrupt.\n(%s)\n",
2323 cf->filename, err_info);
2328 "tethereal: An error occurred while reading \"%s\": %s.\n",
2329 cf->filename, wtap_strerror(err));
2332 if (cf->save_file != NULL) {
2333 /* Now close the capture file. */
2334 if (!wtap_dump_close(args.pdh, &err))
2335 show_capture_file_io_error(cfile.save_file, err, TRUE);
2340 wtap_close(cf->wth);
2347 fill_in_fdata(frame_data *fdata, capture_file *cf,
2348 const struct wtap_pkthdr *phdr, long offset)
2353 fdata->num = cf->count;
2354 fdata->pkt_len = phdr->len;
2355 cum_bytes += phdr->len;
2356 fdata->cum_bytes = cum_bytes;
2357 fdata->cap_len = phdr->caplen;
2358 fdata->file_off = offset;
2359 fdata->lnk_t = phdr->pkt_encap;
2360 fdata->abs_secs = phdr->ts.tv_sec;
2361 fdata->abs_usecs = phdr->ts.tv_usec;
2362 fdata->flags.passed_dfilter = 0;
2363 fdata->flags.encoding = CHAR_ASCII;
2364 fdata->flags.visited = 0;
2365 fdata->flags.marked = 0;
2366 fdata->flags.ref_time = 0;
2368 /* If we don't have the time stamp of the first packet in the
2369 capture, it's because this is the first packet. Save the time
2370 stamp of this packet as the time stamp of the first packet. */
2371 if (!firstsec && !firstusec) {
2372 firstsec = fdata->abs_secs;
2373 firstusec = fdata->abs_usecs;
2376 /* If we don't have the time stamp of the previous displayed packet,
2377 it's because this is the first displayed packet. Save the time
2378 stamp of this packet as the time stamp of the previous displayed
2380 if (!prevsec && !prevusec) {
2381 prevsec = fdata->abs_secs;
2382 prevusec = fdata->abs_usecs;
2385 /* Get the time elapsed between the first packet and this packet. */
2386 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2387 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2389 /* If it's greater than the current elapsed time, set the elapsed time
2390 to it (we check for "greater than" so as not to be confused by
2391 time moving backwards). */
2392 if ((gint32)cf->esec < fdata->rel_secs
2393 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2394 cf->esec = fdata->rel_secs;
2395 cf->eusec = fdata->rel_usecs;
2398 /* Get the time elapsed between the previous displayed packet and
2400 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2401 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2402 prevsec = fdata->abs_secs;
2403 prevusec = fdata->abs_usecs;
2406 /* Free up all data attached to a "frame_data" structure. */
2408 clear_fdata(frame_data *fdata)
2411 g_slist_free(fdata->pfd);
2415 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
2416 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2418 cb_args_t *args = (cb_args_t *) user;
2419 capture_file *cf = args->cf;
2420 wtap_dumper *pdh = args->pdh;
2424 epan_dissect_t *edt;
2429 * Prevent a SIGINFO handler from writing to stdout while we're
2430 * doing so; instead, have it just set a flag telling us to print
2431 * that information when we're done.
2434 #endif /* SIGINFO */
2435 #endif /* HAVE_LIBPCAP */
2439 fill_in_fdata(&fdata, cf, phdr, offset);
2440 edt = epan_dissect_new(TRUE, FALSE);
2441 epan_dissect_prime_dfilter(edt, cf->rfcode);
2442 epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
2443 passed = dfilter_apply_edt(cf->rfcode, edt);
2449 /* The packet passed the read filter. */
2455 /* The current packet may have arrived after a very long silence,
2456 * way past the time to switch files. In order not to have
2457 * the first packet of a new series of events as the last
2458 * [or only] packet in the file, switch before writing!
2460 if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
2461 /* time elasped for this ring file, switch to the next */
2462 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
2463 /* File switch succeeded: reset the condition */
2464 cnd_reset(cnd_ring_timeout);
2466 /* File switch failed: stop here */
2467 /* XXX - we should do something with "loop_err" */
2472 if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
2474 if (ld.pch != NULL && !quiet) {
2475 /* We're capturing packets, so (if -q not specified) we're printing
2476 a count of packets captured; move to the line after the count. */
2477 fprintf(stderr, "\n");
2480 show_capture_file_io_error(cf->save_file, err, FALSE);
2485 wtap_dump_close(pdh, &err);
2490 epan_dissect_free(edt);
2492 clear_fdata(&fdata);
2497 * Allow SIGINFO handlers to write.
2502 * If a SIGINFO handler asked us to write out capture counts, do so.
2506 #endif /* SIGINFO */
2507 #endif /* HAVE_LIBPCAP */
2511 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2520 "tethereal: Not all the packets could be written to \"%s\" because there is "
2521 "no space left on the file system.\n",
2528 "tethereal: Not all the packets could be written to \"%s\" because you are "
2529 "too close to, or over your disk quota.\n",
2534 case WTAP_ERR_CANT_CLOSE:
2536 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2540 case WTAP_ERR_SHORT_WRITE:
2542 "tethereal: Not all the packets could be written to \"%s\".\n",
2549 "tethereal: \"%s\" could not be closed: %s.\n",
2550 fname, wtap_strerror(err));
2553 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2554 fname, wtap_strerror(err));
2561 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
2562 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2564 cb_args_t *args = (cb_args_t *) user;
2565 capture_file *cf = args->cf;
2568 print_args_t print_args;
2569 epan_dissect_t *edt;
2570 gboolean create_proto_tree;
2575 fill_in_fdata(&fdata, cf, phdr, offset);
2577 /* Grab any resolved addresses */
2578 if (g_resolv_flags) {
2579 host_name_lookup_process(NULL);
2583 if (cf->rfcode || verbose || num_tap_filters!=0)
2584 create_proto_tree = TRUE;
2586 create_proto_tree = FALSE;
2587 /* The protocol tree will be "visible", i.e., printed, only if we're
2588 not printing a summary.
2590 We only need the columns if we're *not* verbose; in verbose mode,
2591 we print the protocol tree, not the protocol summary. */
2593 edt = epan_dissect_new(create_proto_tree, verbose);
2595 epan_dissect_prime_dfilter(edt, cf->rfcode);
2598 tap_queue_init(edt);
2599 epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
2600 tap_push_tapped_queue(edt);
2603 passed = dfilter_apply_edt(cf->rfcode, edt);
2606 /* The packet passed the read filter. */
2610 print_args.to_file = TRUE;
2611 print_args.format = print_format;
2612 print_args.print_summary = !verbose;
2613 print_args.print_hex = verbose && print_hex;
2614 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2616 /* init the packet range */
2617 packet_range_init(&print_args.range);
2620 /* Print the information in the protocol tree. */
2621 proto_tree_print(&print_args, edt, stdout);
2623 /* "print_hex_data()" will put out a leading blank line, as well
2624 as a trailing one; print one here, to separate the packets,
2625 only if "print_hex_data()" won't be called. */
2629 /* Just fill in the columns. */
2630 epan_dissect_fill_in_columns(edt);
2632 /* Now print them. */
2633 for (i = 0; i < cf->cinfo.num_cols; i++) {
2634 switch (cf->cinfo.col_fmt[i]) {
2637 * Don't print this if we're doing a live capture from a network
2638 * interface - if we're doing a live capture, you won't be
2639 * able to look at the capture in the future (it's not being
2640 * saved anywhere), so the frame numbers are unlikely to be
2643 * (XXX - it might be nice to be able to save and print at
2644 * the same time, sort of like an "Update list of packets
2645 * in real time" capture in Ethereal.)
2647 if (cf->iface != NULL)
2649 printf("%3s", cf->cinfo.col_data[i]);
2655 case COL_ABS_DATE_TIME: /* XXX - wider */
2656 printf("%10s", cf->cinfo.col_data[i]);
2662 case COL_DEF_DL_SRC:
2663 case COL_RES_DL_SRC:
2664 case COL_UNRES_DL_SRC:
2665 case COL_DEF_NET_SRC:
2666 case COL_RES_NET_SRC:
2667 case COL_UNRES_NET_SRC:
2668 printf("%12s", cf->cinfo.col_data[i]);
2674 case COL_DEF_DL_DST:
2675 case COL_RES_DL_DST:
2676 case COL_UNRES_DL_DST:
2677 case COL_DEF_NET_DST:
2678 case COL_RES_NET_DST:
2679 case COL_UNRES_NET_DST:
2680 printf("%-12s", cf->cinfo.col_data[i]);
2684 printf("%s", cf->cinfo.col_data[i]);
2687 if (i != cf->cinfo.num_cols - 1) {
2689 * This isn't the last column, so we need to print a
2690 * separator between this column and the next.
2692 * If we printed a network source and are printing a
2693 * network destination of the same type next, separate
2694 * them with "->"; if we printed a network destination
2695 * and are printing a network source of the same type
2696 * next, separate them with "<-"; otherwise separate them
2699 switch (cf->cinfo.col_fmt[i]) {
2704 switch (cf->cinfo.col_fmt[i + 1]) {
2718 case COL_DEF_DL_SRC:
2719 case COL_RES_DL_SRC:
2720 case COL_UNRES_DL_SRC:
2721 switch (cf->cinfo.col_fmt[i + 1]) {
2723 case COL_DEF_DL_DST:
2724 case COL_RES_DL_DST:
2725 case COL_UNRES_DL_DST:
2735 case COL_DEF_NET_SRC:
2736 case COL_RES_NET_SRC:
2737 case COL_UNRES_NET_SRC:
2738 switch (cf->cinfo.col_fmt[i + 1]) {
2740 case COL_DEF_NET_DST:
2741 case COL_RES_NET_DST:
2742 case COL_UNRES_NET_DST:
2755 switch (cf->cinfo.col_fmt[i + 1]) {
2769 case COL_DEF_DL_DST:
2770 case COL_RES_DL_DST:
2771 case COL_UNRES_DL_DST:
2772 switch (cf->cinfo.col_fmt[i + 1]) {
2774 case COL_DEF_DL_SRC:
2775 case COL_RES_DL_SRC:
2776 case COL_UNRES_DL_SRC:
2786 case COL_DEF_NET_DST:
2787 case COL_RES_NET_DST:
2788 case COL_UNRES_NET_DST:
2789 switch (cf->cinfo.col_fmt[i + 1]) {
2791 case COL_DEF_NET_SRC:
2792 case COL_RES_NET_SRC:
2793 case COL_UNRES_NET_SRC:
2812 print_hex_data(stdout, print_args.format, edt);
2817 /* The ANSI C standard does not appear to *require* that a line-buffered
2818 stream be flushed to the host environment whenever a newline is
2819 written, it just says that, on such a stream, characters "are
2820 intended to be transmitted to or from the host environment as a
2821 block when a new-line character is encountered".
2823 The Visual C++ 6.0 C implementation doesn't do what is intended;
2824 even if you set a stream to be line-buffered, it still doesn't
2825 flush the buffer at the end of every line.
2827 So, if the "-l" flag was specified, we flush the standard output
2828 at the end of a packet. This will do the right thing if we're
2829 printing packet summary lines, and, as we print the entire protocol
2830 tree for a single packet without waiting for anything to happen,
2831 it should be as good as line-buffered mode if we're printing
2832 protocol trees. (The whole reason for the "-l" flag in either
2833 tcpdump or Tethereal is to allow the output of a live capture to
2834 be piped to a program or script and to have that script see the
2835 information for the packet as soon as it's printed, rather than
2836 having to wait until a standard I/O buffer fills up. */
2840 if (ferror(stdout)) {
2841 show_print_file_io_error(errno);
2844 epan_dissect_free(edt);
2846 clear_fdata(&fdata);
2850 show_print_file_io_error(int err)
2856 "tethereal: Not all the packets could be printed because there is "
2857 "no space left on the file system.\n");
2863 "tethereal: Not all the packets could be printed because you are "
2864 "too close to, or over your disk quota.\n");
2870 "tethereal: An error occurred while printing packets: %s.\n",
2877 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2881 static char errmsg_errno[1024+1];
2884 /* Wiretap error. */
2887 case WTAP_ERR_NOT_REGULAR_FILE:
2888 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2891 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2892 /* Seen only when opening a capture file for reading. */
2893 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
2896 case WTAP_ERR_UNSUPPORTED:
2897 /* Seen only when opening a capture file for reading. */
2898 snprintf(errmsg_errno, sizeof(errmsg_errno),
2899 "The file \"%%s\" is not a capture file in a format Tethereal understands.\n"
2902 errmsg = errmsg_errno;
2905 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2906 /* Seen only when opening a capture file for writing. */
2907 snprintf(errmsg_errno, sizeof(errmsg_errno),
2908 "The file \"%%s\" is a pipe, and %s capture files cannot be "
2909 "written to a pipe.", wtap_file_type_string(file_type));
2910 errmsg = errmsg_errno;
2913 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2914 /* Seen only when opening a capture file for writing. */
2915 errmsg = "Tethereal does not support writing capture files in that format.";
2918 case WTAP_ERR_UNSUPPORTED_ENCAP:
2920 errmsg = "Tethereal cannot save this capture in that format.";
2922 snprintf(errmsg_errno, sizeof(errmsg_errno),
2923 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2926 errmsg = errmsg_errno;
2930 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2932 errmsg = "Tethereal cannot save this capture in that format.";
2934 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2937 case WTAP_ERR_BAD_RECORD:
2938 /* Seen only when opening a capture file for reading. */
2939 snprintf(errmsg_errno, sizeof(errmsg_errno),
2940 "The file \"%%s\" appears to be damaged or corrupt.\n"
2943 errmsg = errmsg_errno;
2946 case WTAP_ERR_CANT_OPEN:
2948 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2950 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2953 case WTAP_ERR_SHORT_READ:
2954 errmsg = "The file \"%s\" appears to have been cut short"
2955 " in the middle of a packet or other data.";
2958 case WTAP_ERR_SHORT_WRITE:
2959 errmsg = "A full header couldn't be written to the file \"%s\".";
2963 snprintf(errmsg_errno, sizeof(errmsg_errno),
2964 "The file \"%%s\" could not be %s: %s.",
2965 for_writing ? "created" : "opened",
2966 wtap_strerror(err));
2967 errmsg = errmsg_errno;
2971 errmsg = file_open_error_message(err, for_writing);
2976 * Open/create errors are reported with an console message in Tethereal.
2979 open_failure_message(const char *filename, int err, gboolean for_writing)
2981 fprintf(stderr, "tethereal: ");
2982 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2983 fprintf(stderr, "\n");
2987 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
2992 char err_msg[2048+1];
2994 wth = wtap_open_offline(fname, &err, &err_info, FALSE);
2998 /* The open succeeded. Fill in the information for this file. */
3000 /* Initialize all data structures used for dissection. */
3004 cf->filed = -1; /* not used, but set it anyway */
3005 cf->f_len = 0; /* not used, but set it anyway */
3007 /* Set the file name because we need it to set the follow stream filter.
3008 XXX - is that still true? We need it for other reasons, though,
3010 cf->filename = g_strdup(fname);
3012 /* Indicate whether it's a permanent or temporary file. */
3013 cf->is_tempfile = is_tempfile;
3015 /* If it's a temporary capture buffer file, mark it as not saved. */
3016 cf->user_saved = !is_tempfile;
3018 cf->cd_t = wtap_file_type(cf->wth);
3020 cf->drops_known = FALSE;
3024 cf->snap = wtap_snapshot_length(cf->wth);
3025 if (cf->snap == 0) {
3026 /* Snapshot length not known. */
3027 cf->has_snap = FALSE;
3028 cf->snap = WTAP_MAX_PACKET_SIZE;
3030 cf->has_snap = TRUE;
3031 firstsec = 0, firstusec = 0;
3032 prevsec = 0, prevusec = 0;
3037 snprintf(err_msg, sizeof err_msg,
3038 cf_open_error_message(err, err_info, FALSE, 0), fname);
3039 fprintf(stderr, "tethereal: %s\n", err_msg);
3045 /* Take care of byte order in the libpcap headers read from pipes.
3046 * (function taken from wiretap/libpcap.c) */
3048 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
3050 if (ld->byte_swapped) {
3051 /* Byte-swap the record header fields. */
3052 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
3053 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
3054 rechdr->incl_len = BSWAP32(rechdr->incl_len);
3055 rechdr->orig_len = BSWAP32(rechdr->orig_len);
3058 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
3059 swapped, in order to match the BPF header layout.
3061 Unfortunately, some files were, according to a comment in the "libpcap"
3062 source, written with version 2.3 in their headers but without the
3063 interchanged fields, so if "incl_len" is greater than "orig_len" - which
3064 would make no sense - we assume that we need to swap them. */
3065 if (hdr->version_major == 2 &&
3066 (hdr->version_minor < 3 ||
3067 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
3070 temp = rechdr->orig_len;
3071 rechdr->orig_len = rechdr->incl_len;
3072 rechdr->incl_len = temp;
3076 /* Mimic pcap_open_live() for pipe captures
3077 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
3079 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
3080 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
3082 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
3083 char *errmsg, int errmsgl)
3085 struct stat pipe_stat;
3089 unsigned int bytes_read;
3092 * XXX Tethereal blocks until we return
3094 if (strcmp(pipename, "-") == 0)
3095 fd = 0; /* read from stdin */
3097 if (stat(pipename, &pipe_stat) < 0) {
3098 if (errno == ENOENT || errno == ENOTDIR)
3099 ld->pipe_err = PIPNEXIST;
3101 snprintf(errmsg, errmsgl,
3102 "The capture session could not be initiated "
3103 "due to error on pipe: %s", strerror(errno));
3104 ld->pipe_err = PIPERR;
3108 if (! S_ISFIFO(pipe_stat.st_mode)) {
3109 if (S_ISCHR(pipe_stat.st_mode)) {
3111 * Assume the user specified an interface on a system where
3112 * interfaces are in /dev. Pretend we haven't seen it.
3114 ld->pipe_err = PIPNEXIST;
3116 snprintf(errmsg, errmsgl,
3117 "The capture session could not be initiated because\n"
3118 "\"%s\" is neither an interface nor a pipe", pipename);
3119 ld->pipe_err = PIPERR;
3123 fd = open(pipename, O_RDONLY);
3125 snprintf(errmsg, errmsgl,
3126 "The capture session could not be initiated "
3127 "due to error on pipe open: %s", strerror(errno));
3128 ld->pipe_err = PIPERR;
3133 ld->from_pipe = TRUE;
3135 /* read the pcap header */
3137 while (bytes_read < sizeof magic) {
3138 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3141 snprintf(errmsg, errmsgl, "End of file on pipe during open");
3143 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3152 /* Host that wrote it has our byte order, and was running
3153 a program using either standard or ss990417 libpcap. */
3154 ld->byte_swapped = FALSE;
3155 ld->modified = FALSE;
3157 case PCAP_MODIFIED_MAGIC:
3158 /* Host that wrote it has our byte order, but was running
3159 a program using either ss990915 or ss991029 libpcap. */
3160 ld->byte_swapped = FALSE;
3161 ld->modified = TRUE;
3163 case PCAP_SWAPPED_MAGIC:
3164 /* Host that wrote it has a byte order opposite to ours,
3165 and was running a program using either standard or
3166 ss990417 libpcap. */
3167 ld->byte_swapped = TRUE;
3168 ld->modified = FALSE;
3170 case PCAP_SWAPPED_MODIFIED_MAGIC:
3171 /* Host that wrote it out has a byte order opposite to
3172 ours, and was running a program using either ss990915
3173 or ss991029 libpcap. */
3174 ld->byte_swapped = TRUE;
3175 ld->modified = TRUE;
3178 /* Not a "libpcap" type we know about. */
3179 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3183 /* Read the rest of the header */
3185 while (bytes_read < sizeof(struct pcap_hdr)) {
3186 b = read(fd, ((char *)hdr)+bytes_read,
3187 sizeof(struct pcap_hdr) - bytes_read);
3190 snprintf(errmsg, errmsgl, "End of file on pipe during open");
3192 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3199 if (ld->byte_swapped) {
3200 /* Byte-swap the header fields about which we care. */
3201 hdr->version_major = BSWAP16(hdr->version_major);
3202 hdr->version_minor = BSWAP16(hdr->version_minor);
3203 hdr->snaplen = BSWAP32(hdr->snaplen);
3204 hdr->network = BSWAP32(hdr->network);
3207 if (hdr->version_major < 2) {
3208 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3212 ld->pipe_state = STATE_EXPECT_REC_HDR;
3213 ld->pipe_err = PIPOK;
3217 ld->pipe_err = PIPERR;
3222 /* We read one record from the pipe, take care of byte order in the record
3223 * header, write the record in the capture file, and update capture statistics. */
3226 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
3227 struct pcaprec_modified_hdr *rechdr, guchar *data,
3228 char *errmsg, int errmsgl)
3230 struct pcap_pkthdr phdr;
3232 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3235 switch (ld->pipe_state) {
3237 case STATE_EXPECT_REC_HDR:
3238 ld->bytes_to_read = ld->modified ?
3239 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3241 ld->pipe_state = STATE_READ_REC_HDR;
3244 case STATE_READ_REC_HDR:
3245 b = read(fd, ((char *)rechdr)+ld->bytes_read,
3246 ld->bytes_to_read - ld->bytes_read);
3249 result = PD_PIPE_EOF;
3251 result = PD_PIPE_ERR;
3254 if ((ld->bytes_read += b) < ld->bytes_to_read)
3256 result = PD_REC_HDR_READ;
3259 case STATE_EXPECT_DATA:
3261 ld->pipe_state = STATE_READ_DATA;
3264 case STATE_READ_DATA:
3265 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
3268 result = PD_PIPE_EOF;
3270 result = PD_PIPE_ERR;
3273 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
3275 result = PD_DATA_READ;
3279 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3282 } /* switch (ld->pipe_state) */
3285 * We've now read as much data as we were expecting, so process it.
3289 case PD_REC_HDR_READ:
3290 /* We've read the header. Take care of byte order. */
3291 adjust_header(ld, hdr, &rechdr->hdr);
3292 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3293 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3294 ld->packet_count+1, rechdr->hdr.incl_len);
3297 ld->pipe_state = STATE_EXPECT_DATA;
3301 /* Fill in a "struct pcap_pkthdr", and process the packet. */
3302 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3303 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3304 phdr.caplen = rechdr->hdr.incl_len;
3305 phdr.len = rechdr->hdr.orig_len;
3307 capture_pcap_cb((guchar *)ld, &phdr, data);
3309 ld->pipe_state = STATE_EXPECT_REC_HDR;
3313 ld->pipe_err = PIPEOF;
3317 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3324 ld->pipe_err = PIPERR;
3325 /* Return here rather than inside the switch to prevent GCC warning */
3329 #endif /* HAVE_LIBPCAP */
3332 * General errors are reported with an console message in Tethereal.
3335 failure_message(const char *msg_format, va_list ap)
3337 fprintf(stderr, "tethereal: ");
3338 vfprintf(stderr, msg_format, ap);
3339 fprintf(stderr, "\n");
3343 * Read errors are reported with an console message in Tethereal.
3346 read_failure_message(const char *filename, int err)
3348 fprintf(stderr, "tethereal: An error occurred while reading from the file \"%s\": %s.\n",
3349 filename, strerror(err));