3 * $Id: tethereal.c,v 1.220 2004/01/18 02:12:59 jmayer 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>
101 #include <wiretap/wtap-capture.h>
102 #include <wiretap/libpcap.h>
106 #include "capture-wpcap.h"
110 * This is the template for the decode as option; it is shared between the
111 * various functions that output the usage for this parameter.
113 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
114 static guint32 firstsec, firstusec;
115 static guint32 prevsec, prevusec;
116 static GString *comp_info_str, *runtime_info_str;
117 static gboolean quiet;
118 static gboolean decode;
119 static gboolean verbose;
120 static gboolean print_hex;
121 static gboolean line_buffered;
122 static guint32 cul_bytes = 0;
123 static int print_format;
126 typedef struct _loop_data {
127 gboolean go; /* TRUE as long as we're supposed to keep capturing */
129 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
133 gboolean output_to_pipe;
136 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
137 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
138 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
140 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
141 STATE_EXPECT_DATA, STATE_READ_DATA
144 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
150 static int capture(int);
151 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
153 static void report_counts(void);
155 static BOOL WINAPI capture_cleanup(DWORD);
157 static void capture_cleanup(int);
159 static void report_counts_siginfo(int);
162 #endif /* HAVE_LIBPCAP */
169 static int load_cap_file(capture_file *, int);
170 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
171 union wtap_pseudo_header *, const guchar *);
172 static void show_capture_file_io_error(const char *, int, gboolean);
173 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
174 union wtap_pseudo_header *, const guchar *);
177 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
178 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
179 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
180 struct pcaprec_modified_hdr *, guchar *, char *, int);
185 ts_type timestamp_type = RELATIVE;
188 int snaplen; /* Maximum captured packet length */
189 int promisc_mode; /* Capture in promiscuous mode */
190 int autostop_count; /* Maximum packet count */
191 gboolean has_autostop_duration; /* TRUE if maximum capture duration
193 gint32 autostop_duration; /* Maximum capture duration */
194 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
196 gint32 autostop_filesize; /* Maximum capture file size */
197 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
198 guint32 ringbuffer_num_files; /* Number of ring buffer files */
199 gboolean has_ring_duration; /* TRUE if ring duration specified */
200 gint32 ringbuffer_duration; /* Switch file after n seconds */
201 int linktype; /* Data link type to use, or -1 for
205 static capture_options capture_opts = {
206 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
207 infinite, in effect */
208 TRUE, /* promiscuous mode is the default */
209 0, /* max packet count - default is 0,
211 FALSE, /* maximum capture duration not
212 specified by default */
213 0, /* maximum capture duration */
214 FALSE, /* maximum capture file size not
215 specified by default */
216 0, /* maximum capture file size */
217 FALSE, /* ring buffer off by default */
218 RINGBUFFER_MIN_NUM_FILES, /* default number of ring buffer
220 FALSE, /* Switch ring file after some */
221 0, /* specified time is off by default */
222 -1 /* Default to not change link type */
225 static gboolean list_link_layer_types;
228 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
229 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
231 #endif /* HAVE_LIBPCAP */
234 print_usage(gboolean print_ver)
241 fprintf(output, "This is GNU t" PACKAGE " " VERSION
243 " (cvs " CVSVERSION ")"
246 comp_info_str->str, runtime_info_str->str);
251 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
253 fprintf(output, "\t[ -b <number of ring buffer files>[:<duration>] ] [ -c <count> ]\n");
254 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
255 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <interface> ]\n");
256 fprintf(output, "\t[ -N <resolving> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
257 fprintf(output, "\t[ -R <read filter> ] [ -s <snaplen> ] [ -t <time stamp format> ]\n");
258 fprintf(output, "\t[ -T pdml|ps|text ] [ -w <savefile> ] [ -y <link type> ]\n");
259 fprintf(output, "\t[ -z <statistics string> ]\n");
261 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
262 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
263 fprintf(output, "\t[ -F <output file type> ] [ -N <resolving> ]\n");
264 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
265 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|text ] [ -w <savefile> ]\n");
266 fprintf(output, "\t[ -z <statistics string> ]\n");
268 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
269 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
270 if (wtap_dump_can_open(i))
271 fprintf(output, "\t%s - %s\n",
272 wtap_file_type_short_string(i), wtap_file_type_string(i));
274 fprintf(output, "\tdefault is libpcap\n");
279 get_natural_int(const char *string, const char *name)
284 number = strtol(string, &p, 10);
285 if (p == string || *p != '\0') {
286 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
291 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
295 if (number > INT_MAX) {
296 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
304 get_positive_int(const char *string, const char *name)
308 number = get_natural_int(string, name);
311 fprintf(stderr, "tethereal: The specified %s is zero\n",
320 * Given a string of the form "<autostop criterion>:<value>", as might appear
321 * as an argument to a "-a" option, parse it and set the criterion in
322 * question. Return an indication of whether it succeeded or failed
326 set_autostop_criterion(const char *autostoparg)
330 colonp = strchr(autostoparg, ':');
338 * Skip over any white space (there probably won't be any, but
339 * as we allow it in the preferences file, we might as well
346 * Put the colon back, so if our caller uses, in an
347 * error message, the string they passed us, the message
353 if (strcmp(autostoparg,"duration") == 0) {
354 capture_opts.has_autostop_duration = TRUE;
355 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
356 } else if (strcmp(autostoparg,"filesize") == 0) {
357 capture_opts.has_autostop_filesize = TRUE;
358 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
362 *colonp = ':'; /* put the colon back */
367 * Given a string of the form "<ring buffer file>:<duration>", as might appear
368 * as an argument to a "-b" option, parse it and set the arguments in
369 * question. Return an indication of whether it succeeded or failed
373 get_ring_arguments(const char *arg)
375 guchar *p = NULL, *colonp;
377 colonp = strchr(arg, ':');
379 if (colonp != NULL) {
384 capture_opts.ringbuffer_num_files =
385 get_natural_int(arg, "number of ring buffer files");
391 * Skip over any white space (there probably won't be any, but
392 * as we allow it in the preferences file, we might as well
399 * Put the colon back, so if our caller uses, in an
400 * error message, the string they passed us, the message
407 capture_opts.has_ring_duration = TRUE;
408 capture_opts.ringbuffer_duration = get_positive_int(p,
409 "ring buffer duration");
411 *colonp = ':'; /* put the colon back */
416 /* structure to keep track of what tap listeners have been registered.
418 typedef struct _ethereal_tap_list {
419 struct _ethereal_tap_list *next;
421 void (*func)(char *arg);
423 static ethereal_tap_list *tap_list=NULL;
426 register_ethereal_tap(char *cmd, void (*func)(char *arg))
428 ethereal_tap_list *newtl;
430 newtl=malloc(sizeof(ethereal_tap_list));
431 newtl->next=tap_list;
439 * For a dissector table, print on the stream described by output,
440 * its short name (which is what's used in the "-d" option) and its
444 display_dissector_table_names(char *table_name, char *ui_name, gpointer output)
446 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
450 * For a dissector handle, print on the stream described by output,
451 * the filter name (which is what's used in the "-d" option) and the full
452 * name for the protocol that corresponds to this handle.
455 display_dissector_names(gchar *table _U_, gpointer handle, gpointer output)
458 const gchar* proto_filter_name;
459 const gchar* proto_ui_name;
461 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
463 if (proto_id != -1) {
464 proto_filter_name = proto_get_protocol_filter_name(proto_id);
465 proto_ui_name = proto_get_protocol_name(proto_id);
466 g_assert(proto_filter_name != NULL);
467 g_assert(proto_ui_name != NULL);
469 fprintf((FILE *)output, "\t%s (%s)\n",
476 * The protocol_name_search structure is used by find_protocol_name_func()
477 * to pass parameters and store results
479 struct protocol_name_search{
480 gchar *searched_name; /* Protocol filter name we are looking for */
481 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
482 guint nb_match; /* How many dissectors matched searched_name */
484 typedef struct protocol_name_search *protocol_name_search_t;
487 * This function parses all dissectors associated with a table to find the
488 * one whose protocol has the specified filter name. It is called
489 * as a reference function in a call to dissector_table_foreach_handle.
490 * The name we are looking for, as well as the results, are stored in the
491 * protocol_name_search struct pointed to by user_data.
492 * If called using dissector_table_foreach_handle, we actually parse the
493 * whole list of dissectors.
496 find_protocol_name_func(gchar *table _U_, gpointer handle, gpointer user_data)
500 const gchar *protocol_filter_name;
501 protocol_name_search_t search_info;
505 search_info = (protocol_name_search_t)user_data;
507 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
508 if (proto_id != -1) {
509 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
510 g_assert(protocol_filter_name != NULL);
511 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
513 if (search_info->nb_match == 0) {
514 /* Record this handle only if this is the first match */
515 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
517 search_info->nb_match++;
523 * Print all layer type names supported.
524 * We send the output to the stream described by the handle output.
528 fprint_all_layer_types(FILE *output)
531 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
535 * Print all protocol names supported for a specific layer type.
536 * table_name contains the layer type name in which the search is performed.
537 * We send the output to the stream described by the handle output.
541 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
544 dissector_table_foreach_handle(table_name,
545 display_dissector_names,
550 * The function below parses the command-line parameters for the decode as
551 * feature (a string pointer by cl_param).
552 * It checks the format of the command-line, searches for a matching table
553 * and dissector. If a table/dissector match is not found, we display a
554 * summary of the available tables/dissectors (on stderr) and return FALSE.
555 * If everything is fine, we get the "Decode as" preference activated,
556 * then we return TRUE.
559 add_decode_as(const gchar *cl_param)
563 gchar *decoded_param;
564 gchar *remaining_param;
566 gchar *dissector_str;
567 dissector_handle_t dissector_matching;
568 dissector_table_t table_matching;
569 ftenum_t dissector_table_selector_type;
570 struct protocol_name_search user_protocol_name;
572 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
575 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
576 g_assert(decoded_param);
577 strcpy(decoded_param, cl_param);
580 /* The lines below will parse this string (modifying it) to extract all
581 necessary information. Note that decoded_param is still needed since
582 strings are not copied - we just save pointers. */
584 /* This section extracts a layer type (table_name) from decoded_param */
585 table_name = decoded_param; /* Layer type string starts from beginning */
587 remaining_param = strchr(table_name, '=');
588 if (remaining_param == NULL) {
589 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
590 /* If the argument does not follow the template, carry on anyway to check
591 if the table name is at least correct. If remaining_param is NULL,
592 we'll exit anyway further down */
595 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
598 /* Remove leading and trailing spaces from the table name */
599 while ( table_name[0] == ' ' )
601 while ( table_name[strlen(table_name) - 1] == ' ' )
602 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
604 /* The following part searches a table matching with the layer type specified */
605 table_matching = NULL;
607 /* Look for the requested table */
608 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
609 fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
612 table_matching = find_dissector_table(table_name);
613 if (!table_matching) {
614 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 */
618 if (!table_matching) {
619 /* Display a list of supported layer types to help the user, if the
620 specified layer type was not found */
621 fprintf(stderr, "tethereal: Valid layer types are:\n");
622 fprint_all_layer_types(stderr);
624 if (remaining_param == NULL || !table_matching) {
625 /* Exit if the layer type was not found, or if no '=' separator was found
627 g_free(decoded_param);
631 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
632 fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
635 remaining_param++; /* Move to the second '=' */
636 *remaining_param = '\0'; /* Remove the second '=' */
638 remaining_param++; /* Position after the layer type string */
640 /* This section extracts a selector value (selector_str) from decoded_param */
642 selector_str = remaining_param; /* Next part starts with the selector number */
644 remaining_param = strchr(selector_str, ',');
645 if (remaining_param == NULL) {
646 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
647 /* If the argument does not follow the template, carry on anyway to check
648 if the selector value is at least correct. If remaining_param is NULL,
649 we'll exit anyway further down */
652 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
655 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
657 switch (dissector_table_selector_type) {
663 /* The selector for this table is an unsigned number. Parse it as such.
664 There's no need to remove leading and trailing spaces from the
665 selector number string, because sscanf will do that for us. */
666 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
667 fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
668 g_free(decoded_param);
675 /* The selector for this table is a string. */
679 /* There are currently no dissector tables with any types other
680 than the ones listed above. */
681 g_assert_not_reached();
684 if (remaining_param == NULL) {
685 /* Exit if no ',' separator was found (see above) */
686 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
687 fprint_all_protocols_for_layer_types(stderr, table_name);
688 g_free(decoded_param);
692 remaining_param++; /* Position after the selector number string */
694 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
696 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
698 /* Remove leading and trailing spaces from the dissector name */
699 while ( dissector_str[0] == ' ' )
701 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
702 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
704 dissector_matching = NULL;
706 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
707 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 */
708 fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
711 user_protocol_name.nb_match = 0;
712 user_protocol_name.searched_name = dissector_str;
713 user_protocol_name.matched_handle = NULL;
715 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 */
717 if (user_protocol_name.nb_match != 0) {
718 dissector_matching = user_protocol_name.matched_handle;
719 if (user_protocol_name.nb_match > 1) {
720 fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
724 /* OK, check whether the problem is that there isn't any such
725 protocol, or that there is but it's not specified as a protocol
726 that's valid for that dissector table.
727 Note, we don't exit here, but dissector_matching will remain NULL,
729 if (proto_get_id_by_filter_name(dissector_str) == -1) {
730 /* No such protocol */
731 fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
733 fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
734 dissector_str, table_name);
739 if (!dissector_matching) {
740 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
741 fprint_all_protocols_for_layer_types(stderr, table_name);
742 g_free(decoded_param);
746 /* This is the end of the code that parses the command-line options.
747 All information is now stored in the variables:
751 The above variables that are strings are still pointing to areas within
752 decoded_parm. decoded_parm thus still needs to be kept allocated in
753 until we stop needing these variables
754 decoded_param will be deallocated at each exit point of this function */
757 /* We now have a pointer to the handle for the requested dissector
758 (requested protocol) inside the variable dissector_matching */
759 switch (dissector_table_selector_type) {
765 /* The selector for this table is an unsigned number. */
766 dissector_change(table_name, selector, dissector_matching);
771 /* The selector for this table is a string. */
772 dissector_change_string(table_name, selector_str, dissector_matching);
776 /* There are currently no dissector tables with any types other
777 than the ones listed above. */
778 g_assert_not_reached();
780 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
785 main(int argc, char *argv[])
789 gboolean arg_error = FALSE;
795 char *gpf_path, *pf_path;
796 char *gdp_path, *dp_path;
797 int gpf_open_errno, gpf_read_errno;
798 int pf_open_errno, pf_read_errno;
799 int gdp_open_errno, gdp_read_errno;
800 int dp_open_errno, dp_read_errno;
803 gboolean capture_filter_specified = FALSE;
804 GList *if_list, *if_entry;
808 gchar err_str[PCAP_ERRBUF_SIZE];
810 gboolean capture_option_specified = FALSE;
812 int out_file_type = WTAP_FILE_PCAP;
813 gchar *cf_name = NULL, *rfilter = NULL;
816 GList *lt_list, *lt_entry;
817 data_link_info_t *data_link_info;
819 #ifdef HAVE_PCAP_OPEN_DEAD
820 struct bpf_program fcode;
822 dfilter_t *rfcode = NULL;
825 ethereal_tap_list *tli;
827 /* Register all dissectors; we must do this before checking for the
828 "-G" flag, as the "-G" flag dumps information registered by the
829 dissectors, and we must do it before we read the preferences, in
830 case any dissectors register preferences. */
831 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
833 /* Register all tap listeners; we do this before we parse the arguments,
834 as the "-z" argument can specify a registered tap. */
835 register_all_tap_listeners();
837 /* Now register the preferences for any non-dissector modules.
838 We must do that before we read the preferences as well. */
839 prefs_register_modules();
841 /* If invoked with the "-G" flag, we dump out information based on
842 the argument to the "-G" flag; if no argument is specified,
843 for backwards compatibility we dump out a glossary of display
846 We do this here to mirror what happens in the GTK+ version, although
847 it's not necessary here. */
848 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
850 proto_registrar_dump_fields();
852 if (strcmp(argv[2], "fields") == 0)
853 proto_registrar_dump_fields();
854 else if (strcmp(argv[2], "protocols") == 0)
855 proto_registrar_dump_protocols();
857 fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
865 /* Set the C-language locale to the native environment. */
866 setlocale(LC_ALL, "");
868 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
869 &pf_open_errno, &pf_read_errno, &pf_path);
870 if (gpf_path != NULL) {
871 if (gpf_open_errno != 0) {
872 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
873 pf_path, strerror(gpf_open_errno));
875 if (gpf_read_errno != 0) {
876 fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
877 pf_path, strerror(gpf_read_errno));
880 if (pf_path != NULL) {
881 if (pf_open_errno != 0) {
882 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
883 strerror(pf_open_errno));
885 if (pf_read_errno != 0) {
886 fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
887 pf_path, strerror(pf_read_errno));
893 /* Set the name resolution code's flags from the preferences. */
894 g_resolv_flags = prefs->name_resolve;
896 /* Read the disabled protocols file. */
897 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
898 &dp_path, &dp_open_errno, &dp_read_errno);
899 if (gdp_path != NULL) {
900 if (gdp_open_errno != 0) {
902 "Could not open global disabled protocols file\n\"%s\": %s.\n",
903 gdp_path, strerror(gdp_open_errno));
905 if (gdp_read_errno != 0) {
907 "I/O error reading global disabled protocols file\n\"%s\": %s.\n",
908 gdp_path, strerror(gdp_read_errno));
912 if (dp_path != NULL) {
913 if (dp_open_errno != 0) {
915 "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
916 strerror(dp_open_errno));
918 if (dp_read_errno != 0) {
920 "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
921 strerror(dp_read_errno));
927 /* Load Wpcap, if possible */
931 init_cap_file(&cfile);
933 /* Assemble the compile-time version information string */
934 comp_info_str = g_string_new("Compiled ");
935 get_compiled_version_info(comp_info_str);
937 /* Assemble the run-time version information string */
938 runtime_info_str = g_string_new("Running ");
939 get_runtime_version_info(runtime_info_str);
941 /* Print format defaults to this. */
942 print_format = PR_FMT_TEXT;
944 /* Now get our args */
945 while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vw:Vxy:z:")) != -1) {
947 case 'a': /* autostop criteria */
949 if (set_autostop_criterion(optarg) == FALSE) {
950 fprintf(stderr, "tethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
954 capture_option_specified = TRUE;
958 case 'b': /* Ringbuffer option */
960 capture_opts.ringbuffer_on = TRUE;
961 if (get_ring_arguments(optarg) == FALSE) {
962 fprintf(stderr, "tethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
966 capture_option_specified = TRUE;
970 case 'c': /* Capture xxx packets */
972 capture_opts.autostop_count =
973 get_positive_int(optarg, "packet count");
975 capture_option_specified = TRUE;
979 case 'd': /* Decode as rule */
980 if (!add_decode_as(optarg))
983 case 'D': /* Print a list of capture devices */
985 if_list = get_interface_list(&err, err_str);
986 if (if_list == NULL) {
989 case CANT_GET_INTERFACE_LIST:
990 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
994 case NO_INTERFACES_FOUND:
995 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1000 i = 1; /* Interface id number */
1001 for (if_entry = g_list_first(if_list); if_entry != NULL;
1002 if_entry = g_list_next(if_entry)) {
1003 if_info = if_entry->data;
1004 printf("%d. %s", i++, if_info->name);
1005 if (if_info->description != NULL)
1006 printf(" (%s)", if_info->description);
1009 free_interface_list(if_list);
1012 capture_option_specified = TRUE;
1018 capture_filter_specified = TRUE;
1020 g_free(cfile.cfilter);
1021 cfile.cfilter = g_strdup(optarg);
1023 capture_option_specified = TRUE;
1028 out_file_type = wtap_short_string_to_file_type(optarg);
1029 if (out_file_type < 0) {
1030 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
1035 case 'h': /* Print help and exit */
1039 case 'i': /* Use interface xxx */
1042 * If the argument is a number, treat it as an index into the list
1043 * of adapters, as printed by "tethereal -D".
1045 * This should be OK on UNIX systems, as interfaces shouldn't have
1046 * names that begin with digits. It can be useful on Windows, where
1047 * more than one interface can have the same name.
1049 adapter_index = strtol(optarg, &p, 10);
1050 if (p != NULL && *p == '\0') {
1051 if (adapter_index < 0) {
1053 "tethereal: The specified adapter index is a negative number\n");
1056 if (adapter_index > INT_MAX) {
1058 "tethereal: The specified adapter index is too large (greater than %d)\n",
1062 if (adapter_index == 0) {
1063 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1066 if_list = get_interface_list(&err, err_str);
1067 if (if_list == NULL) {
1070 case CANT_GET_INTERFACE_LIST:
1071 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1075 case NO_INTERFACES_FOUND:
1076 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1081 if_info = g_list_nth_data(if_list, adapter_index - 1);
1082 if (if_info == NULL) {
1083 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1086 cfile.iface = g_strdup(if_info->name);
1087 free_interface_list(if_list);
1089 cfile.iface = g_strdup(optarg);
1091 capture_option_specified = TRUE;
1095 case 'l': /* "Line-buffer" standard output */
1096 /* This isn't line-buffering, strictly speaking, it's just
1097 flushing the standard output after the information for
1098 each packet is printed; however, that should be good
1099 enough for all the purposes to which "-l" is put (and
1100 is probably actually better for "-V", as it does fewer
1103 See the comment in "wtap_dispatch_cb_print()" for an
1104 explanation of why we do that, and why we don't just
1105 use "setvbuf()" to make the standard output line-buffered
1106 (short version: in Windows, "line-buffered" is the same
1107 as "fully-buffered", and the output buffer is only flushed
1108 when it fills up). */
1109 line_buffered = TRUE;
1111 case 'L': /* Print list of link-layer types and exit */
1113 list_link_layer_types = TRUE;
1116 capture_option_specified = TRUE;
1120 case 'n': /* No name resolution */
1121 g_resolv_flags = RESOLV_NONE;
1123 case 'N': /* Select what types of addresses/port #s to resolve */
1124 if (g_resolv_flags == RESOLV_ALL)
1125 g_resolv_flags = RESOLV_NONE;
1126 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1127 if (badopt != '\0') {
1128 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
1133 case 'o': /* Override preference from command line */
1134 switch (prefs_set_pref(optarg)) {
1136 case PREFS_SET_SYNTAX_ERR:
1137 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
1141 case PREFS_SET_NO_SUCH_PREF:
1142 case PREFS_SET_OBSOLETE:
1143 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
1149 case 'p': /* Don't capture in promiscuous mode */
1151 capture_opts.promisc_mode = FALSE;
1153 capture_option_specified = TRUE;
1157 case 'q': /* Quiet */
1160 case 'r': /* Read capture file xxx */
1161 cf_name = g_strdup(optarg);
1163 case 'R': /* Read file filter */
1166 case 's': /* Set the snapshot (capture) length */
1168 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
1170 capture_option_specified = TRUE;
1174 case 'S': /* show packets in real time */
1177 case 't': /* Time stamp type */
1178 if (strcmp(optarg, "r") == 0)
1179 timestamp_type = RELATIVE;
1180 else if (strcmp(optarg, "a") == 0)
1181 timestamp_type = ABSOLUTE;
1182 else if (strcmp(optarg, "ad") == 0)
1183 timestamp_type = ABSOLUTE_WITH_DATE;
1184 else if (strcmp(optarg, "d") == 0)
1185 timestamp_type = DELTA;
1187 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
1189 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
1190 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
1194 case 'T': /* printing Type */
1195 if (strcmp(optarg, "text") == 0)
1196 print_format = PR_FMT_TEXT;
1197 else if (strcmp(optarg, "pdml") == 0)
1198 print_format = PR_FMT_PDML;
1199 else if (strcmp(optarg, "ps") == 0)
1200 print_format = PR_FMT_PS;
1202 fprintf(stderr, "tethereal: Invalid -T parameter.\n");
1203 fprintf(stderr, "It must be \"ps\", \"text\" or \"pdml\".\n");
1207 case 'v': /* Show version and exit */
1208 printf("t" PACKAGE " " VERSION
1210 " (cvs " CVSVERSION ")"
1213 comp_info_str->str, runtime_info_str->str);
1216 case 'w': /* Write to capture file xxx */
1217 cfile.save_file = g_strdup(optarg);
1219 case 'V': /* Verbose */
1222 case 'x': /* Print packet data in hex (and ASCII) */
1225 case 'y': /* Set the pcap data link type */
1227 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
1228 capture_opts.linktype = pcap_datalink_name_to_val(optarg);
1229 if (capture_opts.linktype == -1) {
1230 fprintf(stderr, "tethereal: The specified data link type \"%s\" is not valid\n",
1234 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1235 /* XXX - just treat it as a number */
1236 capture_opts.linktype = get_natural_int(optarg, "data link type");
1237 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1239 capture_option_specified = TRUE;
1244 for(tli=tap_list;tli;tli=tli->next){
1245 if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
1246 (*tli->func)(optarg);
1251 fprintf(stderr,"tethereal: invalid -z argument.\n");
1252 fprintf(stderr," -z argument must be one of :\n");
1253 for(tli=tap_list;tli;tli=tli->next){
1254 fprintf(stderr," %s\n",tli->cmd);
1260 case '?': /* Bad flag - print usage message */
1266 /* If printing PDML or PS, force -V */
1267 if (print_format == PR_FMT_PDML || print_format == PR_FMT_PS)
1270 /* If no capture filter or read filter has been specified, and there are
1271 still command-line arguments, treat them as the tokens of a capture
1272 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1273 flag was specified. */
1274 if (optind < argc) {
1275 if (cf_name != NULL) {
1276 if (rfilter != NULL) {
1278 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1281 rfilter = get_args_as_string(argc, argv, optind);
1284 if (capture_filter_specified) {
1286 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1289 cfile.cfilter = get_args_as_string(argc, argv, optind);
1291 capture_option_specified = TRUE;
1296 /* See if we're writing a capture file and the file is a pipe */
1298 ld.output_to_pipe = FALSE;
1300 if (cfile.save_file != NULL) {
1301 if (strcmp(cfile.save_file, "-") == 0) {
1303 g_free(cfile.save_file);
1304 cfile.save_file = g_strdup("");
1306 ld.output_to_pipe = TRUE;
1311 err = test_for_fifo(cfile.save_file);
1314 case ENOENT: /* it doesn't exist, so we'll be creating it,
1315 and it won't be a FIFO */
1316 case 0: /* found it, but it's not a FIFO */
1319 case ESPIPE: /* it is a FIFO */
1320 ld.output_to_pipe = TRUE;
1323 default: /* couldn't stat it */
1325 "tethereal: Error testing whether capture file is a pipe: %s\n",
1333 #ifndef HAVE_LIBPCAP
1334 if (capture_option_specified)
1335 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1343 if (list_link_layer_types) {
1344 /* We're supposed to list the link-layer types for an interface;
1345 did the user also specify a capture file to be read? */
1347 /* Yes - that's bogus. */
1348 fprintf(stderr, "tethereal: You cannot specify -L and a capture file to be read.\n");
1351 /* No - did they specify a ring buffer option? */
1352 if (capture_opts.ringbuffer_on) {
1353 fprintf(stderr, "tethereal: Ring buffer requested, but a capture is not being done.\n");
1357 /* If they didn't specify a "-w" flag, but specified a maximum capture
1358 file size, tell them that this doesn't work, and exit. */
1359 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
1360 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1361 "capture isn't being saved to a file.\n");
1365 if (capture_opts.ringbuffer_on) {
1366 /* Ring buffer works only under certain conditions:
1367 a) ring buffer does not work if you're not saving the capture to
1369 b) ring buffer only works if you're saving in libpcap format;
1370 c) it makes no sense to enable the ring buffer if the maximum
1371 file size is set to "infinite";
1372 d) file must not be a pipe. */
1373 if (cfile.save_file == NULL) {
1374 fprintf(stderr, "tethereal: Ring buffer requested, but "
1375 "capture isn't being saved to a file.\n");
1378 if (out_file_type != WTAP_FILE_PCAP) {
1379 fprintf(stderr, "tethereal: Ring buffer requested, but "
1380 "capture isn't being saved in libpcap format.\n");
1383 if (!capture_opts.has_autostop_filesize) {
1384 fprintf(stderr, "tethereal: Ring buffer requested, but "
1385 "no maximum capture file size was specified.\n");
1388 if (ld.output_to_pipe) {
1389 fprintf(stderr, "tethereal: Ring buffer requested, but "
1390 "capture file is a pipe.\n");
1398 /* Start windows sockets */
1399 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1402 /* Notify all registered modules that have had any of their preferences
1403 changed either from one of the preferences file or from the command
1404 line that their preferences have changed. */
1407 /* disabled protocols as per configuration file */
1408 if (gdp_path == NULL && dp_path == NULL) {
1409 set_disabled_protos_list();
1412 /* Build the column format array */
1413 col_setup(&cfile.cinfo, prefs->num_cols);
1414 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1415 cfile.cinfo.col_fmt[i] = get_column_format(i);
1416 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1417 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1419 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1420 cfile.cinfo.col_data[i] = NULL;
1421 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1422 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1424 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1425 cfile.cinfo.col_fence[i] = 0;
1426 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1427 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1430 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1433 for (j = 0; j < NUM_COL_FMTS; j++) {
1434 if (!cfile.cinfo.fmt_matx[i][j])
1437 if (cfile.cinfo.col_first[j] == -1)
1438 cfile.cinfo.col_first[j] = i;
1439 cfile.cinfo.col_last[j] = i;
1444 if (capture_opts.snaplen < 1)
1445 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1446 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1447 capture_opts.snaplen = MIN_PACKET_SIZE;
1449 /* Check the value range of the ringbuffer_num_files parameter */
1450 if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
1451 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
1452 #if RINGBUFFER_MIN_NUM_FILES > 0
1453 else if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
1454 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
1458 if (rfilter != NULL) {
1459 if (!dfilter_compile(rfilter, &rfcode)) {
1460 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1462 #ifdef HAVE_PCAP_OPEN_DEAD
1466 p = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1468 if (pcap_compile(p, &fcode, rfilter, 0, 0) != -1) {
1470 " Note: That display filter code looks like a valid capture filter;\n"
1471 " maybe you mixed them up?\n");
1480 cfile.rfcode = rfcode;
1483 * We're reading a capture file.
1488 * Immediately relinquish any set-UID or set-GID privileges we have;
1489 * we must not be allowed to read any capture files the user running
1490 * Tethereal can't open.
1496 err = cf_open(cf_name, FALSE, &cfile);
1501 err = load_cap_file(&cfile, out_file_type);
1508 /* No capture file specified, so we're supposed to do a live capture
1509 (or get a list of link-layer types for a live capture device);
1510 do we have support for live captures? */
1515 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1520 /* Yes; did the user specify an interface to use? */
1521 if (cfile.iface == NULL) {
1522 /* No - is a default specified in the preferences file? */
1523 if (prefs->capture_device != NULL) {
1525 if_text = strrchr(prefs->capture_device, ' ');
1526 if (if_text == NULL) {
1527 cfile.iface = g_strdup(prefs->capture_device);
1529 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1532 /* No - pick the first one from the list of interfaces. */
1533 if_list = get_interface_list(&err, err_str);
1534 if (if_list == NULL) {
1537 case CANT_GET_INTERFACE_LIST:
1538 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1542 case NO_INTERFACES_FOUND:
1543 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1548 if_info = if_list->data; /* first interface */
1549 cfile.iface = g_strdup(if_info->name);
1550 free_interface_list(if_list);
1554 if (list_link_layer_types) {
1555 /* We were asked to list the link-layer types for an interface.
1556 Get the list of link-layer types for the capture device. */
1557 lt_list = get_pcap_linktype_list(cfile.iface, err_str);
1558 if (lt_list == NULL) {
1559 if (err_str[0] != '\0') {
1560 fprintf(stderr, "tethereal: The list of data link types for the capture device could not be obtained (%s).\n"
1561 "Please check to make sure you have sufficient permissions, and that\n"
1562 "you have the proper interface or pipe specified.\n", err_str);
1564 fprintf(stderr, "tethereal: The capture device has no data link types.\n");
1567 fprintf(stderr, "Data link types (use option -y to set):\n");
1568 for (lt_entry = lt_list; lt_entry != NULL;
1569 lt_entry = g_list_next(lt_entry)) {
1570 data_link_info = lt_entry->data;
1571 fprintf(stderr, " %s", data_link_info->name);
1572 if (data_link_info->description != NULL)
1573 fprintf(stderr, " (%s)", data_link_info->description);
1575 fprintf(stderr, " (not supported)");
1578 free_pcap_linktype_list(lt_list);
1582 capture(out_file_type);
1584 if (capture_opts.ringbuffer_on) {
1588 /* No - complain. */
1589 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1594 draw_tap_listeners(TRUE);
1601 /* Do the low-level work of a capture.
1602 Returns TRUE if it succeeds, FALSE otherwise. */
1604 static condition *volatile cnd_ring_timeout = NULL; /* this must be visible in wtap_dispatch_cb_write */
1607 capture(int out_file_type)
1611 gchar open_err_str[PCAP_ERRBUF_SIZE];
1612 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1613 bpf_u_int32 netnum, netmask;
1614 struct bpf_program fcode;
1615 const char *set_linktype_err_str;
1617 int volatile volatile_err = 0;
1618 int volatile inpkts = 0;
1620 char errmsg[1024+1];
1621 condition *volatile cnd_stop_capturesize = NULL;
1622 condition *volatile cnd_stop_timeout = NULL;
1624 void (*oldhandler)(int);
1625 static const char ppamsg[] = "can't find PPA for ";
1627 volatile int pipe_fd = -1;
1628 struct pcap_hdr hdr;
1629 struct pcaprec_modified_hdr rechdr;
1630 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1632 struct pcap_stat stats;
1635 dfilter_t *rfcode = NULL;
1637 /* Initialize all data structures used for dissection. */
1640 ld.linktype = WTAP_ENCAP_UNKNOWN;
1643 /* Open the network interface to capture from it.
1644 Some versions of libpcap may put warnings into the error buffer
1645 if they succeed; to tell if that's happened, we have to clear
1646 the error buffer, and check if it's still a null string. */
1647 open_err_str[0] = '\0';
1648 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1649 capture_opts.promisc_mode, 1000, open_err_str);
1651 if (ld.pch != NULL) {
1652 /* setting the data link type only works on real interfaces */
1653 if (capture_opts.linktype != -1) {
1654 set_linktype_err_str = set_pcap_linktype(ld.pch, cfile.iface,
1655 capture_opts.linktype);
1656 if (set_linktype_err_str != NULL) {
1657 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1658 set_linktype_err_str);
1663 /* We couldn't open "cfile.iface" as a network device. */
1665 /* On Windows, we don't support capturing on pipes, so we give up. */
1667 /* On Win32 OSes, the capture devices are probably available to all
1668 users; don't warn about permissions problems.
1670 Do, however, warn that WAN devices aren't supported. */
1671 snprintf(errmsg, sizeof errmsg,
1672 "The capture session could not be initiated (%s).\n"
1673 "Please check that you have the proper interface specified.\n"
1675 "Note that the driver Tethereal uses for packet capture on Windows doesn't\n"
1676 "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
1680 /* try to open cfile.iface as a pipe */
1681 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1683 if (pipe_fd == -1) {
1685 if (ld.pipe_err == PIPNEXIST) {
1686 /* Pipe doesn't exist, so output message for interface */
1688 /* If we got a "can't find PPA for XXX" message, warn the user (who
1689 is running Tethereal on HP-UX) that they don't have a version
1690 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1691 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1692 PPA for XXX" rather than "can't find PPA for XXX"). */
1693 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1696 "You are running Tethereal with a version of the libpcap library\n"
1697 "that doesn't handle HP-UX network devices well; this means that\n"
1698 "Tethereal may not be able to capture packets.\n"
1700 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1701 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1702 "packaged binary form from the Software Porting And Archive Centre\n"
1703 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1704 "at the URL lists a number of mirror sites.";
1707 snprintf(errmsg, sizeof errmsg,
1708 "The capture session could not be initiated (%s).\n"
1709 "Please check to make sure you have sufficient permissions, and that\n"
1710 "you have the proper interface or pipe specified.%s", open_err_str,
1714 * Else pipe (or file) does exist and pipe_open_live() has
1719 /* pipe_open_live() succeeded; don't want
1720 error message from pcap_open_live() */
1721 open_err_str[0] = '\0';
1727 * We've opened the capture device, so, if we're set-UID or set-GID,
1728 * relinquish those privileges.
1730 * XXX - if we have saved set-user-ID support, we should give up those
1731 * privileges immediately, and then reclaim them long enough to get
1732 * a list of network interfaces and to open one, and then give them
1733 * up again, so that stuff we do while processing the argument list,
1734 * reading the user's preferences, etc. is done as the real user and
1735 * group, not the effective user and group.
1741 if (cfile.cfilter && !ld.from_pipe) {
1742 /* A capture filter was specified; set it up. */
1743 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1745 * Well, we can't get the netmask for this interface; it's used
1746 * only for filters that check for broadcast IP addresses, so
1747 * we just warn the user, and punt and use 0.
1750 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1753 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1754 if (dfilter_compile(cfile.cfilter, &rfcode)) {
1755 snprintf(errmsg, sizeof errmsg,
1756 "Unable to parse capture filter string (%s).\n"
1757 " Interestingly enough, this looks like a valid display filter\n"
1758 " Are you sure you didn't mix them up?",
1759 pcap_geterr(ld.pch));
1761 snprintf(errmsg, sizeof errmsg,
1762 "Unable to parse capture filter string (%s).",
1763 pcap_geterr(ld.pch));
1767 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1768 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1769 pcap_geterr(ld.pch));
1774 /* Set up to write to the capture file. */
1777 pcap_encap = hdr.network;
1778 file_snaplen = hdr.snaplen;
1782 pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1783 file_snaplen = pcap_snapshot(ld.pch);
1785 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1786 if (cfile.save_file != NULL) {
1787 /* Set up to write to the capture file. */
1788 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1789 strcpy(errmsg, "The network you're capturing from is of a type"
1790 " that Tethereal doesn't support.");
1793 if (capture_opts.ringbuffer_on) {
1794 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1795 capture_opts.ringbuffer_num_files);
1796 if (cfile.save_file_fd != -1) {
1797 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1798 pcap_snapshot(ld.pch), &err);
1800 err = errno; /* "ringbuf_init()" failed */
1804 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1805 ld.linktype, pcap_snapshot(ld.pch), &err);
1808 if (ld.pdh == NULL) {
1809 snprintf(errmsg, sizeof errmsg,
1810 file_open_error_message(err, TRUE, out_file_type),
1811 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1816 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1817 returned a warning; print it, but keep capturing. */
1818 if (open_err_str[0] != '\0')
1819 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1822 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1823 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1825 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1827 XXX - deal with signal semantics on various UNIX platforms. Or just
1828 use "sigaction()" and be done with it? */
1829 signal(SIGTERM, capture_cleanup);
1830 signal(SIGINT, capture_cleanup);
1831 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1832 signal(SIGHUP, oldhandler);
1835 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1836 quiet mode, report the number of packets we've captured. */
1837 signal(SIGINFO, report_counts_siginfo);
1838 #endif /* SIGINFO */
1841 /* Let the user know what interface was chosen. */
1842 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1844 /* initialize capture stop conditions */
1845 init_capture_stop_conditions();
1846 /* create stop conditions */
1847 if (capture_opts.has_autostop_filesize)
1848 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1849 (long)capture_opts.autostop_filesize * 1000);
1850 if (capture_opts.has_autostop_duration)
1851 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1852 (gint32)capture_opts.autostop_duration);
1854 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1855 cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT,
1856 capture_opts.ringbuffer_duration);
1858 if (!setjmp(ld.stopenv)) {
1860 ld.packet_count = 0;
1864 /* We need to be careful with automatic variables defined in the
1865 outer scope which are changed inside the loop. Most compilers
1866 don't try to roll them back to their original values after the
1867 longjmp which causes the loop to finish, but all that the
1868 standards say is that their values are indeterminate. If we
1869 don't want them to be rolled back, we should define them with the
1870 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1871 Programming in the UNIX Environment, p. 178).
1873 The "err" variable causes a particular problem. If we give it
1874 the volatile attribute, then when we pass a reference to it (as
1875 in "&err") to a function, GCC warns: "passing arg <n> of
1876 <function> discards qualifiers from pointer target type".
1877 Therefore within the loop and just beyond we don't use "err".
1878 Within the loop we define "loop_err", and assign its value to
1879 "volatile_err", which is in the outer scope and is checked when
1882 We also define "packet_count_prev" here to keep things tidy,
1883 since it's used only inside the loop. If it were defined in the
1884 outer scope, GCC would give a warning (unnecessary in this case)
1885 that it might be clobbered, and we'd need to give it the volatile
1886 attribute to suppress the warning. */
1889 int packet_count_prev = 0;
1891 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1892 /* We're not stopping at a particular capture file size, and we're
1893 not stopping after some particular amount of time has expired,
1894 so either we have no stop condition or the only stop condition
1895 is a maximum packet count.
1897 If there's no maximum packet count, pass it -1, meaning "until
1898 you run out of packets in the bufferful you read". Otherwise,
1899 pass it the number of packets we have left to capture.
1901 We don't call "pcap_loop()" as, if we're saving to a file that's
1902 a FIFO, we want to flush the FIFO after we're done processing
1903 this libpcap bufferful of packets, so that the program
1904 reading the FIFO sees the packets immediately and doesn't get
1905 any partial packet, forcing it to block in the middle of reading
1907 if (capture_opts.autostop_count == 0)
1910 if (ld.packet_count >= capture_opts.autostop_count) {
1911 /* XXX do we need this test here? */
1912 /* It appears there's nothing more to capture. */
1915 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1918 /* We need to check the capture file size or the timeout after
1924 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1925 errmsg, sizeof errmsg);
1928 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1930 /* Error from "pcap_dispatch()", or error or "no more packets" from
1931 "pipe_dispatch(). */
1933 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1934 /* The specified capture time has elapsed; stop the capture. */
1936 } else if (inpkts > 0) {
1937 if (capture_opts.autostop_count != 0 &&
1938 ld.packet_count >= capture_opts.autostop_count) {
1939 /* The specified number of packets have been captured and have
1940 passed both any capture filter in effect and any read filter
1943 } else if (cnd_stop_capturesize != NULL &&
1944 cnd_eval(cnd_stop_capturesize,
1945 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1946 /* We're saving the capture to a file, and the capture file reached
1947 its maximum size. */
1948 if (capture_opts.ringbuffer_on) {
1949 /* Switch to the next ringbuffer file */
1950 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1951 /* File switch succeeded: reset the condition */
1952 cnd_reset(cnd_stop_capturesize);
1953 if (cnd_ring_timeout) {
1954 cnd_reset(cnd_ring_timeout);
1957 /* File switch failed: stop here */
1958 volatile_err = loop_err;
1962 /* No ringbuffer - just stop. */
1966 if (ld.output_to_pipe) {
1967 if (ld.packet_count > packet_count_prev) {
1968 if (fflush(wtap_dump_file(ld.pdh))) {
1969 volatile_err = errno;
1972 packet_count_prev = ld.packet_count;
1976 } /* while (ld.go) */
1978 /* delete stop conditions */
1979 if (cnd_stop_capturesize != NULL)
1980 cnd_delete(cnd_stop_capturesize);
1981 if (cnd_stop_timeout != NULL)
1982 cnd_delete(cnd_stop_timeout);
1983 if (cnd_ring_timeout != NULL)
1984 cnd_delete(cnd_ring_timeout);
1986 if ((cfile.save_file != NULL) && !quiet) {
1987 /* We're saving to a file, which means we're printing packet counts
1988 to stderr if we are not running silent and deep.
1989 Send a newline so that we move to the line after the packet count. */
1990 fprintf(stderr, "\n");
1993 /* If we got an error while capturing, report it. */
1997 if (ld.pipe_err == PIPERR) {
1998 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2004 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2005 pcap_geterr(ld.pch));
2009 if (volatile_err == 0)
2012 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
2016 if (cfile.save_file != NULL) {
2017 /* We're saving to a file or files; close all files. */
2018 if (capture_opts.ringbuffer_on) {
2019 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
2021 dump_ok = wtap_dump_close(ld.pdh, &err);
2023 /* If we've displayed a message about a write error, there's no point
2024 in displaying another message about an error on close. */
2025 if (!dump_ok && !write_err)
2026 show_capture_file_io_error(cfile.save_file, err, TRUE);
2030 if (ld.from_pipe && pipe_fd >= 0)
2035 /* Get the capture statistics, and, if any packets were dropped, report
2037 if (pcap_stats(ld.pch, &stats) >= 0) {
2038 if (stats.ps_drop != 0) {
2039 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
2042 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
2043 pcap_geterr(ld.pch));
2048 /* Report the number of captured packets if not reported during capture
2049 and we are saving to a file. */
2055 if (capture_opts.ringbuffer_on) {
2056 ringbuf_error_cleanup();
2058 g_free(cfile.save_file);
2059 cfile.save_file = NULL;
2060 fprintf(stderr, "tethereal: %s\n", errmsg);
2076 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2079 struct wtap_pkthdr whdr;
2080 union wtap_pseudo_header pseudo_header;
2081 loop_data *ld = (loop_data *) user;
2085 /* Convert from libpcap to Wiretap format.
2086 If that fails, ignore the packet (wtap_process_pcap_packet has
2087 written an error message). */
2088 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2097 wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
2098 /* Report packet capture count if not quiet */
2101 if (ld->packet_count != 0) {
2102 fprintf(stderr, "\r%u ", ld->packet_count);
2103 /* stderr could be line buffered */
2107 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
2108 &pseudo_header, pd);
2112 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
2118 capture_cleanup(DWORD ctrltype _U_)
2120 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2121 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2122 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2123 like SIGTERM at least when the machine's shutting down.
2125 For now, we handle them all as indications that we should clean up
2126 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2129 However, as handlers run in a new thread, we can't just longjmp
2130 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2131 no other handler - such as one that would terminate the process -
2134 XXX - for some reason, typing ^C to Tethereal, if you run this in
2135 a Cygwin console window in at least some versions of Cygwin,
2136 causes Tethereal to terminate immediately; this routine gets
2137 called, but the main loop doesn't get a chance to run and
2138 exit cleanly, at least if this is compiled with Microsoft Visual
2139 C++ (i.e., it's a property of the Cygwin console window or Bash;
2140 it happens if Tethereal is not built with Cygwin - for all I know,
2141 building it with Cygwin may make the problem go away). */
2147 capture_cleanup(int signum _U_)
2149 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2150 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2151 "ld.go" to FALSE and return, we won't break out of it and quit
2153 longjmp(ld.stopenv, 1);
2161 /* XXX - if we use sigaction, this doesn't have to be done.
2162 (Yes, this isn't necessary on BSD, but just in case a system
2163 where "signal()" has AT&T semantics adopts SIGINFO....) */
2164 signal(SIGINFO, report_counts_siginfo);
2165 #endif /* SIGINFO */
2167 if (cfile.save_file != NULL && quiet) {
2168 /* Report the count only if we're capturing to a file (rather
2169 than printing captured packet information out) and aren't
2170 updating a count as packets arrive. */
2171 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2174 infoprint = FALSE; /* we just reported it */
2175 #endif /* SIGINFO */
2180 report_counts_siginfo(int signum _U_)
2182 int sav_errno = errno;
2183 /* If we've been told to delay printing, just set a flag asking
2184 that we print counts (if we're supposed to), otherwise print
2185 the count of packets captured (if we're supposed to). */
2192 #endif /* SIGINFO */
2193 #endif /* HAVE_LIBPCAP */
2196 load_cap_file(capture_file *cf, int out_file_type)
2199 int snapshot_length;
2205 linktype = wtap_file_encap(cf->wth);
2206 if (cf->save_file != NULL) {
2207 /* Set up to write to the capture file. */
2208 snapshot_length = wtap_snapshot_length(cf->wth);
2209 if (snapshot_length == 0) {
2210 /* Snapshot length of input file not known. */
2211 snapshot_length = WTAP_MAX_PACKET_SIZE;
2213 pdh = wtap_dump_open(cf->save_file, out_file_type,
2214 linktype, snapshot_length, &err);
2217 /* We couldn't set up to write to the capture file. */
2220 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2222 "tethereal: Capture files can't be written in that format.\n");
2225 case WTAP_ERR_UNSUPPORTED_ENCAP:
2226 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2228 "tethereal: The capture file being read cannot be written in "
2232 case WTAP_ERR_CANT_OPEN:
2234 "tethereal: The file \"%s\" couldn't be created for some "
2235 "unknown reason.\n",
2236 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2239 case WTAP_ERR_SHORT_WRITE:
2241 "tethereal: A full header couldn't be written to the file \"%s\".\n",
2242 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2247 "tethereal: The file \"%s\" could not be created: %s\n.",
2248 *cf->save_file == '\0' ? "stdout" : cf->save_file,
2249 wtap_strerror(err));
2256 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
2259 /* Now close the capture file. */
2260 if (!wtap_dump_close(pdh, &err))
2261 show_capture_file_io_error(cfile.save_file, err, TRUE);
2265 print_preamble(stdout, print_format);
2266 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
2268 print_finale(stdout, print_format);
2271 /* Print up a message box noting that the read failed somewhere along
2275 case WTAP_ERR_UNSUPPORTED_ENCAP:
2277 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
2281 case WTAP_ERR_CANT_READ:
2283 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2287 case WTAP_ERR_SHORT_READ:
2289 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2293 case WTAP_ERR_BAD_RECORD:
2295 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
2301 "tethereal: An error occurred while reading \"%s\": %s.\n",
2302 cf->filename, wtap_strerror(err));
2308 wtap_close(cf->wth);
2315 fill_in_fdata(frame_data *fdata, capture_file *cf,
2316 const struct wtap_pkthdr *phdr, long offset)
2321 fdata->num = cf->count;
2322 fdata->pkt_len = phdr->len;
2323 cul_bytes += phdr->len;
2324 fdata->cul_bytes = cul_bytes;
2325 fdata->cap_len = phdr->caplen;
2326 fdata->file_off = offset;
2327 fdata->lnk_t = phdr->pkt_encap;
2328 fdata->abs_secs = phdr->ts.tv_sec;
2329 fdata->abs_usecs = phdr->ts.tv_usec;
2330 fdata->flags.passed_dfilter = 0;
2331 fdata->flags.encoding = CHAR_ASCII;
2332 fdata->flags.visited = 0;
2333 fdata->flags.marked = 0;
2334 fdata->flags.ref_time = 0;
2336 /* If we don't have the time stamp of the first packet in the
2337 capture, it's because this is the first packet. Save the time
2338 stamp of this packet as the time stamp of the first packet. */
2339 if (!firstsec && !firstusec) {
2340 firstsec = fdata->abs_secs;
2341 firstusec = fdata->abs_usecs;
2344 /* If we don't have the time stamp of the previous displayed packet,
2345 it's because this is the first displayed packet. Save the time
2346 stamp of this packet as the time stamp of the previous displayed
2348 if (!prevsec && !prevusec) {
2349 prevsec = fdata->abs_secs;
2350 prevusec = fdata->abs_usecs;
2353 /* Get the time elapsed between the first packet and this packet. */
2354 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2355 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2357 /* If it's greater than the current elapsed time, set the elapsed time
2358 to it (we check for "greater than" so as not to be confused by
2359 time moving backwards). */
2360 if ((gint32)cf->esec < fdata->rel_secs
2361 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2362 cf->esec = fdata->rel_secs;
2363 cf->eusec = fdata->rel_usecs;
2366 /* Get the time elapsed between the previous displayed packet and
2368 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2369 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2370 prevsec = fdata->abs_secs;
2371 prevusec = fdata->abs_usecs;
2374 /* Free up all data attached to a "frame_data" structure. */
2376 clear_fdata(frame_data *fdata)
2379 g_slist_free(fdata->pfd);
2383 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
2384 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2386 cb_args_t *args = (cb_args_t *) user;
2387 capture_file *cf = args->cf;
2388 wtap_dumper *pdh = args->pdh;
2392 epan_dissect_t *edt;
2397 * Prevent a SIGINFO handler from writing to stdout while we're
2398 * doing so; instead, have it just set a flag telling us to print
2399 * that information when we're done.
2402 #endif /* SIGINFO */
2403 #endif /* HAVE_LIBPCAP */
2407 fill_in_fdata(&fdata, cf, phdr, offset);
2408 edt = epan_dissect_new(TRUE, FALSE);
2409 epan_dissect_prime_dfilter(edt, cf->rfcode);
2410 epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
2411 passed = dfilter_apply_edt(cf->rfcode, edt);
2417 /* The packet passed the read filter. */
2423 /* The current packet may have arrived after a very long silence,
2424 * way past the time to switch files. In order not to have
2425 * the first packet of a new series of events as the last
2426 * [or only] packet in the file, switch before writing!
2428 if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
2429 /* time elasped for this ring file, switch to the next */
2430 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
2431 /* File switch succeeded: reset the condition */
2432 cnd_reset(cnd_ring_timeout);
2434 /* File switch failed: stop here */
2435 /* XXX - we should do something with "loop_err" */
2440 if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
2442 if (ld.pch != NULL && !quiet) {
2443 /* We're capturing packets, so (if -q not specified) we're printing
2444 a count of packets captured; move to the line after the count. */
2445 fprintf(stderr, "\n");
2448 show_capture_file_io_error(cf->save_file, err, FALSE);
2453 wtap_dump_close(pdh, &err);
2458 epan_dissect_free(edt);
2460 clear_fdata(&fdata);
2465 * Allow SIGINFO handlers to write.
2470 * If a SIGINFO handler asked us to write out capture counts, do so.
2474 #endif /* SIGINFO */
2475 #endif /* HAVE_LIBPCAP */
2479 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2488 "tethereal: Not all the packets could be written to \"%s\" because there is "
2489 "no space left on the file system.\n",
2496 "tethereal: Not all the packets could be written to \"%s\" because you are "
2497 "too close to, or over your disk quota.\n",
2502 case WTAP_ERR_CANT_CLOSE:
2504 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2508 case WTAP_ERR_SHORT_WRITE:
2510 "tethereal: Not all the packets could be written to \"%s\".\n",
2517 "tethereal: \"%s\" could not be closed: %s.\n",
2518 fname, wtap_strerror(err));
2521 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2522 fname, wtap_strerror(err));
2529 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
2530 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2532 cb_args_t *args = (cb_args_t *) user;
2533 capture_file *cf = args->cf;
2536 print_args_t print_args;
2537 epan_dissect_t *edt;
2538 gboolean create_proto_tree;
2543 fill_in_fdata(&fdata, cf, phdr, offset);
2545 /* Grab any resolved addresses */
2546 if (g_resolv_flags) {
2547 host_name_lookup_process(NULL);
2551 if (cf->rfcode || verbose || num_tap_filters!=0)
2552 create_proto_tree = TRUE;
2554 create_proto_tree = FALSE;
2555 /* The protocol tree will be "visible", i.e., printed, only if we're
2556 not printing a summary.
2558 We only need the columns if we're *not* verbose; in verbose mode,
2559 we print the protocol tree, not the protocol summary. */
2561 edt = epan_dissect_new(create_proto_tree, verbose);
2563 epan_dissect_prime_dfilter(edt, cf->rfcode);
2566 tap_queue_init(edt);
2567 epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
2568 tap_push_tapped_queue(edt);
2571 passed = dfilter_apply_edt(cf->rfcode, edt);
2574 /* The packet passed the read filter. */
2578 print_args.to_file = TRUE;
2579 print_args.format = print_format;
2580 print_args.print_summary = !verbose;
2581 print_args.print_hex = print_hex;
2582 print_args.print_dissections = print_dissections_expanded;
2584 /* init the packet range */
2585 packet_range_init(&print_args.range);
2588 /* Print the information in the protocol tree. */
2589 proto_tree_print(&print_args, edt, stdout);
2591 /* "print_hex_data()" will put out a leading blank line, as well
2592 as a trailing one; print one here, to separate the packets,
2593 only if "print_hex_data()" won't be called. */
2597 /* Just fill in the columns. */
2598 epan_dissect_fill_in_columns(edt);
2600 /* Now print them. */
2601 for (i = 0; i < cf->cinfo.num_cols; i++) {
2602 switch (cf->cinfo.col_fmt[i]) {
2605 * Don't print this if we're doing a live capture from a network
2606 * interface - if we're doing a live capture, you won't be
2607 * able to look at the capture in the future (it's not being
2608 * saved anywhere), so the frame numbers are unlikely to be
2611 * (XXX - it might be nice to be able to save and print at
2612 * the same time, sort of like an "Update list of packets
2613 * in real time" capture in Ethereal.)
2615 if (cf->iface != NULL)
2617 printf("%3s", cf->cinfo.col_data[i]);
2623 case COL_ABS_DATE_TIME: /* XXX - wider */
2624 printf("%10s", cf->cinfo.col_data[i]);
2630 case COL_DEF_DL_SRC:
2631 case COL_RES_DL_SRC:
2632 case COL_UNRES_DL_SRC:
2633 case COL_DEF_NET_SRC:
2634 case COL_RES_NET_SRC:
2635 case COL_UNRES_NET_SRC:
2636 printf("%12s", cf->cinfo.col_data[i]);
2642 case COL_DEF_DL_DST:
2643 case COL_RES_DL_DST:
2644 case COL_UNRES_DL_DST:
2645 case COL_DEF_NET_DST:
2646 case COL_RES_NET_DST:
2647 case COL_UNRES_NET_DST:
2648 printf("%-12s", cf->cinfo.col_data[i]);
2652 printf("%s", cf->cinfo.col_data[i]);
2655 if (i != cf->cinfo.num_cols - 1) {
2657 * This isn't the last column, so we need to print a
2658 * separator between this column and the next.
2660 * If we printed a network source and are printing a
2661 * network destination of the same type next, separate
2662 * them with "->"; if we printed a network destination
2663 * and are printing a network source of the same type
2664 * next, separate them with "<-"; otherwise separate them
2667 switch (cf->cinfo.col_fmt[i]) {
2672 switch (cf->cinfo.col_fmt[i + 1]) {
2686 case COL_DEF_DL_SRC:
2687 case COL_RES_DL_SRC:
2688 case COL_UNRES_DL_SRC:
2689 switch (cf->cinfo.col_fmt[i + 1]) {
2691 case COL_DEF_DL_DST:
2692 case COL_RES_DL_DST:
2693 case COL_UNRES_DL_DST:
2703 case COL_DEF_NET_SRC:
2704 case COL_RES_NET_SRC:
2705 case COL_UNRES_NET_SRC:
2706 switch (cf->cinfo.col_fmt[i + 1]) {
2708 case COL_DEF_NET_DST:
2709 case COL_RES_NET_DST:
2710 case COL_UNRES_NET_DST:
2723 switch (cf->cinfo.col_fmt[i + 1]) {
2737 case COL_DEF_DL_DST:
2738 case COL_RES_DL_DST:
2739 case COL_UNRES_DL_DST:
2740 switch (cf->cinfo.col_fmt[i + 1]) {
2742 case COL_DEF_DL_SRC:
2743 case COL_RES_DL_SRC:
2744 case COL_UNRES_DL_SRC:
2754 case COL_DEF_NET_DST:
2755 case COL_RES_NET_DST:
2756 case COL_UNRES_NET_DST:
2757 switch (cf->cinfo.col_fmt[i + 1]) {
2759 case COL_DEF_NET_SRC:
2760 case COL_RES_NET_SRC:
2761 case COL_UNRES_NET_SRC:
2780 print_hex_data(stdout, print_args.format, edt);
2785 /* The ANSI C standard does not appear to *require* that a line-buffered
2786 stream be flushed to the host environment whenever a newline is
2787 written, it just says that, on such a stream, characters "are
2788 intended to be transmitted to or from the host environment as a
2789 block when a new-line character is encountered".
2791 The Visual C++ 6.0 C implementation doesn't do what is intended;
2792 even if you set a stream to be line-buffered, it still doesn't
2793 flush the buffer at the end of every line.
2795 So, if the "-l" flag was specified, we flush the standard output
2796 at the end of a packet. This will do the right thing if we're
2797 printing packet summary lines, and, as we print the entire protocol
2798 tree for a single packet without waiting for anything to happen,
2799 it should be as good as line-buffered mode if we're printing
2800 protocol trees. (The whole reason for the "-l" flag in either
2801 tcpdump or Tethereal is to allow the output of a live capture to
2802 be piped to a program or script and to have that script see the
2803 information for the packet as soon as it's printed, rather than
2804 having to wait until a standard I/O buffer fills up. */
2808 epan_dissect_free(edt);
2810 clear_fdata(&fdata);
2814 file_open_error_message(int err, gboolean for_writing, int file_type)
2817 static char errmsg_errno[1024+1];
2821 case WTAP_ERR_NOT_REGULAR_FILE:
2822 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2825 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2826 case WTAP_ERR_UNSUPPORTED:
2827 /* Seen only when opening a capture file for reading. */
2828 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
2831 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2832 /* Seen only when opening a capture file for writing. */
2833 snprintf(errmsg_errno, sizeof(errmsg_errno),
2834 "The file \"%%s\" is a pipe, and %s capture files cannot be "
2835 "written to a pipe.", wtap_file_type_string(file_type));
2836 errmsg = errmsg_errno;
2839 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2840 /* Seen only when opening a capture file for writing. */
2841 errmsg = "Tethereal does not support writing capture files in that format.";
2844 case WTAP_ERR_UNSUPPORTED_ENCAP:
2845 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2847 errmsg = "Tethereal cannot save this capture in that format.";
2849 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2852 case WTAP_ERR_BAD_RECORD:
2853 errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2856 case WTAP_ERR_CANT_OPEN:
2858 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2860 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2863 case WTAP_ERR_SHORT_READ:
2864 errmsg = "The file \"%s\" appears to have been cut short"
2865 " in the middle of a packet or other data.";
2868 case WTAP_ERR_SHORT_WRITE:
2869 errmsg = "A full header couldn't be written to the file \"%s\".";
2874 errmsg = "The path to the file \"%s\" does not exist.";
2876 errmsg = "The file \"%s\" does not exist.";
2881 errmsg = "You do not have permission to create or write to the file \"%s\".";
2883 errmsg = "You do not have permission to read the file \"%s\".";
2887 errmsg = "\"%s\" is a directory (folder), not a file.";
2891 snprintf(errmsg_errno, sizeof(errmsg_errno),
2892 "The file \"%%s\" could not be %s: %s.",
2893 for_writing ? "created" : "opened",
2894 wtap_strerror(err));
2895 errmsg = errmsg_errno;
2902 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
2906 char err_msg[2048+1];
2908 wth = wtap_open_offline(fname, &err, FALSE);
2912 /* The open succeeded. Fill in the information for this file. */
2914 /* Initialize all data structures used for dissection. */
2918 cf->filed = -1; /* not used, but set it anyway */
2919 cf->f_len = 0; /* not used, but set it anyway */
2921 /* Set the file name because we need it to set the follow stream filter.
2922 XXX - is that still true? We need it for other reasons, though,
2924 cf->filename = g_strdup(fname);
2926 /* Indicate whether it's a permanent or temporary file. */
2927 cf->is_tempfile = is_tempfile;
2929 /* If it's a temporary capture buffer file, mark it as not saved. */
2930 cf->user_saved = !is_tempfile;
2932 cf->cd_t = wtap_file_type(cf->wth);
2934 cf->drops_known = FALSE;
2938 cf->snap = wtap_snapshot_length(cf->wth);
2939 if (cf->snap == 0) {
2940 /* Snapshot length not known. */
2941 cf->has_snap = FALSE;
2942 cf->snap = WTAP_MAX_PACKET_SIZE;
2944 cf->has_snap = TRUE;
2945 firstsec = 0, firstusec = 0;
2946 prevsec = 0, prevusec = 0;
2951 snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE, 0),
2953 fprintf(stderr, "tethereal: %s\n", err_msg);
2959 /* Take care of byte order in the libpcap headers read from pipes.
2960 * (function taken from wiretap/libpcap.c) */
2962 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
2964 if (ld->byte_swapped) {
2965 /* Byte-swap the record header fields. */
2966 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
2967 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
2968 rechdr->incl_len = BSWAP32(rechdr->incl_len);
2969 rechdr->orig_len = BSWAP32(rechdr->orig_len);
2972 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
2973 swapped, in order to match the BPF header layout.
2975 Unfortunately, some files were, according to a comment in the "libpcap"
2976 source, written with version 2.3 in their headers but without the
2977 interchanged fields, so if "incl_len" is greater than "orig_len" - which
2978 would make no sense - we assume that we need to swap them. */
2979 if (hdr->version_major == 2 &&
2980 (hdr->version_minor < 3 ||
2981 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
2984 temp = rechdr->orig_len;
2985 rechdr->orig_len = rechdr->incl_len;
2986 rechdr->incl_len = temp;
2990 /* Mimic pcap_open_live() for pipe captures
2991 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
2993 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2994 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2996 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
2997 char *errmsg, int errmsgl)
2999 struct stat pipe_stat;
3003 unsigned int bytes_read;
3006 * XXX Tethereal blocks until we return
3008 if (strcmp(pipename, "-") == 0)
3009 fd = 0; /* read from stdin */
3011 if (stat(pipename, &pipe_stat) < 0) {
3012 if (errno == ENOENT || errno == ENOTDIR)
3013 ld->pipe_err = PIPNEXIST;
3015 snprintf(errmsg, errmsgl,
3016 "The capture session could not be initiated "
3017 "due to error on pipe: %s", strerror(errno));
3018 ld->pipe_err = PIPERR;
3022 if (! S_ISFIFO(pipe_stat.st_mode)) {
3023 if (S_ISCHR(pipe_stat.st_mode)) {
3025 * Assume the user specified an interface on a system where
3026 * interfaces are in /dev. Pretend we haven't seen it.
3028 ld->pipe_err = PIPNEXIST;
3030 snprintf(errmsg, errmsgl,
3031 "The capture session could not be initiated because\n"
3032 "\"%s\" is neither an interface nor a pipe", pipename);
3033 ld->pipe_err = PIPERR;
3037 fd = open(pipename, O_RDONLY);
3039 snprintf(errmsg, errmsgl,
3040 "The capture session could not be initiated "
3041 "due to error on pipe open: %s", strerror(errno));
3042 ld->pipe_err = PIPERR;
3047 ld->from_pipe = TRUE;
3049 /* read the pcap header */
3051 while (bytes_read < sizeof magic) {
3052 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3055 snprintf(errmsg, errmsgl, "End of file on pipe during open");
3057 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3066 /* Host that wrote it has our byte order, and was running
3067 a program using either standard or ss990417 libpcap. */
3068 ld->byte_swapped = FALSE;
3069 ld->modified = FALSE;
3071 case PCAP_MODIFIED_MAGIC:
3072 /* Host that wrote it has our byte order, but was running
3073 a program using either ss990915 or ss991029 libpcap. */
3074 ld->byte_swapped = FALSE;
3075 ld->modified = TRUE;
3077 case PCAP_SWAPPED_MAGIC:
3078 /* Host that wrote it has a byte order opposite to ours,
3079 and was running a program using either standard or
3080 ss990417 libpcap. */
3081 ld->byte_swapped = TRUE;
3082 ld->modified = FALSE;
3084 case PCAP_SWAPPED_MODIFIED_MAGIC:
3085 /* Host that wrote it out has a byte order opposite to
3086 ours, and was running a program using either ss990915
3087 or ss991029 libpcap. */
3088 ld->byte_swapped = TRUE;
3089 ld->modified = TRUE;
3092 /* Not a "libpcap" type we know about. */
3093 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3097 /* Read the rest of the header */
3099 while (bytes_read < sizeof(struct pcap_hdr)) {
3100 b = read(fd, ((char *)hdr)+bytes_read,
3101 sizeof(struct pcap_hdr) - bytes_read);
3104 snprintf(errmsg, errmsgl, "End of file on pipe during open");
3106 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3113 if (ld->byte_swapped) {
3114 /* Byte-swap the header fields about which we care. */
3115 hdr->version_major = BSWAP16(hdr->version_major);
3116 hdr->version_minor = BSWAP16(hdr->version_minor);
3117 hdr->snaplen = BSWAP32(hdr->snaplen);
3118 hdr->network = BSWAP32(hdr->network);
3121 if (hdr->version_major < 2) {
3122 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3126 ld->pipe_state = STATE_EXPECT_REC_HDR;
3127 ld->pipe_err = PIPOK;
3131 ld->pipe_err = PIPERR;
3136 /* We read one record from the pipe, take care of byte order in the record
3137 * header, write the record in the capture file, and update capture statistics. */
3140 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
3141 struct pcaprec_modified_hdr *rechdr, guchar *data,
3142 char *errmsg, int errmsgl)
3144 struct pcap_pkthdr phdr;
3146 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3149 switch (ld->pipe_state) {
3151 case STATE_EXPECT_REC_HDR:
3152 ld->bytes_to_read = ld->modified ?
3153 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3155 ld->pipe_state = STATE_READ_REC_HDR;
3158 case STATE_READ_REC_HDR:
3159 b = read(fd, ((char *)rechdr)+ld->bytes_read,
3160 ld->bytes_to_read - ld->bytes_read);
3163 result = PD_PIPE_EOF;
3165 result = PD_PIPE_ERR;
3168 if ((ld->bytes_read += b) < ld->bytes_to_read)
3170 result = PD_REC_HDR_READ;
3173 case STATE_EXPECT_DATA:
3175 ld->pipe_state = STATE_READ_DATA;
3178 case STATE_READ_DATA:
3179 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
3182 result = PD_PIPE_EOF;
3184 result = PD_PIPE_ERR;
3187 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
3189 result = PD_DATA_READ;
3193 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3196 } /* switch (ld->pipe_state) */
3199 * We've now read as much data as we were expecting, so process it.
3203 case PD_REC_HDR_READ:
3204 /* We've read the header. Take care of byte order. */
3205 adjust_header(ld, hdr, &rechdr->hdr);
3206 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3207 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3208 ld->packet_count+1, rechdr->hdr.incl_len);
3211 ld->pipe_state = STATE_EXPECT_DATA;
3215 /* Fill in a "struct pcap_pkthdr", and process the packet. */
3216 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3217 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3218 phdr.caplen = rechdr->hdr.incl_len;
3219 phdr.len = rechdr->hdr.orig_len;
3221 capture_pcap_cb((guchar *)ld, &phdr, data);
3223 ld->pipe_state = STATE_EXPECT_REC_HDR;
3227 ld->pipe_err = PIPEOF;
3231 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3238 ld->pipe_err = PIPERR;
3239 /* Return here rather than inside the switch to prevent GCC warning */
3243 #endif /* HAVE_LIBPCAP */