3 * $Id: tethereal.c,v 1.178 2003/03/12 00:07:32 guy Exp $
5 * Ethereal - Network traffic analyzer
6 * By Gerald Combs <gerald@ethereal.com>
7 * Copyright 1998 Gerald Combs
9 * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10 * and Guy Harris <guy@alum.mit.edu>.
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
55 #ifdef HAVE_SYS_STAT_H
56 # include <sys/stat.h>
59 #ifdef NEED_SNPRINTF_H
60 # include "snprintf.h"
63 #ifdef NEED_STRERROR_H
72 #include <epan/epan.h>
73 #include <epan/filesystem.h>
76 #include <epan/timestamp.h>
77 #include <epan/packet.h>
82 #include <epan/resolv.h>
85 #include "pcap-util.h"
87 #include <epan/conversation.h>
88 #include <epan/plugins.h>
90 #include "conditions.h"
91 #include "capture_stop_conditions.h"
92 #include "ringbuffer.h"
93 #include <epan/epan_dissect.h>
97 #include <wiretap/wtap-capture.h>
98 #include <wiretap/libpcap.h>
102 #include "capture-wpcap.h"
105 static guint32 firstsec, firstusec;
106 static guint32 prevsec, prevusec;
107 static GString *comp_info_str, *runtime_info_str;
108 static gboolean quiet;
109 static gboolean decode;
110 static gboolean verbose;
111 static gboolean print_hex;
112 static gboolean line_buffered;
115 typedef struct _loop_data {
116 gboolean go; /* TRUE as long as we're supposed to keep capturing */
118 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
122 gboolean output_to_pipe;
125 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
126 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
127 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
129 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
130 STATE_EXPECT_DATA, STATE_READ_DATA
133 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
139 static int capture(int);
140 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
142 static void report_counts(void);
144 static BOOL WINAPI capture_cleanup(DWORD);
146 static void capture_cleanup(int);
148 static void report_counts_siginfo(int);
151 #endif /* HAVE_LIBPCAP */
158 static int load_cap_file(capture_file *, int);
159 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
160 union wtap_pseudo_header *, const guchar *);
161 static void show_capture_file_io_error(const char *, int, gboolean);
162 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
163 union wtap_pseudo_header *, const guchar *);
165 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
166 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
167 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
168 struct pcaprec_modified_hdr *, guchar *, char *, int);
172 ts_type timestamp_type = RELATIVE;
175 int snaplen; /* Maximum captured packet length */
176 int promisc_mode; /* Capture in promiscuous mode */
177 int autostop_count; /* Maximum packet count */
178 gboolean has_autostop_duration; /* TRUE if maximum capture duration
180 gint32 autostop_duration; /* Maximum capture duration */
181 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
183 gint32 autostop_filesize; /* Maximum capture file size */
184 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
185 guint32 ringbuffer_num_files; /* Number of ring buffer files */
188 static capture_options capture_opts = {
189 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
190 infinite, in effect */
191 TRUE, /* promiscuous mode is the default */
192 0, /* max packet count - default is 0,
194 FALSE, /* maximum capture duration not
195 specified by default */
196 0, /* maximum capture duration */
197 FALSE, /* maximum capture file size not
198 specified by default */
199 0, /* maximum capture file size */
200 FALSE, /* ring buffer off by default */
201 RINGBUFFER_MIN_NUM_FILES /* default number of ring buffer
206 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
207 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
209 #endif /* HAVE_LIBPCAP */
212 print_usage(gboolean print_ver)
217 fprintf(stderr, "This is GNU t%s %s\n%s\n%s\n", PACKAGE, VERSION,
218 comp_info_str->str, runtime_info_str->str);
221 fprintf(stderr, "\nt%s [ -DvVhqSlp ] [ -a <capture autostop condition> ] ...\n",
223 fprintf(stderr, "\t[ -b <number of ring buffer files> ] [ -c <count> ]\n");
224 fprintf(stderr, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
225 fprintf(stderr, "\t[ -i <interface> ] [ -n ] [ -N <resolving> ]\n");
226 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
227 fprintf(stderr, "\t[ -s <snaplen> ] [ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
229 fprintf(stderr, "\nt%s [ -vVhl ] [ -F <output file type> ] [ -n ] [ -N <resolving> ]\n", PACKAGE);
230 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
231 fprintf(stderr, "\t[ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
233 fprintf(stderr, "\t[ -Z <statistics string> ]\n");
234 fprintf(stderr, "Valid file type arguments to the \"-F\" flag:\n");
235 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
236 if (wtap_dump_can_open(i))
237 fprintf(stderr, "\t%s - %s\n",
238 wtap_file_type_short_string(i), wtap_file_type_string(i));
240 fprintf(stderr, "\tdefault is libpcap\n");
245 get_positive_int(const char *string, const char *name)
250 number = strtol(string, &p, 10);
251 if (p == string || *p != '\0') {
252 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
257 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
262 fprintf(stderr, "tethereal: The specified %s is zero\n",
266 if (number > INT_MAX) {
267 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
275 * Given a string of the form "<autostop criterion>:<value>", as might appear
276 * as an argument to a "-a" option, parse it and set the criterion in
277 * question. Return an indication of whether it succeeded or failed
281 set_autostop_criterion(const char *autostoparg)
285 colonp = strchr(autostoparg, ':');
293 * Skip over any white space (there probably won't be any, but
294 * as we allow it in the preferences file, we might as well
301 * Put the colon back, so if our caller uses, in an
302 * error message, the string they passed us, the message
308 if (strcmp(autostoparg,"duration") == 0) {
309 capture_opts.has_autostop_duration = TRUE;
310 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
311 } else if (strcmp(autostoparg,"filesize") == 0) {
312 capture_opts.has_autostop_filesize = TRUE;
313 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
317 *colonp = ':'; /* put the colon back */
322 /* structure to keep track of what tap listeners have been registered.
324 typedef struct _ethereal_tap_list {
325 struct _ethereal_tap_list *next;
327 void (*func)(char *arg);
329 static ethereal_tap_list *tap_list=NULL;
332 register_ethereal_tap(char *cmd, void (*func)(char *arg), char *dummy _U_, void (*dummy2)(void) _U_)
334 ethereal_tap_list *newtl;
336 newtl=malloc(sizeof(ethereal_tap_list));
337 newtl->next=tap_list;
345 main(int argc, char *argv[])
349 gboolean arg_error = FALSE;
357 int gpf_open_errno, pf_open_errno;
360 gboolean capture_filter_specified = FALSE;
361 GList *if_list, *if_entry;
362 gchar err_str[PCAP_ERRBUF_SIZE];
364 gboolean capture_option_specified = FALSE;
366 int out_file_type = WTAP_FILE_PCAP;
367 gchar *cf_name = NULL, *rfilter = NULL;
371 dfilter_t *rfcode = NULL;
374 ethereal_tap_list *tli;
376 /* Register all dissectors; we must do this before checking for the
377 "-G" flag, as the "-G" flag dumps information registered by the
378 dissectors, and we must do it before we read the preferences, in
379 case any dissectors register preferences. */
380 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
381 register_all_tap_listeners();
383 /* Now register the preferences for any non-dissector modules.
384 We must do that before we read the preferences as well. */
385 prefs_register_modules();
387 /* If invoked with the "-G" flag, we dump out information based on
388 the argument to the "-G" flag; if no argument is specified,
389 for backwards compatibility we dump out a glossary of display
392 We do this here to mirror what happens in the GTK+ version, although
393 it's not necessary here. */
394 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
396 proto_registrar_dump_fields();
398 if (strcmp(argv[2], "fields") == 0)
399 proto_registrar_dump_fields();
400 else if (strcmp(argv[2], "protocols") == 0)
401 proto_registrar_dump_protocols();
403 fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
411 /* Set the C-language locale to the native environment. */
412 setlocale(LC_ALL, "");
414 prefs = read_prefs(&gpf_open_errno, &gpf_path, &pf_open_errno, &pf_path);
415 if (gpf_path != NULL) {
416 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n", pf_path,
417 strerror(gpf_open_errno));
419 if (pf_path != NULL) {
420 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
421 strerror(pf_open_errno));
426 /* Set the name resolution code's flags from the preferences. */
427 g_resolv_flags = prefs->name_resolve;
430 /* Load Wpcap, if possible */
434 init_cap_file(&cfile);
436 /* Assemble the compile-time version information string */
437 comp_info_str = g_string_new("Compiled ");
438 get_compiled_version_info(comp_info_str);
440 /* Assemble the run-time version information string */
441 runtime_info_str = g_string_new("Running ");
442 get_runtime_version_info(runtime_info_str);
444 /* Now get our args */
445 while ((opt = getopt(argc, argv, "a:b:c:Df:F:hi:lnN:o:pqr:R:s:St:vw:Vxz:")) != -1) {
447 case 'a': /* autostop criteria */
449 if (set_autostop_criterion(optarg) == FALSE) {
450 fprintf(stderr, "ethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
454 capture_option_specified = TRUE;
458 case 'b': /* Ringbuffer option */
460 capture_opts.ringbuffer_on = TRUE;
461 capture_opts.ringbuffer_num_files =
462 get_positive_int(optarg, "number of ring buffer files");
464 capture_option_specified = TRUE;
468 case 'c': /* Capture xxx packets */
470 capture_opts.autostop_count =
471 get_positive_int(optarg, "packet count");
473 capture_option_specified = TRUE;
477 case 'D': /* Print a list of capture devices */
479 if_list = get_interface_list(&err, err_str);
480 if (if_list == NULL) {
483 case CANT_GET_INTERFACE_LIST:
484 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
488 case NO_INTERFACES_FOUND:
489 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
494 for (if_entry = g_list_first(if_list); if_entry != NULL;
495 if_entry = g_list_next(if_entry))
496 printf("%s\n", (char *)if_entry->data);
497 free_interface_list(if_list);
500 capture_option_specified = TRUE;
506 capture_filter_specified = TRUE;
508 g_free(cfile.cfilter);
509 cfile.cfilter = g_strdup(optarg);
511 capture_option_specified = TRUE;
516 out_file_type = wtap_short_string_to_file_type(optarg);
517 if (out_file_type < 0) {
518 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
523 case 'h': /* Print help and exit */
527 case 'i': /* Use interface xxx */
529 cfile.iface = g_strdup(optarg);
531 capture_option_specified = TRUE;
535 case 'l': /* "Line-buffer" standard output */
536 /* This isn't line-buffering, strictly speaking, it's just
537 flushing the standard output after the information for
538 each packet is printed; however, that should be good
539 enough for all the purposes to which "-l" is put.
541 See the comment in "wtap_dispatch_cb_print()" for an
542 explanation of why we do that, and why we don't just
543 use "setvbuf()" to make the standard output line-buffered
544 (short version: in Windows, "line-buffered" is the same
545 as "fully-buffered", and the output buffer is only flushed
546 when it fills up). */
547 line_buffered = TRUE;
549 case 'n': /* No name resolution */
550 g_resolv_flags = RESOLV_NONE;
552 case 'N': /* Select what types of addresses/port #s to resolve */
553 if (g_resolv_flags == RESOLV_ALL)
554 g_resolv_flags = RESOLV_NONE;
555 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
556 if (badopt != '\0') {
557 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
562 case 'o': /* Override preference from command line */
563 switch (prefs_set_pref(optarg)) {
565 case PREFS_SET_SYNTAX_ERR:
566 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
570 case PREFS_SET_NO_SUCH_PREF:
571 case PREFS_SET_OBSOLETE:
572 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
578 case 'p': /* Don't capture in promiscuous mode */
580 capture_opts.promisc_mode = FALSE;
582 capture_option_specified = TRUE;
586 case 'q': /* Quiet */
589 case 'r': /* Read capture file xxx */
590 cf_name = g_strdup(optarg);
592 case 'R': /* Read file filter */
595 case 's': /* Set the snapshot (capture) length */
597 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
599 capture_option_specified = TRUE;
603 case 'S': /* show packets in real time */
606 case 't': /* Time stamp type */
607 if (strcmp(optarg, "r") == 0)
608 timestamp_type = RELATIVE;
609 else if (strcmp(optarg, "a") == 0)
610 timestamp_type = ABSOLUTE;
611 else if (strcmp(optarg, "ad") == 0)
612 timestamp_type = ABSOLUTE_WITH_DATE;
613 else if (strcmp(optarg, "d") == 0)
614 timestamp_type = DELTA;
616 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
618 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
619 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
623 case 'v': /* Show version and exit */
624 printf("t%s %s\n%s\n%s\n", PACKAGE, VERSION, comp_info_str->str,
625 runtime_info_str->str);
628 case 'w': /* Write to capture file xxx */
629 cfile.save_file = g_strdup(optarg);
631 case 'V': /* Verbose */
634 case 'x': /* Print packet data in hex (and ASCII) */
638 for(tli=tap_list;tli;tli=tli->next){
639 if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
640 (*tli->func)(optarg);
645 fprintf(stderr,"tethereal: invalid -z argument.\n");
646 fprintf(stderr," -z argument must be one of :\n");
647 for(tli=tap_list;tli;tli=tli->next){
648 fprintf(stderr," %s\n",tli->cmd);
654 case '?': /* Bad flag - print usage message */
660 /* If no capture filter or read filter has been specified, and there are
661 still command-line arguments, treat them as the tokens of a capture
662 filter (if no "-r" flag was specified) or a read filter (if a "-r"
663 flag was specified. */
665 if (cf_name != NULL) {
666 if (rfilter != NULL) {
668 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
671 rfilter = get_args_as_string(argc, argv, optind);
674 if (capture_filter_specified) {
676 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
679 cfile.cfilter = get_args_as_string(argc, argv, optind);
681 capture_option_specified = TRUE;
686 /* See if we're writing a capture file and the file is a pipe */
688 ld.output_to_pipe = FALSE;
690 if (cfile.save_file != NULL) {
691 if (strcmp(cfile.save_file, "-") == 0) {
693 g_free(cfile.save_file);
694 cfile.save_file = g_strdup("");
696 ld.output_to_pipe = TRUE;
701 err = test_for_fifo(cfile.save_file);
704 case ENOENT: /* it doesn't exist, so we'll be creating it,
705 and it won't be a FIFO */
706 case 0: /* found it, but it's not a FIFO */
709 case ESPIPE: /* it is a FIFO */
710 ld.output_to_pipe = TRUE;
713 default: /* couldn't stat it */
715 "tethereal: Error testing whether capture file is a pipe: %s\n",
724 /* If they didn't specify a "-w" flag, but specified a maximum capture
725 file size, tell them that this doesn't work, and exit. */
726 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
727 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
728 "capture isn't being saved to a file.\n");
732 if (capture_opts.ringbuffer_on) {
733 /* Ring buffer works only under certain conditions:
734 a) ring buffer does not work if you're not saving the capture to
736 b) ring buffer only works if you're saving in libpcap format;
737 c) it makes no sense to enable the ring buffer if the maximum
738 file size is set to "infinite";
739 d) file must not be a pipe. */
740 if (cfile.save_file == NULL) {
741 fprintf(stderr, "tethereal: Ring buffer requested, but "
742 "capture isn't being saved to a file.\n");
745 if (out_file_type != WTAP_FILE_PCAP) {
746 fprintf(stderr, "tethereal: Ring buffer requested, but "
747 "capture isn't being saved in libpcap format.\n");
750 if (!capture_opts.has_autostop_filesize) {
751 fprintf(stderr, "tethereal: Ring buffer requested, but "
752 "no maximum capture file size was specified.\n");
755 if (ld.output_to_pipe) {
756 fprintf(stderr, "tethereal: Ring buffer requested, but "
757 "capture file is a pipe.\n");
764 /* Start windows sockets */
765 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
768 /* Notify all registered modules that have had any of their preferences
769 changed either from one of the preferences file or from the command
770 line that their preferences have changed. */
774 if (capture_option_specified)
775 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
782 /* Build the column format array */
783 col_init(&cfile.cinfo, prefs->num_cols);
784 for (i = 0; i < cfile.cinfo.num_cols; i++) {
785 cfile.cinfo.col_fmt[i] = get_column_format(i);
786 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
787 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
789 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
790 cfile.cinfo.col_data[i] = NULL;
791 if (cfile.cinfo.col_fmt[i] == COL_INFO)
792 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
794 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
796 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
797 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
801 if (capture_opts.snaplen < 1)
802 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
803 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
804 capture_opts.snaplen = MIN_PACKET_SIZE;
806 /* Check the value range of the ringbuffer_num_files parameter */
807 if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
808 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
809 else if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
810 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
813 if (rfilter != NULL) {
814 if (!dfilter_compile(rfilter, &rfcode)) {
815 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
820 cfile.rfcode = rfcode;
822 err = open_cap_file(cf_name, FALSE, &cfile);
827 err = load_cap_file(&cfile, out_file_type);
834 /* No capture file specified, so we're supposed to do a live capture;
835 do we have support for live captures? */
840 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
845 /* Yes; did the user specify an interface to use? */
846 if (cfile.iface == NULL) {
847 /* No - is a default specified in the preferences file? */
848 if (prefs->capture_device != NULL) {
850 if_text = strrchr(prefs->capture_device, ' ');
851 if (if_text == NULL) {
852 cfile.iface = g_strdup(prefs->capture_device);
854 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
857 /* No - pick the first one from the list of interfaces. */
858 if_list = get_interface_list(&err, err_str);
859 if (if_list == NULL) {
862 case CANT_GET_INTERFACE_LIST:
863 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
867 case NO_INTERFACES_FOUND:
868 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
873 if_text = strrchr(if_list->data, ' '); /* first interface */
874 if (if_text == NULL) {
875 cfile.iface = g_strdup(if_list->data);
877 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
879 free_interface_list(if_list);
882 capture(out_file_type);
884 if (capture_opts.ringbuffer_on) {
889 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
894 draw_tap_listeners(TRUE);
901 /* Do the low-level work of a capture.
902 Returns TRUE if it succeeds, FALSE otherwise. */
904 capture(int out_file_type)
908 gchar open_err_str[PCAP_ERRBUF_SIZE];
909 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
910 bpf_u_int32 netnum, netmask;
911 struct bpf_program fcode;
912 void (*oldhandler)(int);
914 int volatile volatile_err = 0;
915 int volatile inpkts = 0;
918 condition *volatile cnd_stop_capturesize = NULL;
919 condition *volatile cnd_stop_timeout = NULL;
921 static const char ppamsg[] = "can't find PPA for ";
923 volatile int pipe_fd = -1;
925 struct pcaprec_modified_hdr rechdr;
926 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
928 struct pcap_stat stats;
932 /* Initialize all data structures used for dissection. */
935 ld.linktype = WTAP_ENCAP_UNKNOWN;
938 /* Open the network interface to capture from it.
939 Some versions of libpcap may put warnings into the error buffer
940 if they succeed; to tell if that's happened, we have to clear
941 the error buffer, and check if it's still a null string. */
942 open_err_str[0] = '\0';
943 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
944 capture_opts.promisc_mode, 1000, open_err_str);
946 if (ld.pch == NULL) {
947 /* We couldn't open "cfile.iface" as a network device. */
949 /* On Windows, we don't support capturing on pipes, so we give up. */
951 /* On Win32 OSes, the capture devices are probably available to all
952 users; don't warn about permissions problems.
954 Do, however, warn that WAN devices aren't supported. */
955 snprintf(errmsg, sizeof errmsg,
956 "The capture session could not be initiated (%s).\n"
957 "Please check that you have the proper interface specified.\n"
959 "Note that the driver Tethereal uses for packet capture on Windows doesn't\n"
960 "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
964 /* try to open cfile.iface as a pipe */
965 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
969 if (ld.pipe_err == PIPNEXIST) {
970 /* Pipe doesn't exist, so output message for interface */
972 /* If we got a "can't find PPA for XXX" message, warn the user (who
973 is running Tethereal on HP-UX) that they don't have a version
974 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
975 versions, which properly handle HP-UX, say "can't find /dev/dlpi
976 PPA for XXX" rather than "can't find PPA for XXX"). */
977 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
980 "You are running Tethereal with a version of the libpcap library\n"
981 "that doesn't handle HP-UX network devices well; this means that\n"
982 "Tethereal may not be able to capture packets.\n"
984 "To fix this, you should install libpcap 0.6.2, or a later version\n"
985 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
986 "packaged binary form from the Software Porting And Archive Centre\n"
987 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
988 "at the URL lists a number of mirror sites.";
991 snprintf(errmsg, sizeof errmsg,
992 "The capture session could not be initiated (%s).\n"
993 "Please check to make sure you have sufficient permissions, and that\n"
994 "you have the proper interface or pipe specified.%s", open_err_str,
998 * Else pipe (or file) does exist and pipe_open_live() has
1003 /* pipe_open_live() succeeded; don't want
1004 error message from pcap_open_live() */
1005 open_err_str[0] = '\0';
1009 if (cfile.cfilter && !ld.from_pipe) {
1010 /* A capture filter was specified; set it up. */
1011 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1013 * Well, we can't get the netmask for this interface; it's used
1014 * only for filters that check for broadcast IP addresses, so
1015 * we just warn the user, and punt and use 0.
1018 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1021 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1022 snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1023 pcap_geterr(ld.pch));
1026 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1027 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1028 pcap_geterr(ld.pch));
1033 /* Set up to write to the capture file. */
1036 pcap_encap = hdr.network;
1037 file_snaplen = hdr.snaplen;
1041 pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1042 file_snaplen = pcap_snapshot(ld.pch);
1044 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1045 if (cfile.save_file != NULL) {
1046 /* Set up to write to the capture file. */
1047 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1048 strcpy(errmsg, "The network you're capturing from is of a type"
1049 " that Tethereal doesn't support.");
1052 if (capture_opts.ringbuffer_on) {
1053 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1054 capture_opts.ringbuffer_num_files);
1055 if (cfile.save_file_fd != -1) {
1056 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1057 pcap_snapshot(ld.pch), &err);
1059 err = errno; /* "ringbuf_init()" failed */
1063 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1064 ld.linktype, pcap_snapshot(ld.pch), &err);
1067 if (ld.pdh == NULL) {
1068 snprintf(errmsg, sizeof errmsg,
1069 file_open_error_message(err, TRUE, out_file_type),
1070 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1075 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1076 returned a warning; print it, but keep capturing. */
1077 if (open_err_str[0] != '\0')
1078 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1081 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1082 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1084 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1086 XXX - deal with signal semantics on various UNIX platforms. Or just
1087 use "sigaction()" and be done with it? */
1088 signal(SIGTERM, capture_cleanup);
1089 signal(SIGINT, capture_cleanup);
1090 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1091 signal(SIGHUP, oldhandler);
1094 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1095 quiet mode, report the number of packets we've captured. */
1096 signal(SIGINFO, report_counts_siginfo);
1097 #endif /* SIGINFO */
1100 /* Let the user know what interface was chosen. */
1101 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1103 /* initialize capture stop conditions */
1104 init_capture_stop_conditions();
1105 /* create stop conditions */
1106 if (capture_opts.has_autostop_filesize)
1107 cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1108 (long)capture_opts.autostop_filesize * 1000);
1109 if (capture_opts.has_autostop_duration)
1110 cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1111 (gint32)capture_opts.autostop_duration);
1113 if (!setjmp(ld.stopenv)) {
1115 ld.packet_count = 0;
1119 /* We need to be careful with automatic variables defined in the
1120 outer scope which are changed inside the loop. Most compilers
1121 don't try to roll them back to their original values after the
1122 longjmp which causes the loop to finish, but all that the
1123 standards say is that their values are indeterminate. If we
1124 don't want them to be rolled back, we should define them with the
1125 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1126 Programming in the UNIX Environment, p. 178).
1128 The "err" variable causes a particular problem. If we give it
1129 the volatile attribute, then when we pass a reference to it (as
1130 in "&err") to a function, GCC warns: "passing arg <n> of
1131 <function> discards qualifiers from pointer target type".
1132 Therefore within the loop and just beyond we don't use "err".
1133 Within the loop we define "loop_err", and assign its value to
1134 "volatile_err", which is in the outer scope and is checked when
1137 We also define "packet_count_prev" here to keep things tidy,
1138 since it's used only inside the loop. If it were defined in the
1139 outer scope, GCC would give a warning (unnecessary in this case)
1140 that it might be clobbered, and we'd need to give it the volatile
1141 attribute to suppress the warning. */
1144 int packet_count_prev = 0;
1146 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1147 /* We're not stopping at a particular capture file size, and we're
1148 not stopping after some particular amount of time has expired,
1149 so either we have no stop condition or the only stop condition
1150 is a maximum packet count.
1152 If there's no maximum packet count, pass it -1, meaning "until
1153 you run out of packets in the bufferful you read". Otherwise,
1154 pass it the number of packets we have left to capture.
1156 We don't call "pcap_loop()" as, if we're saving to a file that's
1157 a FIFO, we want to flush the FIFO after we're done processing
1158 this libpcap bufferful of packets, so that the program
1159 reading the FIFO sees the packets immediately and doesn't get
1160 any partial packet, forcing it to block in the middle of reading
1162 if (capture_opts.autostop_count == 0)
1165 if (ld.packet_count >= capture_opts.autostop_count) {
1166 /* XXX do we need this test here? */
1167 /* It appears there's nothing more to capture. */
1170 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1173 /* We need to check the capture file size or the timeout after
1179 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1180 errmsg, sizeof errmsg);
1183 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1185 /* Error from "pcap_dispatch()", or error or "no more packets" from
1186 "pipe_dispatch(). */
1188 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1189 /* The specified capture time has elapsed; stop the capture. */
1191 } else if (inpkts > 0) {
1192 if (capture_opts.autostop_count != 0 &&
1193 ld.packet_count >= capture_opts.autostop_count) {
1194 /* The specified number of packets have been captured and have
1195 passed both any capture filter in effect and any read filter
1198 } else if (cnd_stop_capturesize != NULL &&
1199 cnd_eval(cnd_stop_capturesize,
1200 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1201 /* We're saving the capture to a file, and the capture file reached
1202 its maximum size. */
1203 if (capture_opts.ringbuffer_on) {
1204 /* Switch to the next ringbuffer file */
1205 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1206 /* File switch succeeded: reset the condition */
1207 cnd_reset(cnd_stop_capturesize);
1209 /* File switch failed: stop here */
1210 volatile_err = loop_err;
1214 /* No ringbuffer - just stop. */
1218 if (ld.output_to_pipe) {
1219 if (ld.packet_count > packet_count_prev) {
1220 if (fflush(wtap_dump_file(ld.pdh))) {
1221 volatile_err = errno;
1224 packet_count_prev = ld.packet_count;
1228 } /* while (ld.go) */
1230 /* delete stop conditions */
1231 if (cnd_stop_capturesize != NULL)
1232 cnd_delete(cnd_stop_capturesize);
1233 if (cnd_stop_timeout != NULL)
1234 cnd_delete(cnd_stop_timeout);
1236 if ((cfile.save_file != NULL) && !quiet) {
1237 /* We're saving to a file, which means we're printing packet counts
1238 to stderr if we are not running silent and deep.
1239 Send a newline so that we move to the line after the packet count. */
1240 fprintf(stderr, "\n");
1243 /* If we got an error while capturing, report it. */
1247 if (ld.pipe_err == PIPERR) {
1248 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1254 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1255 pcap_geterr(ld.pch));
1259 if (volatile_err == 0)
1262 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
1266 if (cfile.save_file != NULL) {
1267 /* We're saving to a file or files; close all files. */
1268 if (capture_opts.ringbuffer_on) {
1269 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1271 dump_ok = wtap_dump_close(ld.pdh, &err);
1273 /* If we've displayed a message about a write error, there's no point
1274 in displaying another message about an error on close. */
1275 if (!dump_ok && !write_err)
1276 show_capture_file_io_error(cfile.save_file, err, TRUE);
1280 if (ld.from_pipe && pipe_fd >= 0)
1285 /* Get the capture statistics, and, if any packets were dropped, report
1287 if (pcap_stats(ld.pch, &stats) >= 0) {
1288 if (stats.ps_drop != 0) {
1289 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1292 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
1293 pcap_geterr(ld.pch));
1298 /* Report the number of captured packets if not reported during capture
1299 and we are saving to a file. */
1305 if (capture_opts.ringbuffer_on) {
1306 ringbuf_error_cleanup();
1308 g_free(cfile.save_file);
1309 cfile.save_file = NULL;
1310 fprintf(stderr, "tethereal: %s\n", errmsg);
1326 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
1329 struct wtap_pkthdr whdr;
1330 union wtap_pseudo_header pseudo_header;
1331 loop_data *ld = (loop_data *) user;
1335 /* Convert from libpcap to Wiretap format.
1336 If that fails, ignore the packet (wtap_process_pcap_packet has
1337 written an error message). */
1338 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
1347 wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1348 /* Report packet capture count if not quiet */
1351 if (ld->packet_count != 0) {
1352 fprintf(stderr, "\r%u ", ld->packet_count);
1353 /* stderr could be line buffered */
1357 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
1358 &pseudo_header, pd);
1362 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1368 capture_cleanup(DWORD ctrltype _U_)
1370 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1371 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1372 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1373 like SIGTERM at least when the machine's shutting down.
1375 For now, we handle them all as indications that we should clean up
1376 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1379 However, as handlers run in a new thread, we can't just longjmp
1380 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1381 no other handler - such as one that would terminate the process -
1384 XXX - for some reason, typing ^C to Tethereal, if you run this in
1385 a Cygwin console window in at least some versions of Cygwin,
1386 causes Tethereal to terminate immediately; this routine gets
1387 called, but the main loop doesn't get a chance to run and
1388 exit cleanly, at least if this is compiled with Microsoft Visual
1389 C++ (i.e., it's a property of the Cygwin console window or Bash;
1390 it happens if Tethereal is not built with Cygwin - for all I know,
1391 building it with Cygwin may make the problem go away). */
1397 capture_cleanup(int signum _U_)
1399 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1400 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1401 "ld.go" to FALSE and return, we won't break out of it and quit
1403 longjmp(ld.stopenv, 1);
1411 /* XXX - if we use sigaction, this doesn't have to be done.
1412 (Yes, this isn't necessary on BSD, but just in case a system
1413 where "signal()" has AT&T semantics adopts SIGINFO....) */
1414 signal(SIGINFO, report_counts_siginfo);
1415 #endif /* SIGINFO */
1417 if (cfile.save_file != NULL && quiet) {
1418 /* Report the count only if we're capturing to a file (rather
1419 than printing captured packet information out) and aren't
1420 updating a count as packets arrive. */
1421 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1424 infoprint = FALSE; /* we just reported it */
1425 #endif /* SIGINFO */
1430 report_counts_siginfo(int signum _U_)
1432 /* If we've been told to delay printing, just set a flag asking
1433 that we print counts (if we're supposed to), otherwise print
1434 the count of packets captured (if we're supposed to). */
1440 #endif /* SIGINFO */
1441 #endif /* HAVE_LIBPCAP */
1444 load_cap_file(capture_file *cf, int out_file_type)
1447 int snapshot_length;
1453 linktype = wtap_file_encap(cf->wth);
1454 if (cf->save_file != NULL) {
1455 /* Set up to write to the capture file. */
1456 snapshot_length = wtap_snapshot_length(cf->wth);
1457 if (snapshot_length == 0) {
1458 /* Snapshot length of input file not known. */
1459 snapshot_length = WTAP_MAX_PACKET_SIZE;
1461 pdh = wtap_dump_open(cf->save_file, out_file_type,
1462 linktype, snapshot_length, &err);
1465 /* We couldn't set up to write to the capture file. */
1468 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1470 "tethereal: Capture files can't be written in that format.\n");
1473 case WTAP_ERR_UNSUPPORTED_ENCAP:
1474 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1476 "tethereal: The capture file being read cannot be written in "
1480 case WTAP_ERR_CANT_OPEN:
1482 "tethereal: The file \"%s\" couldn't be created for some "
1483 "unknown reason.\n",
1484 *cf->save_file == '\0' ? "stdout" : cf->save_file);
1487 case WTAP_ERR_SHORT_WRITE:
1489 "tethereal: A full header couldn't be written to the file \"%s\".\n",
1490 *cf->save_file == '\0' ? "stdout" : cf->save_file);
1495 "tethereal: The file \"%s\" could not be created: %s\n.",
1496 *cf->save_file == '\0' ? "stdout" : cf->save_file,
1497 wtap_strerror(err));
1504 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
1507 /* Now close the capture file. */
1508 if (!wtap_dump_close(pdh, &err))
1509 show_capture_file_io_error(cfile.save_file, err, TRUE);
1513 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
1517 /* Print up a message box noting that the read failed somewhere along
1521 case WTAP_ERR_UNSUPPORTED_ENCAP:
1523 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
1527 case WTAP_ERR_CANT_READ:
1529 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
1533 case WTAP_ERR_SHORT_READ:
1535 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
1539 case WTAP_ERR_BAD_RECORD:
1541 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
1547 "tethereal: An error occurred while reading \"%s\": %s.\n",
1548 cf->filename, wtap_strerror(err));
1554 wtap_close(cf->wth);
1561 fill_in_fdata(frame_data *fdata, capture_file *cf,
1562 const struct wtap_pkthdr *phdr, long offset)
1567 fdata->num = cf->count;
1568 fdata->pkt_len = phdr->len;
1569 fdata->cap_len = phdr->caplen;
1570 fdata->file_off = offset;
1571 fdata->lnk_t = phdr->pkt_encap;
1572 fdata->abs_secs = phdr->ts.tv_sec;
1573 fdata->abs_usecs = phdr->ts.tv_usec;
1574 fdata->flags.passed_dfilter = 0;
1575 fdata->flags.encoding = CHAR_ASCII;
1576 fdata->flags.visited = 0;
1577 fdata->flags.marked = 0;
1579 /* If we don't have the time stamp of the first packet in the
1580 capture, it's because this is the first packet. Save the time
1581 stamp of this packet as the time stamp of the first packet. */
1582 if (!firstsec && !firstusec) {
1583 firstsec = fdata->abs_secs;
1584 firstusec = fdata->abs_usecs;
1587 /* If we don't have the time stamp of the previous displayed packet,
1588 it's because this is the first displayed packet. Save the time
1589 stamp of this packet as the time stamp of the previous displayed
1591 if (!prevsec && !prevusec) {
1592 prevsec = fdata->abs_secs;
1593 prevusec = fdata->abs_usecs;
1596 /* Get the time elapsed between the first packet and this packet. */
1597 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
1598 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
1600 /* If it's greater than the current elapsed time, set the elapsed time
1601 to it (we check for "greater than" so as not to be confused by
1602 time moving backwards). */
1603 if ((gint32)cf->esec < fdata->rel_secs
1604 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
1605 cf->esec = fdata->rel_secs;
1606 cf->eusec = fdata->rel_usecs;
1609 /* Get the time elapsed between the previous displayed packet and
1611 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
1612 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
1613 prevsec = fdata->abs_secs;
1614 prevusec = fdata->abs_usecs;
1617 /* Free up all data attached to a "frame_data" structure. */
1619 clear_fdata(frame_data *fdata)
1622 g_slist_free(fdata->pfd);
1626 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
1627 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
1629 cb_args_t *args = (cb_args_t *) user;
1630 capture_file *cf = args->cf;
1631 wtap_dumper *pdh = args->pdh;
1635 epan_dissect_t *edt;
1639 * Prevent a SIGINFO handler from writing to stdout while we're
1640 * doing so; instead, have it just set a flag telling us to print
1641 * that information when we're done.
1644 #endif /* SIGINFO */
1648 fill_in_fdata(&fdata, cf, phdr, offset);
1649 edt = epan_dissect_new(TRUE, FALSE);
1650 epan_dissect_prime_dfilter(edt, cf->rfcode);
1651 epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
1652 passed = dfilter_apply_edt(cf->rfcode, edt);
1658 /* The packet passed the read filter. */
1662 if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
1664 if (ld.pch != NULL && !quiet) {
1665 /* We're capturing packets, so (if -q not specified) we're printing
1666 a count of packets captured; move to the line after the count. */
1667 fprintf(stderr, "\n");
1670 show_capture_file_io_error(cf->save_file, err, FALSE);
1675 wtap_dump_close(pdh, &err);
1680 epan_dissect_free(edt);
1682 clear_fdata(&fdata);
1686 * Allow SIGINFO handlers to write.
1691 * If a SIGINFO handler asked us to write out capture counts, do so.
1695 #endif /* SIGINFO */
1699 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
1708 "tethereal: Not all the packets could be written to \"%s\" because there is "
1709 "no space left on the file system.\n",
1716 "tethereal: Not all the packets could be written to \"%s\" because you are "
1717 "too close to, or over your disk quota.\n",
1722 case WTAP_ERR_CANT_CLOSE:
1724 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
1728 case WTAP_ERR_SHORT_WRITE:
1730 "tethereal: Not all the packets could be written to \"%s\".\n",
1737 "tethereal: \"%s\" could not be closed: %s.\n",
1738 fname, wtap_strerror(err));
1741 "tethereal: An error occurred while writing to \"%s\": %s.\n",
1742 fname, wtap_strerror(err));
1749 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
1750 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
1752 cb_args_t *args = (cb_args_t *) user;
1753 capture_file *cf = args->cf;
1756 print_args_t print_args;
1757 epan_dissect_t *edt;
1758 gboolean create_proto_tree;
1763 fill_in_fdata(&fdata, cf, phdr, offset);
1766 if (cf->rfcode || verbose || num_tap_filters!=0)
1767 create_proto_tree = TRUE;
1769 create_proto_tree = FALSE;
1770 /* The protocol tree will be "visible", i.e., printed, only if we're
1771 not printing a summary.
1773 We only need the columns if we're *not* verbose; in verbose mode,
1774 we print the protocol tree, not the protocol summary. */
1776 edt = epan_dissect_new(create_proto_tree, verbose);
1778 epan_dissect_prime_dfilter(edt, cf->rfcode);
1781 tap_queue_init(edt);
1782 epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
1783 tap_push_tapped_queue(edt);
1786 passed = dfilter_apply_edt(cf->rfcode, edt);
1789 /* The packet passed the read filter. */
1794 /* Print the information in the protocol tree. */
1795 print_args.to_file = TRUE;
1796 print_args.format = PR_FMT_TEXT;
1797 print_args.print_summary = FALSE;
1798 print_args.print_hex = print_hex;
1799 print_args.expand_all = TRUE;
1800 print_args.suppress_unmarked = FALSE;
1801 proto_tree_print(&print_args, edt, stdout);
1803 /* "print_hex_data()" will put out a leading blank line, as well
1804 as a trailing one; print one here, to separate the packets,
1805 only if "print_hex_data()" won't be called. */
1809 /* Just fill in the columns. */
1810 epan_dissect_fill_in_columns(edt);
1812 /* Now print them. */
1813 for (i = 0; i < cf->cinfo.num_cols; i++) {
1814 switch (cf->cinfo.col_fmt[i]) {
1817 * Don't print this if we're doing a live capture from a network
1818 * interface - if we're doing a live capture, you won't be
1819 * able to look at the capture in the future (it's not being
1820 * saved anywhere), so the frame numbers are unlikely to be
1823 * (XXX - it might be nice to be able to save and print at
1824 * the same time, sort of like an "Update list of packets
1825 * in real time" capture in Ethereal.)
1827 if (cf->iface != NULL)
1829 printf("%3s", cf->cinfo.col_data[i]);
1835 case COL_ABS_DATE_TIME: /* XXX - wider */
1836 printf("%10s", cf->cinfo.col_data[i]);
1842 case COL_DEF_DL_SRC:
1843 case COL_RES_DL_SRC:
1844 case COL_UNRES_DL_SRC:
1845 case COL_DEF_NET_SRC:
1846 case COL_RES_NET_SRC:
1847 case COL_UNRES_NET_SRC:
1848 printf("%12s", cf->cinfo.col_data[i]);
1854 case COL_DEF_DL_DST:
1855 case COL_RES_DL_DST:
1856 case COL_UNRES_DL_DST:
1857 case COL_DEF_NET_DST:
1858 case COL_RES_NET_DST:
1859 case COL_UNRES_NET_DST:
1860 printf("%-12s", cf->cinfo.col_data[i]);
1864 printf("%s", cf->cinfo.col_data[i]);
1867 if (i != cf->cinfo.num_cols - 1) {
1869 * This isn't the last column, so we need to print a
1870 * separator between this column and the next.
1872 * If we printed a network source and are printing a
1873 * network destination of the same type next, separate
1874 * them with "->"; if we printed a network destination
1875 * and are printing a network source of the same type
1876 * next, separate them with "<-"; otherwise separate them
1879 switch (cf->cinfo.col_fmt[i]) {
1884 switch (cf->cinfo.col_fmt[i + 1]) {
1898 case COL_DEF_DL_SRC:
1899 case COL_RES_DL_SRC:
1900 case COL_UNRES_DL_SRC:
1901 switch (cf->cinfo.col_fmt[i + 1]) {
1903 case COL_DEF_DL_DST:
1904 case COL_RES_DL_DST:
1905 case COL_UNRES_DL_DST:
1915 case COL_DEF_NET_SRC:
1916 case COL_RES_NET_SRC:
1917 case COL_UNRES_NET_SRC:
1918 switch (cf->cinfo.col_fmt[i + 1]) {
1920 case COL_DEF_NET_DST:
1921 case COL_RES_NET_DST:
1922 case COL_UNRES_NET_DST:
1935 switch (cf->cinfo.col_fmt[i + 1]) {
1949 case COL_DEF_DL_DST:
1950 case COL_RES_DL_DST:
1951 case COL_UNRES_DL_DST:
1952 switch (cf->cinfo.col_fmt[i + 1]) {
1954 case COL_DEF_DL_SRC:
1955 case COL_RES_DL_SRC:
1956 case COL_UNRES_DL_SRC:
1966 case COL_DEF_NET_DST:
1967 case COL_RES_NET_DST:
1968 case COL_UNRES_NET_DST:
1969 switch (cf->cinfo.col_fmt[i + 1]) {
1971 case COL_DEF_NET_SRC:
1972 case COL_RES_NET_SRC:
1973 case COL_UNRES_NET_SRC:
1992 print_hex_data(stdout, print_args.format, edt);
1997 /* The ANSI C standard does not appear to *require* that a line-buffered
1998 stream be flushed to the host environment whenever a newline is
1999 written, it just says that, on such a stream, characters "are
2000 intended to be transmitted to or from the host environment as a
2001 block when a new-line character is encountered".
2003 The Visual C++ 6.0 C implementation doesn't do what is intended;
2004 even if you set a stream to be line-buffered, it still doesn't
2005 flush the buffer at the end of every line.
2007 So, if the "-l" flag was specified, we flush the standard output
2008 at the end of a packet. This will do the right thing if we're
2009 printing packet summary lines, and, as we print the entire protocol
2010 tree for a single packet without waiting for anything to happen,
2011 it should be as good as line-buffered mode if we're printing
2012 protocol trees. (The whole reason for the "-l" flag in either
2013 tcpdump or Tethereal is to allow the output of a live capture to
2014 be piped to a program or script and to have that script see the
2015 information for the packet as soon as it's printed, rather than
2016 having to wait until a standard I/O buffer fills up. */
2020 epan_dissect_free(edt);
2022 clear_fdata(&fdata);
2026 file_open_error_message(int err, gboolean for_writing, int file_type)
2029 static char errmsg_errno[1024+1];
2033 case WTAP_ERR_NOT_REGULAR_FILE:
2034 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2037 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2038 case WTAP_ERR_UNSUPPORTED:
2039 /* Seen only when opening a capture file for reading. */
2040 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
2043 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2044 /* Seen only when opening a capture file for writing. */
2045 snprintf(errmsg_errno, sizeof(errmsg_errno),
2046 "The file \"%%s\" is a pipe, and %s capture files cannot be "
2047 "written to a pipe.", wtap_file_type_string(file_type));
2048 errmsg = errmsg_errno;
2051 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2052 /* Seen only when opening a capture file for writing. */
2053 errmsg = "Tethereal does not support writing capture files in that format.";
2056 case WTAP_ERR_UNSUPPORTED_ENCAP:
2057 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2059 errmsg = "Tethereal cannot save this capture in that format.";
2061 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2064 case WTAP_ERR_BAD_RECORD:
2065 errmsg = "The file \"%s\" appears to be damaged or corrupt.";
2068 case WTAP_ERR_CANT_OPEN:
2070 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2072 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2075 case WTAP_ERR_SHORT_READ:
2076 errmsg = "The file \"%s\" appears to have been cut short"
2077 " in the middle of a packet or other data.";
2080 case WTAP_ERR_SHORT_WRITE:
2081 errmsg = "A full header couldn't be written to the file \"%s\".";
2086 errmsg = "The path to the file \"%s\" does not exist.";
2088 errmsg = "The file \"%s\" does not exist.";
2093 errmsg = "You do not have permission to create or write to the file \"%s\".";
2095 errmsg = "You do not have permission to read the file \"%s\".";
2099 errmsg = "\"%s\" is a directory (folder), not a file.";
2103 snprintf(errmsg_errno, sizeof(errmsg_errno),
2104 "The file \"%%s\" could not be %s: %s.",
2105 for_writing ? "created" : "opened",
2106 wtap_strerror(err));
2107 errmsg = errmsg_errno;
2114 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
2118 char err_msg[2048+1];
2120 wth = wtap_open_offline(fname, &err, FALSE);
2124 /* The open succeeded. Fill in the information for this file. */
2126 /* Initialize all data structures used for dissection. */
2130 cf->filed = -1; /* not used, but set it anyway */
2131 cf->f_len = 0; /* not used, but set it anyway */
2133 /* Set the file name because we need it to set the follow stream filter.
2134 XXX - is that still true? We need it for other reasons, though,
2136 cf->filename = g_strdup(fname);
2138 /* Indicate whether it's a permanent or temporary file. */
2139 cf->is_tempfile = is_tempfile;
2141 /* If it's a temporary capture buffer file, mark it as not saved. */
2142 cf->user_saved = !is_tempfile;
2144 cf->cd_t = wtap_file_type(cf->wth);
2146 cf->drops_known = FALSE;
2150 cf->snap = wtap_snapshot_length(cf->wth);
2151 if (cf->snap == 0) {
2152 /* Snapshot length not known. */
2153 cf->has_snap = FALSE;
2154 cf->snap = WTAP_MAX_PACKET_SIZE;
2156 cf->has_snap = TRUE;
2157 cf->progbar_quantum = 0;
2158 cf->progbar_nextstep = 0;
2159 firstsec = 0, firstusec = 0;
2160 prevsec = 0, prevusec = 0;
2165 snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE, 0),
2167 fprintf(stderr, "tethereal: %s\n", err_msg);
2172 /* Take care of byte order in the libpcap headers read from pipes.
2173 * (function taken from wiretap/libpcap.c) */
2175 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
2177 if (ld->byte_swapped) {
2178 /* Byte-swap the record header fields. */
2179 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
2180 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
2181 rechdr->incl_len = BSWAP32(rechdr->incl_len);
2182 rechdr->orig_len = BSWAP32(rechdr->orig_len);
2185 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
2186 swapped, in order to match the BPF header layout.
2188 Unfortunately, some files were, according to a comment in the "libpcap"
2189 source, written with version 2.3 in their headers but without the
2190 interchanged fields, so if "incl_len" is greater than "orig_len" - which
2191 would make no sense - we assume that we need to swap them. */
2192 if (hdr->version_major == 2 &&
2193 (hdr->version_minor < 3 ||
2194 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
2197 temp = rechdr->orig_len;
2198 rechdr->orig_len = rechdr->incl_len;
2199 rechdr->incl_len = temp;
2203 /* Mimic pcap_open_live() for pipe captures
2204 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
2206 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2207 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2209 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
2210 char *errmsg, int errmsgl)
2212 struct stat pipe_stat;
2216 unsigned int bytes_read;
2219 * XXX Tethereal blocks until we return
2221 if (strcmp(pipename, "-") == 0)
2222 fd = 0; /* read from stdin */
2224 if (stat(pipename, &pipe_stat) < 0) {
2225 if (errno == ENOENT || errno == ENOTDIR)
2226 ld->pipe_err = PIPNEXIST;
2228 snprintf(errmsg, errmsgl,
2229 "The capture session could not be initiated "
2230 "due to error on pipe: %s", strerror(errno));
2231 ld->pipe_err = PIPERR;
2235 if (! S_ISFIFO(pipe_stat.st_mode)) {
2236 if (S_ISCHR(pipe_stat.st_mode)) {
2238 * Assume the user specified an interface on a system where
2239 * interfaces are in /dev. Pretend we haven't seen it.
2241 ld->pipe_err = PIPNEXIST;
2243 snprintf(errmsg, errmsgl,
2244 "The capture session could not be initiated because\n"
2245 "\"%s\" is neither an interface nor a pipe", pipename);
2246 ld->pipe_err = PIPERR;
2250 fd = open(pipename, O_RDONLY);
2252 snprintf(errmsg, errmsgl,
2253 "The capture session could not be initiated "
2254 "due to error on pipe open: %s", strerror(errno));
2255 ld->pipe_err = PIPERR;
2260 ld->from_pipe = TRUE;
2262 /* read the pcap header */
2264 while (bytes_read < sizeof magic) {
2265 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
2268 snprintf(errmsg, errmsgl, "End of file on pipe during open");
2270 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
2279 /* Host that wrote it has our byte order, and was running
2280 a program using either standard or ss990417 libpcap. */
2281 ld->byte_swapped = FALSE;
2282 ld->modified = FALSE;
2284 case PCAP_MODIFIED_MAGIC:
2285 /* Host that wrote it has our byte order, but was running
2286 a program using either ss990915 or ss991029 libpcap. */
2287 ld->byte_swapped = FALSE;
2288 ld->modified = TRUE;
2290 case PCAP_SWAPPED_MAGIC:
2291 /* Host that wrote it has a byte order opposite to ours,
2292 and was running a program using either standard or
2293 ss990417 libpcap. */
2294 ld->byte_swapped = TRUE;
2295 ld->modified = FALSE;
2297 case PCAP_SWAPPED_MODIFIED_MAGIC:
2298 /* Host that wrote it out has a byte order opposite to
2299 ours, and was running a program using either ss990915
2300 or ss991029 libpcap. */
2301 ld->byte_swapped = TRUE;
2302 ld->modified = TRUE;
2305 /* Not a "libpcap" type we know about. */
2306 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2310 /* Read the rest of the header */
2312 while (bytes_read < sizeof(struct pcap_hdr)) {
2313 b = read(fd, ((char *)hdr)+bytes_read,
2314 sizeof(struct pcap_hdr) - bytes_read);
2317 snprintf(errmsg, errmsgl, "End of file on pipe during open");
2319 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
2326 if (ld->byte_swapped) {
2327 /* Byte-swap the header fields about which we care. */
2328 hdr->version_major = BSWAP16(hdr->version_major);
2329 hdr->version_minor = BSWAP16(hdr->version_minor);
2330 hdr->snaplen = BSWAP32(hdr->snaplen);
2331 hdr->network = BSWAP32(hdr->network);
2334 if (hdr->version_major < 2) {
2335 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2339 ld->pipe_state = STATE_EXPECT_REC_HDR;
2340 ld->pipe_err = PIPOK;
2344 ld->pipe_err = PIPERR;
2349 /* We read one record from the pipe, take care of byte order in the record
2350 * header, write the record in the capture file, and update capture statistics. */
2353 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
2354 struct pcaprec_modified_hdr *rechdr, guchar *data,
2355 char *errmsg, int errmsgl)
2357 struct pcap_pkthdr phdr;
2359 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2362 switch (ld->pipe_state) {
2364 case STATE_EXPECT_REC_HDR:
2365 ld->bytes_to_read = ld->modified ?
2366 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2368 ld->pipe_state = STATE_READ_REC_HDR;
2371 case STATE_READ_REC_HDR:
2372 b = read(fd, ((char *)rechdr)+ld->bytes_read,
2373 ld->bytes_to_read - ld->bytes_read);
2376 result = PD_PIPE_EOF;
2378 result = PD_PIPE_ERR;
2381 if ((ld->bytes_read += b) < ld->bytes_to_read)
2383 result = PD_REC_HDR_READ;
2386 case STATE_EXPECT_DATA:
2388 ld->pipe_state = STATE_READ_DATA;
2391 case STATE_READ_DATA:
2392 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
2395 result = PD_PIPE_EOF;
2397 result = PD_PIPE_ERR;
2400 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
2402 result = PD_DATA_READ;
2406 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
2409 } /* switch (ld->pipe_state) */
2412 * We've now read as much data as we were expecting, so process it.
2416 case PD_REC_HDR_READ:
2417 /* We've read the header. Take care of byte order. */
2418 adjust_header(ld, hdr, &rechdr->hdr);
2419 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2420 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2421 ld->packet_count+1, rechdr->hdr.incl_len);
2424 ld->pipe_state = STATE_EXPECT_DATA;
2428 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2429 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
2430 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
2431 phdr.caplen = rechdr->hdr.incl_len;
2432 phdr.len = rechdr->hdr.orig_len;
2434 capture_pcap_cb((guchar *)ld, &phdr, data);
2436 ld->pipe_state = STATE_EXPECT_REC_HDR;
2440 ld->pipe_err = PIPEOF;
2444 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2451 ld->pipe_err = PIPERR;
2452 /* Return here rather than inside the switch to prevent GCC warning */