2 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 * Support for splitting captures into multiple files with a maximum
25 * Seth Webster <swebster@sst.ll.mit.edu>
29 static const char copyright[] _U_ =
30 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
31 The Regents of the University of California. All rights reserved.\n";
32 static const char rcsid[] _U_ =
33 "@(#) $Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.283 2008-09-25 21:45:50 guy Exp $ (LBL)";
39 * tcpdump - monitor tcp/ip traffic on an ethernet.
41 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
42 * Mercilessly hacked and occasionally improved since then via the
43 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
50 #include <tcpdump-stdinc.h>
55 extern int strcasecmp (const char *__s1, const char *__s2);
73 #include <sys/resource.h>
80 #include "netdissect.h"
81 #include "interface.h"
82 #include "addrtoname.h"
84 #include "setsignal.h"
85 #include "gmt2local.h"
86 #include "pcap-missing.h"
92 netdissect_options Gndo;
93 netdissect_options *gndo = &Gndo;
95 static int dflag; /* print filter code */
96 static int Lflag; /* list available data link types and exit */
97 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
98 static int Jflag; /* list available time stamp types */
100 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
102 static int infodelay;
103 static int infoprint;
107 int32_t thiszone; /* seconds offset from gmt to local time */
110 static RETSIGTYPE cleanup(int);
111 static RETSIGTYPE child_cleanup(int);
112 static void usage(void) __attribute__((noreturn));
113 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
115 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
116 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
117 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
118 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
119 static void droproot(const char *, const char *);
120 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
121 __attribute__ ((noreturn, format (printf, 2, 3)));
122 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
125 RETSIGTYPE requestinfo(int);
128 #if defined(USE_WIN32_MM_TIMER)
129 #include <MMsystem.h>
130 static UINT timer_id;
131 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
132 #elif defined(HAVE_ALARM)
133 static void verbose_stats_dump(int sig);
136 static void info(int);
137 static u_int packets_captured;
151 static struct printer printers[] = {
152 { arcnet_if_print, DLT_ARCNET },
153 #ifdef DLT_ARCNET_LINUX
154 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
156 { token_if_print, DLT_IEEE802 },
158 { lane_if_print, DLT_LANE8023 },
161 { cip_if_print, DLT_CIP },
164 { cip_if_print, DLT_ATM_CLIP },
166 { sl_if_print, DLT_SLIP },
167 #ifdef DLT_SLIP_BSDOS
168 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
170 { ppp_if_print, DLT_PPP },
171 #ifdef DLT_PPP_WITHDIRECTION
172 { ppp_if_print, DLT_PPP_WITHDIRECTION },
175 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
177 { fddi_if_print, DLT_FDDI },
178 { null_if_print, DLT_NULL },
180 { null_if_print, DLT_LOOP },
182 { raw_if_print, DLT_RAW },
183 { atm_if_print, DLT_ATM_RFC1483 },
185 { chdlc_if_print, DLT_C_HDLC },
188 { chdlc_if_print, DLT_HDLC },
190 #ifdef DLT_PPP_SERIAL
191 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
194 { pppoe_if_print, DLT_PPP_ETHER },
197 { sll_if_print, DLT_LINUX_SLL },
199 #ifdef DLT_IEEE802_11
200 { ieee802_11_if_print, DLT_IEEE802_11},
203 { ltalk_if_print, DLT_LTALK },
205 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
206 { pflog_if_print, DLT_PFLOG },
209 { fr_if_print, DLT_FR },
212 { fr_if_print, DLT_FRELAY },
215 { sunatm_if_print, DLT_SUNATM },
217 #ifdef DLT_IP_OVER_FC
218 { ipfc_if_print, DLT_IP_OVER_FC },
220 #ifdef DLT_PRISM_HEADER
221 { prism_if_print, DLT_PRISM_HEADER },
223 #ifdef DLT_IEEE802_11_RADIO
224 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
227 { enc_if_print, DLT_ENC },
229 #ifdef DLT_SYMANTEC_FIREWALL
230 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
232 #ifdef DLT_APPLE_IP_OVER_IEEE1394
233 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
235 #ifdef DLT_IEEE802_11_RADIO_AVS
236 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
238 #ifdef DLT_JUNIPER_ATM1
239 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
241 #ifdef DLT_JUNIPER_ATM2
242 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
244 #ifdef DLT_JUNIPER_MFR
245 { juniper_mfr_print, DLT_JUNIPER_MFR },
247 #ifdef DLT_JUNIPER_MLFR
248 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
250 #ifdef DLT_JUNIPER_MLPPP
251 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
253 #ifdef DLT_JUNIPER_PPPOE
254 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
256 #ifdef DLT_JUNIPER_PPPOE_ATM
257 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
259 #ifdef DLT_JUNIPER_GGSN
260 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
262 #ifdef DLT_JUNIPER_ES
263 { juniper_es_print, DLT_JUNIPER_ES },
265 #ifdef DLT_JUNIPER_MONITOR
266 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
268 #ifdef DLT_JUNIPER_SERVICES
269 { juniper_services_print, DLT_JUNIPER_SERVICES },
271 #ifdef DLT_JUNIPER_ETHER
272 { juniper_ether_print, DLT_JUNIPER_ETHER },
274 #ifdef DLT_JUNIPER_PPP
275 { juniper_ppp_print, DLT_JUNIPER_PPP },
277 #ifdef DLT_JUNIPER_FRELAY
278 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
280 #ifdef DLT_JUNIPER_CHDLC
281 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
284 { mfr_if_print, DLT_MFR },
286 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
287 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
289 #ifdef HAVE_PCAP_USB_H
291 { usb_linux_48_byte_print, DLT_USB_LINUX},
292 #endif /* DLT_USB_LINUX */
293 #ifdef DLT_USB_LINUX_MMAPPED
294 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
295 #endif /* DLT_USB_LINUX_MMAPPED */
296 #endif /* HAVE_PCAP_USB_H */
298 { raw_if_print, DLT_IPV4 },
301 { raw_if_print, DLT_IPV6 },
306 static struct ndo_printer ndo_printers[] = {
307 { ether_if_print, DLT_EN10MB },
309 { ipnet_if_print, DLT_IPNET },
311 #ifdef DLT_IEEE802_15_4
312 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
314 #ifdef DLT_IEEE802_15_4_NOFCS
315 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
318 { ppi_if_print, DLT_PPI },
320 #ifdef DLT_NETANALYZER
321 { netanalyzer_if_print, DLT_NETANALYZER },
323 #ifdef DLT_NETANALYZER_TRANSPARENT
324 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
330 lookup_printer(int type)
334 for (p = printers; p->f; ++p)
343 lookup_ndo_printer(int type)
345 struct ndo_printer *p;
347 for (p = ndo_printers; p->f; ++p)
357 static int supports_monitor_mode;
364 netdissect_options *ndo;
367 if_ndo_printer ndo_printer;
374 char *CurrentFileName;
379 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
381 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
384 int *tstamp_types = 0;
385 const char *tstamp_type_name;
388 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
389 if (n_tstamp_types < 0)
390 error("%s", pcap_geterr(pd));
392 if (n_tstamp_types == 0) {
393 fprintf(stderr, "Time stamp type cannot be set for %s\n",
397 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
399 for (i = 0; i < n_tstamp_types; i++) {
400 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
401 if (tstamp_type_name != NULL) {
402 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
403 pcap_tstamp_type_val_to_description(tstamp_types[i]));
405 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
408 pcap_free_tstamp_types(tstamp_types);
414 show_dlts_and_exit(const char *device, pcap_t *pd)
418 const char *dlt_name;
420 n_dlts = pcap_list_datalinks(pd, &dlts);
422 error("%s", pcap_geterr(pd));
423 else if (n_dlts == 0 || !dlts)
424 error("No data link types.");
427 * If the interface is known to support monitor mode, indicate
428 * whether these are the data link types available when not in
429 * monitor mode, if -I wasn't specified, or when in monitor mode,
430 * when -I was specified (the link-layer types available in
431 * monitor mode might be different from the ones available when
432 * not in monitor mode).
434 if (supports_monitor_mode)
435 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
437 Iflag ? "when in monitor mode" : "when not in monitor mode");
439 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
442 while (--n_dlts >= 0) {
443 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
444 if (dlt_name != NULL) {
445 (void) fprintf(stderr, " %s (%s)", dlt_name,
446 pcap_datalink_val_to_description(dlts[n_dlts]));
449 * OK, does tcpdump handle that type?
451 if (lookup_printer(dlts[n_dlts]) == NULL
452 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
453 (void) fprintf(stderr, " (printing not supported)");
454 fprintf(stderr, "\n");
456 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
460 pcap_free_datalinks(dlts);
465 * Set up flags that might or might not be supported depending on the
466 * version of libpcap we're using.
468 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
470 #define B_FLAG_USAGE " [ -B size ]"
471 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
474 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
476 #ifdef HAVE_PCAP_CREATE
478 #else /* HAVE_PCAP_CREATE */
480 #endif /* HAVE_PCAP_CREATE */
482 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
484 #define j_FLAG_USAGE " [ -j tstamptype ]"
486 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
490 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
492 #ifdef HAVE_PCAP_FINDALLDEVS
493 #ifndef HAVE_PCAP_IF_T
494 #undef HAVE_PCAP_FINDALLDEVS
498 #ifdef HAVE_PCAP_FINDALLDEVS
504 #ifdef HAVE_PCAP_DUMP_FLUSH
511 /* Drop root privileges and chroot if necessary */
513 droproot(const char *username, const char *chroot_dir)
515 struct passwd *pw = NULL;
517 if (chroot_dir && !username) {
518 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
522 pw = getpwnam(username);
525 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
526 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
527 chroot_dir, pcap_strerror(errno));
531 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
532 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
533 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
535 (unsigned long)pw->pw_uid,
536 (unsigned long)pw->pw_gid,
537 pcap_strerror(errno));
542 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
565 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
567 char *filename = malloc(NAME_MAX + 1);
569 /* Process with strftime if Gflag is set. */
573 /* Convert Gflag_time to a usable format */
574 if ((local_tm = localtime(&Gflag_time)) == NULL) {
575 error("MakeTimedFilename: localtime");
578 /* There's no good way to detect an error in strftime since a return
579 * value of 0 isn't necessarily failure.
581 strftime(filename, NAME_MAX, orig_name, local_tm);
583 strncpy(filename, orig_name, NAME_MAX);
586 if (cnt == 0 && max_chars == 0)
587 strncpy(buffer, filename, NAME_MAX + 1);
589 if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
590 /* Report an error if the filename is too large */
591 error("too many output files or filename is too long (> %d)", NAME_MAX);
595 static int tcpdump_printf(netdissect_options *ndo _U_,
596 const char *fmt, ...)
603 ret=vfprintf(stdout, fmt, args);
610 main(int argc, char **argv)
612 register int cnt, op, i;
613 bpf_u_int32 localnet, netmask;
614 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
615 pcap_handler callback;
617 struct bpf_program fcode;
619 RETSIGTYPE (*oldhandler)(int);
621 struct print_info printinfo;
622 struct dump_info dumpinfo;
623 u_char *pcap_userdata;
624 char ebuf[PCAP_ERRBUF_SIZE];
625 char *username = NULL;
626 char *chroot_dir = NULL;
627 #ifdef HAVE_PCAP_FINDALLDEVS
628 pcap_if_t *devpointer;
633 if(wsockinit() != 0) return 1;
636 jflag=-1; /* not set */
640 gndo->ndo_default_print=ndo_default_print;
641 gndo->ndo_printf=tcpdump_printf;
642 gndo->ndo_error=ndo_error;
643 gndo->ndo_warning=ndo_warning;
644 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
651 if ((cp = strrchr(argv[0], '/')) != NULL)
652 program_name = cp + 1;
654 program_name = argv[0];
656 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
664 (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:Yz:Z:")) != -1)
668 /* compatibility for old -a */
679 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
681 Bflag = atoi(optarg)*1024;
683 error("invalid packet buffer size %s", optarg);
685 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
690 error("invalid packet count %s", optarg);
694 Cflag = atoi(optarg) * 1000000;
696 error("invalid file size %s", optarg);
703 #ifdef HAVE_PCAP_FINDALLDEVS
705 if (pcap_findalldevs(&devpointer, ebuf) < 0)
708 for (i = 0; devpointer != 0; i++) {
709 printf("%d.%s", i+1, devpointer->name);
710 if (devpointer->description != NULL)
711 printf(" (%s)", devpointer->description);
713 devpointer = devpointer->next;
717 #endif /* HAVE_PCAP_FINDALLDEVS */
728 #ifndef HAVE_LIBCRYPTO
729 warning("crypto code not compiled in");
731 gndo->ndo_espsecret = optarg;
743 Gflag = atoi(optarg);
745 error("invalid number of seconds %s", optarg);
747 /* We will create one file initially. */
750 /* Grab the current time for rotation use. */
751 if ((Gflag_time = time(NULL)) == (time_t)-1) {
752 error("main: can't get current time: %s",
753 pcap_strerror(errno));
766 if (optarg[0] == '0' && optarg[1] == 0)
767 error("Invalid adapter index");
769 #ifdef HAVE_PCAP_FINDALLDEVS
771 * If the argument is a number, treat it as
772 * an index into the list of adapters, as
773 * printed by "tcpdump -D".
775 * This should be OK on UNIX systems, as interfaces
776 * shouldn't have names that begin with digits.
777 * It can be useful on Windows, where more than
778 * one interface can have the same name.
780 if ((devnum = atoi(optarg)) != 0) {
782 error("Invalid adapter index");
784 if (pcap_findalldevs(&devpointer, ebuf) < 0)
788 * Look for the devnum-th entry
789 * in the list of devices
793 i < devnum-1 && devpointer != NULL;
794 i++, devpointer = devpointer->next)
796 if (devpointer == NULL)
797 error("Invalid adapter index");
799 device = devpointer->name;
802 #endif /* HAVE_PCAP_FINDALLDEVS */
806 #ifdef HAVE_PCAP_CREATE
810 #endif /* HAVE_PCAP_CREATE */
812 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
814 jflag = pcap_tstamp_type_name_to_val(optarg);
816 error("invalid time stamp type %s", optarg);
827 * _IOLBF is the same as _IOFBF in Microsoft's C
828 * libraries; the only alternative they offer
831 * XXX - this should really be checking for MSVC++,
832 * not WIN32, if, for example, MinGW has its own
833 * C library that is more UNIX-compatible.
835 setvbuf(stdout, NULL, _IONBF, 0);
837 #ifdef HAVE_SETLINEBUF
840 setvbuf(stdout, NULL, _IOLBF, 0);
851 if (smiLoadModule(optarg) == 0) {
852 error("could not load MIB module %s", optarg);
856 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
857 program_name, optarg);
858 (void)fprintf(stderr, "(no libsmi support)\n");
863 /* TCP-MD5 shared secret */
864 #ifndef HAVE_LIBCRYPTO
865 warning("crypto code not compiled in");
888 ++suppress_default_print;
902 snaplen = strtol(optarg, &end, 0);
903 if (optarg == end || *end != '\0'
904 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
905 error("invalid snaplen %s", optarg);
906 else if (snaplen == 0)
907 snaplen = MAXIMUM_SNAPLEN;
920 if (strcasecmp(optarg, "vat") == 0)
922 else if (strcasecmp(optarg, "wb") == 0)
924 else if (strcasecmp(optarg, "rpc") == 0)
926 else if (strcasecmp(optarg, "rtp") == 0)
928 else if (strcasecmp(optarg, "rtcp") == 0)
929 packettype = PT_RTCP;
930 else if (strcasecmp(optarg, "snmp") == 0)
931 packettype = PT_SNMP;
932 else if (strcasecmp(optarg, "cnfp") == 0)
933 packettype = PT_CNFP;
934 else if (strcasecmp(optarg, "tftp") == 0)
935 packettype = PT_TFTP;
936 else if (strcasecmp(optarg, "aodv") == 0)
937 packettype = PT_AODV;
938 else if (strcasecmp(optarg, "carp") == 0)
939 packettype = PT_CARP;
941 error("unknown packet type `%s'", optarg);
948 #ifdef HAVE_PCAP_DUMP_FLUSH
963 Wflag = atoi(optarg);
965 error("invalid number of output files %s", optarg);
966 WflagChars = getWflagChars(Wflag);
971 ++suppress_default_print;
976 ++suppress_default_print;
980 gndo->ndo_dltname = optarg;
982 pcap_datalink_name_to_val(gndo->ndo_dltname);
983 if (gndo->ndo_dlt < 0)
984 error("invalid data link type %s", gndo->ndo_dltname);
987 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
990 /* Undocumented flag */
991 #ifdef HAVE_PCAP_DEBUG
992 extern int pcap_debug;
1003 zflag = strdup(optarg);
1012 username = strdup(optarg);
1027 case 0: /* Default */
1028 case 4: /* Default + Date*/
1029 thiszone = gmt2local(0);
1032 case 1: /* No time stamp */
1033 case 2: /* Unix timeval style */
1034 case 3: /* Microseconds since previous packet */
1035 case 5: /* Microseconds since first packet */
1038 default: /* Not supported */
1039 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1044 /* if run as root, prepare for chrooting */
1045 if (getuid() == 0 || geteuid() == 0) {
1046 /* future extensibility for cmd-line arguments */
1048 chroot_dir = WITH_CHROOT;
1053 /* if run as root, prepare for dropping root privileges */
1054 if (getuid() == 0 || geteuid() == 0) {
1055 /* Run with '-Z root' to restore old behaviour */
1057 username = WITH_USER;
1061 if (RFileName != NULL) {
1063 const char *dlt_name;
1067 * We don't need network access, so relinquish any set-UID
1068 * or set-GID privileges we have (if any).
1070 * We do *not* want set-UID privileges when opening a
1071 * trace file, as that might let the user read other
1072 * people's trace files (especially if we're set-UID
1075 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1076 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1078 pd = pcap_open_offline(RFileName, ebuf);
1081 dlt = pcap_datalink(pd);
1082 dlt_name = pcap_datalink_val_to_name(dlt);
1083 if (dlt_name == NULL) {
1084 fprintf(stderr, "reading from file %s, link-type %u\n",
1088 "reading from file %s, link-type %s (%s)\n",
1089 RFileName, dlt_name,
1090 pcap_datalink_val_to_description(dlt));
1095 error("-f and -r options are incompatible");
1097 if (device == NULL) {
1098 device = pcap_lookupdev(ebuf);
1103 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1104 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1105 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1109 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1114 #ifdef HAVE_PCAP_CREATE
1115 pd = pcap_create(device, ebuf);
1118 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1120 show_tstamp_types_and_exit(device, pd);
1123 * Is this an interface that supports monitor mode?
1125 if (pcap_can_set_rfmon(pd) == 1)
1126 supports_monitor_mode = 1;
1128 supports_monitor_mode = 0;
1129 status = pcap_set_snaplen(pd, snaplen);
1131 error("%s: Can't set snapshot length: %s",
1132 device, pcap_statustostr(status));
1133 status = pcap_set_promisc(pd, !pflag);
1135 error("%s: Can't set promiscuous mode: %s",
1136 device, pcap_statustostr(status));
1138 status = pcap_set_rfmon(pd, 1);
1140 error("%s: Can't set monitor mode: %s",
1141 device, pcap_statustostr(status));
1143 status = pcap_set_timeout(pd, 1000);
1145 error("%s: pcap_set_timeout failed: %s",
1146 device, pcap_statustostr(status));
1148 status = pcap_set_buffer_size(pd, Bflag);
1150 error("%s: Can't set buffer size: %s",
1151 device, pcap_statustostr(status));
1153 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1155 status = pcap_set_tstamp_type(pd, jflag);
1157 error("%s: Can't set time stamp type: %s",
1158 device, pcap_statustostr(status));
1161 status = pcap_activate(pd);
1164 * pcap_activate() failed.
1166 cp = pcap_geterr(pd);
1167 if (status == PCAP_ERROR)
1169 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1170 status == PCAP_ERROR_PERM_DENIED) &&
1172 error("%s: %s\n(%s)", device,
1173 pcap_statustostr(status), cp);
1175 error("%s: %s", device,
1176 pcap_statustostr(status));
1177 } else if (status > 0) {
1179 * pcap_activate() succeeded, but it's warning us
1180 * of a problem it had.
1182 cp = pcap_geterr(pd);
1183 if (status == PCAP_WARNING)
1185 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1187 warning("%s: %s\n(%s)", device,
1188 pcap_statustostr(status), cp);
1190 warning("%s: %s", device,
1191 pcap_statustostr(status));
1195 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1199 warning("%s", ebuf);
1200 #endif /* HAVE_PCAP_CREATE */
1202 * Let user own process after socket has been opened.
1205 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1206 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1208 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1210 if(pcap_setbuff(pd, Bflag)==-1){
1211 error("%s", pcap_geterr(pd));
1213 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1215 show_dlts_and_exit(device, pd);
1216 if (gndo->ndo_dlt >= 0) {
1217 #ifdef HAVE_PCAP_SET_DATALINK
1218 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1219 error("%s", pcap_geterr(pd));
1222 * We don't actually support changing the
1223 * data link type, so we only let them
1224 * set it to what it already is.
1226 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1227 error("%s is not one of the DLTs supported by this device\n",
1231 (void)fprintf(stderr, "%s: data link type %s\n",
1232 program_name, gndo->ndo_dltname);
1233 (void)fflush(stderr);
1235 i = pcap_snapshot(pd);
1237 warning("snaplen raised from %d to %d", snaplen, i);
1240 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1243 warning("%s", ebuf);
1247 cmdbuf = read_infile(infile);
1249 cmdbuf = copy_argv(&argv[optind]);
1251 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1252 error("%s", pcap_geterr(pd));
1255 bpf_dump(&fcode, dflag);
1259 init_addrtoname(localnet, netmask);
1263 (void)setsignal(SIGPIPE, cleanup);
1264 (void)setsignal(SIGTERM, cleanup);
1265 (void)setsignal(SIGINT, cleanup);
1267 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1268 (void)setsignal(SIGCHLD, child_cleanup);
1270 /* Cooperate with nohup(1) */
1272 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1273 (void)setsignal(SIGHUP, oldhandler);
1278 * If a user name was specified with "-Z", attempt to switch to
1279 * that user's UID. This would probably be used with sudo,
1280 * to allow tcpdump to be run in a special restricted
1281 * account (if you just want to allow users to open capture
1282 * devices, and can't just give users that permission,
1283 * you'd make tcpdump set-UID or set-GID).
1285 * Tcpdump doesn't necessarily write only to one savefile;
1286 * the general only way to allow a -Z instance to write to
1287 * savefiles as the user under whose UID it's run, rather
1288 * than as the user specified with -Z, would thus be to switch
1289 * to the original user ID before opening a capture file and
1290 * then switch back to the -Z user ID after opening the savefile.
1291 * Switching to the -Z user ID only after opening the first
1292 * savefile doesn't handle the general case.
1294 if (getuid() == 0 || geteuid() == 0) {
1295 if (username || chroot_dir)
1296 droproot(username, chroot_dir);
1300 if (pcap_setfilter(pd, &fcode) < 0)
1301 error("%s", pcap_geterr(pd));
1304 /* Do not exceed the default NAME_MAX for files. */
1305 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1307 if (dumpinfo.CurrentFileName == NULL)
1308 error("malloc of dumpinfo.CurrentFileName");
1310 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1312 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1314 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1316 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1318 error("%s", pcap_geterr(pd));
1319 if (Cflag != 0 || Gflag != 0) {
1320 callback = dump_packet_and_trunc;
1321 dumpinfo.WFileName = WFileName;
1324 pcap_userdata = (u_char *)&dumpinfo;
1326 callback = dump_packet;
1327 pcap_userdata = (u_char *)p;
1329 #ifdef HAVE_PCAP_DUMP_FLUSH
1334 type = pcap_datalink(pd);
1335 printinfo.ndo_type = 1;
1336 printinfo.ndo = gndo;
1337 printinfo.p.ndo_printer = lookup_ndo_printer(type);
1338 if (printinfo.p.ndo_printer == NULL) {
1339 printinfo.p.printer = lookup_printer(type);
1340 printinfo.ndo_type = 0;
1341 if (printinfo.p.printer == NULL) {
1342 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1343 if (gndo->ndo_dltname != NULL)
1344 error("packet printing is not supported for link type %s: use -w",
1347 error("packet printing is not supported for link type %d: use -w", type);
1350 callback = print_packet;
1351 pcap_userdata = (u_char *)&printinfo;
1356 * We can't get statistics when reading from a file rather
1357 * than capturing from a device.
1359 if (RFileName == NULL)
1360 (void)setsignal(SIGINFO, requestinfo);
1363 if (vflag > 0 && WFileName) {
1365 * When capturing to a file, "-v" means tcpdump should,
1366 * every 10 secodns, "v"erbosely report the number of
1369 #ifdef USE_WIN32_MM_TIMER
1370 /* call verbose_stats_dump() each 1000 +/-100msec */
1371 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1372 setvbuf(stderr, NULL, _IONBF, 0);
1373 #elif defined(HAVE_ALARM)
1374 (void)setsignal(SIGALRM, verbose_stats_dump);
1380 if (RFileName == NULL) {
1382 const char *dlt_name;
1384 if (!vflag && !WFileName) {
1385 (void)fprintf(stderr,
1386 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1389 (void)fprintf(stderr, "%s: ", program_name);
1390 dlt = pcap_datalink(pd);
1391 dlt_name = pcap_datalink_val_to_name(dlt);
1392 if (dlt_name == NULL) {
1393 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1394 device, dlt, snaplen);
1396 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1398 pcap_datalink_val_to_description(dlt), snaplen);
1400 (void)fflush(stderr);
1403 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1404 if (WFileName == NULL) {
1406 * We're printing packets. Flush the printed output,
1407 * so it doesn't get intermingled with error output.
1411 * We got interrupted, so perhaps we didn't
1412 * manage to finish a line we were printing.
1413 * Print an extra newline, just in case.
1417 (void)fflush(stdout);
1423 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1424 program_name, pcap_geterr(pd));
1426 if (RFileName == NULL) {
1428 * We're doing a live capture. Report the capture
1434 exit(status == -1 ? 1 : 0);
1437 /* make a clean exit on interrupts */
1439 cleanup(int signo _U_)
1441 #ifdef USE_WIN32_MM_TIMER
1443 timeKillEvent(timer_id);
1445 #elif defined(HAVE_ALARM)
1449 #ifdef HAVE_PCAP_BREAKLOOP
1451 * We have "pcap_breakloop()"; use it, so that we do as little
1452 * as possible in the signal handler (it's probably not safe
1453 * to do anything with standard I/O streams in a signal handler -
1454 * the ANSI C standard doesn't say it is).
1459 * We don't have "pcap_breakloop()"; this isn't safe, but
1460 * it's the best we can do. Print the summary if we're
1461 * not reading from a savefile - i.e., if we're doing a
1462 * live capture - and exit.
1464 if (pd != NULL && pcap_file(pd) == NULL) {
1466 * We got interrupted, so perhaps we didn't
1467 * manage to finish a line we were printing.
1468 * Print an extra newline, just in case.
1471 (void)fflush(stdout);
1479 On windows, we do not use a fork, so we do not care less about
1480 waiting a child processes to die
1482 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1484 child_cleanup(int signo _U_)
1488 #endif /* HAVE_FORK && HAVE_VFORK */
1491 info(register int verbose)
1493 struct pcap_stat stat;
1496 * Older versions of libpcap didn't set ps_ifdrop on some
1497 * platforms; initialize it to 0 to handle that.
1500 if (pcap_stats(pd, &stat) < 0) {
1501 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1507 fprintf(stderr, "%s: ", program_name);
1509 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1510 PLURAL_SUFFIX(packets_captured));
1512 fputs(", ", stderr);
1515 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1516 PLURAL_SUFFIX(stat.ps_recv));
1518 fputs(", ", stderr);
1521 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1522 PLURAL_SUFFIX(stat.ps_drop));
1523 if (stat.ps_ifdrop != 0) {
1525 fputs(", ", stderr);
1528 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1529 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1535 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1537 compress_savefile(const char *filename)
1546 * Set to lowest priority so that this doesn't disturb the capture
1549 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1551 setpriority(PRIO_PROCESS, 0, 19);
1553 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1555 "compress_savefile:execlp(%s, %s): %s\n",
1565 #else /* HAVE_FORK && HAVE_VFORK */
1567 compress_savefile(const char *filename)
1570 "compress_savefile failed. Functionality not implemented under your system\n");
1572 #endif /* HAVE_FORK && HAVE_VFORK */
1575 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1577 struct dump_info *dump_info;
1583 dump_info = (struct dump_info *)user;
1586 * XXX - this won't force the file to rotate on the specified time
1587 * boundary, but it will rotate on the first packet received after the
1588 * specified Gflag number of seconds. Note: if a Gflag time boundary
1589 * and a Cflag size boundary coincide, the time rotation will occur
1590 * first thereby cancelling the Cflag boundary (since the file should
1594 /* Check if it is time to rotate */
1597 /* Get the current time */
1598 if ((t = time(NULL)) == (time_t)-1) {
1599 error("dump_and_trunc_packet: can't get current_time: %s",
1600 pcap_strerror(errno));
1604 /* If the time is greater than the specified window, rotate */
1605 if (t - Gflag_time >= Gflag) {
1606 /* Update the Gflag_time */
1608 /* Update Gflag_count */
1611 * Close the current file and open a new one.
1613 pcap_dump_close(dump_info->p);
1616 * Compress the file we just closed, if the user asked for it
1619 compress_savefile(dump_info->CurrentFileName);
1622 * Check to see if we've exceeded the Wflag (when
1625 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1626 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1631 if (dump_info->CurrentFileName != NULL)
1632 free(dump_info->CurrentFileName);
1633 /* Allocate space for max filename + \0. */
1634 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1635 if (dump_info->CurrentFileName == NULL)
1636 error("dump_packet_and_trunc: malloc");
1638 * This is always the first file in the Cflag
1640 * We also don't need numbering if Cflag is not set.
1643 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1646 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1648 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1649 if (dump_info->p == NULL)
1650 error("%s", pcap_geterr(pd));
1655 * XXX - this won't prevent capture files from getting
1656 * larger than Cflag - the last packet written to the
1657 * file could put it over Cflag.
1659 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1661 * Close the current file and open a new one.
1663 pcap_dump_close(dump_info->p);
1666 * Compress the file we just closed, if the user asked for it
1669 compress_savefile(dump_info->CurrentFileName);
1673 if (Cflag_count >= Wflag)
1676 if (dump_info->CurrentFileName != NULL)
1677 free(dump_info->CurrentFileName);
1678 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1679 if (dump_info->CurrentFileName == NULL)
1680 error("dump_packet_and_trunc: malloc");
1681 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1682 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1683 if (dump_info->p == NULL)
1684 error("%s", pcap_geterr(pd));
1687 pcap_dump((u_char *)dump_info->p, h, sp);
1688 #ifdef HAVE_PCAP_DUMP_FLUSH
1690 pcap_dump_flush(dump_info->p);
1699 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1705 pcap_dump(user, h, sp);
1706 #ifdef HAVE_PCAP_DUMP_FLUSH
1708 pcap_dump_flush((pcap_dumper_t *)user);
1717 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1719 struct print_info *print_info;
1727 print_info = (struct print_info *)user;
1730 * Some printers want to check that they're not walking off the
1731 * end of the packet.
1732 * Rather than pass it all the way down, we set this global.
1734 snapend = sp + h->caplen;
1736 if(print_info->ndo_type) {
1737 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1739 hdrlen = (*print_info->p.printer)(h, sp);
1744 * Print the raw packet data in hex and ASCII.
1748 * Include the link-layer header.
1750 hex_and_ascii_print("\n\t", sp, h->caplen);
1753 * Don't include the link-layer header - and if
1754 * we have nothing past the link-layer header,
1757 if (h->caplen > hdrlen)
1758 hex_and_ascii_print("\n\t", sp + hdrlen,
1759 h->caplen - hdrlen);
1763 * Print the raw packet data in hex.
1767 * Include the link-layer header.
1769 hex_print("\n\t", sp, h->caplen);
1772 * Don't include the link-layer header - and if
1773 * we have nothing past the link-layer header,
1776 if (h->caplen > hdrlen)
1777 hex_print("\n\t", sp + hdrlen,
1778 h->caplen - hdrlen);
1782 * Print the raw packet data in ASCII.
1786 * Include the link-layer header.
1788 ascii_print(sp, h->caplen);
1791 * Don't include the link-layer header - and if
1792 * we have nothing past the link-layer header,
1795 if (h->caplen > hdrlen)
1796 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1809 * XXX - there should really be libpcap calls to get the version
1810 * number as a string (the string would be generated from #defines
1811 * at run time, so that it's not generated from string constants
1812 * in the library, as, on many UNIX systems, those constants would
1813 * be statically linked into the application executable image, and
1814 * would thus reflect the version of libpcap on the system on
1815 * which the application was *linked*, not the system on which it's
1818 * That routine should be documented, unlike the "version[]"
1819 * string, so that UNIX vendors providing their own libpcaps
1820 * don't omit it (as a couple of vendors have...).
1822 * Packet.dll should perhaps also export a routine to return the
1823 * version number of the Packet.dll code, to supply the
1824 * "Wpcap_version" information on Windows.
1826 char WDversion[]="current-cvs.tcpdump.org";
1827 #if !defined(HAVE_GENERATED_VERSION)
1828 char version[]="current-cvs.tcpdump.org";
1830 char pcap_version[]="current-cvs.tcpdump.org";
1831 char Wpcap_version[]="3.1";
1835 * By default, print the specified data out in hex and ASCII.
1838 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1840 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1844 default_print(const u_char *bp, u_int length)
1846 ndo_default_print(gndo, bp, length);
1850 RETSIGTYPE requestinfo(int signo _U_)
1860 * Called once each second in verbose mode while dumping to file
1862 #ifdef USE_WIN32_MM_TIMER
1863 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1864 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1866 struct pcap_stat stat;
1868 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1869 fprintf(stderr, "Got %u\r", packets_captured);
1871 #elif defined(HAVE_ALARM)
1872 static void verbose_stats_dump(int sig _U_)
1874 struct pcap_stat stat;
1876 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1877 fprintf(stderr, "Got %u\r", packets_captured);
1885 extern char version[];
1886 #ifndef HAVE_PCAP_LIB_VERSION
1887 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1888 extern char pcap_version[];
1889 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1890 static char pcap_version[] = "unknown";
1891 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1892 #endif /* HAVE_PCAP_LIB_VERSION */
1894 #ifdef HAVE_PCAP_LIB_VERSION
1896 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1898 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1900 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1901 #else /* HAVE_PCAP_LIB_VERSION */
1903 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1904 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1906 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1907 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1909 #endif /* HAVE_PCAP_LIB_VERSION */
1910 (void)fprintf(stderr,
1911 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1912 (void)fprintf(stderr,
1913 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1914 (void)fprintf(stderr,
1915 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
1916 (void)fprintf(stderr,
1917 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1918 (void)fprintf(stderr,
1919 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
1920 (void)fprintf(stderr,
1921 "\t\t[ -Z user ] [ expression ]\n");
1929 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1933 (void)fprintf(stderr, "%s: ", program_name);
1935 (void)vfprintf(stderr, fmt, ap);
1939 if (fmt[-1] != '\n')
1940 (void)fputc('\n', stderr);
1948 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1952 (void)fprintf(stderr, "%s: WARNING: ", program_name);
1954 (void)vfprintf(stderr, fmt, ap);
1958 if (fmt[-1] != '\n')
1959 (void)fputc('\n', stderr);