3 * $Id: tethereal.c,v 1.176 2003/01/01 03:51:02 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>
60 #include <zlib.h> /* to get the libz version number */
63 #ifdef NEED_SNPRINTF_H
64 # include "snprintf.h"
70 #include <net-snmp/version.h>
71 #endif /* HAVE_NET_SNMP */
74 #include <ucd-snmp/version.h>
75 #endif /* HAVE_UCD_SNMP */
77 #endif /* HAVE_SOME_SNMP */
79 #ifdef NEED_STRERROR_H
88 #include <epan/epan.h>
89 #include <epan/filesystem.h>
92 #include <epan/timestamp.h>
93 #include <epan/packet.h>
98 #include <epan/resolv.h>
101 #include "pcap-util.h"
103 #include <epan/conversation.h>
104 #include <epan/plugins.h>
105 #include "register.h"
106 #include "conditions.h"
107 #include "capture_stop_conditions.h"
108 #include "ringbuffer.h"
109 #include <epan/epan_dissect.h>
113 #include <wiretap/wtap-capture.h>
114 #include <wiretap/libpcap.h>
118 #include "capture-wpcap.h"
121 static guint32 firstsec, firstusec;
122 static guint32 prevsec, prevusec;
123 static GString *comp_info_str;
124 static gboolean quiet;
125 static gboolean decode;
126 static gboolean verbose;
127 static gboolean print_hex;
128 static gboolean line_buffered;
131 typedef struct _loop_data {
132 gboolean go; /* TRUE as long as we're supposed to keep capturing */
134 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
138 gboolean output_to_pipe;
141 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
142 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
143 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
145 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
146 STATE_EXPECT_DATA, STATE_READ_DATA
149 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
155 static int capture(int);
156 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
158 static void report_counts(void);
160 static BOOL WINAPI capture_cleanup(DWORD);
162 static void capture_cleanup(int);
164 static void report_counts_siginfo(int);
167 #endif /* HAVE_LIBPCAP */
174 static int load_cap_file(capture_file *, int);
175 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
176 union wtap_pseudo_header *, const guchar *);
177 static void show_capture_file_io_error(const char *, int, gboolean);
178 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
179 union wtap_pseudo_header *, const guchar *);
181 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
182 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
183 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
184 struct pcaprec_modified_hdr *, guchar *, char *, int);
188 ts_type timestamp_type = RELATIVE;
191 int snaplen; /* Maximum captured packet length */
192 int promisc_mode; /* Capture in promiscuous mode */
193 int autostop_count; /* Maximum packet count */
194 gboolean has_autostop_duration; /* TRUE if maximum capture duration
196 gint32 autostop_duration; /* Maximum capture duration */
197 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
199 gint32 autostop_filesize; /* Maximum capture file size */
200 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
201 guint32 ringbuffer_num_files; /* Number of ring buffer files */
204 static capture_options capture_opts = {
205 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
206 infinite, in effect */
207 TRUE, /* promiscuous mode is the default */
208 0, /* max packet count - default is 0,
210 FALSE, /* maximum capture duration not
211 specified by default */
212 0, /* maximum capture duration */
213 FALSE, /* maximum capture file size not
214 specified by default */
215 0, /* maximum capture file size */
216 FALSE, /* ring buffer off by default */
217 RINGBUFFER_MIN_NUM_FILES /* default number of ring buffer
222 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
223 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
225 #endif /* HAVE_LIBPCAP */
228 print_usage(gboolean print_ver)
233 fprintf(stderr, "This is GNU t%s %s, compiled %s\n", PACKAGE, VERSION,
237 fprintf(stderr, "\nt%s [ -DvVhqSlp ] [ -a <capture autostop condition> ] ...\n",
239 fprintf(stderr, "\t[ -b <number of ring buffer files> ] [ -c <count> ]\n");
240 fprintf(stderr, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
241 fprintf(stderr, "\t[ -i <interface> ] [ -n ] [ -N <resolving> ]\n");
242 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
243 fprintf(stderr, "\t[ -s <snaplen> ] [ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
245 fprintf(stderr, "\nt%s [ -vVhl ] [ -F <output file type> ] [ -n ] [ -N <resolving> ]\n", PACKAGE);
246 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
247 fprintf(stderr, "\t[ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
249 fprintf(stderr, "\t[ -Z <statistics string> ]\n");
250 fprintf(stderr, "Valid file type arguments to the \"-F\" flag:\n");
251 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
252 if (wtap_dump_can_open(i))
253 fprintf(stderr, "\t%s - %s\n",
254 wtap_file_type_short_string(i), wtap_file_type_string(i));
256 fprintf(stderr, "\tdefault is libpcap\n");
261 get_positive_int(const char *string, const char *name)
266 number = strtol(string, &p, 10);
267 if (p == string || *p != '\0') {
268 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
273 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
278 fprintf(stderr, "tethereal: The specified %s is zero\n",
282 if (number > INT_MAX) {
283 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
291 * Given a string of the form "<autostop criterion>:<value>", as might appear
292 * as an argument to a "-a" option, parse it and set the criterion in
293 * question. Return an indication of whether it succeeded or failed
297 set_autostop_criterion(const char *autostoparg)
301 colonp = strchr(autostoparg, ':');
309 * Skip over any white space (there probably won't be any, but
310 * as we allow it in the preferences file, we might as well
317 * Put the colon back, so if our caller uses, in an
318 * error message, the string they passed us, the message
324 if (strcmp(autostoparg,"duration") == 0) {
325 capture_opts.has_autostop_duration = TRUE;
326 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
327 } else if (strcmp(autostoparg,"filesize") == 0) {
328 capture_opts.has_autostop_filesize = TRUE;
329 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
333 *colonp = ':'; /* put the colon back */
338 /* structure to keep track of what tap listeners have been registered.
340 typedef struct _ethereal_tap_list {
341 struct _ethereal_tap_list *next;
343 void (*func)(char *arg);
345 static ethereal_tap_list *tap_list=NULL;
348 register_ethereal_tap(char *cmd, void (*func)(char *arg), char *dummy _U_, void (*dummy2)(void) _U_)
350 ethereal_tap_list *newtl;
352 newtl=malloc(sizeof(ethereal_tap_list));
353 newtl->next=tap_list;
361 main(int argc, char *argv[])
365 gboolean arg_error = FALSE;
367 #ifdef HAVE_PCAP_VERSION
368 extern char pcap_version[];
369 #endif /* HAVE_PCAP_VERSION */
370 #endif /* HAVE_LIBPCAP */
378 int gpf_open_errno, pf_open_errno;
381 gboolean capture_filter_specified = FALSE;
382 GList *if_list, *if_entry;
383 gchar err_str[PCAP_ERRBUF_SIZE];
385 gboolean capture_option_specified = FALSE;
387 int out_file_type = WTAP_FILE_PCAP;
388 gchar *cf_name = NULL, *rfilter = NULL;
392 dfilter_t *rfcode = NULL;
395 ethereal_tap_list *tli;
397 /* Register all dissectors; we must do this before checking for the
398 "-G" flag, as the "-G" flag dumps information registered by the
399 dissectors, and we must do it before we read the preferences, in
400 case any dissectors register preferences. */
401 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
402 register_all_tap_listeners();
404 /* Now register the preferences for any non-dissector modules.
405 We must do that before we read the preferences as well. */
406 prefs_register_modules();
408 /* If invoked with the "-G" flag, we dump out information based on
409 the argument to the "-G" flag; if no argument is specified,
410 for backwards compatibility we dump out a glossary of display
413 We do this here to mirror what happens in the GTK+ version, although
414 it's not necessary here. */
415 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
417 proto_registrar_dump_fields();
419 if (strcmp(argv[2], "fields") == 0)
420 proto_registrar_dump_fields();
421 else if (strcmp(argv[2], "protocols") == 0)
422 proto_registrar_dump_protocols();
424 fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
432 /* Set the C-language locale to the native environment. */
433 setlocale(LC_ALL, "");
435 prefs = read_prefs(&gpf_open_errno, &gpf_path, &pf_open_errno, &pf_path);
436 if (gpf_path != NULL) {
437 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n", pf_path,
438 strerror(gpf_open_errno));
440 if (pf_path != NULL) {
441 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
442 strerror(pf_open_errno));
447 /* Set the name resolution code's flags from the preferences. */
448 g_resolv_flags = prefs->name_resolve;
451 /* Load Wpcap, if possible */
455 init_cap_file(&cfile);
457 /* Assemble the compile-time options */
458 comp_info_str = g_string_new("");
460 g_string_append(comp_info_str, "with ");
461 g_string_sprintfa(comp_info_str,
462 #ifdef GLIB_MAJOR_VERSION
463 "GLib %d.%d.%d", GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION,
466 "GLib (version unknown)");
470 g_string_append(comp_info_str, ", with libpcap ");
471 #ifdef HAVE_PCAP_VERSION
472 g_string_append(comp_info_str, pcap_version);
473 #else /* HAVE_PCAP_VERSION */
474 g_string_append(comp_info_str, "(version unknown)");
475 #endif /* HAVE_PCAP_VERSION */
476 #else /* HAVE_LIBPCAP */
477 g_string_append(comp_info_str, ", without libpcap");
478 #endif /* HAVE_LIBPCAP */
481 g_string_append(comp_info_str, ", with libz ");
483 g_string_append(comp_info_str, ZLIB_VERSION);
484 #else /* ZLIB_VERSION */
485 g_string_append(comp_info_str, "(version unknown)");
486 #endif /* ZLIB_VERSION */
487 #else /* HAVE_LIBZ */
488 g_string_append(comp_info_str, ", without libz");
489 #endif /* HAVE_LIBZ */
491 /* Oh, this is pretty. */
492 /* Oh, ha. you think that was pretty. Try this:! --Wes */
493 #ifdef HAVE_SOME_SNMP
496 g_string_append(comp_info_str, ", with UCD-SNMP ");
497 g_string_append(comp_info_str, VersionInfo);
498 #endif /* HAVE_UCD_SNMP */
501 g_string_append(comp_info_str, ", with Net-SNMP ");
502 g_string_append(comp_info_str, netsnmp_get_version());
503 #endif /* HAVE_NET_SNMP */
505 #else /* no SNMP library */
506 g_string_append(comp_info_str, ", without UCD-SNMP or Net-SNMP");
507 #endif /* HAVE_SOME_SNMP */
509 /* Now get our args */
510 while ((opt = getopt(argc, argv, "a:b:c:Df:F:hi:lnN:o:pqr:R:s:St:vw:Vxz:")) != -1) {
512 case 'a': /* autostop criteria */
514 if (set_autostop_criterion(optarg) == FALSE) {
515 fprintf(stderr, "ethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
519 capture_option_specified = TRUE;
523 case 'b': /* Ringbuffer option */
525 capture_opts.ringbuffer_on = TRUE;
526 capture_opts.ringbuffer_num_files =
527 get_positive_int(optarg, "number of ring buffer files");
529 capture_option_specified = TRUE;
533 case 'c': /* Capture xxx packets */
535 capture_opts.autostop_count =
536 get_positive_int(optarg, "packet count");
538 capture_option_specified = TRUE;
542 case 'D': /* Print a list of capture devices */
544 if_list = get_interface_list(&err, err_str);
545 if (if_list == NULL) {
548 case CANT_GET_INTERFACE_LIST:
549 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
553 case NO_INTERFACES_FOUND:
554 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
559 for (if_entry = g_list_first(if_list); if_entry != NULL;
560 if_entry = g_list_next(if_entry))
561 printf("%s\n", (char *)if_entry->data);
562 free_interface_list(if_list);
565 capture_option_specified = TRUE;
571 capture_filter_specified = TRUE;
573 g_free(cfile.cfilter);
574 cfile.cfilter = g_strdup(optarg);
576 capture_option_specified = TRUE;
581 out_file_type = wtap_short_string_to_file_type(optarg);
582 if (out_file_type < 0) {
583 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
588 case 'h': /* Print help and exit */
592 case 'i': /* Use interface xxx */
594 cfile.iface = g_strdup(optarg);
596 capture_option_specified = TRUE;
600 case 'l': /* "Line-buffer" standard output */
601 /* This isn't line-buffering, strictly speaking, it's just
602 flushing the standard output after the information for
603 each packet is printed; however, that should be good
604 enough for all the purposes to which "-l" is put.
606 See the comment in "wtap_dispatch_cb_print()" for an
607 explanation of why we do that, and why we don't just
608 use "setvbuf()" to make the standard output line-buffered
609 (short version: in Windows, "line-buffered" is the same
610 as "fully-buffered", and the output buffer is only flushed
611 when it fills up). */
612 line_buffered = TRUE;
614 case 'n': /* No name resolution */
615 g_resolv_flags = RESOLV_NONE;
617 case 'N': /* Select what types of addresses/port #s to resolve */
618 if (g_resolv_flags == RESOLV_ALL)
619 g_resolv_flags = RESOLV_NONE;
620 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
621 if (badopt != '\0') {
622 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
627 case 'o': /* Override preference from command line */
628 switch (prefs_set_pref(optarg)) {
630 case PREFS_SET_SYNTAX_ERR:
631 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
635 case PREFS_SET_NO_SUCH_PREF:
636 case PREFS_SET_OBSOLETE:
637 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
643 case 'p': /* Don't capture in promiscuous mode */
645 capture_opts.promisc_mode = FALSE;
647 capture_option_specified = TRUE;
651 case 'q': /* Quiet */
654 case 'r': /* Read capture file xxx */
655 cf_name = g_strdup(optarg);
657 case 'R': /* Read file filter */
660 case 's': /* Set the snapshot (capture) length */
662 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
664 capture_option_specified = TRUE;
668 case 'S': /* show packets in real time */
671 case 't': /* Time stamp type */
672 if (strcmp(optarg, "r") == 0)
673 timestamp_type = RELATIVE;
674 else if (strcmp(optarg, "a") == 0)
675 timestamp_type = ABSOLUTE;
676 else if (strcmp(optarg, "ad") == 0)
677 timestamp_type = ABSOLUTE_WITH_DATE;
678 else if (strcmp(optarg, "d") == 0)
679 timestamp_type = DELTA;
681 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
683 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
684 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
688 case 'v': /* Show version and exit */
689 printf("t%s %s, %s\n", PACKAGE, VERSION, comp_info_str->str);
692 case 'w': /* Write to capture file xxx */
693 cfile.save_file = g_strdup(optarg);
695 case 'V': /* Verbose */
698 case 'x': /* Print packet data in hex (and ASCII) */
702 for(tli=tap_list;tli;tli=tli->next){
703 if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
704 (*tli->func)(optarg);
709 fprintf(stderr,"tethereal: invalid -z argument.\n");
710 fprintf(stderr," -z argument must be one of :\n");
711 for(tli=tap_list;tli;tli=tli->next){
712 fprintf(stderr," %s\n",tli->cmd);
718 case '?': /* Bad flag - print usage message */
724 /* If no capture filter or read filter has been specified, and there are
725 still command-line arguments, treat them as the tokens of a capture
726 filter (if no "-r" flag was specified) or a read filter (if a "-r"
727 flag was specified. */
729 if (cf_name != NULL) {
730 if (rfilter != NULL) {
732 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
735 rfilter = get_args_as_string(argc, argv, optind);
738 if (capture_filter_specified) {
740 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
743 cfile.cfilter = get_args_as_string(argc, argv, optind);
745 capture_option_specified = TRUE;
750 /* See if we're writing a capture file and the file is a pipe */
752 ld.output_to_pipe = FALSE;
754 if (cfile.save_file != NULL) {
755 if (strcmp(cfile.save_file, "-") == 0) {
757 g_free(cfile.save_file);
758 cfile.save_file = g_strdup("");
760 ld.output_to_pipe = TRUE;
765 err = test_for_fifo(cfile.save_file);
768 case ENOENT: /* it doesn't exist, so we'll be creating it,
769 and it won't be a FIFO */
770 case 0: /* found it, but it's not a FIFO */
773 case ESPIPE: /* it is a FIFO */
774 ld.output_to_pipe = TRUE;
777 default: /* couldn't stat it */
779 "tethereal: Error testing whether capture file is a pipe: %s\n",
788 /* If they didn't specify a "-w" flag, but specified a maximum capture
789 file size, tell them that this doesn't work, and exit. */
790 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
791 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
792 "capture isn't being saved to a file.\n");
796 if (capture_opts.ringbuffer_on) {
797 /* Ring buffer works only under certain conditions:
798 a) ring buffer does not work if you're not saving the capture to
800 b) ring buffer only works if you're saving in libpcap format;
801 c) it makes no sense to enable the ring buffer if the maximum
802 file size is set to "infinite";
803 d) file must not be a pipe. */
804 if (cfile.save_file == NULL) {
805 fprintf(stderr, "tethereal: Ring buffer requested, but "
806 "capture isn't being saved to a file.\n");
809 if (out_file_type != WTAP_FILE_PCAP) {
810 fprintf(stderr, "tethereal: Ring buffer requested, but "
811 "capture isn't being saved in libpcap format.\n");
814 if (!capture_opts.has_autostop_filesize) {
815 fprintf(stderr, "tethereal: Ring buffer requested, but "
816 "no maximum capture file size was specified.\n");
819 if (ld.output_to_pipe) {
820 fprintf(stderr, "tethereal: Ring buffer requested, but "
821 "capture file is a pipe.\n");
828 /* Start windows sockets */
829 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
832 /* Notify all registered modules that have had any of their preferences
833 changed either from one of the preferences file or from the command
834 line that their preferences have changed. */
838 if (capture_option_specified)
839 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
846 /* Build the column format array */
847 col_init(&cfile.cinfo, prefs->num_cols);
848 for (i = 0; i < cfile.cinfo.num_cols; i++) {
849 cfile.cinfo.col_fmt[i] = get_column_format(i);
850 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
851 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
853 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
854 cfile.cinfo.col_data[i] = NULL;
855 if (cfile.cinfo.col_fmt[i] == COL_INFO)
856 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
858 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
860 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
861 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
865 if (capture_opts.snaplen < 1)
866 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
867 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
868 capture_opts.snaplen = MIN_PACKET_SIZE;
870 /* Check the value range of the ringbuffer_num_files parameter */
871 if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
872 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
873 else if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
874 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
877 if (rfilter != NULL) {
878 if (!dfilter_compile(rfilter, &rfcode)) {
879 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
884 cfile.rfcode = rfcode;
886 err = open_cap_file(cf_name, FALSE, &cfile);
891 err = load_cap_file(&cfile, out_file_type);
898 /* No capture file specified, so we're supposed to do a live capture;
899 do we have support for live captures? */
904 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
909 /* Yes; did the user specify an interface to use? */
910 if (cfile.iface == NULL) {
911 /* No - is a default specified in the preferences file? */
912 if (prefs->capture_device != NULL) {
914 if_text = strrchr(prefs->capture_device, ' ');
915 if (if_text == NULL) {
916 cfile.iface = g_strdup(prefs->capture_device);
918 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
921 /* No - pick the first one from the list of interfaces. */
922 if_list = get_interface_list(&err, err_str);
923 if (if_list == NULL) {
926 case CANT_GET_INTERFACE_LIST:
927 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
931 case NO_INTERFACES_FOUND:
932 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
937 if_text = strrchr(if_list->data, ' '); /* first interface */
938 if (if_text == NULL) {
939 cfile.iface = g_strdup(if_list->data);
941 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
943 free_interface_list(if_list);
946 capture(out_file_type);
948 if (capture_opts.ringbuffer_on) {
953 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
958 draw_tap_listeners(TRUE);
965 /* Do the low-level work of a capture.
966 Returns TRUE if it succeeds, FALSE otherwise. */
968 capture(int out_file_type)
972 gchar open_err_str[PCAP_ERRBUF_SIZE];
973 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
974 bpf_u_int32 netnum, netmask;
975 struct bpf_program fcode;
976 void (*oldhandler)(int);
978 int volatile volatile_err = 0;
979 int volatile inpkts = 0;
982 condition *volatile cnd_stop_capturesize = NULL;
983 condition *volatile cnd_stop_timeout = NULL;
985 static const char ppamsg[] = "can't find PPA for ";
987 volatile int pipe_fd = -1;
989 struct pcaprec_modified_hdr rechdr;
990 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
992 struct pcap_stat stats;
996 /* Initialize all data structures used for dissection. */
999 ld.linktype = WTAP_ENCAP_UNKNOWN;
1002 /* Open the network interface to capture from it.
1003 Some versions of libpcap may put warnings into the error buffer
1004 if they succeed; to tell if that's happened, we have to clear
1005 the error buffer, and check if it's still a null string. */
1006 open_err_str[0] = '\0';
1007 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1008 capture_opts.promisc_mode, 1000, open_err_str);
1010 if (ld.pch == NULL) {
1011 /* We couldn't open "cfile.iface" as a network device. */
1013 /* On Windows, we don't support capturing on pipes, so we give up. */
1015 /* On Win32 OSes, the capture devices are probably available to all
1016 users; don't warn about permissions problems.
1018 Do, however, warn that WAN devices aren't supported. */
1019 snprintf(errmsg, sizeof errmsg,
1020 "The capture session could not be initiated (%s).\n"
1021 "Please check that you have the proper interface specified.\n"
1023 "Note that the driver Tethereal uses for packet capture on Windows doesn't\n"
1024 "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
1028 /* try to open cfile.iface as a pipe */
1029 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1031 if (pipe_fd == -1) {
1033 if (ld.pipe_err == PIPNEXIST) {
1034 /* Pipe doesn't exist, so output message for interface */
1036 /* If we got a "can't find PPA for XXX" message, warn the user (who
1037 is running Tethereal on HP-UX) that they don't have a version
1038 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1039 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1040 PPA for XXX" rather than "can't find PPA for XXX"). */
1041 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1044 "You are running Tethereal with a version of the libpcap library\n"
1045 "that doesn't handle HP-UX network devices well; this means that\n"
1046 "Tethereal may not be able to capture packets.\n"
1048 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1049 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1050 "packaged binary form from the Software Porting And Archive Centre\n"
1051 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1052 "at the URL lists a number of mirror sites.";
1055 snprintf(errmsg, sizeof errmsg,
1056 "The capture session could not be initiated (%s).\n"
1057 "Please check to make sure you have sufficient permissions, and that\n"
1058 "you have the proper interface or pipe specified.%s", open_err_str,
1062 * Else pipe (or file) does exist and pipe_open_live() has
1067 /* pipe_open_live() succeeded; don't want
1068 error message from pcap_open_live() */
1069 open_err_str[0] = '\0';
1073 if (cfile.cfilter && !ld.from_pipe) {
1074 /* A capture filter was specified; set it up. */
1075 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1077 * Well, we can't get the netmask for this interface; it's used
1078 * only for filters that check for broadcast IP addresses, so
1079 * we just warn the user, and punt and use 0.
1082 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1085 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1086 snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1087 pcap_geterr(ld.pch));
1090 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1091 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1092 pcap_geterr(ld.pch));
1097 /* Set up to write to the capture file. */
1100 pcap_encap = hdr.network;
1101 file_snaplen = hdr.snaplen;
1105 pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1106 file_snaplen = pcap_snapshot(ld.pch);
1108 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1109 if (cfile.save_file != NULL) {
1110 /* Set up to write to the capture file. */
1111 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1112 strcpy(errmsg, "The network you're capturing from is of a type"
1113 " that Tethereal doesn't support.");
1116 if (capture_opts.ringbuffer_on) {
1117 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1118 capture_opts.ringbuffer_num_files);
1119 if (cfile.save_file_fd != -1) {
1120 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1121 pcap_snapshot(ld.pch), &err);
1123 err = errno; /* "ringbuf_init()" failed */
1127 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1128 ld.linktype, pcap_snapshot(ld.pch), &err);
1131 if (ld.pdh == NULL) {
1132 snprintf(errmsg, sizeof errmsg,
1133 file_open_error_message(err, TRUE, out_file_type),
1134 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1139 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1140 returned a warning; print it, but keep capturing. */
1141 if (open_err_str[0] != '\0')
1142 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1145 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1146 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1148 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1150 XXX - deal with signal semantics on various UNIX platforms. Or just
1151 use "sigaction()" and be done with it? */
1152 signal(SIGTERM, capture_cleanup);
1153 signal(SIGINT, capture_cleanup);
1154 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1155 signal(SIGHUP, oldhandler);
1158 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1159 quiet mode, report the number of packets we've captured. */
1160 signal(SIGINFO, report_counts_siginfo);
1161 #endif /* SIGINFO */
1164 /* Let the user know what interface was chosen. */
1165 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1167 /* initialize capture stop conditions */
1168 init_capture_stop_conditions();
1169 /* create stop conditions */
1170 if (capture_opts.has_autostop_filesize)
1171 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1172 (long)capture_opts.autostop_filesize * 1000);
1173 if (capture_opts.has_autostop_duration)
1174 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1175 (gint32)capture_opts.autostop_duration);
1177 if (!setjmp(ld.stopenv)) {
1179 ld.packet_count = 0;
1183 /* We need to be careful with automatic variables defined in the
1184 outer scope which are changed inside the loop. Most compilers
1185 don't try to roll them back to their original values after the
1186 longjmp which causes the loop to finish, but all that the
1187 standards say is that their values are indeterminate. If we
1188 don't want them to be rolled back, we should define them with the
1189 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1190 Programming in the UNIX Environment, p. 178).
1192 The "err" variable causes a particular problem. If we give it
1193 the volatile attribute, then when we pass a reference to it (as
1194 in "&err") to a function, GCC warns: "passing arg <n> of
1195 <function> discards qualifiers from pointer target type".
1196 Therefore within the loop and just beyond we don't use "err".
1197 Within the loop we define "loop_err", and assign its value to
1198 "volatile_err", which is in the outer scope and is checked when
1201 We also define "packet_count_prev" here to keep things tidy,
1202 since it's used only inside the loop. If it were defined in the
1203 outer scope, GCC would give a warning (unnecessary in this case)
1204 that it might be clobbered, and we'd need to give it the volatile
1205 attribute to suppress the warning. */
1208 int packet_count_prev = 0;
1210 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1211 /* We're not stopping at a particular capture file size, and we're
1212 not stopping after some particular amount of time has expired,
1213 so either we have no stop condition or the only stop condition
1214 is a maximum packet count.
1216 If there's no maximum packet count, pass it -1, meaning "until
1217 you run out of packets in the bufferful you read". Otherwise,
1218 pass it the number of packets we have left to capture.
1220 We don't call "pcap_loop()" as, if we're saving to a file that's
1221 a FIFO, we want to flush the FIFO after we're done processing
1222 this libpcap bufferful of packets, so that the program
1223 reading the FIFO sees the packets immediately and doesn't get
1224 any partial packet, forcing it to block in the middle of reading
1226 if (capture_opts.autostop_count == 0)
1229 if (ld.packet_count >= capture_opts.autostop_count) {
1230 /* XXX do we need this test here? */
1231 /* It appears there's nothing more to capture. */
1234 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1237 /* We need to check the capture file size or the timeout after
1243 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1244 errmsg, sizeof errmsg);
1247 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1249 /* Error from "pcap_dispatch()", or error or "no more packets" from
1250 "pipe_dispatch(). */
1252 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1253 /* The specified capture time has elapsed; stop the capture. */
1255 } else if (inpkts > 0) {
1256 if (capture_opts.autostop_count != 0 &&
1257 ld.packet_count >= capture_opts.autostop_count) {
1258 /* The specified number of packets have been captured and have
1259 passed both any capture filter in effect and any read filter
1262 } else if (cnd_stop_capturesize != NULL &&
1263 cnd_eval(cnd_stop_capturesize,
1264 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1265 /* We're saving the capture to a file, and the capture file reached
1266 its maximum size. */
1267 if (capture_opts.ringbuffer_on) {
1268 /* Switch to the next ringbuffer file */
1269 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1270 /* File switch succeeded: reset the condition */
1271 cnd_reset(cnd_stop_capturesize);
1273 /* File switch failed: stop here */
1274 volatile_err = loop_err;
1278 /* No ringbuffer - just stop. */
1282 if (ld.output_to_pipe) {
1283 if (ld.packet_count > packet_count_prev) {
1284 if (fflush(wtap_dump_file(ld.pdh))) {
1285 volatile_err = errno;
1288 packet_count_prev = ld.packet_count;
1292 } /* while (ld.go) */
1294 /* delete stop conditions */
1295 if (cnd_stop_capturesize != NULL)
1296 cnd_delete(cnd_stop_capturesize);
1297 if (cnd_stop_timeout != NULL)
1298 cnd_delete(cnd_stop_timeout);
1300 if ((cfile.save_file != NULL) && !quiet) {
1301 /* We're saving to a file, which means we're printing packet counts
1302 to stderr if we are not running silent and deep.
1303 Send a newline so that we move to the line after the packet count. */
1304 fprintf(stderr, "\n");
1307 /* If we got an error while capturing, report it. */
1311 if (ld.pipe_err == PIPERR) {
1312 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1318 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1319 pcap_geterr(ld.pch));
1323 if (volatile_err == 0)
1326 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
1330 if (cfile.save_file != NULL) {
1331 /* We're saving to a file or files; close all files. */
1332 if (capture_opts.ringbuffer_on) {
1333 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1335 dump_ok = wtap_dump_close(ld.pdh, &err);
1337 /* If we've displayed a message about a write error, there's no point
1338 in displaying another message about an error on close. */
1339 if (!dump_ok && !write_err)
1340 show_capture_file_io_error(cfile.save_file, err, TRUE);
1344 if (ld.from_pipe && pipe_fd >= 0)
1349 /* Get the capture statistics, and, if any packets were dropped, report
1351 if (pcap_stats(ld.pch, &stats) >= 0) {
1352 if (stats.ps_drop != 0) {
1353 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1356 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
1357 pcap_geterr(ld.pch));
1362 /* Report the number of captured packets if not reported during capture
1363 and we are saving to a file. */
1369 if (capture_opts.ringbuffer_on) {
1370 ringbuf_error_cleanup();
1372 g_free(cfile.save_file);
1373 cfile.save_file = NULL;
1374 fprintf(stderr, "tethereal: %s\n", errmsg);
1390 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
1393 struct wtap_pkthdr whdr;
1394 union wtap_pseudo_header pseudo_header;
1395 loop_data *ld = (loop_data *) user;
1399 /* Convert from libpcap to Wiretap format.
1400 If that fails, ignore the packet (wtap_process_pcap_packet has
1401 written an error message). */
1402 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
1411 wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1412 /* Report packet capture count if not quiet */
1415 if (ld->packet_count != 0) {
1416 fprintf(stderr, "\r%u ", ld->packet_count);
1417 /* stderr could be line buffered */
1421 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
1422 &pseudo_header, pd);
1426 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1432 capture_cleanup(DWORD ctrltype _U_)
1434 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1435 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1436 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1437 like SIGTERM at least when the machine's shutting down.
1439 For now, we handle them all as indications that we should clean up
1440 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1443 However, as handlers run in a new thread, we can't just longjmp
1444 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1445 no other handler - such as one that would terminate the process -
1448 XXX - for some reason, typing ^C to Tethereal, if you run this in
1449 a Cygwin console window in at least some versions of Cygwin,
1450 causes Tethereal to terminate immediately; this routine gets
1451 called, but the main loop doesn't get a chance to run and
1452 exit cleanly, at least if this is compiled with Microsoft Visual
1453 C++ (i.e., it's a property of the Cygwin console window or Bash;
1454 it happens if Tethereal is not built with Cygwin - for all I know,
1455 building it with Cygwin may make the problem go away). */
1461 capture_cleanup(int signum _U_)
1463 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1464 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1465 "ld.go" to FALSE and return, we won't break out of it and quit
1467 longjmp(ld.stopenv, 1);
1475 /* XXX - if we use sigaction, this doesn't have to be done.
1476 (Yes, this isn't necessary on BSD, but just in case a system
1477 where "signal()" has AT&T semantics adopts SIGINFO....) */
1478 signal(SIGINFO, report_counts_siginfo);
1479 #endif /* SIGINFO */
1481 if (cfile.save_file != NULL && quiet) {
1482 /* Report the count only if we're capturing to a file (rather
1483 than printing captured packet information out) and aren't
1484 updating a count as packets arrive. */
1485 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1488 infoprint = FALSE; /* we just reported it */
1489 #endif /* SIGINFO */
1494 report_counts_siginfo(int signum _U_)
1496 /* If we've been told to delay printing, just set a flag asking
1497 that we print counts (if we're supposed to), otherwise print
1498 the count of packets captured (if we're supposed to). */
1504 #endif /* SIGINFO */
1505 #endif /* HAVE_LIBPCAP */
1508 load_cap_file(capture_file *cf, int out_file_type)
1511 int snapshot_length;
1517 linktype = wtap_file_encap(cf->wth);
1518 if (cf->save_file != NULL) {
1519 /* Set up to write to the capture file. */
1520 snapshot_length = wtap_snapshot_length(cf->wth);
1521 if (snapshot_length == 0) {
1522 /* Snapshot length of input file not known. */
1523 snapshot_length = WTAP_MAX_PACKET_SIZE;
1525 pdh = wtap_dump_open(cf->save_file, out_file_type,
1526 linktype, snapshot_length, &err);
1529 /* We couldn't set up to write to the capture file. */
1532 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1534 "tethereal: Capture files can't be written in that format.\n");
1537 case WTAP_ERR_UNSUPPORTED_ENCAP:
1538 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1540 "tethereal: The capture file being read cannot be written in "
1544 case WTAP_ERR_CANT_OPEN:
1546 "tethereal: The file \"%s\" couldn't be created for some "
1547 "unknown reason.\n",
1548 *cf->save_file == '\0' ? "stdout" : cf->save_file);
1551 case WTAP_ERR_SHORT_WRITE:
1553 "tethereal: A full header couldn't be written to the file \"%s\".\n",
1554 *cf->save_file == '\0' ? "stdout" : cf->save_file);
1559 "tethereal: The file \"%s\" could not be created: %s\n.",
1560 *cf->save_file == '\0' ? "stdout" : cf->save_file,
1561 wtap_strerror(err));
1568 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
1571 /* Now close the capture file. */
1572 if (!wtap_dump_close(pdh, &err))
1573 show_capture_file_io_error(cfile.save_file, err, TRUE);
1577 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
1581 /* Print up a message box noting that the read failed somewhere along
1585 case WTAP_ERR_UNSUPPORTED_ENCAP:
1587 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
1591 case WTAP_ERR_CANT_READ:
1593 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
1597 case WTAP_ERR_SHORT_READ:
1599 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
1603 case WTAP_ERR_BAD_RECORD:
1605 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
1611 "tethereal: An error occurred while reading \"%s\": %s.\n",
1612 cf->filename, wtap_strerror(err));
1618 wtap_close(cf->wth);
1625 fill_in_fdata(frame_data *fdata, capture_file *cf,
1626 const struct wtap_pkthdr *phdr, long offset)
1631 fdata->num = cf->count;
1632 fdata->pkt_len = phdr->len;
1633 fdata->cap_len = phdr->caplen;
1634 fdata->file_off = offset;
1635 fdata->lnk_t = phdr->pkt_encap;
1636 fdata->abs_secs = phdr->ts.tv_sec;
1637 fdata->abs_usecs = phdr->ts.tv_usec;
1638 fdata->flags.passed_dfilter = 0;
1639 fdata->flags.encoding = CHAR_ASCII;
1640 fdata->flags.visited = 0;
1641 fdata->flags.marked = 0;
1643 /* If we don't have the time stamp of the first packet in the
1644 capture, it's because this is the first packet. Save the time
1645 stamp of this packet as the time stamp of the first packet. */
1646 if (!firstsec && !firstusec) {
1647 firstsec = fdata->abs_secs;
1648 firstusec = fdata->abs_usecs;
1651 /* If we don't have the time stamp of the previous displayed packet,
1652 it's because this is the first displayed packet. Save the time
1653 stamp of this packet as the time stamp of the previous displayed
1655 if (!prevsec && !prevusec) {
1656 prevsec = fdata->abs_secs;
1657 prevusec = fdata->abs_usecs;
1660 /* Get the time elapsed between the first packet and this packet. */
1661 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
1662 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
1664 /* If it's greater than the current elapsed time, set the elapsed time
1665 to it (we check for "greater than" so as not to be confused by
1666 time moving backwards). */
1667 if ((gint32)cf->esec < fdata->rel_secs
1668 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
1669 cf->esec = fdata->rel_secs;
1670 cf->eusec = fdata->rel_usecs;
1673 /* Get the time elapsed between the previous displayed packet and
1675 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
1676 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
1677 prevsec = fdata->abs_secs;
1678 prevusec = fdata->abs_usecs;
1681 /* Free up all data attached to a "frame_data" structure. */
1683 clear_fdata(frame_data *fdata)
1686 g_slist_free(fdata->pfd);
1690 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
1691 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
1693 cb_args_t *args = (cb_args_t *) user;
1694 capture_file *cf = args->cf;
1695 wtap_dumper *pdh = args->pdh;
1699 epan_dissect_t *edt;
1703 * Prevent a SIGINFO handler from writing to stdout while we're
1704 * doing so; instead, have it just set a flag telling us to print
1705 * that information when we're done.
1708 #endif /* SIGINFO */
1712 fill_in_fdata(&fdata, cf, phdr, offset);
1713 edt = epan_dissect_new(TRUE, FALSE);
1714 epan_dissect_prime_dfilter(edt, cf->rfcode);
1715 epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
1716 passed = dfilter_apply_edt(cf->rfcode, edt);
1722 /* The packet passed the read filter. */
1726 if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
1728 if (ld.pch != NULL && !quiet) {
1729 /* We're capturing packets, so (if -q not specified) we're printing
1730 a count of packets captured; move to the line after the count. */
1731 fprintf(stderr, "\n");
1734 show_capture_file_io_error(cf->save_file, err, FALSE);
1739 wtap_dump_close(pdh, &err);
1744 epan_dissect_free(edt);
1746 clear_fdata(&fdata);
1750 * Allow SIGINFO handlers to write.
1755 * If a SIGINFO handler asked us to write out capture counts, do so.
1759 #endif /* SIGINFO */
1763 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
1772 "tethereal: Not all the packets could be written to \"%s\" because there is "
1773 "no space left on the file system.\n",
1780 "tethereal: Not all the packets could be written to \"%s\" because you are "
1781 "too close to, or over your disk quota.\n",
1786 case WTAP_ERR_CANT_CLOSE:
1788 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
1792 case WTAP_ERR_SHORT_WRITE:
1794 "tethereal: Not all the packets could be written to \"%s\".\n",
1801 "tethereal: \"%s\" could not be closed: %s.\n",
1802 fname, wtap_strerror(err));
1805 "tethereal: An error occurred while writing to \"%s\": %s.\n",
1806 fname, wtap_strerror(err));
1813 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
1814 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
1816 cb_args_t *args = (cb_args_t *) user;
1817 capture_file *cf = args->cf;
1820 print_args_t print_args;
1821 epan_dissect_t *edt;
1822 gboolean create_proto_tree;
1827 fill_in_fdata(&fdata, cf, phdr, offset);
1830 if (cf->rfcode || verbose || num_tap_filters!=0)
1831 create_proto_tree = TRUE;
1833 create_proto_tree = FALSE;
1834 /* The protocol tree will be "visible", i.e., printed, only if we're
1835 not printing a summary.
1837 We only need the columns if we're *not* verbose; in verbose mode,
1838 we print the protocol tree, not the protocol summary. */
1840 edt = epan_dissect_new(create_proto_tree, verbose);
1842 epan_dissect_prime_dfilter(edt, cf->rfcode);
1845 tap_queue_init(edt);
1846 epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
1847 tap_push_tapped_queue(edt);
1850 passed = dfilter_apply_edt(cf->rfcode, edt);
1853 /* The packet passed the read filter. */
1858 /* Print the information in the protocol tree. */
1859 print_args.to_file = TRUE;
1860 print_args.format = PR_FMT_TEXT;
1861 print_args.print_summary = FALSE;
1862 print_args.print_hex = print_hex;
1863 print_args.expand_all = TRUE;
1864 print_args.suppress_unmarked = FALSE;
1865 proto_tree_print(&print_args, edt, stdout);
1867 /* "print_hex_data()" will put out a leading blank line, as well
1868 as a trailing one; print one here, to separate the packets,
1869 only if "print_hex_data()" won't be called. */
1873 /* Just fill in the columns. */
1874 epan_dissect_fill_in_columns(edt);
1876 /* Now print them. */
1877 for (i = 0; i < cf->cinfo.num_cols; i++) {
1878 switch (cf->cinfo.col_fmt[i]) {
1881 * Don't print this if we're doing a live capture from a network
1882 * interface - if we're doing a live capture, you won't be
1883 * able to look at the capture in the future (it's not being
1884 * saved anywhere), so the frame numbers are unlikely to be
1887 * (XXX - it might be nice to be able to save and print at
1888 * the same time, sort of like an "Update list of packets
1889 * in real time" capture in Ethereal.)
1891 if (cf->iface != NULL)
1893 printf("%3s", cf->cinfo.col_data[i]);
1899 case COL_ABS_DATE_TIME: /* XXX - wider */
1900 printf("%10s", cf->cinfo.col_data[i]);
1906 case COL_DEF_DL_SRC:
1907 case COL_RES_DL_SRC:
1908 case COL_UNRES_DL_SRC:
1909 case COL_DEF_NET_SRC:
1910 case COL_RES_NET_SRC:
1911 case COL_UNRES_NET_SRC:
1912 printf("%12s", cf->cinfo.col_data[i]);
1918 case COL_DEF_DL_DST:
1919 case COL_RES_DL_DST:
1920 case COL_UNRES_DL_DST:
1921 case COL_DEF_NET_DST:
1922 case COL_RES_NET_DST:
1923 case COL_UNRES_NET_DST:
1924 printf("%-12s", cf->cinfo.col_data[i]);
1928 printf("%s", cf->cinfo.col_data[i]);
1931 if (i != cf->cinfo.num_cols - 1) {
1933 * This isn't the last column, so we need to print a
1934 * separator between this column and the next.
1936 * If we printed a network source and are printing a
1937 * network destination of the same type next, separate
1938 * them with "->"; if we printed a network destination
1939 * and are printing a network source of the same type
1940 * next, separate them with "<-"; otherwise separate them
1943 switch (cf->cinfo.col_fmt[i]) {
1948 switch (cf->cinfo.col_fmt[i + 1]) {
1962 case COL_DEF_DL_SRC:
1963 case COL_RES_DL_SRC:
1964 case COL_UNRES_DL_SRC:
1965 switch (cf->cinfo.col_fmt[i + 1]) {
1967 case COL_DEF_DL_DST:
1968 case COL_RES_DL_DST:
1969 case COL_UNRES_DL_DST:
1979 case COL_DEF_NET_SRC:
1980 case COL_RES_NET_SRC:
1981 case COL_UNRES_NET_SRC:
1982 switch (cf->cinfo.col_fmt[i + 1]) {
1984 case COL_DEF_NET_DST:
1985 case COL_RES_NET_DST:
1986 case COL_UNRES_NET_DST:
1999 switch (cf->cinfo.col_fmt[i + 1]) {
2013 case COL_DEF_DL_DST:
2014 case COL_RES_DL_DST:
2015 case COL_UNRES_DL_DST:
2016 switch (cf->cinfo.col_fmt[i + 1]) {
2018 case COL_DEF_DL_SRC:
2019 case COL_RES_DL_SRC:
2020 case COL_UNRES_DL_SRC:
2030 case COL_DEF_NET_DST:
2031 case COL_RES_NET_DST:
2032 case COL_UNRES_NET_DST:
2033 switch (cf->cinfo.col_fmt[i + 1]) {
2035 case COL_DEF_NET_SRC:
2036 case COL_RES_NET_SRC:
2037 case COL_UNRES_NET_SRC:
2056 print_hex_data(stdout, print_args.format, edt);
2061 /* The ANSI C standard does not appear to *require* that a line-buffered
2062 stream be flushed to the host environment whenever a newline is
2063 written, it just says that, on such a stream, characters "are
2064 intended to be transmitted to or from the host environment as a
2065 block when a new-line character is encountered".
2067 The Visual C++ 6.0 C implementation doesn't do what is intended;
2068 even if you set a stream to be line-buffered, it still doesn't
2069 flush the buffer at the end of every line.
2071 So, if the "-l" flag was specified, we flush the standard output
2072 at the end of a packet. This will do the right thing if we're
2073 printing packet summary lines, and, as we print the entire protocol
2074 tree for a single packet without waiting for anything to happen,
2075 it should be as good as line-buffered mode if we're printing
2076 protocol trees. (The whole reason for the "-l" flag in either
2077 tcpdump or Tethereal is to allow the output of a live capture to
2078 be piped to a program or script and to have that script see the
2079 information for the packet as soon as it's printed, rather than
2080 having to wait until a standard I/O buffer fills up. */
2084 epan_dissect_free(edt);
2086 clear_fdata(&fdata);
2090 file_open_error_message(int err, gboolean for_writing, int file_type)
2093 static char errmsg_errno[1024+1];
2097 case WTAP_ERR_NOT_REGULAR_FILE:
2098 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2101 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2102 case WTAP_ERR_UNSUPPORTED:
2103 /* Seen only when opening a capture file for reading. */
2104 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
2107 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2108 /* Seen only when opening a capture file for writing. */
2109 snprintf(errmsg_errno, sizeof(errmsg_errno),
2110 "The file \"%%s\" is a pipe, and %s capture files cannot be "
2111 "written to a pipe.", wtap_file_type_string(file_type));
2112 errmsg = errmsg_errno;
2115 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2116 /* Seen only when opening a capture file for writing. */
2117 errmsg = "Tethereal does not support writing capture files in that format.";
2120 case WTAP_ERR_UNSUPPORTED_ENCAP:
2121 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2123 errmsg = "Tethereal cannot save this capture in that format.";
2125 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2128 case WTAP_ERR_BAD_RECORD:
2129 errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2132 case WTAP_ERR_CANT_OPEN:
2134 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2136 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2139 case WTAP_ERR_SHORT_READ:
2140 errmsg = "The file \"%s\" appears to have been cut short"
2141 " in the middle of a packet or other data.";
2144 case WTAP_ERR_SHORT_WRITE:
2145 errmsg = "A full header couldn't be written to the file \"%s\".";
2150 errmsg = "The path to the file \"%s\" does not exist.";
2152 errmsg = "The file \"%s\" does not exist.";
2157 errmsg = "You do not have permission to create or write to the file \"%s\".";
2159 errmsg = "You do not have permission to read the file \"%s\".";
2163 errmsg = "\"%s\" is a directory (folder), not a file.";
2167 snprintf(errmsg_errno, sizeof(errmsg_errno),
2168 "The file \"%%s\" could not be %s: %s.",
2169 for_writing ? "created" : "opened",
2170 wtap_strerror(err));
2171 errmsg = errmsg_errno;
2178 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
2182 char err_msg[2048+1];
2184 wth = wtap_open_offline(fname, &err, FALSE);
2188 /* The open succeeded. Fill in the information for this file. */
2190 /* Initialize all data structures used for dissection. */
2194 cf->filed = -1; /* not used, but set it anyway */
2195 cf->f_len = 0; /* not used, but set it anyway */
2197 /* Set the file name because we need it to set the follow stream filter.
2198 XXX - is that still true? We need it for other reasons, though,
2200 cf->filename = g_strdup(fname);
2202 /* Indicate whether it's a permanent or temporary file. */
2203 cf->is_tempfile = is_tempfile;
2205 /* If it's a temporary capture buffer file, mark it as not saved. */
2206 cf->user_saved = !is_tempfile;
2208 cf->cd_t = wtap_file_type(cf->wth);
2210 cf->drops_known = FALSE;
2214 cf->snap = wtap_snapshot_length(cf->wth);
2215 if (cf->snap == 0) {
2216 /* Snapshot length not known. */
2217 cf->has_snap = FALSE;
2218 cf->snap = WTAP_MAX_PACKET_SIZE;
2220 cf->has_snap = TRUE;
2221 cf->progbar_quantum = 0;
2222 cf->progbar_nextstep = 0;
2223 firstsec = 0, firstusec = 0;
2224 prevsec = 0, prevusec = 0;
2229 snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE, 0),
2231 fprintf(stderr, "tethereal: %s\n", err_msg);
2236 /* Take care of byte order in the libpcap headers read from pipes.
2237 * (function taken from wiretap/libpcap.c) */
2239 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
2241 if (ld->byte_swapped) {
2242 /* Byte-swap the record header fields. */
2243 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
2244 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
2245 rechdr->incl_len = BSWAP32(rechdr->incl_len);
2246 rechdr->orig_len = BSWAP32(rechdr->orig_len);
2249 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
2250 swapped, in order to match the BPF header layout.
2252 Unfortunately, some files were, according to a comment in the "libpcap"
2253 source, written with version 2.3 in their headers but without the
2254 interchanged fields, so if "incl_len" is greater than "orig_len" - which
2255 would make no sense - we assume that we need to swap them. */
2256 if (hdr->version_major == 2 &&
2257 (hdr->version_minor < 3 ||
2258 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
2261 temp = rechdr->orig_len;
2262 rechdr->orig_len = rechdr->incl_len;
2263 rechdr->incl_len = temp;
2267 /* Mimic pcap_open_live() for pipe captures
2268 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
2270 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2271 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2273 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
2274 char *errmsg, int errmsgl)
2276 struct stat pipe_stat;
2280 unsigned int bytes_read;
2283 * XXX Tethereal blocks until we return
2285 if (strcmp(pipename, "-") == 0)
2286 fd = 0; /* read from stdin */
2288 if (stat(pipename, &pipe_stat) < 0) {
2289 if (errno == ENOENT || errno == ENOTDIR)
2290 ld->pipe_err = PIPNEXIST;
2292 snprintf(errmsg, errmsgl,
2293 "The capture session could not be initiated "
2294 "due to error on pipe: %s", strerror(errno));
2295 ld->pipe_err = PIPERR;
2299 if (! S_ISFIFO(pipe_stat.st_mode)) {
2300 if (S_ISCHR(pipe_stat.st_mode)) {
2302 * Assume the user specified an interface on a system where
2303 * interfaces are in /dev. Pretend we haven't seen it.
2305 ld->pipe_err = PIPNEXIST;
2307 snprintf(errmsg, errmsgl,
2308 "The capture session could not be initiated because\n"
2309 "\"%s\" is neither an interface nor a pipe", pipename);
2310 ld->pipe_err = PIPERR;
2314 fd = open(pipename, O_RDONLY);
2316 snprintf(errmsg, errmsgl,
2317 "The capture session could not be initiated "
2318 "due to error on pipe open: %s", strerror(errno));
2319 ld->pipe_err = PIPERR;
2324 ld->from_pipe = TRUE;
2326 /* read the pcap header */
2328 while (bytes_read < sizeof magic) {
2329 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
2332 snprintf(errmsg, errmsgl, "End of file on pipe during open");
2334 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
2343 /* Host that wrote it has our byte order, and was running
2344 a program using either standard or ss990417 libpcap. */
2345 ld->byte_swapped = FALSE;
2346 ld->modified = FALSE;
2348 case PCAP_MODIFIED_MAGIC:
2349 /* Host that wrote it has our byte order, but was running
2350 a program using either ss990915 or ss991029 libpcap. */
2351 ld->byte_swapped = FALSE;
2352 ld->modified = TRUE;
2354 case PCAP_SWAPPED_MAGIC:
2355 /* Host that wrote it has a byte order opposite to ours,
2356 and was running a program using either standard or
2357 ss990417 libpcap. */
2358 ld->byte_swapped = TRUE;
2359 ld->modified = FALSE;
2361 case PCAP_SWAPPED_MODIFIED_MAGIC:
2362 /* Host that wrote it out has a byte order opposite to
2363 ours, and was running a program using either ss990915
2364 or ss991029 libpcap. */
2365 ld->byte_swapped = TRUE;
2366 ld->modified = TRUE;
2369 /* Not a "libpcap" type we know about. */
2370 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2374 /* Read the rest of the header */
2376 while (bytes_read < sizeof(struct pcap_hdr)) {
2377 b = read(fd, ((char *)hdr)+bytes_read,
2378 sizeof(struct pcap_hdr) - bytes_read);
2381 snprintf(errmsg, errmsgl, "End of file on pipe during open");
2383 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
2390 if (ld->byte_swapped) {
2391 /* Byte-swap the header fields about which we care. */
2392 hdr->version_major = BSWAP16(hdr->version_major);
2393 hdr->version_minor = BSWAP16(hdr->version_minor);
2394 hdr->snaplen = BSWAP32(hdr->snaplen);
2395 hdr->network = BSWAP32(hdr->network);
2398 if (hdr->version_major < 2) {
2399 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2403 ld->pipe_state = STATE_EXPECT_REC_HDR;
2404 ld->pipe_err = PIPOK;
2408 ld->pipe_err = PIPERR;
2413 /* We read one record from the pipe, take care of byte order in the record
2414 * header, write the record in the capture file, and update capture statistics. */
2417 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
2418 struct pcaprec_modified_hdr *rechdr, guchar *data,
2419 char *errmsg, int errmsgl)
2421 struct pcap_pkthdr phdr;
2423 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2426 switch (ld->pipe_state) {
2428 case STATE_EXPECT_REC_HDR:
2429 ld->bytes_to_read = ld->modified ?
2430 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2432 ld->pipe_state = STATE_READ_REC_HDR;
2435 case STATE_READ_REC_HDR:
2436 b = read(fd, ((char *)rechdr)+ld->bytes_read,
2437 ld->bytes_to_read - ld->bytes_read);
2440 result = PD_PIPE_EOF;
2442 result = PD_PIPE_ERR;
2445 if ((ld->bytes_read += b) < ld->bytes_to_read)
2447 result = PD_REC_HDR_READ;
2450 case STATE_EXPECT_DATA:
2452 ld->pipe_state = STATE_READ_DATA;
2455 case STATE_READ_DATA:
2456 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
2459 result = PD_PIPE_EOF;
2461 result = PD_PIPE_ERR;
2464 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
2466 result = PD_DATA_READ;
2470 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
2473 } /* switch (ld->pipe_state) */
2476 * We've now read as much data as we were expecting, so process it.
2480 case PD_REC_HDR_READ:
2481 /* We've read the header. Take care of byte order. */
2482 adjust_header(ld, hdr, &rechdr->hdr);
2483 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2484 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2485 ld->packet_count+1, rechdr->hdr.incl_len);
2488 ld->pipe_state = STATE_EXPECT_DATA;
2492 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2493 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
2494 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
2495 phdr.caplen = rechdr->hdr.incl_len;
2496 phdr.len = rechdr->hdr.orig_len;
2498 capture_pcap_cb((guchar *)ld, &phdr, data);
2500 ld->pipe_state = STATE_EXPECT_REC_HDR;
2504 ld->pipe_err = PIPEOF;
2508 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2515 ld->pipe_err = PIPERR;
2516 /* Return here rather than inside the switch to prevent GCC warning */