3 * $Id: tethereal.c,v 1.194 2003/09/07 00:47:55 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
72 #include <epan/epan.h>
73 #include <epan/filesystem.h>
76 #include <epan/timestamp.h>
77 #include <epan/packet.h>
79 #include "disabled_protos.h"
83 #include <epan/resolv.h>
86 #include "pcap-util.h"
88 #include <epan/conversation.h>
89 #include <epan/plugins.h>
91 #include "conditions.h"
92 #include "capture_stop_conditions.h"
93 #include "ringbuffer.h"
94 #include <epan/epan_dissect.h>
98 #include <wiretap/wtap-capture.h>
99 #include <wiretap/libpcap.h>
103 #include "capture-wpcap.h"
107 * This is the template for the decode as option; it is shared between the
108 * various functions that output the usage for this parameter.
110 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
111 static guint32 firstsec, firstusec;
112 static guint32 prevsec, prevusec;
113 static GString *comp_info_str, *runtime_info_str;
114 static gboolean quiet;
115 static gboolean decode;
116 static gboolean verbose;
117 static gboolean print_hex;
118 static gboolean line_buffered;
119 static guint32 cul_bytes = 0;
122 typedef struct _loop_data {
123 gboolean go; /* TRUE as long as we're supposed to keep capturing */
125 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
129 gboolean output_to_pipe;
132 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
133 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
134 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
136 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
137 STATE_EXPECT_DATA, STATE_READ_DATA
140 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
146 static int capture(int);
147 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
149 static void report_counts(void);
151 static BOOL WINAPI capture_cleanup(DWORD);
153 static void capture_cleanup(int);
155 static void report_counts_siginfo(int);
158 #endif /* HAVE_LIBPCAP */
165 static int load_cap_file(capture_file *, int);
166 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
167 union wtap_pseudo_header *, const guchar *);
168 static void show_capture_file_io_error(const char *, int, gboolean);
169 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
170 union wtap_pseudo_header *, const guchar *);
173 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
174 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
175 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
176 struct pcaprec_modified_hdr *, guchar *, char *, int);
181 ts_type timestamp_type = RELATIVE;
184 int snaplen; /* Maximum captured packet length */
185 int promisc_mode; /* Capture in promiscuous mode */
186 int autostop_count; /* Maximum packet count */
187 gboolean has_autostop_duration; /* TRUE if maximum capture duration
189 gint32 autostop_duration; /* Maximum capture duration */
190 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
192 gint32 autostop_filesize; /* Maximum capture file size */
193 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
194 guint32 ringbuffer_num_files; /* Number of ring buffer files */
195 gboolean has_ring_duration; /* TRUE if ring duration specified */
196 gint32 ringbuffer_duration; /* Switch file after n seconds */
199 static capture_options capture_opts = {
200 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
201 infinite, in effect */
202 TRUE, /* promiscuous mode is the default */
203 0, /* max packet count - default is 0,
205 FALSE, /* maximum capture duration not
206 specified by default */
207 0, /* maximum capture duration */
208 FALSE, /* maximum capture file size not
209 specified by default */
210 0, /* maximum capture file size */
211 FALSE, /* ring buffer off by default */
212 RINGBUFFER_MIN_NUM_FILES, /* default number of ring buffer
214 FALSE, /* Switch ring file after some */
215 0 /* specified time is off by default */
219 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
220 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
222 #endif /* HAVE_LIBPCAP */
225 print_usage(gboolean print_ver)
230 fprintf(stderr, "This is GNU t%s %s\n%s\n%s\n", PACKAGE, VERSION,
231 comp_info_str->str, runtime_info_str->str);
234 fprintf(stderr, "\nt%s [ -vh ] [ -DlnpqSVx ] [ -a <capture autostop condition> ] ...\n",
236 fprintf(stderr, "\t[ -b <number of ring buffer files>[:<duration>] ] [ -c <count> ]\n");
237 fprintf(stderr, "\t[ -d %s ] ...\n", decode_as_arg_template);
238 fprintf(stderr, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <interface> ]\n");
239 fprintf(stderr, "\t[ -N <resolving> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
240 fprintf(stderr, "\t[ -R <read filter> ] [ -s <snaplen> ] [ -t <time stamp format> ]\n");
241 fprintf(stderr, "\t[ -w <savefile> ] [ -Z <statistics string> ]\n");
243 fprintf(stderr, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
244 fprintf(stderr, "\t[ -d %s ] ...\n", decode_as_arg_template);
245 fprintf(stderr, "\t[ -F <output file type> ] [ -N <resolving> ]\n");
246 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
247 fprintf(stderr, "\t[ -t <time stamp format> ] [ -w <savefile> ] [ -Z <statistics string> ]\n");
249 fprintf(stderr, "Valid file type arguments to the \"-F\" flag:\n");
250 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
251 if (wtap_dump_can_open(i))
252 fprintf(stderr, "\t%s - %s\n",
253 wtap_file_type_short_string(i), wtap_file_type_string(i));
255 fprintf(stderr, "\tdefault is libpcap\n");
260 get_natural_int(const char *string, const char *name)
265 number = strtol(string, &p, 10);
266 if (p == string || *p != '\0') {
267 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
272 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
276 if (number > INT_MAX) {
277 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
285 get_positive_int(const char *string, const char *name)
289 number = get_natural_int(string, name);
292 fprintf(stderr, "tethereal: The specified %s is zero\n",
301 * Given a string of the form "<autostop criterion>:<value>", as might appear
302 * as an argument to a "-a" option, parse it and set the criterion in
303 * question. Return an indication of whether it succeeded or failed
307 set_autostop_criterion(const char *autostoparg)
311 colonp = strchr(autostoparg, ':');
319 * Skip over any white space (there probably won't be any, but
320 * as we allow it in the preferences file, we might as well
327 * Put the colon back, so if our caller uses, in an
328 * error message, the string they passed us, the message
334 if (strcmp(autostoparg,"duration") == 0) {
335 capture_opts.has_autostop_duration = TRUE;
336 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
337 } else if (strcmp(autostoparg,"filesize") == 0) {
338 capture_opts.has_autostop_filesize = TRUE;
339 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
343 *colonp = ':'; /* put the colon back */
348 * Given a string of the form "<ring buffer file>:<duration>", as might appear
349 * as an argument to a "-b" option, parse it and set the arguments in
350 * question. Return an indication of whether it succeeded or failed
354 get_ring_arguments(const char *arg)
356 guchar *p = NULL, *colonp;
358 colonp = strchr(arg, ':');
360 if (colonp != NULL) {
365 capture_opts.ringbuffer_num_files =
366 get_natural_int(arg, "number of ring buffer files");
372 * Skip over any white space (there probably won't be any, but
373 * as we allow it in the preferences file, we might as well
380 * Put the colon back, so if our caller uses, in an
381 * error message, the string they passed us, the message
388 capture_opts.has_ring_duration = TRUE;
389 capture_opts.ringbuffer_duration = get_positive_int(p,
390 "ring buffer duration");
392 *colonp = ':'; /* put the colon back */
397 /* structure to keep track of what tap listeners have been registered.
399 typedef struct _ethereal_tap_list {
400 struct _ethereal_tap_list *next;
402 void (*func)(char *arg);
404 static ethereal_tap_list *tap_list=NULL;
407 register_ethereal_tap(char *cmd, void (*func)(char *arg))
409 ethereal_tap_list *newtl;
411 newtl=malloc(sizeof(ethereal_tap_list));
412 newtl->next=tap_list;
420 * For a dissector table, print on the stream described by output,
421 * its short name (which is what's used in the "-d" option) and its
425 display_dissector_table_names(char *table_name, char *ui_name, gpointer output)
427 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
431 * For a dissector handle, print on the stream described by output,
432 * the filter name (which is what's used in the "-d" option) and the full
433 * name for the protocol that corresponds to this handle.
436 display_dissector_names(gchar *table _U_, gpointer handle, gpointer output)
439 const gchar* proto_filter_name;
440 const gchar* proto_ui_name;
442 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
444 if (proto_id != -1) {
445 proto_filter_name = proto_get_protocol_filter_name(proto_id);
446 proto_ui_name = proto_get_protocol_name(proto_id);
447 g_assert(proto_filter_name != NULL);
448 g_assert(proto_ui_name != NULL);
450 fprintf((FILE *)output, "\t%s (%s)\n",
457 * The protocol_name_search structure is used by find_protocol_name_func()
458 * to pass parameters and store results
460 struct protocol_name_search{
461 gchar *searched_name; /* Protocol filter name we are looking for */
462 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
463 guint nb_match; /* How many dissectors matched searched_name */
465 typedef struct protocol_name_search *protocol_name_search_t;
468 * This function parses all dissectors associated with a table to find the
469 * one whose protocol has the specified filter name. It is called
470 * as a reference function in a call to dissector_table_foreach_handle.
471 * The name we are looking for, as well as the results, are stored in the
472 * protocol_name_search struct pointed to by user_data.
473 * If called using dissector_table_foreach_handle, we actually parse the
474 * whole list of dissectors.
477 find_protocol_name_func(gchar *table _U_, gpointer handle, gpointer user_data)
481 const gchar *protocol_filter_name;
482 protocol_name_search_t search_info;
486 search_info = (protocol_name_search_t)user_data;
488 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
489 if (proto_id != -1) {
490 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
491 g_assert(protocol_filter_name != NULL);
492 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
494 if (search_info->nb_match == 0) {
495 /* Record this handle only if this is the first match */
496 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
498 search_info->nb_match++;
504 * Print all layer type names supported.
505 * We send the output to the stream described by the handle output.
509 fprint_all_layer_types(FILE *output)
512 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
516 * Print all protocol names supported for a specific layer type.
517 * table_name contains the layer type name in which the search is performed.
518 * We send the output to the stream described by the handle output.
522 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
525 dissector_table_foreach_handle(table_name,
526 display_dissector_names,
531 * The function below parses the command-line parameters for the decode as
532 * feature (a string pointer by cl_param).
533 * It checks the format of the command-line, searches for a matching table
534 * and dissector. If a table/dissector match is not found, we display a
535 * summary of the available tables/dissectors (on stderr) and return FALSE.
536 * If everything is fine, we get the "Decode as" preference activated,
537 * then we return TRUE.
540 add_decode_as(const gchar *cl_param)
544 gchar *decoded_param;
545 gchar *remaining_param;
547 gchar *dissector_str;
548 dissector_handle_t dissector_matching;
549 dissector_table_t table_matching;
550 ftenum_t dissector_table_selector_type;
551 struct protocol_name_search user_protocol_name;
553 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
556 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
557 g_assert(decoded_param);
558 strcpy(decoded_param, cl_param);
561 /* The lines below will parse this string (modifying it) to extract all
562 necessary information. Note that decoded_param is still needed since
563 strings are not copied - we just save pointers. */
565 /* This section extracts a layer type (table_name) from decoded_param */
566 table_name = decoded_param; /* Layer type string starts from beginning */
568 remaining_param = strchr(table_name, '=');
569 if (remaining_param == NULL) {
570 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
571 /* If the argument does not follow the template, carry on anyway to check
572 if the table name is at least correct. If remaining_param is NULL,
573 we'll exit anyway further down */
576 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
579 /* Remove leading and trailing spaces from the table name */
580 while ( table_name[0] == ' ' )
582 while ( table_name[strlen(table_name) - 1] == ' ' )
583 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
585 /* The following part searches a table matching with the layer type specified */
586 table_matching = NULL;
588 /* Look for the requested table */
589 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
590 fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
593 table_matching = find_dissector_table(table_name);
594 if (!table_matching) {
595 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 */
599 if (!table_matching) {
600 /* Display a list of supported layer types to help the user, if the
601 specified layer type was not found */
602 fprintf(stderr, "tethereal: Valid layer types are:\n");
603 fprint_all_layer_types(stderr);
605 if (remaining_param == NULL || !table_matching) {
606 /* Exit if the layer type was not found, or if no '=' separator was found
608 g_free(decoded_param);
612 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
613 fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
616 remaining_param++; /* Move to the second '=' */
617 *remaining_param = '\0'; /* Remove the second '=' */
619 remaining_param++; /* Position after the layer type string */
621 /* This section extracts a selector value (selector_str) from decoded_param */
623 selector_str = remaining_param; /* Next part starts with the selector number */
625 remaining_param = strchr(selector_str, ',');
626 if (remaining_param == NULL) {
627 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
628 /* If the argument does not follow the template, carry on anyway to check
629 if the selector value is at least correct. If remaining_param is NULL,
630 we'll exit anyway further down */
633 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
636 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
638 switch (dissector_table_selector_type) {
644 /* The selector for this table is an unsigned number. Parse it as such.
645 There's no need to remove leading and trailing spaces from the
646 selector number string, because sscanf will do that for us. */
647 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
648 fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
649 g_free(decoded_param);
656 /* The selector for this table is a string. */
660 /* There are currently no dissector tables with any types other
661 than the ones listed above. */
662 g_assert_not_reached();
665 if (remaining_param == NULL) {
666 /* Exit if no ',' separator was found (see above) */
667 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
668 fprint_all_protocols_for_layer_types(stderr, table_name);
669 g_free(decoded_param);
673 remaining_param++; /* Position after the selector number string */
675 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
677 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
679 /* Remove leading and trailing spaces from the dissector name */
680 while ( dissector_str[0] == ' ' )
682 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
683 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
685 dissector_matching = NULL;
687 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
688 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 */
689 fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
692 user_protocol_name.nb_match = 0;
693 user_protocol_name.searched_name = dissector_str;
694 user_protocol_name.matched_handle = NULL;
696 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 */
698 if (user_protocol_name.nb_match != 0) {
699 dissector_matching = user_protocol_name.matched_handle;
700 if (user_protocol_name.nb_match > 1) {
701 fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
705 /* OK, check whether the problem is that there isn't any such
706 protocol, or that there is but it's not specified as a protocol
707 that's valid for that dissector table.
708 Note, we don't exit here, but dissector_matching will remain NULL,
710 if (proto_get_id_by_filter_name(dissector_str) == -1) {
711 /* No such protocol */
712 fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
714 fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
715 dissector_str, table_name);
720 if (!dissector_matching) {
721 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
722 fprint_all_protocols_for_layer_types(stderr, table_name);
723 g_free(decoded_param);
727 /* This is the end of the code that parses the command-line options.
728 All information is now stored in the variables:
732 The above variables that are strings are still pointing to areas within
733 decoded_parm. decoded_parm thus still needs to be kept allocated in
734 until we stop needing these variables
735 decoded_param will be deallocated at each exit point of this function */
738 /* We now have a pointer to the handle for the requested dissector
739 (requested protocol) inside the variable dissector_matching */
740 switch (dissector_table_selector_type) {
746 /* The selector for this table is an unsigned number. */
747 dissector_change(table_name, selector, dissector_matching);
752 /* The selector for this table is a string. */
753 dissector_change_string(table_name, selector_str, dissector_matching);
757 /* There are currently no dissector tables with any types other
758 than the ones listed above. */
759 g_assert_not_reached();
761 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
766 main(int argc, char *argv[])
770 gboolean arg_error = FALSE;
776 char *gpf_path, *pf_path;
778 int gpf_open_errno, gpf_read_errno;
779 int pf_open_errno, pf_read_errno;
780 int dp_open_errno, dp_read_errno;
783 gboolean capture_filter_specified = FALSE;
784 GList *if_list, *if_entry;
787 gchar err_str[PCAP_ERRBUF_SIZE];
789 gboolean capture_option_specified = FALSE;
791 int out_file_type = WTAP_FILE_PCAP;
792 gchar *cf_name = NULL, *rfilter = NULL;
796 dfilter_t *rfcode = NULL;
799 ethereal_tap_list *tli;
801 /* Register all dissectors; we must do this before checking for the
802 "-G" flag, as the "-G" flag dumps information registered by the
803 dissectors, and we must do it before we read the preferences, in
804 case any dissectors register preferences. */
805 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
807 /* Register all tap listeners; we do this before we parse the arguments,
808 as the "-z" argument can specify a registered tap. */
809 register_all_tap_listeners();
811 /* Now register the preferences for any non-dissector modules.
812 We must do that before we read the preferences as well. */
813 prefs_register_modules();
815 /* If invoked with the "-G" flag, we dump out information based on
816 the argument to the "-G" flag; if no argument is specified,
817 for backwards compatibility we dump out a glossary of display
820 We do this here to mirror what happens in the GTK+ version, although
821 it's not necessary here. */
822 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
824 proto_registrar_dump_fields();
826 if (strcmp(argv[2], "fields") == 0)
827 proto_registrar_dump_fields();
828 else if (strcmp(argv[2], "protocols") == 0)
829 proto_registrar_dump_protocols();
831 fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
839 /* Set the C-language locale to the native environment. */
840 setlocale(LC_ALL, "");
842 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
843 &pf_open_errno, &pf_read_errno, &pf_path);
844 if (gpf_path != NULL) {
845 if (gpf_open_errno != 0) {
846 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
847 pf_path, strerror(gpf_open_errno));
849 if (gpf_read_errno != 0) {
850 fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
851 pf_path, strerror(gpf_read_errno));
854 if (pf_path != NULL) {
855 if (pf_open_errno != 0) {
856 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
857 strerror(pf_open_errno));
859 if (pf_read_errno != 0) {
860 fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
861 pf_path, strerror(pf_read_errno));
867 /* Set the name resolution code's flags from the preferences. */
868 g_resolv_flags = prefs->name_resolve;
870 /* Read the disabled protocols file. */
871 read_disabled_protos_list(&dp_path, &dp_open_errno, &dp_read_errno);
872 if (dp_path != NULL) {
873 if (dp_open_errno != 0) {
875 "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
876 strerror(dp_open_errno));
878 if (dp_read_errno != 0) {
880 "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
881 strerror(dp_read_errno));
887 /* Load Wpcap, if possible */
891 init_cap_file(&cfile);
893 /* Assemble the compile-time version information string */
894 comp_info_str = g_string_new("Compiled ");
895 get_compiled_version_info(comp_info_str);
897 /* Assemble the run-time version information string */
898 runtime_info_str = g_string_new("Running ");
899 get_runtime_version_info(runtime_info_str);
901 /* Now get our args */
902 while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lnN:o:pqr:R:s:St:vw:Vxz:")) != -1) {
904 case 'a': /* autostop criteria */
906 if (set_autostop_criterion(optarg) == FALSE) {
907 fprintf(stderr, "tethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
911 capture_option_specified = TRUE;
915 case 'b': /* Ringbuffer option */
917 capture_opts.ringbuffer_on = TRUE;
918 if (get_ring_arguments(optarg) == FALSE) {
919 fprintf(stderr, "tethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
923 capture_option_specified = TRUE;
927 case 'c': /* Capture xxx packets */
929 capture_opts.autostop_count =
930 get_positive_int(optarg, "packet count");
932 capture_option_specified = TRUE;
936 case 'd': /* Decode as rule */
937 if (!add_decode_as(optarg))
940 case 'D': /* Print a list of capture devices */
942 if_list = get_interface_list(&err, err_str);
943 if (if_list == NULL) {
946 case CANT_GET_INTERFACE_LIST:
947 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
951 case NO_INTERFACES_FOUND:
952 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
957 i = 1; /* Interface id number */
958 for (if_entry = g_list_first(if_list); if_entry != NULL;
959 if_entry = g_list_next(if_entry))
960 printf("%d. %s\n", i++, (char *)if_entry->data);
961 free_interface_list(if_list);
964 capture_option_specified = TRUE;
970 capture_filter_specified = TRUE;
972 g_free(cfile.cfilter);
973 cfile.cfilter = g_strdup(optarg);
975 capture_option_specified = TRUE;
980 out_file_type = wtap_short_string_to_file_type(optarg);
981 if (out_file_type < 0) {
982 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
987 case 'h': /* Print help and exit */
991 case 'i': /* Use interface xxx */
994 * If the argument is a number, treat it as an index into the list
995 * of adapters, as printed by "tethereal -D".
997 * This should be OK on UNIX systems, as interfaces shouldn't have
998 * names that begin with digits. It can be useful on Windows, where
999 * more than one interface can have the same name.
1001 adapter_index = strtol(optarg, &p, 10);
1002 if (p != NULL && *p == '\0') {
1003 if (adapter_index < 0) {
1005 "tethereal: The specified adapter index is a negative number\n");
1008 if (adapter_index > INT_MAX) {
1010 "tethereal: The specified adapter index is too large (greater than %d)\n",
1014 if (adapter_index == 0) {
1015 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1018 if_list = get_interface_list(&err, err_str);
1019 if (if_list == NULL) {
1022 case CANT_GET_INTERFACE_LIST:
1023 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1027 case NO_INTERFACES_FOUND:
1028 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1033 if_text = (char *)g_list_nth_data(if_list, adapter_index - 1);
1034 if (if_text == NULL) {
1035 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1039 /* XXX - why is this done? */
1040 if_text = strchr(if_text, '\\');
1042 cfile.iface = g_strdup(if_text);
1043 free_interface_list(if_list);
1045 cfile.iface = g_strdup(optarg);
1047 capture_option_specified = TRUE;
1051 case 'l': /* "Line-buffer" standard output */
1052 /* This isn't line-buffering, strictly speaking, it's just
1053 flushing the standard output after the information for
1054 each packet is printed; however, that should be good
1055 enough for all the purposes to which "-l" is put.
1057 See the comment in "wtap_dispatch_cb_print()" for an
1058 explanation of why we do that, and why we don't just
1059 use "setvbuf()" to make the standard output line-buffered
1060 (short version: in Windows, "line-buffered" is the same
1061 as "fully-buffered", and the output buffer is only flushed
1062 when it fills up). */
1063 line_buffered = TRUE;
1065 case 'n': /* No name resolution */
1066 g_resolv_flags = RESOLV_NONE;
1068 case 'N': /* Select what types of addresses/port #s to resolve */
1069 if (g_resolv_flags == RESOLV_ALL)
1070 g_resolv_flags = RESOLV_NONE;
1071 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1072 if (badopt != '\0') {
1073 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
1078 case 'o': /* Override preference from command line */
1079 switch (prefs_set_pref(optarg)) {
1081 case PREFS_SET_SYNTAX_ERR:
1082 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
1086 case PREFS_SET_NO_SUCH_PREF:
1087 case PREFS_SET_OBSOLETE:
1088 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
1094 case 'p': /* Don't capture in promiscuous mode */
1096 capture_opts.promisc_mode = FALSE;
1098 capture_option_specified = TRUE;
1102 case 'q': /* Quiet */
1105 case 'r': /* Read capture file xxx */
1106 cf_name = g_strdup(optarg);
1108 case 'R': /* Read file filter */
1111 case 's': /* Set the snapshot (capture) length */
1113 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
1115 capture_option_specified = TRUE;
1119 case 'S': /* show packets in real time */
1122 case 't': /* Time stamp type */
1123 if (strcmp(optarg, "r") == 0)
1124 timestamp_type = RELATIVE;
1125 else if (strcmp(optarg, "a") == 0)
1126 timestamp_type = ABSOLUTE;
1127 else if (strcmp(optarg, "ad") == 0)
1128 timestamp_type = ABSOLUTE_WITH_DATE;
1129 else if (strcmp(optarg, "d") == 0)
1130 timestamp_type = DELTA;
1132 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
1134 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
1135 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
1139 case 'v': /* Show version and exit */
1140 printf("t%s %s\n%s\n%s\n", PACKAGE, VERSION, comp_info_str->str,
1141 runtime_info_str->str);
1144 case 'w': /* Write to capture file xxx */
1145 cfile.save_file = g_strdup(optarg);
1147 case 'V': /* Verbose */
1150 case 'x': /* Print packet data in hex (and ASCII) */
1154 for(tli=tap_list;tli;tli=tli->next){
1155 if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
1156 (*tli->func)(optarg);
1161 fprintf(stderr,"tethereal: invalid -z argument.\n");
1162 fprintf(stderr," -z argument must be one of :\n");
1163 for(tli=tap_list;tli;tli=tli->next){
1164 fprintf(stderr," %s\n",tli->cmd);
1170 case '?': /* Bad flag - print usage message */
1176 /* If no capture filter or read filter has been specified, and there are
1177 still command-line arguments, treat them as the tokens of a capture
1178 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1179 flag was specified. */
1180 if (optind < argc) {
1181 if (cf_name != NULL) {
1182 if (rfilter != NULL) {
1184 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1187 rfilter = get_args_as_string(argc, argv, optind);
1190 if (capture_filter_specified) {
1192 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1195 cfile.cfilter = get_args_as_string(argc, argv, optind);
1197 capture_option_specified = TRUE;
1202 /* See if we're writing a capture file and the file is a pipe */
1204 ld.output_to_pipe = FALSE;
1206 if (cfile.save_file != NULL) {
1207 if (strcmp(cfile.save_file, "-") == 0) {
1209 g_free(cfile.save_file);
1210 cfile.save_file = g_strdup("");
1212 ld.output_to_pipe = TRUE;
1217 err = test_for_fifo(cfile.save_file);
1220 case ENOENT: /* it doesn't exist, so we'll be creating it,
1221 and it won't be a FIFO */
1222 case 0: /* found it, but it's not a FIFO */
1225 case ESPIPE: /* it is a FIFO */
1226 ld.output_to_pipe = TRUE;
1229 default: /* couldn't stat it */
1231 "tethereal: Error testing whether capture file is a pipe: %s\n",
1240 /* If they didn't specify a "-w" flag, but specified a maximum capture
1241 file size, tell them that this doesn't work, and exit. */
1242 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
1243 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1244 "capture isn't being saved to a file.\n");
1248 if (capture_opts.ringbuffer_on) {
1249 /* Ring buffer works only under certain conditions:
1250 a) ring buffer does not work if you're not saving the capture to
1252 b) ring buffer only works if you're saving in libpcap format;
1253 c) it makes no sense to enable the ring buffer if the maximum
1254 file size is set to "infinite";
1255 d) file must not be a pipe. */
1256 if (cfile.save_file == NULL) {
1257 fprintf(stderr, "tethereal: Ring buffer requested, but "
1258 "capture isn't being saved to a file.\n");
1261 if (out_file_type != WTAP_FILE_PCAP) {
1262 fprintf(stderr, "tethereal: Ring buffer requested, but "
1263 "capture isn't being saved in libpcap format.\n");
1266 if (!capture_opts.has_autostop_filesize) {
1267 fprintf(stderr, "tethereal: Ring buffer requested, but "
1268 "no maximum capture file size was specified.\n");
1271 if (ld.output_to_pipe) {
1272 fprintf(stderr, "tethereal: Ring buffer requested, but "
1273 "capture file is a pipe.\n");
1280 /* Start windows sockets */
1281 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1284 /* Notify all registered modules that have had any of their preferences
1285 changed either from one of the preferences file or from the command
1286 line that their preferences have changed. */
1289 /* disabled protocols as per configuration file */
1290 if (dp_path == NULL) {
1291 set_disabled_protos_list();
1294 #ifndef HAVE_LIBPCAP
1295 if (capture_option_specified)
1296 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1303 /* Build the column format array */
1304 col_setup(&cfile.cinfo, prefs->num_cols);
1305 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1306 cfile.cinfo.col_fmt[i] = get_column_format(i);
1307 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1308 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1310 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1311 cfile.cinfo.col_data[i] = NULL;
1312 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1313 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1315 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1316 cfile.cinfo.col_fence[i] = 0;
1317 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1318 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1322 if (capture_opts.snaplen < 1)
1323 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1324 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1325 capture_opts.snaplen = MIN_PACKET_SIZE;
1327 /* Check the value range of the ringbuffer_num_files parameter */
1328 if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
1329 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
1330 #if RINGBUFFER_MIN_NUM_FILES > 0
1331 else if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
1332 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
1336 if (rfilter != NULL) {
1337 if (!dfilter_compile(rfilter, &rfcode)) {
1338 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1343 cfile.rfcode = rfcode;
1345 err = open_cap_file(cf_name, FALSE, &cfile);
1350 err = load_cap_file(&cfile, out_file_type);
1357 /* No capture file specified, so we're supposed to do a live capture;
1358 do we have support for live captures? */
1363 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1368 /* Yes; did the user specify an interface to use? */
1369 if (cfile.iface == NULL) {
1370 /* No - is a default specified in the preferences file? */
1371 if (prefs->capture_device != NULL) {
1373 if_text = strrchr(prefs->capture_device, ' ');
1374 if (if_text == NULL) {
1375 cfile.iface = g_strdup(prefs->capture_device);
1377 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1380 /* No - pick the first one from the list of interfaces. */
1381 if_list = get_interface_list(&err, err_str);
1382 if (if_list == NULL) {
1385 case CANT_GET_INTERFACE_LIST:
1386 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
1390 case NO_INTERFACES_FOUND:
1391 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1396 if_text = strrchr(if_list->data, ' '); /* first interface */
1397 if (if_text == NULL) {
1398 cfile.iface = g_strdup(if_list->data);
1400 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1402 free_interface_list(if_list);
1405 capture(out_file_type);
1407 if (capture_opts.ringbuffer_on) {
1411 /* No - complain. */
1412 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1417 draw_tap_listeners(TRUE);
1424 /* Do the low-level work of a capture.
1425 Returns TRUE if it succeeds, FALSE otherwise. */
1427 capture(int out_file_type)
1431 gchar open_err_str[PCAP_ERRBUF_SIZE];
1432 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1433 bpf_u_int32 netnum, netmask;
1434 struct bpf_program fcode;
1435 void (*oldhandler)(int);
1437 int volatile volatile_err = 0;
1438 int volatile inpkts = 0;
1440 char errmsg[1024+1];
1441 condition *volatile cnd_stop_capturesize = NULL;
1442 condition *volatile cnd_stop_timeout = NULL;
1443 condition *volatile cnd_ring_timeout = NULL;
1445 static const char ppamsg[] = "can't find PPA for ";
1447 volatile int pipe_fd = -1;
1448 struct pcap_hdr hdr;
1449 struct pcaprec_modified_hdr rechdr;
1450 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1452 struct pcap_stat stats;
1456 /* Initialize all data structures used for dissection. */
1459 ld.linktype = WTAP_ENCAP_UNKNOWN;
1462 /* Open the network interface to capture from it.
1463 Some versions of libpcap may put warnings into the error buffer
1464 if they succeed; to tell if that's happened, we have to clear
1465 the error buffer, and check if it's still a null string. */
1466 open_err_str[0] = '\0';
1467 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1468 capture_opts.promisc_mode, 1000, open_err_str);
1470 if (ld.pch == NULL) {
1471 /* We couldn't open "cfile.iface" as a network device. */
1473 /* On Windows, we don't support capturing on pipes, so we give up. */
1475 /* On Win32 OSes, the capture devices are probably available to all
1476 users; don't warn about permissions problems.
1478 Do, however, warn that WAN devices aren't supported. */
1479 snprintf(errmsg, sizeof errmsg,
1480 "The capture session could not be initiated (%s).\n"
1481 "Please check that you have the proper interface specified.\n"
1483 "Note that the driver Tethereal uses for packet capture on Windows doesn't\n"
1484 "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
1488 /* try to open cfile.iface as a pipe */
1489 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1491 if (pipe_fd == -1) {
1493 if (ld.pipe_err == PIPNEXIST) {
1494 /* Pipe doesn't exist, so output message for interface */
1496 /* If we got a "can't find PPA for XXX" message, warn the user (who
1497 is running Tethereal on HP-UX) that they don't have a version
1498 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1499 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1500 PPA for XXX" rather than "can't find PPA for XXX"). */
1501 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1504 "You are running Tethereal with a version of the libpcap library\n"
1505 "that doesn't handle HP-UX network devices well; this means that\n"
1506 "Tethereal may not be able to capture packets.\n"
1508 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1509 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1510 "packaged binary form from the Software Porting And Archive Centre\n"
1511 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1512 "at the URL lists a number of mirror sites.";
1515 snprintf(errmsg, sizeof errmsg,
1516 "The capture session could not be initiated (%s).\n"
1517 "Please check to make sure you have sufficient permissions, and that\n"
1518 "you have the proper interface or pipe specified.%s", open_err_str,
1522 * Else pipe (or file) does exist and pipe_open_live() has
1527 /* pipe_open_live() succeeded; don't want
1528 error message from pcap_open_live() */
1529 open_err_str[0] = '\0';
1533 if (cfile.cfilter && !ld.from_pipe) {
1534 /* A capture filter was specified; set it up. */
1535 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1537 * Well, we can't get the netmask for this interface; it's used
1538 * only for filters that check for broadcast IP addresses, so
1539 * we just warn the user, and punt and use 0.
1542 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1545 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1546 snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1547 pcap_geterr(ld.pch));
1550 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1551 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1552 pcap_geterr(ld.pch));
1557 /* Set up to write to the capture file. */
1560 pcap_encap = hdr.network;
1561 file_snaplen = hdr.snaplen;
1565 pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1566 file_snaplen = pcap_snapshot(ld.pch);
1568 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1569 if (cfile.save_file != NULL) {
1570 /* Set up to write to the capture file. */
1571 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1572 strcpy(errmsg, "The network you're capturing from is of a type"
1573 " that Tethereal doesn't support.");
1576 if (capture_opts.ringbuffer_on) {
1577 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1578 capture_opts.ringbuffer_num_files);
1579 if (cfile.save_file_fd != -1) {
1580 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1581 pcap_snapshot(ld.pch), &err);
1583 err = errno; /* "ringbuf_init()" failed */
1587 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1588 ld.linktype, pcap_snapshot(ld.pch), &err);
1591 if (ld.pdh == NULL) {
1592 snprintf(errmsg, sizeof errmsg,
1593 file_open_error_message(err, TRUE, out_file_type),
1594 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1599 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1600 returned a warning; print it, but keep capturing. */
1601 if (open_err_str[0] != '\0')
1602 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1605 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1606 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1608 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1610 XXX - deal with signal semantics on various UNIX platforms. Or just
1611 use "sigaction()" and be done with it? */
1612 signal(SIGTERM, capture_cleanup);
1613 signal(SIGINT, capture_cleanup);
1614 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1615 signal(SIGHUP, oldhandler);
1618 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1619 quiet mode, report the number of packets we've captured. */
1620 signal(SIGINFO, report_counts_siginfo);
1621 #endif /* SIGINFO */
1624 /* Let the user know what interface was chosen. */
1625 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1627 /* initialize capture stop conditions */
1628 init_capture_stop_conditions();
1629 /* create stop conditions */
1630 if (capture_opts.has_autostop_filesize)
1631 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1632 (long)capture_opts.autostop_filesize * 1000);
1633 if (capture_opts.has_autostop_duration)
1634 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1635 (gint32)capture_opts.autostop_duration);
1637 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1638 cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT,
1639 capture_opts.ringbuffer_duration);
1641 if (!setjmp(ld.stopenv)) {
1643 ld.packet_count = 0;
1647 /* We need to be careful with automatic variables defined in the
1648 outer scope which are changed inside the loop. Most compilers
1649 don't try to roll them back to their original values after the
1650 longjmp which causes the loop to finish, but all that the
1651 standards say is that their values are indeterminate. If we
1652 don't want them to be rolled back, we should define them with the
1653 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1654 Programming in the UNIX Environment, p. 178).
1656 The "err" variable causes a particular problem. If we give it
1657 the volatile attribute, then when we pass a reference to it (as
1658 in "&err") to a function, GCC warns: "passing arg <n> of
1659 <function> discards qualifiers from pointer target type".
1660 Therefore within the loop and just beyond we don't use "err".
1661 Within the loop we define "loop_err", and assign its value to
1662 "volatile_err", which is in the outer scope and is checked when
1665 We also define "packet_count_prev" here to keep things tidy,
1666 since it's used only inside the loop. If it were defined in the
1667 outer scope, GCC would give a warning (unnecessary in this case)
1668 that it might be clobbered, and we'd need to give it the volatile
1669 attribute to suppress the warning. */
1672 int packet_count_prev = 0;
1674 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1675 /* We're not stopping at a particular capture file size, and we're
1676 not stopping after some particular amount of time has expired,
1677 so either we have no stop condition or the only stop condition
1678 is a maximum packet count.
1680 If there's no maximum packet count, pass it -1, meaning "until
1681 you run out of packets in the bufferful you read". Otherwise,
1682 pass it the number of packets we have left to capture.
1684 We don't call "pcap_loop()" as, if we're saving to a file that's
1685 a FIFO, we want to flush the FIFO after we're done processing
1686 this libpcap bufferful of packets, so that the program
1687 reading the FIFO sees the packets immediately and doesn't get
1688 any partial packet, forcing it to block in the middle of reading
1690 if (capture_opts.autostop_count == 0)
1693 if (ld.packet_count >= capture_opts.autostop_count) {
1694 /* XXX do we need this test here? */
1695 /* It appears there's nothing more to capture. */
1698 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1701 /* We need to check the capture file size or the timeout after
1707 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1708 errmsg, sizeof errmsg);
1711 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1713 /* Error from "pcap_dispatch()", or error or "no more packets" from
1714 "pipe_dispatch(). */
1716 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1717 /* The specified capture time has elapsed; stop the capture. */
1719 } else if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
1720 /* time elasped for this ring file, swith to the next */
1721 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1722 /* File switch succeeded: reset the condition */
1723 cnd_reset(cnd_ring_timeout);
1725 /* File switch failed: stop here */
1728 } else if (inpkts > 0) {
1729 if (capture_opts.autostop_count != 0 &&
1730 ld.packet_count >= capture_opts.autostop_count) {
1731 /* The specified number of packets have been captured and have
1732 passed both any capture filter in effect and any read filter
1735 } else if (cnd_stop_capturesize != NULL &&
1736 cnd_eval(cnd_stop_capturesize,
1737 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1738 /* We're saving the capture to a file, and the capture file reached
1739 its maximum size. */
1740 if (capture_opts.ringbuffer_on) {
1741 /* Switch to the next ringbuffer file */
1742 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1743 /* File switch succeeded: reset the condition */
1744 cnd_reset(cnd_stop_capturesize);
1745 if (cnd_ring_timeout) {
1746 cnd_reset(cnd_ring_timeout);
1749 /* File switch failed: stop here */
1750 volatile_err = loop_err;
1754 /* No ringbuffer - just stop. */
1758 if (ld.output_to_pipe) {
1759 if (ld.packet_count > packet_count_prev) {
1760 if (fflush(wtap_dump_file(ld.pdh))) {
1761 volatile_err = errno;
1764 packet_count_prev = ld.packet_count;
1768 } /* while (ld.go) */
1770 /* delete stop conditions */
1771 if (cnd_stop_capturesize != NULL)
1772 cnd_delete(cnd_stop_capturesize);
1773 if (cnd_stop_timeout != NULL)
1774 cnd_delete(cnd_stop_timeout);
1775 if (cnd_ring_timeout != NULL)
1776 cnd_delete(cnd_ring_timeout);
1778 if ((cfile.save_file != NULL) && !quiet) {
1779 /* We're saving to a file, which means we're printing packet counts
1780 to stderr if we are not running silent and deep.
1781 Send a newline so that we move to the line after the packet count. */
1782 fprintf(stderr, "\n");
1785 /* If we got an error while capturing, report it. */
1789 if (ld.pipe_err == PIPERR) {
1790 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1796 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1797 pcap_geterr(ld.pch));
1801 if (volatile_err == 0)
1804 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
1808 if (cfile.save_file != NULL) {
1809 /* We're saving to a file or files; close all files. */
1810 if (capture_opts.ringbuffer_on) {
1811 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1813 dump_ok = wtap_dump_close(ld.pdh, &err);
1815 /* If we've displayed a message about a write error, there's no point
1816 in displaying another message about an error on close. */
1817 if (!dump_ok && !write_err)
1818 show_capture_file_io_error(cfile.save_file, err, TRUE);
1822 if (ld.from_pipe && pipe_fd >= 0)
1827 /* Get the capture statistics, and, if any packets were dropped, report
1829 if (pcap_stats(ld.pch, &stats) >= 0) {
1830 if (stats.ps_drop != 0) {
1831 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1834 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
1835 pcap_geterr(ld.pch));
1840 /* Report the number of captured packets if not reported during capture
1841 and we are saving to a file. */
1847 if (capture_opts.ringbuffer_on) {
1848 ringbuf_error_cleanup();
1850 g_free(cfile.save_file);
1851 cfile.save_file = NULL;
1852 fprintf(stderr, "tethereal: %s\n", errmsg);
1868 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
1871 struct wtap_pkthdr whdr;
1872 union wtap_pseudo_header pseudo_header;
1873 loop_data *ld = (loop_data *) user;
1877 /* Convert from libpcap to Wiretap format.
1878 If that fails, ignore the packet (wtap_process_pcap_packet has
1879 written an error message). */
1880 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
1889 wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1890 /* Report packet capture count if not quiet */
1893 if (ld->packet_count != 0) {
1894 fprintf(stderr, "\r%u ", ld->packet_count);
1895 /* stderr could be line buffered */
1899 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
1900 &pseudo_header, pd);
1904 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1910 capture_cleanup(DWORD ctrltype _U_)
1912 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1913 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1914 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1915 like SIGTERM at least when the machine's shutting down.
1917 For now, we handle them all as indications that we should clean up
1918 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1921 However, as handlers run in a new thread, we can't just longjmp
1922 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1923 no other handler - such as one that would terminate the process -
1926 XXX - for some reason, typing ^C to Tethereal, if you run this in
1927 a Cygwin console window in at least some versions of Cygwin,
1928 causes Tethereal to terminate immediately; this routine gets
1929 called, but the main loop doesn't get a chance to run and
1930 exit cleanly, at least if this is compiled with Microsoft Visual
1931 C++ (i.e., it's a property of the Cygwin console window or Bash;
1932 it happens if Tethereal is not built with Cygwin - for all I know,
1933 building it with Cygwin may make the problem go away). */
1939 capture_cleanup(int signum _U_)
1941 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1942 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1943 "ld.go" to FALSE and return, we won't break out of it and quit
1945 longjmp(ld.stopenv, 1);
1953 /* XXX - if we use sigaction, this doesn't have to be done.
1954 (Yes, this isn't necessary on BSD, but just in case a system
1955 where "signal()" has AT&T semantics adopts SIGINFO....) */
1956 signal(SIGINFO, report_counts_siginfo);
1957 #endif /* SIGINFO */
1959 if (cfile.save_file != NULL && quiet) {
1960 /* Report the count only if we're capturing to a file (rather
1961 than printing captured packet information out) and aren't
1962 updating a count as packets arrive. */
1963 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1966 infoprint = FALSE; /* we just reported it */
1967 #endif /* SIGINFO */
1972 report_counts_siginfo(int signum _U_)
1974 int sav_errno = errno;
1975 /* If we've been told to delay printing, just set a flag asking
1976 that we print counts (if we're supposed to), otherwise print
1977 the count of packets captured (if we're supposed to). */
1984 #endif /* SIGINFO */
1985 #endif /* HAVE_LIBPCAP */
1988 load_cap_file(capture_file *cf, int out_file_type)
1991 int snapshot_length;
1997 linktype = wtap_file_encap(cf->wth);
1998 if (cf->save_file != NULL) {
1999 /* Set up to write to the capture file. */
2000 snapshot_length = wtap_snapshot_length(cf->wth);
2001 if (snapshot_length == 0) {
2002 /* Snapshot length of input file not known. */
2003 snapshot_length = WTAP_MAX_PACKET_SIZE;
2005 pdh = wtap_dump_open(cf->save_file, out_file_type,
2006 linktype, snapshot_length, &err);
2009 /* We couldn't set up to write to the capture file. */
2012 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2014 "tethereal: Capture files can't be written in that format.\n");
2017 case WTAP_ERR_UNSUPPORTED_ENCAP:
2018 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2020 "tethereal: The capture file being read cannot be written in "
2024 case WTAP_ERR_CANT_OPEN:
2026 "tethereal: The file \"%s\" couldn't be created for some "
2027 "unknown reason.\n",
2028 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2031 case WTAP_ERR_SHORT_WRITE:
2033 "tethereal: A full header couldn't be written to the file \"%s\".\n",
2034 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2039 "tethereal: The file \"%s\" could not be created: %s\n.",
2040 *cf->save_file == '\0' ? "stdout" : cf->save_file,
2041 wtap_strerror(err));
2048 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
2051 /* Now close the capture file. */
2052 if (!wtap_dump_close(pdh, &err))
2053 show_capture_file_io_error(cfile.save_file, err, TRUE);
2057 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
2061 /* Print up a message box noting that the read failed somewhere along
2065 case WTAP_ERR_UNSUPPORTED_ENCAP:
2067 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
2071 case WTAP_ERR_CANT_READ:
2073 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2077 case WTAP_ERR_SHORT_READ:
2079 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2083 case WTAP_ERR_BAD_RECORD:
2085 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
2091 "tethereal: An error occurred while reading \"%s\": %s.\n",
2092 cf->filename, wtap_strerror(err));
2098 wtap_close(cf->wth);
2105 fill_in_fdata(frame_data *fdata, capture_file *cf,
2106 const struct wtap_pkthdr *phdr, long offset)
2111 fdata->num = cf->count;
2112 fdata->pkt_len = phdr->len;
2113 cul_bytes += phdr->len;
2114 fdata->cul_bytes = cul_bytes;
2115 fdata->cap_len = phdr->caplen;
2116 fdata->file_off = offset;
2117 fdata->lnk_t = phdr->pkt_encap;
2118 fdata->abs_secs = phdr->ts.tv_sec;
2119 fdata->abs_usecs = phdr->ts.tv_usec;
2120 fdata->flags.passed_dfilter = 0;
2121 fdata->flags.encoding = CHAR_ASCII;
2122 fdata->flags.visited = 0;
2123 fdata->flags.marked = 0;
2125 /* If we don't have the time stamp of the first packet in the
2126 capture, it's because this is the first packet. Save the time
2127 stamp of this packet as the time stamp of the first packet. */
2128 if (!firstsec && !firstusec) {
2129 firstsec = fdata->abs_secs;
2130 firstusec = fdata->abs_usecs;
2133 /* If we don't have the time stamp of the previous displayed packet,
2134 it's because this is the first displayed packet. Save the time
2135 stamp of this packet as the time stamp of the previous displayed
2137 if (!prevsec && !prevusec) {
2138 prevsec = fdata->abs_secs;
2139 prevusec = fdata->abs_usecs;
2142 /* Get the time elapsed between the first packet and this packet. */
2143 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2144 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2146 /* If it's greater than the current elapsed time, set the elapsed time
2147 to it (we check for "greater than" so as not to be confused by
2148 time moving backwards). */
2149 if ((gint32)cf->esec < fdata->rel_secs
2150 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2151 cf->esec = fdata->rel_secs;
2152 cf->eusec = fdata->rel_usecs;
2155 /* Get the time elapsed between the previous displayed packet and
2157 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2158 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2159 prevsec = fdata->abs_secs;
2160 prevusec = fdata->abs_usecs;
2163 /* Free up all data attached to a "frame_data" structure. */
2165 clear_fdata(frame_data *fdata)
2168 g_slist_free(fdata->pfd);
2172 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
2173 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2175 cb_args_t *args = (cb_args_t *) user;
2176 capture_file *cf = args->cf;
2177 wtap_dumper *pdh = args->pdh;
2181 epan_dissect_t *edt;
2186 * Prevent a SIGINFO handler from writing to stdout while we're
2187 * doing so; instead, have it just set a flag telling us to print
2188 * that information when we're done.
2191 #endif /* SIGINFO */
2192 #endif /* HAVE_LIBPCAP */
2196 fill_in_fdata(&fdata, cf, phdr, offset);
2197 edt = epan_dissect_new(TRUE, FALSE);
2198 epan_dissect_prime_dfilter(edt, cf->rfcode);
2199 epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
2200 passed = dfilter_apply_edt(cf->rfcode, edt);
2206 /* The packet passed the read filter. */
2210 if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
2212 if (ld.pch != NULL && !quiet) {
2213 /* We're capturing packets, so (if -q not specified) we're printing
2214 a count of packets captured; move to the line after the count. */
2215 fprintf(stderr, "\n");
2218 show_capture_file_io_error(cf->save_file, err, FALSE);
2223 wtap_dump_close(pdh, &err);
2228 epan_dissect_free(edt);
2230 clear_fdata(&fdata);
2235 * Allow SIGINFO handlers to write.
2240 * If a SIGINFO handler asked us to write out capture counts, do so.
2244 #endif /* SIGINFO */
2245 #endif /* HAVE_LIBPCAP */
2249 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2258 "tethereal: Not all the packets could be written to \"%s\" because there is "
2259 "no space left on the file system.\n",
2266 "tethereal: Not all the packets could be written to \"%s\" because you are "
2267 "too close to, or over your disk quota.\n",
2272 case WTAP_ERR_CANT_CLOSE:
2274 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2278 case WTAP_ERR_SHORT_WRITE:
2280 "tethereal: Not all the packets could be written to \"%s\".\n",
2287 "tethereal: \"%s\" could not be closed: %s.\n",
2288 fname, wtap_strerror(err));
2291 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2292 fname, wtap_strerror(err));
2299 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
2300 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
2302 cb_args_t *args = (cb_args_t *) user;
2303 capture_file *cf = args->cf;
2306 print_args_t print_args;
2307 epan_dissect_t *edt;
2308 gboolean create_proto_tree;
2313 fill_in_fdata(&fdata, cf, phdr, offset);
2315 /* Grab any resolved addresses */
2316 if (g_resolv_flags) {
2317 host_name_lookup_process(NULL);
2321 if (cf->rfcode || verbose || num_tap_filters!=0)
2322 create_proto_tree = TRUE;
2324 create_proto_tree = FALSE;
2325 /* The protocol tree will be "visible", i.e., printed, only if we're
2326 not printing a summary.
2328 We only need the columns if we're *not* verbose; in verbose mode,
2329 we print the protocol tree, not the protocol summary. */
2331 edt = epan_dissect_new(create_proto_tree, verbose);
2333 epan_dissect_prime_dfilter(edt, cf->rfcode);
2336 tap_queue_init(edt);
2337 epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
2338 tap_push_tapped_queue(edt);
2341 passed = dfilter_apply_edt(cf->rfcode, edt);
2344 /* The packet passed the read filter. */
2349 /* Print the information in the protocol tree. */
2350 print_args.to_file = TRUE;
2351 print_args.format = PR_FMT_TEXT;
2352 print_args.print_summary = FALSE;
2353 print_args.print_hex = print_hex;
2354 print_args.expand_all = TRUE;
2355 print_args.suppress_unmarked = FALSE;
2356 proto_tree_print(&print_args, edt, stdout);
2358 /* "print_hex_data()" will put out a leading blank line, as well
2359 as a trailing one; print one here, to separate the packets,
2360 only if "print_hex_data()" won't be called. */
2364 /* Just fill in the columns. */
2365 epan_dissect_fill_in_columns(edt);
2367 /* Now print them. */
2368 for (i = 0; i < cf->cinfo.num_cols; i++) {
2369 switch (cf->cinfo.col_fmt[i]) {
2372 * Don't print this if we're doing a live capture from a network
2373 * interface - if we're doing a live capture, you won't be
2374 * able to look at the capture in the future (it's not being
2375 * saved anywhere), so the frame numbers are unlikely to be
2378 * (XXX - it might be nice to be able to save and print at
2379 * the same time, sort of like an "Update list of packets
2380 * in real time" capture in Ethereal.)
2382 if (cf->iface != NULL)
2384 printf("%3s", cf->cinfo.col_data[i]);
2390 case COL_ABS_DATE_TIME: /* XXX - wider */
2391 printf("%10s", cf->cinfo.col_data[i]);
2397 case COL_DEF_DL_SRC:
2398 case COL_RES_DL_SRC:
2399 case COL_UNRES_DL_SRC:
2400 case COL_DEF_NET_SRC:
2401 case COL_RES_NET_SRC:
2402 case COL_UNRES_NET_SRC:
2403 printf("%12s", cf->cinfo.col_data[i]);
2409 case COL_DEF_DL_DST:
2410 case COL_RES_DL_DST:
2411 case COL_UNRES_DL_DST:
2412 case COL_DEF_NET_DST:
2413 case COL_RES_NET_DST:
2414 case COL_UNRES_NET_DST:
2415 printf("%-12s", cf->cinfo.col_data[i]);
2419 printf("%s", cf->cinfo.col_data[i]);
2422 if (i != cf->cinfo.num_cols - 1) {
2424 * This isn't the last column, so we need to print a
2425 * separator between this column and the next.
2427 * If we printed a network source and are printing a
2428 * network destination of the same type next, separate
2429 * them with "->"; if we printed a network destination
2430 * and are printing a network source of the same type
2431 * next, separate them with "<-"; otherwise separate them
2434 switch (cf->cinfo.col_fmt[i]) {
2439 switch (cf->cinfo.col_fmt[i + 1]) {
2453 case COL_DEF_DL_SRC:
2454 case COL_RES_DL_SRC:
2455 case COL_UNRES_DL_SRC:
2456 switch (cf->cinfo.col_fmt[i + 1]) {
2458 case COL_DEF_DL_DST:
2459 case COL_RES_DL_DST:
2460 case COL_UNRES_DL_DST:
2470 case COL_DEF_NET_SRC:
2471 case COL_RES_NET_SRC:
2472 case COL_UNRES_NET_SRC:
2473 switch (cf->cinfo.col_fmt[i + 1]) {
2475 case COL_DEF_NET_DST:
2476 case COL_RES_NET_DST:
2477 case COL_UNRES_NET_DST:
2490 switch (cf->cinfo.col_fmt[i + 1]) {
2504 case COL_DEF_DL_DST:
2505 case COL_RES_DL_DST:
2506 case COL_UNRES_DL_DST:
2507 switch (cf->cinfo.col_fmt[i + 1]) {
2509 case COL_DEF_DL_SRC:
2510 case COL_RES_DL_SRC:
2511 case COL_UNRES_DL_SRC:
2521 case COL_DEF_NET_DST:
2522 case COL_RES_NET_DST:
2523 case COL_UNRES_NET_DST:
2524 switch (cf->cinfo.col_fmt[i + 1]) {
2526 case COL_DEF_NET_SRC:
2527 case COL_RES_NET_SRC:
2528 case COL_UNRES_NET_SRC:
2547 print_hex_data(stdout, print_args.format, edt);
2552 /* The ANSI C standard does not appear to *require* that a line-buffered
2553 stream be flushed to the host environment whenever a newline is
2554 written, it just says that, on such a stream, characters "are
2555 intended to be transmitted to or from the host environment as a
2556 block when a new-line character is encountered".
2558 The Visual C++ 6.0 C implementation doesn't do what is intended;
2559 even if you set a stream to be line-buffered, it still doesn't
2560 flush the buffer at the end of every line.
2562 So, if the "-l" flag was specified, we flush the standard output
2563 at the end of a packet. This will do the right thing if we're
2564 printing packet summary lines, and, as we print the entire protocol
2565 tree for a single packet without waiting for anything to happen,
2566 it should be as good as line-buffered mode if we're printing
2567 protocol trees. (The whole reason for the "-l" flag in either
2568 tcpdump or Tethereal is to allow the output of a live capture to
2569 be piped to a program or script and to have that script see the
2570 information for the packet as soon as it's printed, rather than
2571 having to wait until a standard I/O buffer fills up. */
2575 epan_dissect_free(edt);
2577 clear_fdata(&fdata);
2581 file_open_error_message(int err, gboolean for_writing, int file_type)
2584 static char errmsg_errno[1024+1];
2588 case WTAP_ERR_NOT_REGULAR_FILE:
2589 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2592 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2593 case WTAP_ERR_UNSUPPORTED:
2594 /* Seen only when opening a capture file for reading. */
2595 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
2598 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2599 /* Seen only when opening a capture file for writing. */
2600 snprintf(errmsg_errno, sizeof(errmsg_errno),
2601 "The file \"%%s\" is a pipe, and %s capture files cannot be "
2602 "written to a pipe.", wtap_file_type_string(file_type));
2603 errmsg = errmsg_errno;
2606 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2607 /* Seen only when opening a capture file for writing. */
2608 errmsg = "Tethereal does not support writing capture files in that format.";
2611 case WTAP_ERR_UNSUPPORTED_ENCAP:
2612 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2614 errmsg = "Tethereal cannot save this capture in that format.";
2616 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2619 case WTAP_ERR_BAD_RECORD:
2620 errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2623 case WTAP_ERR_CANT_OPEN:
2625 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2627 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2630 case WTAP_ERR_SHORT_READ:
2631 errmsg = "The file \"%s\" appears to have been cut short"
2632 " in the middle of a packet or other data.";
2635 case WTAP_ERR_SHORT_WRITE:
2636 errmsg = "A full header couldn't be written to the file \"%s\".";
2641 errmsg = "The path to the file \"%s\" does not exist.";
2643 errmsg = "The file \"%s\" does not exist.";
2648 errmsg = "You do not have permission to create or write to the file \"%s\".";
2650 errmsg = "You do not have permission to read the file \"%s\".";
2654 errmsg = "\"%s\" is a directory (folder), not a file.";
2658 snprintf(errmsg_errno, sizeof(errmsg_errno),
2659 "The file \"%%s\" could not be %s: %s.",
2660 for_writing ? "created" : "opened",
2661 wtap_strerror(err));
2662 errmsg = errmsg_errno;
2669 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
2673 char err_msg[2048+1];
2675 wth = wtap_open_offline(fname, &err, FALSE);
2679 /* The open succeeded. Fill in the information for this file. */
2681 /* Initialize all data structures used for dissection. */
2685 cf->filed = -1; /* not used, but set it anyway */
2686 cf->f_len = 0; /* not used, but set it anyway */
2688 /* Set the file name because we need it to set the follow stream filter.
2689 XXX - is that still true? We need it for other reasons, though,
2691 cf->filename = g_strdup(fname);
2693 /* Indicate whether it's a permanent or temporary file. */
2694 cf->is_tempfile = is_tempfile;
2696 /* If it's a temporary capture buffer file, mark it as not saved. */
2697 cf->user_saved = !is_tempfile;
2699 cf->cd_t = wtap_file_type(cf->wth);
2701 cf->drops_known = FALSE;
2705 cf->snap = wtap_snapshot_length(cf->wth);
2706 if (cf->snap == 0) {
2707 /* Snapshot length not known. */
2708 cf->has_snap = FALSE;
2709 cf->snap = WTAP_MAX_PACKET_SIZE;
2711 cf->has_snap = TRUE;
2712 cf->progbar_quantum = 0;
2713 cf->progbar_nextstep = 0;
2714 firstsec = 0, firstusec = 0;
2715 prevsec = 0, prevusec = 0;
2720 snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE, 0),
2722 fprintf(stderr, "tethereal: %s\n", err_msg);
2728 /* Take care of byte order in the libpcap headers read from pipes.
2729 * (function taken from wiretap/libpcap.c) */
2731 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
2733 if (ld->byte_swapped) {
2734 /* Byte-swap the record header fields. */
2735 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
2736 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
2737 rechdr->incl_len = BSWAP32(rechdr->incl_len);
2738 rechdr->orig_len = BSWAP32(rechdr->orig_len);
2741 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
2742 swapped, in order to match the BPF header layout.
2744 Unfortunately, some files were, according to a comment in the "libpcap"
2745 source, written with version 2.3 in their headers but without the
2746 interchanged fields, so if "incl_len" is greater than "orig_len" - which
2747 would make no sense - we assume that we need to swap them. */
2748 if (hdr->version_major == 2 &&
2749 (hdr->version_minor < 3 ||
2750 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
2753 temp = rechdr->orig_len;
2754 rechdr->orig_len = rechdr->incl_len;
2755 rechdr->incl_len = temp;
2759 /* Mimic pcap_open_live() for pipe captures
2760 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
2762 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2763 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2765 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
2766 char *errmsg, int errmsgl)
2768 struct stat pipe_stat;
2772 unsigned int bytes_read;
2775 * XXX Tethereal blocks until we return
2777 if (strcmp(pipename, "-") == 0)
2778 fd = 0; /* read from stdin */
2780 if (stat(pipename, &pipe_stat) < 0) {
2781 if (errno == ENOENT || errno == ENOTDIR)
2782 ld->pipe_err = PIPNEXIST;
2784 snprintf(errmsg, errmsgl,
2785 "The capture session could not be initiated "
2786 "due to error on pipe: %s", strerror(errno));
2787 ld->pipe_err = PIPERR;
2791 if (! S_ISFIFO(pipe_stat.st_mode)) {
2792 if (S_ISCHR(pipe_stat.st_mode)) {
2794 * Assume the user specified an interface on a system where
2795 * interfaces are in /dev. Pretend we haven't seen it.
2797 ld->pipe_err = PIPNEXIST;
2799 snprintf(errmsg, errmsgl,
2800 "The capture session could not be initiated because\n"
2801 "\"%s\" is neither an interface nor a pipe", pipename);
2802 ld->pipe_err = PIPERR;
2806 fd = open(pipename, O_RDONLY);
2808 snprintf(errmsg, errmsgl,
2809 "The capture session could not be initiated "
2810 "due to error on pipe open: %s", strerror(errno));
2811 ld->pipe_err = PIPERR;
2816 ld->from_pipe = TRUE;
2818 /* read the pcap header */
2820 while (bytes_read < sizeof magic) {
2821 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
2824 snprintf(errmsg, errmsgl, "End of file on pipe during open");
2826 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
2835 /* Host that wrote it has our byte order, and was running
2836 a program using either standard or ss990417 libpcap. */
2837 ld->byte_swapped = FALSE;
2838 ld->modified = FALSE;
2840 case PCAP_MODIFIED_MAGIC:
2841 /* Host that wrote it has our byte order, but was running
2842 a program using either ss990915 or ss991029 libpcap. */
2843 ld->byte_swapped = FALSE;
2844 ld->modified = TRUE;
2846 case PCAP_SWAPPED_MAGIC:
2847 /* Host that wrote it has a byte order opposite to ours,
2848 and was running a program using either standard or
2849 ss990417 libpcap. */
2850 ld->byte_swapped = TRUE;
2851 ld->modified = FALSE;
2853 case PCAP_SWAPPED_MODIFIED_MAGIC:
2854 /* Host that wrote it out has a byte order opposite to
2855 ours, and was running a program using either ss990915
2856 or ss991029 libpcap. */
2857 ld->byte_swapped = TRUE;
2858 ld->modified = TRUE;
2861 /* Not a "libpcap" type we know about. */
2862 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2866 /* Read the rest of the header */
2868 while (bytes_read < sizeof(struct pcap_hdr)) {
2869 b = read(fd, ((char *)hdr)+bytes_read,
2870 sizeof(struct pcap_hdr) - bytes_read);
2873 snprintf(errmsg, errmsgl, "End of file on pipe during open");
2875 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
2882 if (ld->byte_swapped) {
2883 /* Byte-swap the header fields about which we care. */
2884 hdr->version_major = BSWAP16(hdr->version_major);
2885 hdr->version_minor = BSWAP16(hdr->version_minor);
2886 hdr->snaplen = BSWAP32(hdr->snaplen);
2887 hdr->network = BSWAP32(hdr->network);
2890 if (hdr->version_major < 2) {
2891 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2895 ld->pipe_state = STATE_EXPECT_REC_HDR;
2896 ld->pipe_err = PIPOK;
2900 ld->pipe_err = PIPERR;
2905 /* We read one record from the pipe, take care of byte order in the record
2906 * header, write the record in the capture file, and update capture statistics. */
2909 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
2910 struct pcaprec_modified_hdr *rechdr, guchar *data,
2911 char *errmsg, int errmsgl)
2913 struct pcap_pkthdr phdr;
2915 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2918 switch (ld->pipe_state) {
2920 case STATE_EXPECT_REC_HDR:
2921 ld->bytes_to_read = ld->modified ?
2922 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2924 ld->pipe_state = STATE_READ_REC_HDR;
2927 case STATE_READ_REC_HDR:
2928 b = read(fd, ((char *)rechdr)+ld->bytes_read,
2929 ld->bytes_to_read - ld->bytes_read);
2932 result = PD_PIPE_EOF;
2934 result = PD_PIPE_ERR;
2937 if ((ld->bytes_read += b) < ld->bytes_to_read)
2939 result = PD_REC_HDR_READ;
2942 case STATE_EXPECT_DATA:
2944 ld->pipe_state = STATE_READ_DATA;
2947 case STATE_READ_DATA:
2948 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
2951 result = PD_PIPE_EOF;
2953 result = PD_PIPE_ERR;
2956 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
2958 result = PD_DATA_READ;
2962 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
2965 } /* switch (ld->pipe_state) */
2968 * We've now read as much data as we were expecting, so process it.
2972 case PD_REC_HDR_READ:
2973 /* We've read the header. Take care of byte order. */
2974 adjust_header(ld, hdr, &rechdr->hdr);
2975 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2976 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2977 ld->packet_count+1, rechdr->hdr.incl_len);
2980 ld->pipe_state = STATE_EXPECT_DATA;
2984 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2985 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
2986 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
2987 phdr.caplen = rechdr->hdr.incl_len;
2988 phdr.len = rechdr->hdr.orig_len;
2990 capture_pcap_cb((guchar *)ld, &phdr, data);
2992 ld->pipe_state = STATE_EXPECT_REC_HDR;
2996 ld->pipe_err = PIPEOF;
3000 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3007 ld->pipe_err = PIPERR;
3008 /* Return here rather than inside the switch to prevent GCC warning */
3012 #endif /* HAVE_LIBPCAP */