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.
27 /* With MSVC and a libethereal.dll this file needs to import some variables
28 in a special way. Therefore _NEED_VAR_IMPORT_ is defined. */
29 #define _NEED_VAR_IMPORT_
59 #ifdef HAVE_SYS_STAT_H
60 # include <sys/stat.h>
63 #ifdef NEED_SNPRINTF_H
64 # include "snprintf.h"
67 #ifdef NEED_STRERROR_H
75 #include "svnversion.h"
78 #include <epan/epan.h>
79 #include <epan/filesystem.h>
82 #include <epan/timestamp.h>
83 #include <epan/packet.h>
85 #include "disabled_protos.h"
86 #include <epan/prefs.h>
89 #include <epan/addr_resolv.h>
91 #include "clopts_common.h"
92 #include "version_info.h"
94 #include "pcap-util.h"
96 #include <epan/conversation.h>
97 #include <epan/plugins.h>
99 #include "conditions.h"
100 #include "capture_stop_conditions.h"
101 #include "ringbuffer.h"
102 #include <epan/epan_dissect.h>
103 #include <epan/tap.h>
104 #include <epan/timestamp.h>
107 #include <wiretap/wtap-capture.h>
108 #include <wiretap/libpcap.h>
112 #include "capture-wpcap.h"
116 * This is the template for the decode as option; it is shared between the
117 * various functions that output the usage for this parameter.
119 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
121 static guint32 firstsec, firstusec;
122 static guint32 prevsec, prevusec;
123 static GString *comp_info_str, *runtime_info_str;
124 static gboolean quiet;
126 static gboolean print_packet_info; /* TRUE if we're to print packet information */
128 * The way the packet decode is to be written.
131 WRITE_TEXT, /* summary or detail text */
132 WRITE_XML /* PDML or PSML */
133 /* Add CSV and the like here */
135 static output_action_e output_action;
136 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
137 static gboolean verbose;
138 static gboolean print_hex;
139 static gboolean line_buffered;
140 static guint32 cum_bytes = 0;
141 static print_format_e print_format = PR_FMT_TEXT;
142 static print_stream_t *print_stream;
145 typedef struct _loop_data {
146 gboolean go; /* TRUE as long as we're supposed to keep capturing */
148 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
152 gboolean output_to_pipe;
155 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
156 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
157 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
159 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
160 STATE_EXPECT_DATA, STATE_READ_DATA
163 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
169 static int capture(int);
170 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
172 static void report_counts(void);
174 static BOOL WINAPI capture_cleanup(DWORD);
176 static void capture_cleanup(int);
178 static void report_counts_siginfo(int);
181 #endif /* HAVE_LIBPCAP */
183 static int load_cap_file(capture_file *, int);
184 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
185 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
186 const guchar *pd, int *err);
187 static void show_capture_file_io_error(const char *, int, gboolean);
188 static void show_print_file_io_error(int err);
189 static gboolean write_preamble(capture_file *cf);
190 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
191 static gboolean write_finale(void);
192 static char *cf_open_error_message(int err, gchar *err_info,
193 gboolean for_writing, int file_type);
196 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
197 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
198 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
199 struct pcaprec_modified_hdr *, guchar *, char *, int);
203 static void open_failure_message(const char *filename, int err,
204 gboolean for_writing);
205 static void failure_message(const char *msg_format, va_list ap);
206 static void read_failure_message(const char *filename, int err);
211 int snaplen; /* Maximum captured packet length */
212 int promisc_mode; /* Capture in promiscuous mode */
213 int autostop_count; /* Maximum packet count */
214 gboolean has_autostop_duration; /* TRUE if maximum capture duration
216 gint32 autostop_duration; /* Maximum capture duration */
217 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
219 gint32 autostop_filesize; /* Maximum capture file size */
220 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
221 guint32 ringbuffer_num_files; /* Number of ring buffer files */
222 gboolean has_ring_duration; /* TRUE if ring duration specified */
223 gint32 ringbuffer_duration; /* Switch file after n seconds */
224 int linktype; /* Data link type to use, or -1 for
228 static capture_options capture_opts = {
229 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
230 infinite, in effect */
231 TRUE, /* promiscuous mode is the default */
232 0, /* max packet count - default is 0,
234 FALSE, /* maximum capture duration not
235 specified by default */
236 0, /* maximum capture duration */
237 FALSE, /* maximum capture file size not
238 specified by default */
239 0, /* maximum capture file size */
240 FALSE, /* ring buffer off by default */
241 RINGBUFFER_MIN_NUM_FILES, /* default number of ring buffer
243 FALSE, /* Switch ring file after some */
244 0, /* specified time is off by default */
245 -1 /* Default to not change link type */
248 static gboolean list_link_layer_types;
251 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
252 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
254 #endif /* HAVE_LIBPCAP */
257 print_usage(gboolean print_ver)
264 fprintf(output, "This is GNU t" PACKAGE " " VERSION
268 "\n (C) 1998-2004 Gerald Combs <gerald@ethereal.com>"
271 comp_info_str->str, runtime_info_str->str);
276 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
278 fprintf(output, "\t[ -b <number of ring buffer files>[:<duration>] ] [ -c <count> ]\n");
279 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
280 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <interface> ]\n");
281 fprintf(output, "\t[ -N <resolving> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
282 fprintf(output, "\t[ -R <read filter> ] [ -s <snaplen> ] [ -t <time stamp format> ]\n");
283 fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -y <link type> ]\n");
284 fprintf(output, "\t[ -z <statistics string> ]\n");
286 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
287 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
288 fprintf(output, "\t[ -F <output file type> ] [ -N <resolving> ]\n");
289 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
290 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ] [ -w <savefile> ]\n");
291 fprintf(output, "\t[ -z <statistics string> ]\n");
293 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
294 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
295 if (wtap_dump_can_open(i))
296 fprintf(output, "\t%s - %s\n",
297 wtap_file_type_short_string(i), wtap_file_type_string(i));
299 fprintf(output, "\tdefault is libpcap\n");
304 get_natural_int(const char *string, const char *name)
309 number = strtol(string, &p, 10);
310 if (p == string || *p != '\0') {
311 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
316 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
320 if (number > INT_MAX) {
321 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
329 get_positive_int(const char *string, const char *name)
333 number = get_natural_int(string, name);
336 fprintf(stderr, "tethereal: The specified %s is zero\n",
345 * Given a string of the form "<autostop criterion>:<value>", as might appear
346 * as an argument to a "-a" option, parse it and set the criterion in
347 * question. Return an indication of whether it succeeded or failed
351 set_autostop_criterion(const char *autostoparg)
355 colonp = strchr(autostoparg, ':');
363 * Skip over any white space (there probably won't be any, but
364 * as we allow it in the preferences file, we might as well
371 * Put the colon back, so if our caller uses, in an
372 * error message, the string they passed us, the message
378 if (strcmp(autostoparg,"duration") == 0) {
379 capture_opts.has_autostop_duration = TRUE;
380 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
381 } else if (strcmp(autostoparg,"filesize") == 0) {
382 capture_opts.has_autostop_filesize = TRUE;
383 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
387 *colonp = ':'; /* put the colon back */
392 * Given a string of the form "<ring buffer file>:<duration>", as might appear
393 * as an argument to a "-b" option, parse it and set the arguments in
394 * question. Return an indication of whether it succeeded or failed
398 get_ring_arguments(const char *arg)
400 guchar *p = NULL, *colonp;
402 colonp = strchr(arg, ':');
404 if (colonp != NULL) {
409 capture_opts.ringbuffer_num_files =
410 get_natural_int(arg, "number of ring buffer files");
416 * Skip over any white space (there probably won't be any, but
417 * as we allow it in the preferences file, we might as well
424 * Put the colon back, so if our caller uses, in an
425 * error message, the string they passed us, the message
432 capture_opts.has_ring_duration = TRUE;
433 capture_opts.ringbuffer_duration = get_positive_int(p,
434 "ring buffer duration");
436 *colonp = ':'; /* put the colon back */
441 /* structure to keep track of what tap listeners have been registered.
443 typedef struct _ethereal_tap_list {
444 struct _ethereal_tap_list *next;
446 void (*func)(char *arg);
448 static ethereal_tap_list *tap_list=NULL;
451 register_ethereal_tap(char *cmd, void (*func)(char *arg))
453 ethereal_tap_list *newtl;
455 newtl=malloc(sizeof(ethereal_tap_list));
456 newtl->next=tap_list;
464 * For a dissector table, print on the stream described by output,
465 * its short name (which is what's used in the "-d" option) and its
469 display_dissector_table_names(char *table_name, char *ui_name, gpointer output)
471 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
475 * For a dissector handle, print on the stream described by output,
476 * the filter name (which is what's used in the "-d" option) and the full
477 * name for the protocol that corresponds to this handle.
480 display_dissector_names(gchar *table _U_, gpointer handle, gpointer output)
483 const gchar* proto_filter_name;
484 const gchar* proto_ui_name;
486 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
488 if (proto_id != -1) {
489 proto_filter_name = proto_get_protocol_filter_name(proto_id);
490 proto_ui_name = proto_get_protocol_name(proto_id);
491 g_assert(proto_filter_name != NULL);
492 g_assert(proto_ui_name != NULL);
494 fprintf((FILE *)output, "\t%s (%s)\n",
501 * The protocol_name_search structure is used by find_protocol_name_func()
502 * to pass parameters and store results
504 struct protocol_name_search{
505 gchar *searched_name; /* Protocol filter name we are looking for */
506 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
507 guint nb_match; /* How many dissectors matched searched_name */
509 typedef struct protocol_name_search *protocol_name_search_t;
512 * This function parses all dissectors associated with a table to find the
513 * one whose protocol has the specified filter name. It is called
514 * as a reference function in a call to dissector_table_foreach_handle.
515 * The name we are looking for, as well as the results, are stored in the
516 * protocol_name_search struct pointed to by user_data.
517 * If called using dissector_table_foreach_handle, we actually parse the
518 * whole list of dissectors.
521 find_protocol_name_func(gchar *table _U_, gpointer handle, gpointer user_data)
525 const gchar *protocol_filter_name;
526 protocol_name_search_t search_info;
530 search_info = (protocol_name_search_t)user_data;
532 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
533 if (proto_id != -1) {
534 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
535 g_assert(protocol_filter_name != NULL);
536 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
538 if (search_info->nb_match == 0) {
539 /* Record this handle only if this is the first match */
540 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
542 search_info->nb_match++;
548 * Print all layer type names supported.
549 * We send the output to the stream described by the handle output.
553 fprint_all_layer_types(FILE *output)
556 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
560 * Print all protocol names supported for a specific layer type.
561 * table_name contains the layer type name in which the search is performed.
562 * We send the output to the stream described by the handle output.
566 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
569 dissector_table_foreach_handle(table_name,
570 display_dissector_names,
575 * The function below parses the command-line parameters for the decode as
576 * feature (a string pointer by cl_param).
577 * It checks the format of the command-line, searches for a matching table
578 * and dissector. If a table/dissector match is not found, we display a
579 * summary of the available tables/dissectors (on stderr) and return FALSE.
580 * If everything is fine, we get the "Decode as" preference activated,
581 * then we return TRUE.
584 add_decode_as(const gchar *cl_param)
588 gchar *decoded_param;
589 gchar *remaining_param;
591 gchar *dissector_str;
592 dissector_handle_t dissector_matching;
593 dissector_table_t table_matching;
594 ftenum_t dissector_table_selector_type;
595 struct protocol_name_search user_protocol_name;
597 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
600 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
601 g_assert(decoded_param);
602 strcpy(decoded_param, cl_param);
605 /* The lines below will parse this string (modifying it) to extract all
606 necessary information. Note that decoded_param is still needed since
607 strings are not copied - we just save pointers. */
609 /* This section extracts a layer type (table_name) from decoded_param */
610 table_name = decoded_param; /* Layer type string starts from beginning */
612 remaining_param = strchr(table_name, '=');
613 if (remaining_param == NULL) {
614 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
615 /* If the argument does not follow the template, carry on anyway to check
616 if the table name is at least correct. If remaining_param is NULL,
617 we'll exit anyway further down */
620 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
623 /* Remove leading and trailing spaces from the table name */
624 while ( table_name[0] == ' ' )
626 while ( table_name[strlen(table_name) - 1] == ' ' )
627 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
629 /* The following part searches a table matching with the layer type specified */
630 table_matching = NULL;
632 /* Look for the requested table */
633 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
634 fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
637 table_matching = find_dissector_table(table_name);
638 if (!table_matching) {
639 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 */
643 if (!table_matching) {
644 /* Display a list of supported layer types to help the user, if the
645 specified layer type was not found */
646 fprintf(stderr, "tethereal: Valid layer types are:\n");
647 fprint_all_layer_types(stderr);
649 if (remaining_param == NULL || !table_matching) {
650 /* Exit if the layer type was not found, or if no '=' separator was found
652 g_free(decoded_param);
656 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
657 fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
660 remaining_param++; /* Move to the second '=' */
661 *remaining_param = '\0'; /* Remove the second '=' */
663 remaining_param++; /* Position after the layer type string */
665 /* This section extracts a selector value (selector_str) from decoded_param */
667 selector_str = remaining_param; /* Next part starts with the selector number */
669 remaining_param = strchr(selector_str, ',');
670 if (remaining_param == NULL) {
671 fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
672 /* If the argument does not follow the template, carry on anyway to check
673 if the selector value is at least correct. If remaining_param is NULL,
674 we'll exit anyway further down */
677 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
680 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
682 switch (dissector_table_selector_type) {
688 /* The selector for this table is an unsigned number. Parse it as such.
689 There's no need to remove leading and trailing spaces from the
690 selector number string, because sscanf will do that for us. */
691 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
692 fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
693 g_free(decoded_param);
700 /* The selector for this table is a string. */
704 /* There are currently no dissector tables with any types other
705 than the ones listed above. */
706 g_assert_not_reached();
709 if (remaining_param == NULL) {
710 /* Exit if no ',' separator was found (see above) */
711 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
712 fprint_all_protocols_for_layer_types(stderr, table_name);
713 g_free(decoded_param);
717 remaining_param++; /* Position after the selector number string */
719 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
721 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
723 /* Remove leading and trailing spaces from the dissector name */
724 while ( dissector_str[0] == ' ' )
726 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
727 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
729 dissector_matching = NULL;
731 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
732 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 */
733 fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
736 user_protocol_name.nb_match = 0;
737 user_protocol_name.searched_name = dissector_str;
738 user_protocol_name.matched_handle = NULL;
740 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 */
742 if (user_protocol_name.nb_match != 0) {
743 dissector_matching = user_protocol_name.matched_handle;
744 if (user_protocol_name.nb_match > 1) {
745 fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
749 /* OK, check whether the problem is that there isn't any such
750 protocol, or that there is but it's not specified as a protocol
751 that's valid for that dissector table.
752 Note, we don't exit here, but dissector_matching will remain NULL,
754 if (proto_get_id_by_filter_name(dissector_str) == -1) {
755 /* No such protocol */
756 fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
758 fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
759 dissector_str, table_name);
764 if (!dissector_matching) {
765 fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
766 fprint_all_protocols_for_layer_types(stderr, table_name);
767 g_free(decoded_param);
771 /* This is the end of the code that parses the command-line options.
772 All information is now stored in the variables:
776 The above variables that are strings are still pointing to areas within
777 decoded_parm. decoded_parm thus still needs to be kept allocated in
778 until we stop needing these variables
779 decoded_param will be deallocated at each exit point of this function */
782 /* We now have a pointer to the handle for the requested dissector
783 (requested protocol) inside the variable dissector_matching */
784 switch (dissector_table_selector_type) {
790 /* The selector for this table is an unsigned number. */
791 dissector_change(table_name, selector, dissector_matching);
796 /* The selector for this table is a string. */
797 dissector_change_string(table_name, selector_str, dissector_matching);
801 /* There are currently no dissector tables with any types other
802 than the ones listed above. */
803 g_assert_not_reached();
805 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
810 main(int argc, char *argv[])
814 gboolean arg_error = FALSE;
820 char *gpf_path, *pf_path;
821 char *gdp_path, *dp_path;
822 int gpf_open_errno, gpf_read_errno;
823 int pf_open_errno, pf_read_errno;
824 int gdp_open_errno, gdp_read_errno;
825 int dp_open_errno, dp_read_errno;
828 gboolean capture_filter_specified = FALSE;
829 GList *if_list, *if_entry;
833 gchar err_str[PCAP_ERRBUF_SIZE];
834 gchar *cant_get_if_list_errstr;
836 gboolean capture_option_specified = FALSE;
838 int out_file_type = WTAP_FILE_PCAP;
839 gchar *cf_name = NULL, *rfilter = NULL;
842 GList *lt_list, *lt_entry;
843 data_link_info_t *data_link_info;
845 #ifdef HAVE_PCAP_OPEN_DEAD
846 struct bpf_program fcode;
848 dfilter_t *rfcode = NULL;
851 ethereal_tap_list *tli;
853 set_timestamp_setting(TS_RELATIVE);
855 /* Register all dissectors; we must do this before checking for the
856 "-G" flag, as the "-G" flag dumps information registered by the
857 dissectors, and we must do it before we read the preferences, in
858 case any dissectors register preferences. */
859 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
860 failure_message,open_failure_message,read_failure_message);
862 /* Register all tap listeners; we do this before we parse the arguments,
863 as the "-z" argument can specify a registered tap. */
864 register_all_tap_listeners();
866 /* Now register the preferences for any non-dissector modules.
867 We must do that before we read the preferences as well. */
868 prefs_register_modules();
870 /* If invoked with the "-G" flag, we dump out information based on
871 the argument to the "-G" flag; if no argument is specified,
872 for backwards compatibility we dump out a glossary of display
875 We do this here to mirror what happens in the GTK+ version, although
876 it's not necessary here. */
877 handle_dashG_option(argc, argv, "tethereal");
879 /* Set the C-language locale to the native environment. */
880 setlocale(LC_ALL, "");
882 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
883 &pf_open_errno, &pf_read_errno, &pf_path);
884 if (gpf_path != NULL) {
885 if (gpf_open_errno != 0) {
886 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
887 pf_path, strerror(gpf_open_errno));
889 if (gpf_read_errno != 0) {
890 fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
891 pf_path, strerror(gpf_read_errno));
894 if (pf_path != NULL) {
895 if (pf_open_errno != 0) {
896 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
897 strerror(pf_open_errno));
899 if (pf_read_errno != 0) {
900 fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
901 pf_path, strerror(pf_read_errno));
907 /* Set the name resolution code's flags from the preferences. */
908 g_resolv_flags = prefs->name_resolve;
910 /* Read the disabled protocols file. */
911 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
912 &dp_path, &dp_open_errno, &dp_read_errno);
913 if (gdp_path != NULL) {
914 if (gdp_open_errno != 0) {
916 "Could not open global disabled protocols file\n\"%s\": %s.\n",
917 gdp_path, strerror(gdp_open_errno));
919 if (gdp_read_errno != 0) {
921 "I/O error reading global disabled protocols file\n\"%s\": %s.\n",
922 gdp_path, strerror(gdp_read_errno));
926 if (dp_path != NULL) {
927 if (dp_open_errno != 0) {
929 "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
930 strerror(dp_open_errno));
932 if (dp_read_errno != 0) {
934 "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
935 strerror(dp_read_errno));
941 /* Load Wpcap, if possible */
945 init_cap_file(&cfile);
947 /* Assemble the compile-time version information string */
948 comp_info_str = g_string_new("Compiled ");
949 get_compiled_version_info(comp_info_str);
951 /* Assemble the run-time version information string */
952 runtime_info_str = g_string_new("Running ");
953 get_runtime_version_info(runtime_info_str);
955 /* Print format defaults to this. */
956 print_format = PR_FMT_TEXT;
958 /* Now get our args */
959 while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vw:Vxy:z:")) != -1) {
961 case 'a': /* autostop criteria */
963 if (set_autostop_criterion(optarg) == FALSE) {
964 fprintf(stderr, "tethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
968 capture_option_specified = TRUE;
972 case 'b': /* Ringbuffer option */
974 capture_opts.ringbuffer_on = TRUE;
975 if (get_ring_arguments(optarg) == FALSE) {
976 fprintf(stderr, "tethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
980 capture_option_specified = TRUE;
984 case 'c': /* Capture xxx packets */
986 capture_opts.autostop_count =
987 get_positive_int(optarg, "packet count");
989 capture_option_specified = TRUE;
993 case 'd': /* Decode as rule */
994 if (!add_decode_as(optarg))
997 case 'D': /* Print a list of capture devices */
999 if_list = get_interface_list(&err, err_str);
1000 if (if_list == NULL) {
1003 case CANT_GET_INTERFACE_LIST:
1004 cant_get_if_list_errstr =
1005 cant_get_if_list_error_message(err_str);
1006 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1007 g_free(cant_get_if_list_errstr);
1010 case NO_INTERFACES_FOUND:
1011 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1016 i = 1; /* Interface id number */
1017 for (if_entry = g_list_first(if_list); if_entry != NULL;
1018 if_entry = g_list_next(if_entry)) {
1019 if_info = if_entry->data;
1020 printf("%d. %s", i++, if_info->name);
1021 if (if_info->description != NULL)
1022 printf(" (%s)", if_info->description);
1025 free_interface_list(if_list);
1028 capture_option_specified = TRUE;
1034 capture_filter_specified = TRUE;
1036 g_free(cfile.cfilter);
1037 cfile.cfilter = g_strdup(optarg);
1039 capture_option_specified = TRUE;
1044 out_file_type = wtap_short_string_to_file_type(optarg);
1045 if (out_file_type < 0) {
1046 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
1051 case 'h': /* Print help and exit */
1055 case 'i': /* Use interface xxx */
1058 * If the argument is a number, treat it as an index into the list
1059 * of adapters, as printed by "tethereal -D".
1061 * This should be OK on UNIX systems, as interfaces shouldn't have
1062 * names that begin with digits. It can be useful on Windows, where
1063 * more than one interface can have the same name.
1065 adapter_index = strtol(optarg, &p, 10);
1066 if (p != NULL && *p == '\0') {
1067 if (adapter_index < 0) {
1069 "tethereal: The specified adapter index is a negative number\n");
1072 if (adapter_index > INT_MAX) {
1074 "tethereal: The specified adapter index is too large (greater than %d)\n",
1078 if (adapter_index == 0) {
1079 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1082 if_list = get_interface_list(&err, err_str);
1083 if (if_list == NULL) {
1086 case CANT_GET_INTERFACE_LIST:
1087 cant_get_if_list_errstr =
1088 cant_get_if_list_error_message(err_str);
1089 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1090 g_free(cant_get_if_list_errstr);
1093 case NO_INTERFACES_FOUND:
1094 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1099 if_info = g_list_nth_data(if_list, adapter_index - 1);
1100 if (if_info == NULL) {
1101 fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1104 cfile.iface = g_strdup(if_info->name);
1105 free_interface_list(if_list);
1107 cfile.iface = g_strdup(optarg);
1109 capture_option_specified = TRUE;
1113 case 'l': /* "Line-buffer" standard output */
1114 /* This isn't line-buffering, strictly speaking, it's just
1115 flushing the standard output after the information for
1116 each packet is printed; however, that should be good
1117 enough for all the purposes to which "-l" is put (and
1118 is probably actually better for "-V", as it does fewer
1121 See the comment in "process_packet()" for an explanation of
1122 why we do that, and why we don't just use "setvbuf()" to
1123 make the standard output line-buffered (short version: in
1124 Windows, "line-buffered" is the same as "fully-buffered",
1125 and the output buffer is only flushed when it fills up). */
1126 line_buffered = TRUE;
1128 case 'L': /* Print list of link-layer types and exit */
1130 list_link_layer_types = TRUE;
1133 capture_option_specified = TRUE;
1137 case 'n': /* No name resolution */
1138 g_resolv_flags = RESOLV_NONE;
1140 case 'N': /* Select what types of addresses/port #s to resolve */
1141 if (g_resolv_flags == RESOLV_ALL)
1142 g_resolv_flags = RESOLV_NONE;
1143 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1144 if (badopt != '\0') {
1145 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
1150 case 'o': /* Override preference from command line */
1151 switch (prefs_set_pref(optarg)) {
1153 case PREFS_SET_SYNTAX_ERR:
1154 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
1158 case PREFS_SET_NO_SUCH_PREF:
1159 case PREFS_SET_OBSOLETE:
1160 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
1166 case 'p': /* Don't capture in promiscuous mode */
1168 capture_opts.promisc_mode = FALSE;
1170 capture_option_specified = TRUE;
1174 case 'q': /* Quiet */
1177 case 'r': /* Read capture file xxx */
1178 cf_name = g_strdup(optarg);
1180 case 'R': /* Read file filter */
1183 case 's': /* Set the snapshot (capture) length */
1185 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
1187 capture_option_specified = TRUE;
1191 case 'S': /* show packets in real time */
1192 print_packet_info = TRUE;
1194 case 't': /* Time stamp type */
1195 if (strcmp(optarg, "r") == 0)
1196 set_timestamp_setting(TS_RELATIVE);
1197 else if (strcmp(optarg, "a") == 0)
1198 set_timestamp_setting(TS_ABSOLUTE);
1199 else if (strcmp(optarg, "ad") == 0)
1200 set_timestamp_setting(TS_ABSOLUTE_WITH_DATE);
1201 else if (strcmp(optarg, "d") == 0)
1202 set_timestamp_setting(TS_DELTA);
1204 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
1206 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
1207 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
1211 case 'T': /* printing Type */
1212 if (strcmp(optarg, "text") == 0) {
1213 output_action = WRITE_TEXT;
1214 print_format = PR_FMT_TEXT;
1215 } else if (strcmp(optarg, "ps") == 0) {
1216 output_action = WRITE_TEXT;
1217 print_format = PR_FMT_PS;
1218 } else if (strcmp(optarg, "pdml") == 0) {
1219 output_action = WRITE_XML;
1221 } else if (strcmp(optarg, "psml") == 0) {
1222 output_action = WRITE_XML;
1225 fprintf(stderr, "tethereal: Invalid -T parameter.\n");
1226 fprintf(stderr, "It must be \"ps\", \"text\", \"pdml\", or \"psml\".\n");
1230 case 'v': /* Show version and exit */
1231 printf("t" PACKAGE " " VERSION
1236 comp_info_str->str, runtime_info_str->str);
1239 case 'w': /* Write to capture file xxx */
1240 cfile.save_file = g_strdup(optarg);
1242 case 'V': /* Verbose */
1245 case 'x': /* Print packet data in hex (and ASCII) */
1248 case 'y': /* Set the pcap data link type */
1250 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
1251 capture_opts.linktype = pcap_datalink_name_to_val(optarg);
1252 if (capture_opts.linktype == -1) {
1253 fprintf(stderr, "tethereal: The specified data link type \"%s\" is not valid\n",
1257 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1258 /* XXX - just treat it as a number */
1259 capture_opts.linktype = get_natural_int(optarg, "data link type");
1260 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1262 capture_option_specified = TRUE;
1267 for(tli=tap_list;tli;tli=tli->next){
1268 if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
1269 (*tli->func)(optarg);
1274 fprintf(stderr,"tethereal: invalid -z argument.\n");
1275 fprintf(stderr," -z argument must be one of :\n");
1276 for(tli=tap_list;tli;tli=tli->next){
1277 fprintf(stderr," %s\n",tli->cmd);
1283 case '?': /* Bad flag - print usage message */
1289 /* If no capture filter or read filter has been specified, and there are
1290 still command-line arguments, treat them as the tokens of a capture
1291 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1292 flag was specified. */
1293 if (optind < argc) {
1294 if (cf_name != NULL) {
1295 if (rfilter != NULL) {
1297 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1300 rfilter = get_args_as_string(argc, argv, optind);
1303 if (capture_filter_specified) {
1305 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1308 cfile.cfilter = get_args_as_string(argc, argv, optind);
1310 capture_option_specified = TRUE;
1315 /* See if we're writing a capture file and the file is a pipe */
1317 ld.output_to_pipe = FALSE;
1319 if (cfile.save_file != NULL) {
1320 /* We're writing to a capture file. */
1321 if (strcmp(cfile.save_file, "-") == 0) {
1322 /* Write to the standard output. */
1323 g_free(cfile.save_file);
1324 cfile.save_file = g_strdup("");
1326 /* XXX - should we check whether it's a pipe? It's arguably
1327 silly to do "-w - >output_file" rather than "-w output_file",
1328 but by not checking we might be violating the Principle Of
1329 Least Astonishment. */
1330 ld.output_to_pipe = TRUE;
1335 err = test_for_fifo(cfile.save_file);
1338 case ENOENT: /* it doesn't exist, so we'll be creating it,
1339 and it won't be a FIFO */
1340 case 0: /* found it, but it's not a FIFO */
1343 case ESPIPE: /* it is a FIFO */
1344 ld.output_to_pipe = TRUE;
1347 default: /* couldn't stat it */
1349 "tethereal: Error testing whether capture file is a pipe: %s\n",
1356 /* We're not writing to a file, so we should print packet information
1357 unless "-q" was specified. */
1359 print_packet_info = TRUE;
1362 #ifndef HAVE_LIBPCAP
1363 if (capture_option_specified)
1364 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1371 /* We don't support capture filters when reading from a capture file
1372 (the BPF compiler doesn't support all link-layer types that we
1373 support in capture files we read). */
1375 if (cf_name != NULL) {
1376 if (capture_filter_specified) {
1378 "tethereal: Only read filters, not capture filters, can be specified when reading a capture file.\n");
1385 if (output_action != WRITE_TEXT) {
1386 fprintf(stderr, "tethereal: Raw packet hex data can only be printed as text or PostScript\n");
1392 if (list_link_layer_types) {
1393 /* We're supposed to list the link-layer types for an interface;
1394 did the user also specify a capture file to be read? */
1396 /* Yes - that's bogus. */
1397 fprintf(stderr, "tethereal: You cannot specify -L and a capture file to be read.\n");
1400 /* No - did they specify a ring buffer option? */
1401 if (capture_opts.ringbuffer_on) {
1402 fprintf(stderr, "tethereal: Ring buffer requested, but a capture is not being done.\n");
1406 /* If they didn't specify a "-w" flag, but specified a maximum capture
1407 file size, tell them that this doesn't work, and exit. */
1408 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
1409 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1410 "capture isn't being saved to a file.\n");
1414 if (capture_opts.ringbuffer_on) {
1415 /* Ring buffer works only under certain conditions:
1416 a) ring buffer does not work if you're not saving the capture to
1418 b) ring buffer only works if you're saving in libpcap format;
1419 c) it makes no sense to enable the ring buffer if the maximum
1420 file size is set to "infinite";
1421 d) file must not be a pipe. */
1422 if (cfile.save_file == NULL) {
1423 fprintf(stderr, "tethereal: Ring buffer requested, but "
1424 "capture isn't being saved to a file.\n");
1427 if (out_file_type != WTAP_FILE_PCAP) {
1428 fprintf(stderr, "tethereal: Ring buffer requested, but "
1429 "capture isn't being saved in libpcap format.\n");
1432 if (!capture_opts.has_autostop_filesize) {
1433 fprintf(stderr, "tethereal: Ring buffer requested, but "
1434 "no maximum capture file size was specified.\n");
1437 if (ld.output_to_pipe) {
1438 fprintf(stderr, "tethereal: Ring buffer requested, but "
1439 "capture file is a pipe.\n");
1447 /* Start windows sockets */
1448 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1451 /* Notify all registered modules that have had any of their preferences
1452 changed either from one of the preferences file or from the command
1453 line that their preferences have changed. */
1456 /* disabled protocols as per configuration file */
1457 if (gdp_path == NULL && dp_path == NULL) {
1458 set_disabled_protos_list();
1461 /* Build the column format array */
1462 col_setup(&cfile.cinfo, prefs->num_cols);
1463 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1464 cfile.cinfo.col_fmt[i] = get_column_format(i);
1465 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1466 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1468 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1469 cfile.cinfo.col_data[i] = NULL;
1470 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1471 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1473 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1474 cfile.cinfo.col_fence[i] = 0;
1475 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1476 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1479 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1482 for (j = 0; j < NUM_COL_FMTS; j++) {
1483 if (!cfile.cinfo.fmt_matx[i][j])
1486 if (cfile.cinfo.col_first[j] == -1)
1487 cfile.cinfo.col_first[j] = i;
1488 cfile.cinfo.col_last[j] = i;
1493 if (capture_opts.snaplen < 1)
1494 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1495 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1496 capture_opts.snaplen = MIN_PACKET_SIZE;
1498 /* Check the value range of the ringbuffer_num_files parameter */
1499 if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
1500 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
1501 #if RINGBUFFER_MIN_NUM_FILES > 0
1502 else if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
1503 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
1507 if (rfilter != NULL) {
1508 if (!dfilter_compile(rfilter, &rfcode)) {
1509 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1511 #ifdef HAVE_PCAP_OPEN_DEAD
1515 p = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1517 if (pcap_compile(p, &fcode, rfilter, 0, 0) != -1) {
1519 " Note: That display filter code looks like a valid capture filter;\n"
1520 " maybe you mixed them up?\n");
1529 cfile.rfcode = rfcode;
1531 if (print_packet_info) {
1532 /* If we're printing as text or PostScript, we have
1533 to create a print stream. */
1534 if (output_action == WRITE_TEXT) {
1535 switch (print_format) {
1538 print_stream = print_stream_text_stdio_new(stdout);
1542 print_stream = print_stream_ps_stdio_new(stdout);
1546 g_assert_not_reached();
1551 /* We have to dissect each packet if:
1553 we're printing information about each packet;
1555 we're using a read filter on the packets;
1557 we're using any taps. */
1558 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1562 * We're reading a capture file.
1567 * Immediately relinquish any set-UID or set-GID privileges we have;
1568 * we must not be allowed to read any capture files the user running
1569 * Tethereal can't open.
1575 err = cf_open(cf_name, FALSE, &cfile);
1580 err = load_cap_file(&cfile, out_file_type);
1587 /* No capture file specified, so we're supposed to do a live capture
1588 (or get a list of link-layer types for a live capture device);
1589 do we have support for live captures? */
1594 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1599 /* Yes; did the user specify an interface to use? */
1600 if (cfile.iface == NULL) {
1601 /* No - is a default specified in the preferences file? */
1602 if (prefs->capture_device != NULL) {
1604 if_text = strrchr(prefs->capture_device, ' ');
1605 if (if_text == NULL) {
1606 cfile.iface = g_strdup(prefs->capture_device);
1608 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1611 /* No - pick the first one from the list of interfaces. */
1612 if_list = get_interface_list(&err, err_str);
1613 if (if_list == NULL) {
1616 case CANT_GET_INTERFACE_LIST:
1617 cant_get_if_list_errstr =
1618 cant_get_if_list_error_message(err_str);
1619 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1620 g_free(cant_get_if_list_errstr);
1623 case NO_INTERFACES_FOUND:
1624 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1629 if_info = if_list->data; /* first interface */
1630 cfile.iface = g_strdup(if_info->name);
1631 free_interface_list(if_list);
1635 if (list_link_layer_types) {
1636 /* We were asked to list the link-layer types for an interface.
1637 Get the list of link-layer types for the capture device. */
1638 lt_list = get_pcap_linktype_list(cfile.iface, err_str);
1639 if (lt_list == NULL) {
1640 if (err_str[0] != '\0') {
1641 fprintf(stderr, "tethereal: The list of data link types for the capture device could not be obtained (%s).\n"
1642 "Please check to make sure you have sufficient permissions, and that\n"
1643 "you have the proper interface or pipe specified.\n", err_str);
1645 fprintf(stderr, "tethereal: The capture device has no data link types.\n");
1648 fprintf(stderr, "Data link types (use option -y to set):\n");
1649 for (lt_entry = lt_list; lt_entry != NULL;
1650 lt_entry = g_list_next(lt_entry)) {
1651 data_link_info = lt_entry->data;
1652 fprintf(stderr, " %s", data_link_info->name);
1653 if (data_link_info->description != NULL)
1654 fprintf(stderr, " (%s)", data_link_info->description);
1656 fprintf(stderr, " (not supported)");
1659 free_pcap_linktype_list(lt_list);
1663 capture(out_file_type);
1665 if (capture_opts.ringbuffer_on) {
1669 /* No - complain. */
1670 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1675 draw_tap_listeners(TRUE);
1682 /* Do the low-level work of a capture.
1683 Returns TRUE if it succeeds, FALSE otherwise. */
1685 static condition *volatile cnd_ring_timeout = NULL; /* this must be visible in process_packet */
1688 capture(int out_file_type)
1692 gchar open_err_str[PCAP_ERRBUF_SIZE];
1693 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1694 bpf_u_int32 netnum, netmask;
1695 struct bpf_program fcode;
1696 const char *set_linktype_err_str;
1698 int volatile volatile_err = 0;
1699 int volatile inpkts = 0;
1701 char errmsg[1024+1];
1702 condition *volatile cnd_stop_capturesize = NULL;
1703 condition *volatile cnd_stop_timeout = NULL;
1705 void (*oldhandler)(int);
1706 static const char ppamsg[] = "can't find PPA for ";
1708 volatile int pipe_fd = -1;
1709 struct pcap_hdr hdr;
1710 struct pcaprec_modified_hdr rechdr;
1711 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1713 struct pcap_stat stats;
1716 dfilter_t *rfcode = NULL;
1718 /* Initialize all data structures used for dissection. */
1721 ld.linktype = WTAP_ENCAP_UNKNOWN;
1724 /* Open the network interface to capture from it.
1725 Some versions of libpcap may put warnings into the error buffer
1726 if they succeed; to tell if that's happened, we have to clear
1727 the error buffer, and check if it's still a null string. */
1728 open_err_str[0] = '\0';
1729 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1730 capture_opts.promisc_mode, 1000, open_err_str);
1732 if (ld.pch != NULL) {
1733 /* setting the data link type only works on real interfaces */
1734 if (capture_opts.linktype != -1) {
1735 set_linktype_err_str = set_pcap_linktype(ld.pch, cfile.iface,
1736 capture_opts.linktype);
1737 if (set_linktype_err_str != NULL) {
1738 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1739 set_linktype_err_str);
1744 /* We couldn't open "cfile.iface" as a network device. */
1746 /* On Windows, we don't support capturing on pipes, so we give up. */
1748 /* On Win32 OSes, the capture devices are probably available to all
1749 users; don't warn about permissions problems.
1751 Do, however, warn that WAN devices aren't supported. */
1752 snprintf(errmsg, sizeof errmsg,
1753 "The capture session could not be initiated (%s).\n"
1754 "Please check that you have the proper interface specified.\n"
1756 "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
1757 "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
1758 "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
1759 "don't support capturing on PPP/WAN interfaces at all.\n",
1763 /* try to open cfile.iface as a pipe */
1764 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1766 if (pipe_fd == -1) {
1768 if (ld.pipe_err == PIPNEXIST) {
1769 /* Pipe doesn't exist, so output message for interface */
1771 /* If we got a "can't find PPA for XXX" message, warn the user (who
1772 is running Tethereal on HP-UX) that they don't have a version
1773 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1774 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1775 PPA for XXX" rather than "can't find PPA for XXX"). */
1776 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1779 "You are running Tethereal with a version of the libpcap library\n"
1780 "that doesn't handle HP-UX network devices well; this means that\n"
1781 "Tethereal may not be able to capture packets.\n"
1783 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1784 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1785 "packaged binary form from the Software Porting And Archive Centre\n"
1786 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1787 "at the URL lists a number of mirror sites.";
1790 snprintf(errmsg, sizeof errmsg,
1791 "The capture session could not be initiated (%s).\n"
1792 "Please check to make sure you have sufficient permissions, and that\n"
1793 "you have the proper interface or pipe specified.%s", open_err_str,
1797 * Else pipe (or file) does exist and pipe_open_live() has
1802 /* pipe_open_live() succeeded; don't want
1803 error message from pcap_open_live() */
1804 open_err_str[0] = '\0';
1810 * We've opened the capture device, so, if we're set-UID or set-GID,
1811 * relinquish those privileges.
1813 * XXX - if we have saved set-user-ID support, we should give up those
1814 * privileges immediately, and then reclaim them long enough to get
1815 * a list of network interfaces and to open one, and then give them
1816 * up again, so that stuff we do while processing the argument list,
1817 * reading the user's preferences, etc. is done as the real user and
1818 * group, not the effective user and group.
1824 if (cfile.cfilter && !ld.from_pipe) {
1825 /* A capture filter was specified; set it up. */
1826 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1828 * Well, we can't get the netmask for this interface; it's used
1829 * only for filters that check for broadcast IP addresses, so
1830 * we just warn the user, and punt and use 0.
1833 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1836 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1837 if (dfilter_compile(cfile.cfilter, &rfcode)) {
1838 snprintf(errmsg, sizeof errmsg,
1839 "Unable to parse capture filter string (%s).\n"
1840 " Interestingly enough, this looks like a valid display filter\n"
1841 " Are you sure you didn't mix them up?",
1842 pcap_geterr(ld.pch));
1844 snprintf(errmsg, sizeof errmsg,
1845 "Unable to parse capture filter string (%s).",
1846 pcap_geterr(ld.pch));
1850 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1851 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1852 pcap_geterr(ld.pch));
1857 /* Set up to write to the capture file. */
1860 pcap_encap = hdr.network;
1861 file_snaplen = hdr.snaplen;
1865 pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1866 file_snaplen = pcap_snapshot(ld.pch);
1868 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1869 if (cfile.save_file != NULL) {
1870 /* Set up to write to the capture file. */
1871 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1872 strcpy(errmsg, "The network you're capturing from is of a type"
1873 " that Tethereal doesn't support.");
1876 if (capture_opts.ringbuffer_on) {
1877 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1878 capture_opts.ringbuffer_num_files);
1879 if (cfile.save_file_fd != -1) {
1880 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1881 file_snaplen, &err);
1883 err = errno; /* "ringbuf_init()" failed */
1887 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1888 ld.linktype, file_snaplen, &err);
1891 if (ld.pdh == NULL) {
1892 snprintf(errmsg, sizeof errmsg,
1893 cf_open_error_message(err, NULL, TRUE, out_file_type),
1894 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1899 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1900 returned a warning; print it, but keep capturing. */
1901 if (open_err_str[0] != '\0')
1902 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1905 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1906 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1908 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1910 XXX - deal with signal semantics on various UNIX platforms. Or just
1911 use "sigaction()" and be done with it? */
1912 signal(SIGTERM, capture_cleanup);
1913 signal(SIGINT, capture_cleanup);
1914 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1915 signal(SIGHUP, oldhandler);
1918 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1919 quiet mode, report the number of packets we've captured. */
1920 signal(SIGINFO, report_counts_siginfo);
1921 #endif /* SIGINFO */
1924 /* Let the user know what interface was chosen. */
1925 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1927 /* initialize capture stop conditions */
1928 init_capture_stop_conditions();
1929 /* create stop conditions */
1930 if (capture_opts.has_autostop_filesize)
1931 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1932 (long)capture_opts.autostop_filesize * 1000);
1933 if (capture_opts.has_autostop_duration)
1934 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1935 (gint32)capture_opts.autostop_duration);
1937 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1938 cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT,
1939 capture_opts.ringbuffer_duration);
1941 if (!setjmp(ld.stopenv)) {
1943 ld.packet_count = 0;
1947 /* We need to be careful with automatic variables defined in the
1948 outer scope which are changed inside the loop. Most compilers
1949 don't try to roll them back to their original values after the
1950 longjmp which causes the loop to finish, but all that the
1951 standards say is that their values are indeterminate. If we
1952 don't want them to be rolled back, we should define them with the
1953 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1954 Programming in the UNIX Environment, p. 178).
1956 The "err" variable causes a particular problem. If we give it
1957 the volatile attribute, then when we pass a reference to it (as
1958 in "&err") to a function, GCC warns: "passing arg <n> of
1959 <function> discards qualifiers from pointer target type".
1960 Therefore within the loop and just beyond we don't use "err".
1961 Within the loop we define "loop_err", and assign its value to
1962 "volatile_err", which is in the outer scope and is checked when
1965 We also define "packet_count_prev" here to keep things tidy,
1966 since it's used only inside the loop. If it were defined in the
1967 outer scope, GCC would give a warning (unnecessary in this case)
1968 that it might be clobbered, and we'd need to give it the volatile
1969 attribute to suppress the warning. */
1972 int packet_count_prev = 0;
1974 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1975 /* We're not stopping at a particular capture file size, and we're
1976 not stopping after some particular amount of time has expired,
1977 so either we have no stop condition or the only stop condition
1978 is a maximum packet count.
1980 If there's no maximum packet count, pass it -1, meaning "until
1981 you run out of packets in the bufferful you read". Otherwise,
1982 pass it the number of packets we have left to capture.
1984 We don't call "pcap_loop()" as, if we're saving to a file that's
1985 a FIFO, we want to flush the FIFO after we're done processing
1986 this libpcap bufferful of packets, so that the program
1987 reading the FIFO sees the packets immediately and doesn't get
1988 any partial packet, forcing it to block in the middle of reading
1990 if (capture_opts.autostop_count == 0)
1993 if (ld.packet_count >= capture_opts.autostop_count) {
1994 /* XXX do we need this test here? */
1995 /* It appears there's nothing more to capture. */
1998 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
2001 /* We need to check the capture file size or the timeout after
2007 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
2008 errmsg, sizeof errmsg);
2011 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
2013 /* Error from "pcap_dispatch()", or error or "no more packets" from
2014 "pipe_dispatch(). */
2016 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
2017 /* The specified capture time has elapsed; stop the capture. */
2019 } else if (inpkts > 0) {
2020 if (capture_opts.autostop_count != 0 &&
2021 ld.packet_count >= capture_opts.autostop_count) {
2022 /* The specified number of packets have been captured and have
2023 passed both any capture filter in effect and any read filter
2026 } else if (cnd_stop_capturesize != NULL &&
2027 cnd_eval(cnd_stop_capturesize,
2028 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
2029 /* We're saving the capture to a file, and the capture file reached
2030 its maximum size. */
2031 if (capture_opts.ringbuffer_on) {
2032 /* Switch to the next ringbuffer file */
2033 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
2034 /* File switch succeeded: reset the condition */
2035 cnd_reset(cnd_stop_capturesize);
2036 if (cnd_ring_timeout) {
2037 cnd_reset(cnd_ring_timeout);
2040 /* File switch failed: stop here */
2041 volatile_err = loop_err;
2045 /* No ringbuffer - just stop. */
2049 if (ld.output_to_pipe) {
2050 if (ld.packet_count > packet_count_prev) {
2051 if (fflush(wtap_dump_file(ld.pdh))) {
2052 volatile_err = errno;
2055 packet_count_prev = ld.packet_count;
2059 } /* while (ld.go) */
2061 /* delete stop conditions */
2062 if (cnd_stop_capturesize != NULL)
2063 cnd_delete(cnd_stop_capturesize);
2064 if (cnd_stop_timeout != NULL)
2065 cnd_delete(cnd_stop_timeout);
2066 if (cnd_ring_timeout != NULL)
2067 cnd_delete(cnd_ring_timeout);
2069 if ((cfile.save_file != NULL) && !quiet) {
2070 /* We're saving to a file, which means we're printing packet counts
2071 to stderr if we are not running silent and deep.
2072 Send a newline so that we move to the line after the packet count. */
2073 fprintf(stderr, "\n");
2076 /* If we got an error while capturing, report it. */
2080 if (ld.pipe_err == PIPERR) {
2081 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2087 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2088 pcap_geterr(ld.pch));
2092 if (volatile_err == 0)
2095 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
2099 if (cfile.save_file != NULL) {
2100 /* We're saving to a file or files; close all files. */
2101 if (capture_opts.ringbuffer_on) {
2102 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
2104 dump_ok = wtap_dump_close(ld.pdh, &err);
2106 /* If we've displayed a message about a write error, there's no point
2107 in displaying another message about an error on close. */
2108 if (!dump_ok && !write_err)
2109 show_capture_file_io_error(cfile.save_file, err, TRUE);
2113 if (ld.from_pipe && pipe_fd >= 0)
2118 /* Get the capture statistics, and, if any packets were dropped, report
2120 if (pcap_stats(ld.pch, &stats) >= 0) {
2121 if (stats.ps_drop != 0) {
2122 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
2125 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
2126 pcap_geterr(ld.pch));
2131 /* Report the number of captured packets if not reported during capture
2132 and we are saving to a file. */
2138 if (capture_opts.ringbuffer_on) {
2139 ringbuf_error_cleanup();
2141 g_free(cfile.save_file);
2142 cfile.save_file = NULL;
2143 fprintf(stderr, "tethereal: %s\n", errmsg);
2159 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2162 struct wtap_pkthdr whdr;
2163 union wtap_pseudo_header pseudo_header;
2164 loop_data *ld = (loop_data *) user;
2168 /* Convert from libpcap to Wiretap format.
2169 If that fails, ignore the packet (wtap_process_pcap_packet has
2170 written an error message). */
2171 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2178 * Prevent a SIGINFO handler from writing to stdout while we're
2179 * doing so; instead, have it just set a flag telling us to print
2180 * that information when we're done.
2183 #endif /* SIGINFO */
2185 /* The current packet may have arrived after a very long silence,
2186 * way past the time to switch files. In order not to have
2187 * the first packet of a new series of events as the last
2188 * [or only] packet in the file, switch before writing!
2190 if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
2191 /* time elapsed for this ring file, switch to the next */
2192 if (ringbuf_switch_file(&cfile, &ld->pdh, &loop_err)) {
2193 /* File switch succeeded: reset the condition */
2194 cnd_reset(cnd_ring_timeout);
2196 /* File switch failed: stop here */
2197 /* XXX - we should do something with "loop_err" */
2202 if (!process_packet(&cfile, ld->pdh, 0, &whdr, &pseudo_header, pd, &err)) {
2203 /* Error writing to a capture file */
2205 /* We're capturing packets, so (if -q not specified) we're printing
2206 a count of packets captured; move to the line after the count. */
2207 fprintf(stderr, "\n");
2209 show_capture_file_io_error(cfile.save_file, err, FALSE);
2210 pcap_close(ld->pch);
2211 wtap_dump_close(ld->pdh, &err);
2217 * Allow SIGINFO handlers to write.
2222 * If a SIGINFO handler asked us to write out capture counts, do so.
2226 #endif /* SIGINFO */
2231 capture_cleanup(DWORD ctrltype _U_)
2233 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2234 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2235 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2236 like SIGTERM at least when the machine's shutting down.
2238 For now, we handle them all as indications that we should clean up
2239 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2242 However, as handlers run in a new thread, we can't just longjmp
2243 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2244 no other handler - such as one that would terminate the process -
2247 XXX - for some reason, typing ^C to Tethereal, if you run this in
2248 a Cygwin console window in at least some versions of Cygwin,
2249 causes Tethereal to terminate immediately; this routine gets
2250 called, but the main loop doesn't get a chance to run and
2251 exit cleanly, at least if this is compiled with Microsoft Visual
2252 C++ (i.e., it's a property of the Cygwin console window or Bash;
2253 it happens if Tethereal is not built with Cygwin - for all I know,
2254 building it with Cygwin may make the problem go away). */
2260 capture_cleanup(int signum _U_)
2262 /* Longjmp back to the starting point; "pcap_dispatch()", on many
2263 UNIX platforms, just keeps looping if it gets EINTR, so if we set
2264 "ld.go" to FALSE and return, we won't break out of it and quit
2266 longjmp(ld.stopenv, 1);
2274 /* XXX - if we use sigaction, this doesn't have to be done.
2275 (Yes, this isn't necessary on BSD, but just in case a system
2276 where "signal()" has AT&T semantics adopts SIGINFO....) */
2277 signal(SIGINFO, report_counts_siginfo);
2278 #endif /* SIGINFO */
2280 if (quiet || print_packet_info) {
2281 /* Report the count only if we aren't printing a packet count
2282 as packets arrive. */
2283 fprintf(stderr, "%u packets captured\n", ld.packet_count);
2286 infoprint = FALSE; /* we just reported it */
2287 #endif /* SIGINFO */
2292 report_counts_siginfo(int signum _U_)
2294 int sav_errno = errno;
2295 /* If we've been told to delay printing, just set a flag asking
2296 that we print counts (if we're supposed to), otherwise print
2297 the count of packets captured (if we're supposed to). */
2304 #endif /* SIGINFO */
2305 #endif /* HAVE_LIBPCAP */
2308 load_cap_file(capture_file *cf, int out_file_type)
2311 int snapshot_length;
2317 linktype = wtap_file_encap(cf->wth);
2318 if (cf->save_file != NULL) {
2319 /* Set up to write to the capture file. */
2320 snapshot_length = wtap_snapshot_length(cf->wth);
2321 if (snapshot_length == 0) {
2322 /* Snapshot length of input file not known. */
2323 snapshot_length = WTAP_MAX_PACKET_SIZE;
2325 pdh = wtap_dump_open(cf->save_file, out_file_type,
2326 linktype, snapshot_length, &err);
2329 /* We couldn't set up to write to the capture file. */
2332 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2334 "tethereal: Capture files can't be written in that format.\n");
2337 case WTAP_ERR_UNSUPPORTED_ENCAP:
2338 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2340 "tethereal: The capture file being read cannot be written in "
2344 case WTAP_ERR_CANT_OPEN:
2346 "tethereal: The file \"%s\" couldn't be created for some "
2347 "unknown reason.\n",
2348 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2351 case WTAP_ERR_SHORT_WRITE:
2353 "tethereal: A full header couldn't be written to the file \"%s\".\n",
2354 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2359 "tethereal: The file \"%s\" could not be created: %s\n.",
2360 *cf->save_file == '\0' ? "stdout" : cf->save_file,
2361 wtap_strerror(err));
2367 if (!write_preamble(cf)) {
2369 show_print_file_io_error(err);
2374 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2375 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
2376 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2378 /* Error writing to a capture file */
2379 show_capture_file_io_error(cf->save_file, err, FALSE);
2380 wtap_dump_close(pdh, &err);
2385 /* Print a message noting that the read failed somewhere along the line. */
2388 case WTAP_ERR_UNSUPPORTED_ENCAP:
2390 "tethereal: \"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)\n",
2391 cf->filename, err_info);
2394 case WTAP_ERR_CANT_READ:
2396 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2400 case WTAP_ERR_SHORT_READ:
2402 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2406 case WTAP_ERR_BAD_RECORD:
2408 "tethereal: \"%s\" appears to be damaged or corrupt.\n(%s)\n",
2409 cf->filename, err_info);
2414 "tethereal: An error occurred while reading \"%s\": %s.\n",
2415 cf->filename, wtap_strerror(err));
2418 if (cf->save_file != NULL) {
2419 /* Now close the capture file. */
2420 if (!wtap_dump_close(pdh, &err))
2421 show_capture_file_io_error(cfile.save_file, err, TRUE);
2424 if (cf->save_file != NULL) {
2425 /* Now close the capture file. */
2426 if (!wtap_dump_close(pdh, &err))
2427 show_capture_file_io_error(cfile.save_file, err, TRUE);
2429 if (!write_finale()) {
2431 show_print_file_io_error(err);
2437 wtap_close(cf->wth);
2444 fill_in_fdata(frame_data *fdata, capture_file *cf,
2445 const struct wtap_pkthdr *phdr, long offset)
2450 fdata->num = cf->count;
2451 fdata->pkt_len = phdr->len;
2452 cum_bytes += phdr->len;
2453 fdata->cum_bytes = cum_bytes;
2454 fdata->cap_len = phdr->caplen;
2455 fdata->file_off = offset;
2456 fdata->lnk_t = phdr->pkt_encap;
2457 fdata->abs_secs = phdr->ts.tv_sec;
2458 fdata->abs_usecs = phdr->ts.tv_usec;
2459 fdata->flags.passed_dfilter = 0;
2460 fdata->flags.encoding = CHAR_ASCII;
2461 fdata->flags.visited = 0;
2462 fdata->flags.marked = 0;
2463 fdata->flags.ref_time = 0;
2465 /* If we don't have the time stamp of the first packet in the
2466 capture, it's because this is the first packet. Save the time
2467 stamp of this packet as the time stamp of the first packet. */
2468 if (!firstsec && !firstusec) {
2469 firstsec = fdata->abs_secs;
2470 firstusec = fdata->abs_usecs;
2473 /* If we don't have the time stamp of the previous displayed packet,
2474 it's because this is the first displayed packet. Save the time
2475 stamp of this packet as the time stamp of the previous displayed
2477 if (!prevsec && !prevusec) {
2478 prevsec = fdata->abs_secs;
2479 prevusec = fdata->abs_usecs;
2482 /* Get the time elapsed between the first packet and this packet. */
2483 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2484 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2486 /* If it's greater than the current elapsed time, set the elapsed time
2487 to it (we check for "greater than" so as not to be confused by
2488 time moving backwards). */
2489 if ((gint32)cf->esec < fdata->rel_secs
2490 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2491 cf->esec = fdata->rel_secs;
2492 cf->eusec = fdata->rel_usecs;
2495 /* Get the time elapsed between the previous displayed packet and
2497 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2498 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2499 prevsec = fdata->abs_secs;
2500 prevusec = fdata->abs_usecs;
2503 /* Free up all data attached to a "frame_data" structure. */
2505 clear_fdata(frame_data *fdata)
2508 g_slist_free(fdata->pfd);
2512 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2513 const struct wtap_pkthdr *whdr,
2514 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2518 gboolean create_proto_tree;
2519 epan_dissect_t *edt;
2522 /* Count this packet. */
2525 /* If we're going to print packet information, or we're going to
2526 run a read filter, or we're going to process taps, set up to
2527 do a dissection and do so. */
2528 if (do_dissection) {
2529 fill_in_fdata(&fdata, cf, whdr, offset);
2531 if (print_packet_info) {
2532 /* Grab any resolved addresses */
2534 if (g_resolv_flags) {
2535 host_name_lookup_process(NULL);
2540 if (cf->rfcode || verbose || num_tap_filters!=0)
2541 create_proto_tree = TRUE;
2543 create_proto_tree = FALSE;
2544 /* The protocol tree will be "visible", i.e., printed, only if we're
2545 printing packet details, which is true if we're printing stuff
2546 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2548 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2550 /* If we're running a read filter, prime the epan_dissect_t with that
2553 epan_dissect_prime_dfilter(edt, cf->rfcode);
2555 tap_queue_init(edt);
2557 /* We only need the columns if we're printing packet info but we're
2558 *not* verbose; in verbose mode, we print the protocol tree, not
2559 the protocol summary. */
2560 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2561 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2563 tap_push_tapped_queue(edt);
2565 /* Run the read filter if we have one. */
2567 passed = dfilter_apply_edt(cf->rfcode, edt);
2571 /* We're not running a display filter and we're not printing any
2572 packet information, so we don't need to do a dissection, and all
2573 packets are processed. */
2579 /* Count this packet. */
2584 /* Process this packet. */
2586 /* We're writing to a capture file; write this packet. */
2587 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2589 /* Report packet capture count if not quiet */
2590 if (!quiet && !print_packet_info) {
2591 /* Don't print a packet count if we were asked not to with "-q"
2592 or if we're also printing packet info. */
2593 if (ld.packet_count != 0) {
2594 fprintf(stderr, "\r%u ", ld.packet_count);
2595 /* stderr could be line buffered */
2600 if (print_packet_info) {
2601 /* We're printing packet information; print the information for
2603 print_packet(cf, edt);
2605 /* The ANSI C standard does not appear to *require* that a line-buffered
2606 stream be flushed to the host environment whenever a newline is
2607 written, it just says that, on such a stream, characters "are
2608 intended to be transmitted to or from the host environment as a
2609 block when a new-line character is encountered".
2611 The Visual C++ 6.0 C implementation doesn't do what is intended;
2612 even if you set a stream to be line-buffered, it still doesn't
2613 flush the buffer at the end of every line.
2615 So, if the "-l" flag was specified, we flush the standard output
2616 at the end of a packet. This will do the right thing if we're
2617 printing packet summary lines, and, as we print the entire protocol
2618 tree for a single packet without waiting for anything to happen,
2619 it should be as good as line-buffered mode if we're printing
2620 protocol trees. (The whole reason for the "-l" flag in either
2621 tcpdump or Tethereal is to allow the output of a live capture to
2622 be piped to a program or script and to have that script see the
2623 information for the packet as soon as it's printed, rather than
2624 having to wait until a standard I/O buffer fills up. */
2628 if (ferror(stdout)) {
2629 show_print_file_io_error(errno);
2635 if (do_dissection) {
2636 epan_dissect_free(edt);
2637 clear_fdata(&fdata);
2643 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2652 "tethereal: Not all the packets could be written to \"%s\" because there is "
2653 "no space left on the file system.\n",
2660 "tethereal: Not all the packets could be written to \"%s\" because you are "
2661 "too close to, or over your disk quota.\n",
2666 case WTAP_ERR_CANT_CLOSE:
2668 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2672 case WTAP_ERR_SHORT_WRITE:
2674 "tethereal: Not all the packets could be written to \"%s\".\n",
2681 "tethereal: \"%s\" could not be closed: %s.\n",
2682 fname, wtap_strerror(err));
2685 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2686 fname, wtap_strerror(err));
2693 write_preamble(capture_file *cf)
2695 switch (output_action) {
2698 return print_preamble(print_stream, cf->filename);
2703 write_pdml_preamble(stdout);
2705 write_psml_preamble(stdout);
2706 return !ferror(stdout);
2709 g_assert_not_reached();
2715 print_columns(capture_file *cf)
2717 static char *line_bufp = NULL;
2718 static size_t line_buf_len = 0;
2723 if (line_bufp == NULL) {
2725 line_bufp = g_malloc(line_buf_len + 1);
2729 for (i = 0; i < cf->cinfo.num_cols; i++) {
2730 switch (cf->cinfo.col_fmt[i]) {
2733 * Don't print this if we're doing a live capture from a network
2734 * interface - if we're doing a live capture, you won't be
2735 * able to look at the capture in the future (it's not being
2736 * saved anywhere), so the frame numbers are unlikely to be
2739 * (XXX - it might be nice to be able to save and print at
2740 * the same time, sort of like an "Update list of packets
2741 * in real time" capture in Ethereal.)
2743 if (cf->iface != NULL)
2745 column_len = strlen(cf->cinfo.col_data[i]);
2748 if (buf_offset + column_len > line_buf_len) {
2750 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2752 snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%3s", cf->cinfo.col_data[i]);
2758 case COL_ABS_DATE_TIME: /* XXX - wider */
2759 column_len = strlen(cf->cinfo.col_data[i]);
2760 if (column_len < 10)
2762 if (buf_offset + column_len > line_buf_len) {
2764 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2766 snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%10s", cf->cinfo.col_data[i]);
2772 case COL_DEF_DL_SRC:
2773 case COL_RES_DL_SRC:
2774 case COL_UNRES_DL_SRC:
2775 case COL_DEF_NET_SRC:
2776 case COL_RES_NET_SRC:
2777 case COL_UNRES_NET_SRC:
2778 column_len = strlen(cf->cinfo.col_data[i]);
2779 if (column_len < 12)
2781 if (buf_offset + column_len > line_buf_len) {
2783 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2785 snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%12s", cf->cinfo.col_data[i]);
2791 case COL_DEF_DL_DST:
2792 case COL_RES_DL_DST:
2793 case COL_UNRES_DL_DST:
2794 case COL_DEF_NET_DST:
2795 case COL_RES_NET_DST:
2796 case COL_UNRES_NET_DST:
2797 column_len = strlen(cf->cinfo.col_data[i]);
2798 if (column_len < 12)
2800 if (buf_offset + column_len > line_buf_len) {
2802 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2804 snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%-12s", cf->cinfo.col_data[i]);
2808 column_len = strlen(cf->cinfo.col_data[i]);
2809 if (buf_offset + column_len > line_buf_len) {
2811 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2813 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2816 buf_offset += column_len;
2817 if (i != cf->cinfo.num_cols - 1) {
2819 * This isn't the last column, so we need to print a
2820 * separator between this column and the next.
2822 * If we printed a network source and are printing a
2823 * network destination of the same type next, separate
2824 * them with "->"; if we printed a network destination
2825 * and are printing a network source of the same type
2826 * next, separate them with "<-"; otherwise separate them
2829 * We add enough space to the buffer for " <- " or " -> ",
2830 * even if we're only adding " ".
2832 if (buf_offset + 4 > line_buf_len) {
2834 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2836 switch (cf->cinfo.col_fmt[i]) {
2841 switch (cf->cinfo.col_fmt[i + 1]) {
2846 strcat(line_bufp + buf_offset, " -> ");
2851 strcat(line_bufp + buf_offset, " ");
2857 case COL_DEF_DL_SRC:
2858 case COL_RES_DL_SRC:
2859 case COL_UNRES_DL_SRC:
2860 switch (cf->cinfo.col_fmt[i + 1]) {
2862 case COL_DEF_DL_DST:
2863 case COL_RES_DL_DST:
2864 case COL_UNRES_DL_DST:
2865 strcat(line_bufp + buf_offset, " -> ");
2870 strcat(line_bufp + buf_offset, " ");
2876 case COL_DEF_NET_SRC:
2877 case COL_RES_NET_SRC:
2878 case COL_UNRES_NET_SRC:
2879 switch (cf->cinfo.col_fmt[i + 1]) {
2881 case COL_DEF_NET_DST:
2882 case COL_RES_NET_DST:
2883 case COL_UNRES_NET_DST:
2884 strcat(line_bufp + buf_offset, " -> ");
2889 strcat(line_bufp + buf_offset, " ");
2898 switch (cf->cinfo.col_fmt[i + 1]) {
2903 strcat(line_bufp + buf_offset, " <- ");
2908 strcat(line_bufp + buf_offset, " ");
2914 case COL_DEF_DL_DST:
2915 case COL_RES_DL_DST:
2916 case COL_UNRES_DL_DST:
2917 switch (cf->cinfo.col_fmt[i + 1]) {
2919 case COL_DEF_DL_SRC:
2920 case COL_RES_DL_SRC:
2921 case COL_UNRES_DL_SRC:
2922 strcat(line_bufp + buf_offset, " <- ");
2927 strcat(line_bufp + buf_offset, " ");
2933 case COL_DEF_NET_DST:
2934 case COL_RES_NET_DST:
2935 case COL_UNRES_NET_DST:
2936 switch (cf->cinfo.col_fmt[i + 1]) {
2938 case COL_DEF_NET_SRC:
2939 case COL_RES_NET_SRC:
2940 case COL_UNRES_NET_SRC:
2941 strcat(line_bufp + buf_offset, " <- ");
2946 strcat(line_bufp + buf_offset, " ");
2953 strcat(line_bufp + buf_offset, " ");
2959 return print_line(print_stream, 0, line_bufp);
2963 print_packet(capture_file *cf, epan_dissect_t *edt)
2965 print_args_t print_args;
2968 /* Print the information in the protocol tree. */
2969 switch (output_action) {
2972 print_args.to_file = TRUE;
2973 print_args.format = print_format;
2974 print_args.print_summary = !verbose;
2975 print_args.print_hex = verbose && print_hex;
2976 print_args.print_formfeed = FALSE;
2977 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2979 /* init the packet range */
2980 packet_range_init(&print_args.range);
2982 if (!proto_tree_print(&print_args, edt, print_stream))
2985 /* "print_hex_data()" will put out a leading blank line, as well
2986 as a trailing one; print one here, to separate the packets,
2987 only if "print_hex_data()" won't be called. */
2988 if (!print_line(print_stream, 0, ""))
2994 proto_tree_write_pdml(edt, stdout);
2996 return !ferror(stdout);
2999 /* Just fill in the columns. */
3000 epan_dissect_fill_in_columns(edt);
3002 /* Now print them. */
3003 switch (output_action) {
3006 if (!print_columns(cf))
3011 proto_tree_write_psml(edt, stdout);
3012 return !ferror(stdout);
3016 if (!print_hex_data(print_stream, edt))
3018 if (!print_line(print_stream, 0, ""))
3027 switch (output_action) {
3030 return print_finale(print_stream);
3035 write_pdml_finale(stdout);
3037 write_psml_finale(stdout);
3038 return !ferror(stdout);
3041 g_assert_not_reached();
3047 show_print_file_io_error(int err)
3053 "tethereal: Not all the packets could be printed because there is "
3054 "no space left on the file system.\n");
3060 "tethereal: Not all the packets could be printed because you are "
3061 "too close to, or over your disk quota.\n");
3067 "tethereal: An error occurred while printing packets: %s.\n",
3074 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3078 static char errmsg_errno[1024+1];
3081 /* Wiretap error. */
3084 case WTAP_ERR_NOT_REGULAR_FILE:
3085 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3088 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3089 /* Seen only when opening a capture file for reading. */
3090 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
3093 case WTAP_ERR_UNSUPPORTED:
3094 /* Seen only when opening a capture file for reading. */
3095 snprintf(errmsg_errno, sizeof(errmsg_errno),
3096 "The file \"%%s\" is not a capture file in a format Tethereal understands.\n"
3099 errmsg = errmsg_errno;
3102 case WTAP_ERR_CANT_WRITE_TO_PIPE:
3103 /* Seen only when opening a capture file for writing. */
3104 snprintf(errmsg_errno, sizeof(errmsg_errno),
3105 "The file \"%%s\" is a pipe, and %s capture files cannot be "
3106 "written to a pipe.", wtap_file_type_string(file_type));
3107 errmsg = errmsg_errno;
3110 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3111 /* Seen only when opening a capture file for writing. */
3112 errmsg = "Tethereal does not support writing capture files in that format.";
3115 case WTAP_ERR_UNSUPPORTED_ENCAP:
3117 errmsg = "Tethereal cannot save this capture in that format.";
3119 snprintf(errmsg_errno, sizeof(errmsg_errno),
3120 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
3123 errmsg = errmsg_errno;
3127 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3129 errmsg = "Tethereal cannot save this capture in that format.";
3131 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
3134 case WTAP_ERR_BAD_RECORD:
3135 /* Seen only when opening a capture file for reading. */
3136 snprintf(errmsg_errno, sizeof(errmsg_errno),
3137 "The file \"%%s\" appears to be damaged or corrupt.\n"
3140 errmsg = errmsg_errno;
3143 case WTAP_ERR_CANT_OPEN:
3145 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3147 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3150 case WTAP_ERR_SHORT_READ:
3151 errmsg = "The file \"%s\" appears to have been cut short"
3152 " in the middle of a packet or other data.";
3155 case WTAP_ERR_SHORT_WRITE:
3156 errmsg = "A full header couldn't be written to the file \"%s\".";
3160 snprintf(errmsg_errno, sizeof(errmsg_errno),
3161 "The file \"%%s\" could not be %s: %s.",
3162 for_writing ? "created" : "opened",
3163 wtap_strerror(err));
3164 errmsg = errmsg_errno;
3168 errmsg = file_open_error_message(err, for_writing);
3173 * Open/create errors are reported with an console message in Tethereal.
3176 open_failure_message(const char *filename, int err, gboolean for_writing)
3178 fprintf(stderr, "tethereal: ");
3179 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3180 fprintf(stderr, "\n");
3184 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
3189 char err_msg[2048+1];
3191 wth = wtap_open_offline(fname, &err, &err_info, FALSE);
3195 /* The open succeeded. Fill in the information for this file. */
3197 /* Initialize all data structures used for dissection. */
3201 cf->filed = -1; /* not used, but set it anyway */
3202 cf->f_len = 0; /* not used, but set it anyway */
3204 /* Set the file name because we need it to set the follow stream filter.
3205 XXX - is that still true? We need it for other reasons, though,
3207 cf->filename = g_strdup(fname);
3209 /* Indicate whether it's a permanent or temporary file. */
3210 cf->is_tempfile = is_tempfile;
3212 /* If it's a temporary capture buffer file, mark it as not saved. */
3213 cf->user_saved = !is_tempfile;
3215 cf->cd_t = wtap_file_type(cf->wth);
3217 cf->drops_known = FALSE;
3221 cf->snap = wtap_snapshot_length(cf->wth);
3222 if (cf->snap == 0) {
3223 /* Snapshot length not known. */
3224 cf->has_snap = FALSE;
3225 cf->snap = WTAP_MAX_PACKET_SIZE;
3227 cf->has_snap = TRUE;
3228 firstsec = 0, firstusec = 0;
3229 prevsec = 0, prevusec = 0;
3234 snprintf(err_msg, sizeof err_msg,
3235 cf_open_error_message(err, err_info, FALSE, 0), fname);
3236 fprintf(stderr, "tethereal: %s\n", err_msg);
3242 /* Take care of byte order in the libpcap headers read from pipes.
3243 * (function taken from wiretap/libpcap.c) */
3245 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
3247 if (ld->byte_swapped) {
3248 /* Byte-swap the record header fields. */
3249 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
3250 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
3251 rechdr->incl_len = BSWAP32(rechdr->incl_len);
3252 rechdr->orig_len = BSWAP32(rechdr->orig_len);
3255 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
3256 swapped, in order to match the BPF header layout.
3258 Unfortunately, some files were, according to a comment in the "libpcap"
3259 source, written with version 2.3 in their headers but without the
3260 interchanged fields, so if "incl_len" is greater than "orig_len" - which
3261 would make no sense - we assume that we need to swap them. */
3262 if (hdr->version_major == 2 &&
3263 (hdr->version_minor < 3 ||
3264 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
3267 temp = rechdr->orig_len;
3268 rechdr->orig_len = rechdr->incl_len;
3269 rechdr->incl_len = temp;
3273 /* Mimic pcap_open_live() for pipe captures
3274 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
3276 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
3277 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
3279 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
3280 char *errmsg, int errmsgl)
3282 struct stat pipe_stat;
3286 unsigned int bytes_read;
3289 * XXX Tethereal blocks until we return
3291 if (strcmp(pipename, "-") == 0)
3292 fd = 0; /* read from stdin */
3294 if (stat(pipename, &pipe_stat) < 0) {
3295 if (errno == ENOENT || errno == ENOTDIR)
3296 ld->pipe_err = PIPNEXIST;
3298 snprintf(errmsg, errmsgl,
3299 "The capture session could not be initiated "
3300 "due to error on pipe: %s", strerror(errno));
3301 ld->pipe_err = PIPERR;
3305 if (! S_ISFIFO(pipe_stat.st_mode)) {
3306 if (S_ISCHR(pipe_stat.st_mode)) {
3308 * Assume the user specified an interface on a system where
3309 * interfaces are in /dev. Pretend we haven't seen it.
3311 ld->pipe_err = PIPNEXIST;
3313 snprintf(errmsg, errmsgl,
3314 "The capture session could not be initiated because\n"
3315 "\"%s\" is neither an interface nor a pipe", pipename);
3316 ld->pipe_err = PIPERR;
3320 fd = open(pipename, O_RDONLY);
3322 snprintf(errmsg, errmsgl,
3323 "The capture session could not be initiated "
3324 "due to error on pipe open: %s", strerror(errno));
3325 ld->pipe_err = PIPERR;
3330 ld->from_pipe = TRUE;
3332 /* read the pcap header */
3334 while (bytes_read < sizeof magic) {
3335 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3338 snprintf(errmsg, errmsgl, "End of file on pipe during open");
3340 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3349 /* Host that wrote it has our byte order, and was running
3350 a program using either standard or ss990417 libpcap. */
3351 ld->byte_swapped = FALSE;
3352 ld->modified = FALSE;
3354 case PCAP_MODIFIED_MAGIC:
3355 /* Host that wrote it has our byte order, but was running
3356 a program using either ss990915 or ss991029 libpcap. */
3357 ld->byte_swapped = FALSE;
3358 ld->modified = TRUE;
3360 case PCAP_SWAPPED_MAGIC:
3361 /* Host that wrote it has a byte order opposite to ours,
3362 and was running a program using either standard or
3363 ss990417 libpcap. */
3364 ld->byte_swapped = TRUE;
3365 ld->modified = FALSE;
3367 case PCAP_SWAPPED_MODIFIED_MAGIC:
3368 /* Host that wrote it out has a byte order opposite to
3369 ours, and was running a program using either ss990915
3370 or ss991029 libpcap. */
3371 ld->byte_swapped = TRUE;
3372 ld->modified = TRUE;
3375 /* Not a "libpcap" type we know about. */
3376 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3380 /* Read the rest of the header */
3382 while (bytes_read < sizeof(struct pcap_hdr)) {
3383 b = read(fd, ((char *)hdr)+bytes_read,
3384 sizeof(struct pcap_hdr) - bytes_read);
3387 snprintf(errmsg, errmsgl, "End of file on pipe during open");
3389 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3396 if (ld->byte_swapped) {
3397 /* Byte-swap the header fields about which we care. */
3398 hdr->version_major = BSWAP16(hdr->version_major);
3399 hdr->version_minor = BSWAP16(hdr->version_minor);
3400 hdr->snaplen = BSWAP32(hdr->snaplen);
3401 hdr->network = BSWAP32(hdr->network);
3404 if (hdr->version_major < 2) {
3405 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3409 ld->pipe_state = STATE_EXPECT_REC_HDR;
3410 ld->pipe_err = PIPOK;
3414 ld->pipe_err = PIPERR;
3419 /* We read one record from the pipe, take care of byte order in the record
3420 * header, write the record in the capture file, and update capture statistics. */
3423 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
3424 struct pcaprec_modified_hdr *rechdr, guchar *data,
3425 char *errmsg, int errmsgl)
3427 struct pcap_pkthdr phdr;
3429 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3432 switch (ld->pipe_state) {
3434 case STATE_EXPECT_REC_HDR:
3435 ld->bytes_to_read = ld->modified ?
3436 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3438 ld->pipe_state = STATE_READ_REC_HDR;
3441 case STATE_READ_REC_HDR:
3442 b = read(fd, ((char *)rechdr)+ld->bytes_read,
3443 ld->bytes_to_read - ld->bytes_read);
3446 result = PD_PIPE_EOF;
3448 result = PD_PIPE_ERR;
3451 if ((ld->bytes_read += b) < ld->bytes_to_read)
3453 result = PD_REC_HDR_READ;
3456 case STATE_EXPECT_DATA:
3458 ld->pipe_state = STATE_READ_DATA;
3461 case STATE_READ_DATA:
3462 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
3465 result = PD_PIPE_EOF;
3467 result = PD_PIPE_ERR;
3470 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
3472 result = PD_DATA_READ;
3476 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3479 } /* switch (ld->pipe_state) */
3482 * We've now read as much data as we were expecting, so process it.
3486 case PD_REC_HDR_READ:
3487 /* We've read the header. Take care of byte order. */
3488 adjust_header(ld, hdr, &rechdr->hdr);
3489 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3490 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3491 ld->packet_count+1, rechdr->hdr.incl_len);
3494 ld->pipe_state = STATE_EXPECT_DATA;
3498 /* Fill in a "struct pcap_pkthdr", and process the packet. */
3499 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3500 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3501 phdr.caplen = rechdr->hdr.incl_len;
3502 phdr.len = rechdr->hdr.orig_len;
3504 capture_pcap_cb((guchar *)ld, &phdr, data);
3506 ld->pipe_state = STATE_EXPECT_REC_HDR;
3510 ld->pipe_err = PIPEOF;
3514 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3521 ld->pipe_err = PIPERR;
3522 /* Return here rather than inside the switch to prevent GCC warning */
3526 #endif /* HAVE_LIBPCAP */
3529 * General errors are reported with an console message in Tethereal.
3532 failure_message(const char *msg_format, va_list ap)
3534 fprintf(stderr, "tethereal: ");
3535 vfprintf(stderr, msg_format, ap);
3536 fprintf(stderr, "\n");
3540 * Read errors are reported with an console message in Tethereal.
3543 read_failure_message(const char *filename, int err)
3545 fprintf(stderr, "tethereal: An error occurred while reading from the file \"%s\": %s.\n",
3546 filename, strerror(err));