3 * $Id: tethereal.c,v 1.157 2002/09/06 22:45:40 sahlberg 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.
56 #include <zlib.h> /* to get the libz version number */
59 #ifdef NEED_SNPRINTF_H
60 # include "snprintf.h"
63 #ifdef HAVE_UCD_SNMP_VERSION_H
64 #include <ucd-snmp/version.h>
65 #endif /* HAVE_UCD_SNMP_VERSION_H */
67 #ifdef NEED_STRERROR_H
76 #include <epan/epan.h>
77 #include <epan/filesystem.h>
80 #include <epan/timestamp.h>
81 #include <epan/packet.h>
86 #include <epan/resolv.h>
89 #include "pcap-util.h"
91 #include <epan/conversation.h>
92 #include <epan/plugins.h>
94 #include "conditions.h"
95 #include "capture_stop_conditions.h"
96 #include "ringbuffer.h"
97 #include <epan/epan_dissect.h>
99 #include "tap-rpcstat.h"
100 #include "tap-rpcprogs.h"
103 #include <wiretap/wtap-capture.h>
107 #include "capture-wpcap.h"
110 static guint32 firstsec, firstusec;
111 static guint32 prevsec, prevusec;
112 static GString *comp_info_str;
113 static gboolean quiet;
114 static gboolean decode;
115 static gboolean verbose;
116 static gboolean print_hex;
117 static gboolean line_buffered;
120 typedef struct _loop_data {
121 gboolean go; /* TRUE as long as we're supposed to keep capturing */
126 gboolean output_to_pipe;
132 static int capture(int);
133 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
136 static BOOL WINAPI capture_cleanup(DWORD);
138 static void capture_cleanup(int);
140 #endif /* HAVE_LIBPCAP */
147 static int load_cap_file(capture_file *, int);
148 static void wtap_dispatch_cb_write(guchar *, const struct wtap_pkthdr *, long,
149 union wtap_pseudo_header *, const guchar *);
150 static void show_capture_file_io_error(const char *, int, gboolean);
151 static void wtap_dispatch_cb_print(guchar *, const struct wtap_pkthdr *, long,
152 union wtap_pseudo_header *, const guchar *);
155 ts_type timestamp_type = RELATIVE;
158 int snaplen; /* Maximum captured packet length */
159 int promisc_mode; /* Capture in promiscuous mode */
160 int autostop_count; /* Maximum packet count */
161 gboolean has_autostop_duration; /* TRUE if maximum capture duration
163 gint32 autostop_duration; /* Maximum capture duration */
164 gboolean has_autostop_filesize; /* TRUE if maximum capture file size
166 gint32 autostop_filesize; /* Maximum capture file size */
167 gboolean ringbuffer_on; /* TRUE if ring buffer in use */
168 guint32 ringbuffer_num_files; /* Number of ring buffer files */
171 static capture_options capture_opts = {
172 WTAP_MAX_PACKET_SIZE, /* snapshot length - default is
173 infinite, in effect */
174 TRUE, /* promiscuous mode is the default */
175 0, /* max packet count - default is 0,
177 FALSE, /* maximum capture duration not
178 specified by default */
179 0, /* maximum capture duration */
180 FALSE, /* maximum capture file size not
181 specified by default */
182 0, /* maximum capture file size */
183 FALSE, /* ring buffer off by default */
184 RINGBUFFER_MIN_NUM_FILES /* default number of ring buffer
190 print_usage(gboolean print_ver)
195 fprintf(stderr, "This is GNU t%s %s, compiled %s\n", PACKAGE, VERSION,
199 fprintf(stderr, "\nt%s [ -DvVhqSlp ] [ -a <capture autostop condition> ] ...\n",
201 fprintf(stderr, "\t[ -b <number of ring buffer files> ] [ -c <count> ]\n");
202 fprintf(stderr, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
203 fprintf(stderr, "\t[ -i <interface> ] [ -n ] [ -N <resolving> ]\n");
204 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
205 fprintf(stderr, "\t[ -s <snaplen> ] [ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
207 fprintf(stderr, "\nt%s [ -vVhl ] [ -F <output file type> ] [ -n ] [ -N <resolving> ]\n", PACKAGE);
208 fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
209 fprintf(stderr, "\t[ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
211 fprintf(stderr, "\t[ -Z <statistics string> ]\n");
212 fprintf(stderr, "Valid file type arguments to the \"-F\" flag:\n");
213 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
214 if (wtap_dump_can_open(i))
215 fprintf(stderr, "\t%s - %s\n",
216 wtap_file_type_short_string(i), wtap_file_type_string(i));
218 fprintf(stderr, "\tdefault is libpcap\n");
223 get_positive_int(const char *string, const char *name)
228 number = strtol(string, &p, 10);
229 if (p == string || *p != '\0') {
230 fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
235 fprintf(stderr, "tethereal: The specified %s is a negative number\n",
240 fprintf(stderr, "tethereal: The specified %s is zero\n",
244 if (number > INT_MAX) {
245 fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
253 * Given a string of the form "<autostop criterion>:<value>", as might appear
254 * as an argument to a "-a" option, parse it and set the criterion in
255 * question. Return an indication of whether it succeeded or failed
259 set_autostop_criterion(const char *autostoparg)
263 colonp = strchr(autostoparg, ':');
271 * Skip over any white space (there probably won't be any, but
272 * as we allow it in the preferences file, we might as well
279 * Put the colon back, so if our caller uses, in an
280 * error message, the string they passed us, the message
286 if (strcmp(autostoparg,"duration") == 0) {
287 capture_opts.has_autostop_duration = TRUE;
288 capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
289 } else if (strcmp(autostoparg,"filesize") == 0) {
290 capture_opts.has_autostop_filesize = TRUE;
291 capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
295 *colonp = ':'; /* put the colon back */
301 main(int argc, char *argv[])
305 gboolean arg_error = FALSE;
307 #ifdef HAVE_PCAP_VERSION
308 extern char pcap_version[];
309 #endif /* HAVE_PCAP_VERSION */
310 #endif /* HAVE_LIBPCAP */
318 int gpf_open_errno, pf_open_errno;
321 gboolean capture_filter_specified = FALSE;
322 GList *if_list, *if_entry;
323 gchar err_str[PCAP_ERRBUF_SIZE];
325 gboolean capture_option_specified = FALSE;
327 int out_file_type = WTAP_FILE_PCAP;
328 gchar *cf_name = NULL, *rfilter = NULL;
332 dfilter_t *rfcode = NULL;
336 /* Register all dissectors; we must do this before checking for the
337 "-G" flag, as the "-G" flag dumps information registered by the
338 dissectors, and we must do it before we read the preferences, in
339 case any dissectors register preferences. */
340 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
342 /* Now register the preferences for any non-dissector modules.
343 We must do that before we read the preferences as well. */
344 prefs_register_modules();
346 /* If invoked with the "-G" flag, we dump out information based on
347 the argument to the "-G" flag; if no argument is specified,
348 for backwards compatibility we dump out a glossary of display
351 We do this here to mirror what happens in the GTK+ version, although
352 it's not necessary here. */
353 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
355 proto_registrar_dump_fields();
357 if (strcmp(argv[2], "fields") == 0)
358 proto_registrar_dump_fields();
359 else if (strcmp(argv[2], "protocols") == 0)
360 proto_registrar_dump_protocols();
362 fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
370 /* Set the C-language locale to the native environment. */
371 setlocale(LC_ALL, "");
373 prefs = read_prefs(&gpf_open_errno, &gpf_path, &pf_open_errno, &pf_path);
374 if (gpf_path != NULL) {
375 fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n", pf_path,
376 strerror(gpf_open_errno));
378 if (pf_path != NULL) {
379 fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
380 strerror(pf_open_errno));
385 /* Set the name resolution code's flags from the preferences. */
386 g_resolv_flags = prefs->name_resolve;
389 /* Load Wpcap, if possible */
393 init_cap_file(&cfile);
395 /* Assemble the compile-time options */
396 comp_info_str = g_string_new("");
398 g_string_append(comp_info_str, "with ");
399 g_string_sprintfa(comp_info_str,
400 #ifdef GLIB_MAJOR_VERSION
401 "GLib %d.%d.%d", GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION,
404 "GLib (version unknown)");
408 g_string_append(comp_info_str, ", with libpcap ");
409 #ifdef HAVE_PCAP_VERSION
410 g_string_append(comp_info_str, pcap_version);
411 #else /* HAVE_PCAP_VERSION */
412 g_string_append(comp_info_str, "(version unknown)");
413 #endif /* HAVE_PCAP_VERSION */
414 #else /* HAVE_LIBPCAP */
415 g_string_append(comp_info_str, ", without libpcap");
416 #endif /* HAVE_LIBPCAP */
419 g_string_append(comp_info_str, ", with libz ");
421 g_string_append(comp_info_str, ZLIB_VERSION);
422 #else /* ZLIB_VERSION */
423 g_string_append(comp_info_str, "(version unknown)");
424 #endif /* ZLIB_VERSION */
425 #else /* HAVE_LIBZ */
426 g_string_append(comp_info_str, ", without libz");
427 #endif /* HAVE_LIBZ */
429 /* Oh, this is pretty */
431 g_string_append(comp_info_str, ", with UCD SNMP ");
432 #ifdef HAVE_UCD_SNMP_VERSION_H
433 g_string_append(comp_info_str, VersionInfo);
434 #else /* HAVE_UCD_SNMP_VERSION_H */
435 g_string_append(comp_info_str, "(version unknown)");
436 #endif /* HAVE_UCD_SNMP_VERSION_H */
437 #else /* no SNMP library */
438 g_string_append(comp_info_str, ", without UCD SNMP");
441 /* Now get our args */
442 while ((opt = getopt(argc, argv, "a:b:c:Df:F:hi:lnN:o:pqr:R:s:St:vw:Vxz:")) != -1) {
444 case 'a': /* autostop criteria */
446 if (set_autostop_criterion(optarg) == FALSE) {
447 fprintf(stderr, "ethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
451 capture_option_specified = TRUE;
455 case 'b': /* Ringbuffer option */
457 capture_opts.ringbuffer_on = TRUE;
458 capture_opts.ringbuffer_num_files =
459 get_positive_int(optarg, "number of ring buffer files");
461 capture_option_specified = TRUE;
465 case 'c': /* Capture xxx packets */
467 capture_opts.autostop_count =
468 get_positive_int(optarg, "packet count");
470 capture_option_specified = TRUE;
474 case 'D': /* Print a list of capture devices */
476 if_list = get_interface_list(&err, err_str);
477 if (if_list == NULL) {
480 case CANT_GET_INTERFACE_LIST:
481 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
485 case NO_INTERFACES_FOUND:
486 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
491 for (if_entry = g_list_first(if_list); if_entry != NULL;
492 if_entry = g_list_next(if_entry))
493 printf("%s\n", (char *)if_entry->data);
494 free_interface_list(if_list);
497 capture_option_specified = TRUE;
503 capture_filter_specified = TRUE;
505 g_free(cfile.cfilter);
506 cfile.cfilter = g_strdup(optarg);
508 capture_option_specified = TRUE;
513 out_file_type = wtap_short_string_to_file_type(optarg);
514 if (out_file_type < 0) {
515 fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
520 case 'h': /* Print help and exit */
524 case 'i': /* Use interface xxx */
526 cfile.iface = g_strdup(optarg);
528 capture_option_specified = TRUE;
532 case 'l': /* "Line-buffer" standard output */
533 /* This isn't line-buffering, strictly speaking, it's just
534 flushing the standard output after the information for
535 each packet is printed; however, that should be good
536 enough for all the purposes to which "-l" is put.
538 See the comment in "wtap_dispatch_cb_print()" for an
539 explanation of why we do that, and why we don't just
540 use "setvbuf()" to make the standard output line-buffered
541 (short version: in Windows, "line-buffered" is the same
542 as "fully-buffered", and the output buffer is only flushed
543 when it fills up). */
544 line_buffered = TRUE;
546 case 'n': /* No name resolution */
547 g_resolv_flags = RESOLV_NONE;
549 case 'N': /* Select what types of addresses/port #s to resolve */
550 if (g_resolv_flags == RESOLV_ALL)
551 g_resolv_flags = RESOLV_NONE;
552 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
553 if (badopt != '\0') {
554 fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
559 case 'o': /* Override preference from command line */
560 switch (prefs_set_pref(optarg)) {
562 case PREFS_SET_SYNTAX_ERR:
563 fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
567 case PREFS_SET_NO_SUCH_PREF:
568 case PREFS_SET_OBSOLETE:
569 fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
575 case 'p': /* Don't capture in promiscuous mode */
577 capture_opts.promisc_mode = FALSE;
579 capture_option_specified = TRUE;
583 case 'q': /* Quiet */
586 case 'r': /* Read capture file xxx */
587 cf_name = g_strdup(optarg);
589 case 'R': /* Read file filter */
592 case 's': /* Set the snapshot (capture) length */
594 capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
596 capture_option_specified = TRUE;
600 case 'S': /* show packets in real time */
603 case 't': /* Time stamp type */
604 if (strcmp(optarg, "r") == 0)
605 timestamp_type = RELATIVE;
606 else if (strcmp(optarg, "a") == 0)
607 timestamp_type = ABSOLUTE;
608 else if (strcmp(optarg, "ad") == 0)
609 timestamp_type = ABSOLUTE_WITH_DATE;
610 else if (strcmp(optarg, "d") == 0)
611 timestamp_type = DELTA;
613 fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
615 fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
616 fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
620 case 'v': /* Show version and exit */
621 printf("t%s %s, %s\n", PACKAGE, VERSION, comp_info_str->str);
624 case 'w': /* Write to capture file xxx */
625 cfile.save_file = g_strdup(optarg);
627 case 'V': /* Verbose */
630 case 'x': /* Print packet data in hex (and ASCII) */
634 if(!strncmp(optarg,"rpc,",4)){
635 if(!strncmp(optarg,"rpc,rtt,",8)){
636 int rpcprogram, rpcversion;
637 if(sscanf(optarg,"rpc,rtt,%d,%d",&rpcprogram,&rpcversion)==2){
638 rpcstat_init(rpcprogram,rpcversion);
640 fprintf(stderr, "tethereal: invalid \"-z rpc,rtt,<program>,<version>\" argument\n");
643 } else if(!strncmp(optarg,"rpc,programs",12)){
646 fprintf(stderr, "tethereal: invalid -z argument. Argument must be one of:\n");
647 fprintf(stderr, " \"-z rpc,rtt,<program>,<version>\"\n");
648 fprintf(stderr, " \"-z rpc,programs\"\n");
652 fprintf(stderr, "tethereal: invalid -z argument. Argument must be:\n");
653 fprintf(stderr, " \"-z rpc,...\"\n");
658 case '?': /* Bad flag - print usage message */
664 /* If no capture filter or read filter has been specified, and there are
665 still command-line arguments, treat them as the tokens of a capture
666 filter (if no "-r" flag was specified) or a read filter (if a "-r"
667 flag was specified. */
669 if (cf_name != NULL) {
670 if (rfilter != NULL) {
672 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
675 rfilter = get_args_as_string(argc, argv, optind);
678 if (capture_filter_specified) {
680 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
683 cfile.cfilter = get_args_as_string(argc, argv, optind);
685 capture_option_specified = TRUE;
690 /* See if we're writing a capture file and the file is a pipe */
692 ld.output_to_pipe = FALSE;
694 if (cfile.save_file != NULL) {
695 if (!strcmp(cfile.save_file, "-")) {
697 g_free(cfile.save_file);
698 cfile.save_file = g_strdup("");
700 ld.output_to_pipe = TRUE;
705 err = test_for_fifo(cfile.save_file);
708 case ENOENT: /* it doesn't exist, so we'll be creating it,
709 and it won't be a FIFO */
710 case 0: /* found it, but it's not a FIFO */
713 case ESPIPE: /* it is a FIFO */
714 ld.output_to_pipe = TRUE;
717 default: /* couldn't stat it */
719 "tethereal: Error testing whether capture file is a pipe: %s\n",
728 /* If they didn't specify a "-w" flag, but specified a maximum capture
729 file size, tell them that this doesn't work, and exit. */
730 if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
731 fprintf(stderr, "tethereal: Maximum capture file size specified, but "
732 "capture isn't being saved to a file.\n");
736 if (capture_opts.ringbuffer_on) {
737 /* Ring buffer works only under certain conditions:
738 a) ring buffer does not work if you're not saving the capture to
740 b) ring buffer only works if you're saving in libpcap format;
741 c) it makes no sense to enable the ring buffer if the maximum
742 file size is set to "infinite";
743 d) file must not be a pipe. */
744 if (cfile.save_file == NULL) {
745 fprintf(stderr, "tethereal: Ring buffer requested, but "
746 "capture isn't being saved to a file.\n");
749 if (out_file_type != WTAP_FILE_PCAP) {
750 fprintf(stderr, "tethereal: Ring buffer requested, but "
751 "capture isn't being saved in libpcap format.\n");
754 if (!capture_opts.has_autostop_filesize) {
755 fprintf(stderr, "tethereal: Ring buffer requested, but "
756 "no maximum capture file size was specified.\n");
759 if (ld.output_to_pipe) {
760 fprintf(stderr, "tethereal: Ring buffer requested, but "
761 "capture file is a pipe.\n");
768 /* Start windows sockets */
769 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
772 /* Notify all registered modules that have had any of their preferences
773 changed either from one of the preferences file or from the command
774 line that their preferences have changed. */
778 if (capture_option_specified)
779 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
786 /* Build the column format array */
787 col_init(&cfile.cinfo, prefs->num_cols);
788 for (i = 0; i < cfile.cinfo.num_cols; i++) {
789 cfile.cinfo.col_fmt[i] = get_column_format(i);
790 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
791 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
793 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
794 cfile.cinfo.col_data[i] = NULL;
795 if (cfile.cinfo.col_fmt[i] == COL_INFO)
796 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
798 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
800 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
801 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
805 if (capture_opts.snaplen < 1)
806 capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
807 else if (capture_opts.snaplen < MIN_PACKET_SIZE)
808 capture_opts.snaplen = MIN_PACKET_SIZE;
810 /* Check the value range of the ringbuffer_num_files parameter */
811 if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
812 capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
813 else if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
814 capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
817 if (rfilter != NULL) {
818 if (!dfilter_compile(rfilter, &rfcode)) {
819 fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
824 cfile.rfcode = rfcode;
826 err = open_cap_file(cf_name, FALSE, &cfile);
831 err = load_cap_file(&cfile, out_file_type);
838 /* No capture file specified, so we're supposed to do a live capture;
839 do we have support for live captures? */
844 fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
849 /* Yes; did the user specify an interface to use? */
850 if (cfile.iface == NULL) {
851 /* No - is a default specified in the preferences file? */
852 if (prefs->capture_device != NULL) {
854 if_text = strrchr(prefs->capture_device, ' ');
855 if (if_text == NULL) {
856 cfile.iface = g_strdup(prefs->capture_device);
858 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
861 /* No - pick the first one from the list of interfaces. */
862 if_list = get_interface_list(&err, err_str);
863 if (if_list == NULL) {
866 case CANT_GET_INTERFACE_LIST:
867 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
871 case NO_INTERFACES_FOUND:
872 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
877 if_text = strrchr(if_list->data, ' '); /* first interface */
878 if (if_text == NULL) {
879 cfile.iface = g_strdup(if_list->data);
881 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
883 free_interface_list(if_list);
886 capture(out_file_type);
888 if (capture_opts.ringbuffer_on) {
893 fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
898 draw_tap_listeners(TRUE);
905 /* Do the low-level work of a capture.
906 Returns TRUE if it succeeds, FALSE otherwise. */
908 capture(int out_file_type)
910 gchar open_err_str[PCAP_ERRBUF_SIZE];
911 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
912 bpf_u_int32 netnum, netmask;
913 struct bpf_program fcode;
914 void (*oldhandler)(int);
916 int volatile volatile_err = 0;
917 int volatile inpkts = 0;
920 condition *volatile cnd_stop_capturesize = NULL;
921 condition *volatile cnd_stop_timeout = NULL;
923 static const char ppamsg[] = "can't find PPA for ";
926 struct pcap_stat stats;
930 /* Initialize all data structures used for dissection. */
933 ld.linktype = WTAP_ENCAP_UNKNOWN;
936 /* Open the network interface to capture from it.
937 Some versions of libpcap may put warnings into the error buffer
938 if they succeed; to tell if that's happened, we have to clear
939 the error buffer, and check if it's still a null string. */
940 open_err_str[0] = '\0';
941 ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
942 capture_opts.promisc_mode, 1000, open_err_str);
944 if (ld.pch == NULL) {
945 /* Well, we couldn't start the capture. */
947 /* On Win32 OSes, the capture devices are probably available to all
948 users; don't warn about permissions problems.
950 Do, however, warn that Token Ring and PPP devices aren't supported. */
951 snprintf(errmsg, sizeof errmsg,
952 "The capture session could not be initiated (%s).\n"
953 "Please check that you have the proper interface specified.\n"
955 "Note that the driver Tethereal uses for packet capture on Windows\n"
956 "doesn't support capturing on Token Ring interfaces, and doesn't\n"
957 "support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
960 /* If we got a "can't find PPA for XXX" message, warn the user (who
961 is running Ethereal on HP-UX) that they don't have a version
962 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
963 versions, which properly handle HP-UX, say "can't find /dev/dlpi
964 PPA for XXX" rather than "can't find PPA for XXX"). */
965 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
968 "You are running Tethereal with a version of the libpcap library\n"
969 "that doesn't handle HP-UX network devices well; this means that\n"
970 "Tethereal may not be able to capture packets.\n"
972 "To fix this, you should install libpcap 0.6.2, or a later version\n"
973 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
974 "packaged binary form from the Software Porting And Archive Centre\n"
975 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
976 "at the URL lists a number of mirror sites.";
979 snprintf(errmsg, sizeof errmsg,
980 "The capture session could not be initiated (%s).\n"
981 "Please check to make sure you have sufficient permissions, and that\n"
982 "you have the proper interface specified.%s", open_err_str, libpcap_warn);
988 /* A capture filter was specified; set it up. */
989 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
991 * Well, we can't get the netmask for this interface; it's used
992 * only for filters that check for broadcast IP addresses, so
993 * we just warn the user, and punt and use 0.
996 "Warning: Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
999 if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1000 snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1001 pcap_geterr(ld.pch));
1004 if (pcap_setfilter(ld.pch, &fcode) < 0) {
1005 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1006 pcap_geterr(ld.pch));
1011 ld.linktype = wtap_pcap_encap_to_wtap_encap(get_pcap_linktype(ld.pch,
1013 if (cfile.save_file != NULL) {
1014 /* Set up to write to the capture file. */
1015 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1016 strcpy(errmsg, "The network you're capturing from is of a type"
1017 " that Tethereal doesn't support.");
1020 if (capture_opts.ringbuffer_on) {
1021 cfile.save_file_fd = ringbuf_init(cfile.save_file,
1022 capture_opts.ringbuffer_num_files);
1023 if (cfile.save_file_fd != -1) {
1024 ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1025 pcap_snapshot(ld.pch), &err);
1027 err = errno; /* "ringbuf_init()" failed */
1031 ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1032 ld.linktype, pcap_snapshot(ld.pch), &err);
1035 if (ld.pdh == NULL) {
1036 snprintf(errmsg, sizeof errmsg,
1037 file_open_error_message(err, TRUE, out_file_type),
1038 *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1043 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1044 returned a warning; print it, but keep capturing. */
1045 if (open_err_str[0] != '\0')
1046 fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1049 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1050 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1052 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1054 XXX - deal with signal semantics on various UNIX platforms. Or just
1055 use "sigaction()" and be done with it? */
1056 signal(SIGTERM, capture_cleanup);
1057 signal(SIGINT, capture_cleanup);
1058 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1059 signal(SIGHUP, oldhandler);
1062 /* Let the user know what interface was chosen. */
1063 fprintf(stderr, "Capturing on %s\n", cfile.iface);
1065 /* initialize capture stop conditions */
1066 init_capture_stop_conditions();
1067 /* create stop conditions */
1068 if (capture_opts.has_autostop_filesize)
1069 cnd_stop_capturesize = cnd_new((char*)CND_CLASS_CAPTURESIZE,
1070 (long)capture_opts.autostop_filesize * 1000);
1071 if (capture_opts.has_autostop_duration)
1072 cnd_stop_timeout = cnd_new((char*)CND_CLASS_TIMEOUT,
1073 (gint32)capture_opts.autostop_duration);
1075 if (!setjmp(ld.stopenv))
1079 ld.packet_count = 0;
1081 /* We need to be careful with automatic variables defined in the
1082 outer scope which are changed inside the loop. Most compilers
1083 don't try to roll them back to their original values after the
1084 longjmp which causes the loop to finish, but all that the
1085 standards say is that their values are indeterminate. If we
1086 don't want them to be rolled back, we should define them with the
1087 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1088 Programming in the UNIX Environment, p. 178).
1090 The "err" variable causes a particular problem. If we give it
1091 the volatile attribute, then when we pass a reference to it (as
1092 in "&err") to a function, GCC warns: "passing arg <n> of
1093 <function> discards qualifiers from pointer target type".
1094 Therefore within the loop and just beyond we don't use "err".
1095 Within the loop we define "loop_err", and assign its value to
1096 "volatile_err", which is in the outer scope and is checked when
1099 We also define "packet_count_prev" here to keep things tidy,
1100 since it's used only inside the loop. If it were defined in the
1101 outer scope, GCC would give a warning (unnecessary in this case)
1102 that it might be clobbered, and we'd need to give it the volatile
1103 attribute to suppress the warning. */
1106 int packet_count_prev = 0;
1108 if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1109 /* We're not stopping at a particular capture file size, and we're
1110 not stopping after some particular amount of time has expired,
1111 so either we have no stop condition or the only stop condition
1112 is a maximum packet count.
1114 If there's no maximum packet count, pass it -1, meaning "until
1115 you run out of packets in the bufferful you read". Otherwise,
1116 pass it the number of packets we have left to capture.
1118 We don't call "pcap_loop()" as, if we're saving to a file that's
1119 a FIFO, we want to flush the FIFO after we're done processing
1120 this libpcap bufferful of packets, so that the program
1121 reading the FIFO sees the packets immediately and doesn't get
1122 any partial packet, forcing it to block in the middle of reading
1124 if (capture_opts.autostop_count == 0)
1127 if (ld.packet_count >= capture_opts.autostop_count) {
1128 /* XXX do we need this test here? */
1129 /* It appears there's nothing more to capture. */
1132 pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1135 /* We need to check the capture file size or the timeout after
1139 inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
1141 /* Error from "pcap_dispatch()". */
1143 } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1144 /* The specified capture time has elapsed; stop the capture. */
1146 } else if (inpkts > 0) {
1147 if (capture_opts.autostop_count != 0 &&
1148 ld.packet_count >= capture_opts.autostop_count) {
1149 /* The specified number of packets have been captured and have
1150 passed both any capture filter in effect and any read filter
1153 } else if (cnd_stop_capturesize != NULL &&
1154 cnd_eval(cnd_stop_capturesize,
1155 (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1156 /* We're saving the capture to a file, and the capture file reached
1157 its maximum size. */
1158 if (capture_opts.ringbuffer_on) {
1159 /* Switch to the next ringbuffer file */
1160 if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
1161 /* File switch succeeded: reset the condition */
1162 cnd_reset(cnd_stop_capturesize);
1164 /* File switch failed: stop here */
1165 volatile_err = loop_err;
1169 /* No ringbuffer - just stop. */
1173 if (ld.output_to_pipe) {
1174 if (ld.packet_count > packet_count_prev) {
1175 if (fflush(wtap_dump_file(ld.pdh))) {
1176 volatile_err = errno;
1179 packet_count_prev = ld.packet_count;
1183 } /* while (ld.go) */
1185 /* delete stop conditions */
1186 if (cnd_stop_capturesize != NULL)
1187 cnd_delete(cnd_stop_capturesize);
1188 if (cnd_stop_timeout != NULL)
1189 cnd_delete(cnd_stop_timeout);
1191 if ((cfile.save_file != NULL) && !quiet) {
1192 /* We're saving to a file, which means we're printing packet counts
1193 to stderr if we are not running silent and deep.
1194 Send a newline so that we move to the line after the packet count. */
1195 fprintf(stderr, "\n");
1198 /* If we got an error while capturing, report it. */
1200 fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1201 pcap_geterr(ld.pch));
1204 if (volatile_err == 0)
1207 show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
1211 if (cfile.save_file != NULL) {
1212 /* We're saving to a file or files; close all files. */
1213 if (capture_opts.ringbuffer_on) {
1214 dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1216 dump_ok = wtap_dump_close(ld.pdh, &err);
1218 /* If we've displayed a message about a write error, there's no point
1219 in displaying another message about an error on close. */
1220 if (!dump_ok && !write_err)
1221 show_capture_file_io_error(cfile.save_file, err, TRUE);
1224 /* Get the capture statistics, and, if any packets were dropped, report
1226 if (pcap_stats(ld.pch, &stats) >= 0) {
1227 if (stats.ps_drop != 0) {
1228 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1231 fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
1232 pcap_geterr(ld.pch));
1234 /* Report the number of captured packets if not reported during capture
1235 and we are saving to a file. */
1236 if (quiet && (cfile.save_file != NULL)) {
1237 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1245 if (capture_opts.ringbuffer_on) {
1246 ringbuf_error_cleanup();
1248 g_free(cfile.save_file);
1249 cfile.save_file = NULL;
1250 fprintf(stderr, "tethereal: %s\n", errmsg);
1258 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
1261 struct wtap_pkthdr whdr;
1262 union wtap_pseudo_header pseudo_header;
1263 loop_data *ld = (loop_data *) user;
1267 /* Convert from libpcap to Wiretap format.
1268 If that fails, ignore the packet (wtap_process_pcap_packet has
1269 written an error message). */
1270 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
1279 wtap_dispatch_cb_write((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1280 /* Report packet capture count if not quiet */
1283 if (ld->packet_count != 0) {
1284 fprintf(stderr, "\r%u ", ld->packet_count);
1285 /* stderr could be line buffered */
1289 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0,
1290 &pseudo_header, pd);
1294 wtap_dispatch_cb_print((guchar *)&args, &whdr, 0, &pseudo_header, pd);
1300 capture_cleanup(DWORD ctrltype _U_)
1302 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1303 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1304 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1305 like SIGTERM at least when the machine's shutting down.
1307 For now, we handle them all as indications that we should clean up
1308 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1311 However, as handlers run in a new thread, we can't just longjmp
1312 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1313 no other handler - such as one that would terminate the process -
1316 XXX - for some reason, typing ^C to Tethereal, if you run this in
1317 a Cygwin console window in at least some versions of Cygwin,
1318 causes Tethereal to terminate immediately; this routine gets
1319 called, but the main loop doesn't get a chance to run and
1320 exit cleanly, at least if this is compiled with Microsoft Visual
1321 C++ (i.e., it's a property of the Cygwin console window or Bash;
1322 it happens if Tethereal is not built with Cygwin - for all I know,
1323 building it with Cygwin may make the problem go away). */
1329 capture_cleanup(int signum _U_)
1331 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1332 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1333 "ld.go" to FALSE and return, we won't break out of it and quit
1335 longjmp(ld.stopenv, 1);
1338 #endif /* HAVE_LIBPCAP */
1341 load_cap_file(capture_file *cf, int out_file_type)
1344 int snapshot_length;
1350 linktype = wtap_file_encap(cf->wth);
1351 if (cf->save_file != NULL) {
1352 /* Set up to write to the capture file. */
1353 snapshot_length = wtap_snapshot_length(cf->wth);
1354 if (snapshot_length == 0) {
1355 /* Snapshot length of input file not known. */
1356 snapshot_length = WTAP_MAX_PACKET_SIZE;
1358 pdh = wtap_dump_open(cf->save_file, out_file_type,
1359 linktype, snapshot_length, &err);
1362 /* We couldn't set up to write to the capture file. */
1365 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1367 "tethereal: Capture files can't be written in that format.\n");
1370 case WTAP_ERR_UNSUPPORTED_ENCAP:
1371 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1373 "tethereal: The capture file being read cannot be written in "
1377 case WTAP_ERR_CANT_OPEN:
1379 "tethereal: The file \"%s\" couldn't be created for some "
1380 "unknown reason.\n",
1381 *cf->save_file == '\0' ? "stdout" : cf->save_file);
1384 case WTAP_ERR_SHORT_WRITE:
1386 "tethereal: A full header couldn't be written to the file \"%s\".\n",
1387 *cf->save_file == '\0' ? "stdout" : cf->save_file);
1392 "tethereal: The file \"%s\" could not be created: %s\n.",
1393 *cf->save_file == '\0' ? "stdout" : cf->save_file,
1394 wtap_strerror(err));
1401 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (guchar *) &args,
1404 /* Now close the capture file. */
1405 if (!wtap_dump_close(pdh, &err))
1406 show_capture_file_io_error(cfile.save_file, err, TRUE);
1410 success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (guchar *) &args,
1414 /* Print up a message box noting that the read failed somewhere along
1418 case WTAP_ERR_UNSUPPORTED_ENCAP:
1420 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
1424 case WTAP_ERR_CANT_READ:
1426 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
1430 case WTAP_ERR_SHORT_READ:
1432 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
1436 case WTAP_ERR_BAD_RECORD:
1438 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
1444 "tethereal: An error occurred while reading \"%s\": %s.\n",
1445 cf->filename, wtap_strerror(err));
1451 wtap_close(cf->wth);
1458 fill_in_fdata(frame_data *fdata, capture_file *cf,
1459 const struct wtap_pkthdr *phdr, long offset)
1464 fdata->num = cf->count;
1465 fdata->pkt_len = phdr->len;
1466 fdata->cap_len = phdr->caplen;
1467 fdata->file_off = offset;
1468 fdata->lnk_t = phdr->pkt_encap;
1469 fdata->abs_secs = phdr->ts.tv_sec;
1470 fdata->abs_usecs = phdr->ts.tv_usec;
1471 fdata->flags.passed_dfilter = 0;
1472 fdata->flags.encoding = CHAR_ASCII;
1473 fdata->flags.visited = 0;
1474 fdata->flags.marked = 0;
1476 /* If we don't have the time stamp of the first packet in the
1477 capture, it's because this is the first packet. Save the time
1478 stamp of this packet as the time stamp of the first packet. */
1479 if (!firstsec && !firstusec) {
1480 firstsec = fdata->abs_secs;
1481 firstusec = fdata->abs_usecs;
1484 /* If we don't have the time stamp of the previous displayed packet,
1485 it's because this is the first displayed packet. Save the time
1486 stamp of this packet as the time stamp of the previous displayed
1488 if (!prevsec && !prevusec) {
1489 prevsec = fdata->abs_secs;
1490 prevusec = fdata->abs_usecs;
1493 /* Get the time elapsed between the first packet and this packet. */
1494 compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
1495 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
1497 /* If it's greater than the current elapsed time, set the elapsed time
1498 to it (we check for "greater than" so as not to be confused by
1499 time moving backwards). */
1500 if ((gint32)cf->esec < fdata->rel_secs
1501 || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
1502 cf->esec = fdata->rel_secs;
1503 cf->eusec = fdata->rel_usecs;
1506 /* Get the time elapsed between the previous displayed packet and
1508 compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
1509 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
1510 prevsec = fdata->abs_secs;
1511 prevusec = fdata->abs_usecs;
1514 /* Free up all data attached to a "frame_data" structure. */
1516 clear_fdata(frame_data *fdata)
1519 g_slist_free(fdata->pfd);
1523 wtap_dispatch_cb_write(guchar *user, const struct wtap_pkthdr *phdr,
1524 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
1526 cb_args_t *args = (cb_args_t *) user;
1527 capture_file *cf = args->cf;
1528 wtap_dumper *pdh = args->pdh;
1532 epan_dissect_t *edt;
1536 fill_in_fdata(&fdata, cf, phdr, offset);
1537 edt = epan_dissect_new(TRUE, FALSE);
1538 epan_dissect_prime_dfilter(edt, cf->rfcode);
1539 epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
1540 passed = dfilter_apply_edt(cf->rfcode, edt);
1546 /* The packet passed the read filter. */
1550 if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
1552 if (ld.pch != NULL && !quiet) {
1553 /* We're capturing packets, so (if -q not specified) we're printing
1554 a count of packets captured; move to the line after the count. */
1555 fprintf(stderr, "\n");
1558 show_capture_file_io_error(cf->save_file, err, FALSE);
1563 wtap_dump_close(pdh, &err);
1568 epan_dissect_free(edt);
1570 clear_fdata(&fdata);
1574 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
1583 "tethereal: Not all the packets could be written to \"%s\" because there is "
1584 "no space left on the file system.\n",
1591 "tethereal: Not all the packets could be written to \"%s\" because you are "
1592 "too close to, or over your disk quota.\n",
1597 case WTAP_ERR_CANT_CLOSE:
1599 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
1603 case WTAP_ERR_SHORT_WRITE:
1605 "tethereal: Not all the packets could be written to \"%s\".\n",
1612 "tethereal: \"%s\" could not be closed: %s.\n",
1613 fname, wtap_strerror(err));
1616 "tethereal: An error occurred while writing to \"%s\": %s.\n",
1617 fname, wtap_strerror(err));
1624 wtap_dispatch_cb_print(guchar *user, const struct wtap_pkthdr *phdr,
1625 long offset, union wtap_pseudo_header *pseudo_header, const guchar *buf)
1627 cb_args_t *args = (cb_args_t *) user;
1628 capture_file *cf = args->cf;
1631 print_args_t print_args;
1632 epan_dissect_t *edt;
1633 gboolean create_proto_tree;
1638 fill_in_fdata(&fdata, cf, phdr, offset);
1641 if (cf->rfcode || verbose)
1642 create_proto_tree = TRUE;
1644 create_proto_tree = FALSE;
1645 /* The protocol tree will be "visible", i.e., printed, only if we're
1646 not printing a summary.
1648 We only need the columns if we're *not* verbose; in verbose mode,
1649 we print the protocol tree, not the protocol summary. */
1650 edt = epan_dissect_new(create_proto_tree, verbose);
1652 epan_dissect_prime_dfilter(edt, cf->rfcode);
1655 tap_queue_init(pseudo_header, buf, &fdata);
1656 epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
1657 tap_push_tapped_queue();
1660 passed = dfilter_apply_edt(cf->rfcode, edt);
1663 /* The packet passed the read filter. */
1668 /* Print the information in the protocol tree. */
1669 print_args.to_file = TRUE;
1670 print_args.format = PR_FMT_TEXT;
1671 print_args.print_summary = FALSE;
1672 print_args.print_hex = print_hex;
1673 print_args.expand_all = TRUE;
1674 print_args.suppress_unmarked = FALSE;
1675 proto_tree_print(&print_args, edt, stdout);
1677 /* "print_hex_data()" will put out a leading blank line, as well
1678 as a trailing one; print one here, to separate the packets,
1679 only if "print_hex_data()" won't be called. */
1683 /* Just fill in the columns. */
1684 epan_dissect_fill_in_columns(edt);
1686 /* Now print them. */
1687 for (i = 0; i < cf->cinfo.num_cols; i++) {
1688 switch (cf->cinfo.col_fmt[i]) {
1691 * Don't print this if we're doing a live capture from a network
1692 * interface - if we're doing a live capture, you won't be
1693 * able to look at the capture in the future (it's not being
1694 * saved anywhere), so the frame numbers are unlikely to be
1697 * (XXX - it might be nice to be able to save and print at
1698 * the same time, sort of like an "Update list of packets
1699 * in real time" capture in Ethereal.)
1701 if (cf->iface != NULL)
1703 printf("%3s", cf->cinfo.col_data[i]);
1709 case COL_ABS_DATE_TIME: /* XXX - wider */
1710 printf("%10s", cf->cinfo.col_data[i]);
1716 case COL_DEF_DL_SRC:
1717 case COL_RES_DL_SRC:
1718 case COL_UNRES_DL_SRC:
1719 case COL_DEF_NET_SRC:
1720 case COL_RES_NET_SRC:
1721 case COL_UNRES_NET_SRC:
1722 printf("%12s", cf->cinfo.col_data[i]);
1728 case COL_DEF_DL_DST:
1729 case COL_RES_DL_DST:
1730 case COL_UNRES_DL_DST:
1731 case COL_DEF_NET_DST:
1732 case COL_RES_NET_DST:
1733 case COL_UNRES_NET_DST:
1734 printf("%-12s", cf->cinfo.col_data[i]);
1738 printf("%s", cf->cinfo.col_data[i]);
1741 if (i != cf->cinfo.num_cols - 1) {
1743 * This isn't the last column, so we need to print a
1744 * separator between this column and the next.
1746 * If we printed a network source and are printing a
1747 * network destination of the same type next, separate
1748 * them with "->"; if we printed a network destination
1749 * and are printing a network source of the same type
1750 * next, separate them with "<-"; otherwise separate them
1753 switch (cf->cinfo.col_fmt[i]) {
1758 switch (cf->cinfo.col_fmt[i + 1]) {
1772 case COL_DEF_DL_SRC:
1773 case COL_RES_DL_SRC:
1774 case COL_UNRES_DL_SRC:
1775 switch (cf->cinfo.col_fmt[i + 1]) {
1777 case COL_DEF_DL_DST:
1778 case COL_RES_DL_DST:
1779 case COL_UNRES_DL_DST:
1789 case COL_DEF_NET_SRC:
1790 case COL_RES_NET_SRC:
1791 case COL_UNRES_NET_SRC:
1792 switch (cf->cinfo.col_fmt[i + 1]) {
1794 case COL_DEF_NET_DST:
1795 case COL_RES_NET_DST:
1796 case COL_UNRES_NET_DST:
1809 switch (cf->cinfo.col_fmt[i + 1]) {
1823 case COL_DEF_DL_DST:
1824 case COL_RES_DL_DST:
1825 case COL_UNRES_DL_DST:
1826 switch (cf->cinfo.col_fmt[i + 1]) {
1828 case COL_DEF_DL_SRC:
1829 case COL_RES_DL_SRC:
1830 case COL_UNRES_DL_SRC:
1840 case COL_DEF_NET_DST:
1841 case COL_RES_NET_DST:
1842 case COL_UNRES_NET_DST:
1843 switch (cf->cinfo.col_fmt[i + 1]) {
1845 case COL_DEF_NET_SRC:
1846 case COL_RES_NET_SRC:
1847 case COL_UNRES_NET_SRC:
1866 print_hex_data(stdout, print_args.format, edt);
1871 /* The ANSI C standard does not appear to *require* that a line-buffered
1872 stream be flushed to the host environment whenever a newline is
1873 written, it just says that, on such a stream, characters "are
1874 intended to be transmitted to or from the host environment as a
1875 block when a new-line character is encountered".
1877 The Visual C++ 6.0 C implementation doesn't do what is intended;
1878 even if you set a stream to be line-buffered, it still doesn't
1879 flush the buffer at the end of every line.
1881 So, if the "-l" flag was specified, we flush the standard output
1882 at the end of a packet. This will do the right thing if we're
1883 printing packet summary lines, and, as we print the entire protocol
1884 tree for a single packet without waiting for anything to happen,
1885 it should be as good as line-buffered mode if we're printing
1886 protocol trees. (The whole reason for the "-l" flag in either
1887 tcpdump or Tethereal is to allow the output of a live capture to
1888 be piped to a program or script and to have that script see the
1889 information for the packet as soon as it's printed, rather than
1890 having to wait until a standard I/O buffer fills up. */
1894 epan_dissect_free(edt);
1896 clear_fdata(&fdata);
1900 file_open_error_message(int err, gboolean for_writing, int file_type)
1903 static char errmsg_errno[1024+1];
1907 case WTAP_ERR_NOT_REGULAR_FILE:
1908 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
1911 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
1912 case WTAP_ERR_UNSUPPORTED:
1913 /* Seen only when opening a capture file for reading. */
1914 errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
1917 case WTAP_ERR_CANT_WRITE_TO_PIPE:
1918 /* Seen only when opening a capture file for writing. */
1919 snprintf(errmsg_errno, sizeof(errmsg_errno),
1920 "The file \"%%s\" is a pipe, and %s capture files cannot be "
1921 "written to a pipe.", wtap_file_type_string(file_type));
1922 errmsg = errmsg_errno;
1925 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1926 /* Seen only when opening a capture file for writing. */
1927 errmsg = "Tethereal does not support writing capture files in that format.";
1930 case WTAP_ERR_UNSUPPORTED_ENCAP:
1931 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1933 errmsg = "Tethereal cannot save this capture in that format.";
1935 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
1938 case WTAP_ERR_BAD_RECORD:
1939 errmsg = "The file \"%s\" appears to be damaged or corrupt.";
1942 case WTAP_ERR_CANT_OPEN:
1944 errmsg = "The file \"%s\" could not be created for some unknown reason.";
1946 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
1949 case WTAP_ERR_SHORT_READ:
1950 errmsg = "The file \"%s\" appears to have been cut short"
1951 " in the middle of a packet or other data.";
1954 case WTAP_ERR_SHORT_WRITE:
1955 errmsg = "A full header couldn't be written to the file \"%s\".";
1960 errmsg = "The path to the file \"%s\" does not exist.";
1962 errmsg = "The file \"%s\" does not exist.";
1967 errmsg = "You do not have permission to create or write to the file \"%s\".";
1969 errmsg = "You do not have permission to read the file \"%s\".";
1973 errmsg = "\"%s\" is a directory (folder), not a file.";
1977 snprintf(errmsg_errno, sizeof(errmsg_errno),
1978 "The file \"%%s\" could not be %s: %s.",
1979 for_writing ? "created" : "opened",
1980 wtap_strerror(err));
1981 errmsg = errmsg_errno;
1988 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
1992 char err_msg[2048+1];
1994 wth = wtap_open_offline(fname, &err, FALSE);
1998 /* The open succeeded. Fill in the information for this file. */
2000 /* Initialize all data structures used for dissection. */
2004 cf->filed = -1; /* not used, but set it anyway */
2005 cf->f_len = 0; /* not used, but set it anyway */
2007 /* Set the file name because we need it to set the follow stream filter.
2008 XXX - is that still true? We need it for other reasons, though,
2010 cf->filename = g_strdup(fname);
2012 /* Indicate whether it's a permanent or temporary file. */
2013 cf->is_tempfile = is_tempfile;
2015 /* If it's a temporary capture buffer file, mark it as not saved. */
2016 cf->user_saved = !is_tempfile;
2018 cf->cd_t = wtap_file_type(cf->wth);
2020 cf->drops_known = FALSE;
2024 cf->snap = wtap_snapshot_length(cf->wth);
2025 if (cf->snap == 0) {
2026 /* Snapshot length not known. */
2027 cf->has_snap = FALSE;
2028 cf->snap = WTAP_MAX_PACKET_SIZE;
2030 cf->has_snap = TRUE;
2031 cf->progbar_quantum = 0;
2032 cf->progbar_nextstep = 0;
2033 firstsec = 0, firstusec = 0;
2034 prevsec = 0, prevusec = 0;
2039 snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE, 0),
2041 fprintf(stderr, "tethereal: %s\n", err_msg);