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)";
37 * tcpdump - monitor tcp/ip traffic on an ethernet.
39 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
40 * Mercilessly hacked and occasionally improved since then via the
41 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
48 #include <tcpdump-stdinc.h>
53 extern int strcasecmp (const char *__s1, const char *__s2);
71 #include <sys/resource.h>
78 #include "netdissect.h"
79 #include "interface.h"
80 #include "addrtoname.h"
82 #include "setsignal.h"
83 #include "gmt2local.h"
84 #include "pcap-missing.h"
90 netdissect_options Gndo;
91 netdissect_options *gndo = &Gndo;
93 static int dflag; /* print filter code */
94 static int Lflag; /* list available data link types and exit */
95 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
96 static int Jflag; /* list available time stamp types */
98 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
100 static int infodelay;
101 static int infoprint;
105 int32_t thiszone; /* seconds offset from gmt to local time */
108 static RETSIGTYPE cleanup(int);
109 static RETSIGTYPE child_cleanup(int);
110 static void usage(void) __attribute__((noreturn));
111 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
113 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
114 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
115 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
116 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
117 static void droproot(const char *, const char *);
118 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
119 __attribute__ ((noreturn, format (printf, 2, 3)));
120 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
123 RETSIGTYPE requestinfo(int);
126 #if defined(USE_WIN32_MM_TIMER)
127 #include <MMsystem.h>
128 static UINT timer_id;
129 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
130 #elif defined(HAVE_ALARM)
131 static void verbose_stats_dump(int sig);
134 static void info(int);
135 static u_int packets_captured;
149 static struct printer printers[] = {
150 { arcnet_if_print, DLT_ARCNET },
151 #ifdef DLT_ARCNET_LINUX
152 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
154 { token_if_print, DLT_IEEE802 },
156 { lane_if_print, DLT_LANE8023 },
159 { cip_if_print, DLT_CIP },
162 { cip_if_print, DLT_ATM_CLIP },
164 { sl_if_print, DLT_SLIP },
165 #ifdef DLT_SLIP_BSDOS
166 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
168 { ppp_if_print, DLT_PPP },
169 #ifdef DLT_PPP_WITHDIRECTION
170 { ppp_if_print, DLT_PPP_WITHDIRECTION },
173 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
175 { fddi_if_print, DLT_FDDI },
176 { null_if_print, DLT_NULL },
178 { null_if_print, DLT_LOOP },
180 { raw_if_print, DLT_RAW },
181 { atm_if_print, DLT_ATM_RFC1483 },
183 { chdlc_if_print, DLT_C_HDLC },
186 { chdlc_if_print, DLT_HDLC },
188 #ifdef DLT_PPP_SERIAL
189 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
192 { pppoe_if_print, DLT_PPP_ETHER },
195 { sll_if_print, DLT_LINUX_SLL },
197 #ifdef DLT_IEEE802_11
198 { ieee802_11_if_print, DLT_IEEE802_11},
201 { ltalk_if_print, DLT_LTALK },
203 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
204 { pflog_if_print, DLT_PFLOG },
207 { fr_if_print, DLT_FR },
210 { fr_if_print, DLT_FRELAY },
213 { sunatm_if_print, DLT_SUNATM },
215 #ifdef DLT_IP_OVER_FC
216 { ipfc_if_print, DLT_IP_OVER_FC },
218 #ifdef DLT_PRISM_HEADER
219 { prism_if_print, DLT_PRISM_HEADER },
221 #ifdef DLT_IEEE802_11_RADIO
222 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
225 { enc_if_print, DLT_ENC },
227 #ifdef DLT_SYMANTEC_FIREWALL
228 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
230 #ifdef DLT_APPLE_IP_OVER_IEEE1394
231 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
233 #ifdef DLT_IEEE802_11_RADIO_AVS
234 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
236 #ifdef DLT_JUNIPER_ATM1
237 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
239 #ifdef DLT_JUNIPER_ATM2
240 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
242 #ifdef DLT_JUNIPER_MFR
243 { juniper_mfr_print, DLT_JUNIPER_MFR },
245 #ifdef DLT_JUNIPER_MLFR
246 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
248 #ifdef DLT_JUNIPER_MLPPP
249 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
251 #ifdef DLT_JUNIPER_PPPOE
252 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
254 #ifdef DLT_JUNIPER_PPPOE_ATM
255 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
257 #ifdef DLT_JUNIPER_GGSN
258 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
260 #ifdef DLT_JUNIPER_ES
261 { juniper_es_print, DLT_JUNIPER_ES },
263 #ifdef DLT_JUNIPER_MONITOR
264 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
266 #ifdef DLT_JUNIPER_SERVICES
267 { juniper_services_print, DLT_JUNIPER_SERVICES },
269 #ifdef DLT_JUNIPER_ETHER
270 { juniper_ether_print, DLT_JUNIPER_ETHER },
272 #ifdef DLT_JUNIPER_PPP
273 { juniper_ppp_print, DLT_JUNIPER_PPP },
275 #ifdef DLT_JUNIPER_FRELAY
276 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
278 #ifdef DLT_JUNIPER_CHDLC
279 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
282 { mfr_if_print, DLT_MFR },
284 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
285 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
287 #ifdef HAVE_PCAP_USB_H
289 { usb_linux_48_byte_print, DLT_USB_LINUX},
290 #endif /* DLT_USB_LINUX */
291 #ifdef DLT_USB_LINUX_MMAPPED
292 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
293 #endif /* DLT_USB_LINUX_MMAPPED */
294 #endif /* HAVE_PCAP_USB_H */
296 { raw_if_print, DLT_IPV4 },
299 { raw_if_print, DLT_IPV6 },
304 static struct ndo_printer ndo_printers[] = {
305 { ether_if_print, DLT_EN10MB },
307 { ipnet_if_print, DLT_IPNET },
309 #ifdef DLT_IEEE802_15_4
310 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
312 #ifdef DLT_IEEE802_15_4_NOFCS
313 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
316 { ppi_if_print, DLT_PPI },
318 #ifdef DLT_NETANALYZER
319 { netanalyzer_if_print, DLT_NETANALYZER },
321 #ifdef DLT_NETANALYZER_TRANSPARENT
322 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
328 lookup_printer(int type)
332 for (p = printers; p->f; ++p)
341 lookup_ndo_printer(int type)
343 struct ndo_printer *p;
345 for (p = ndo_printers; p->f; ++p)
355 static int supports_monitor_mode;
362 netdissect_options *ndo;
365 if_ndo_printer ndo_printer;
372 char *CurrentFileName;
377 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
379 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
382 int *tstamp_types = 0;
383 const char *tstamp_type_name;
386 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
387 if (n_tstamp_types < 0)
388 error("%s", pcap_geterr(pd));
390 if (n_tstamp_types == 0) {
391 fprintf(stderr, "Time stamp type cannot be set for %s\n",
395 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
397 for (i = 0; i < n_tstamp_types; i++) {
398 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
399 if (tstamp_type_name != NULL) {
400 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
401 pcap_tstamp_type_val_to_description(tstamp_types[i]));
403 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
406 pcap_free_tstamp_types(tstamp_types);
412 show_dlts_and_exit(const char *device, pcap_t *pd)
416 const char *dlt_name;
418 n_dlts = pcap_list_datalinks(pd, &dlts);
420 error("%s", pcap_geterr(pd));
421 else if (n_dlts == 0 || !dlts)
422 error("No data link types.");
425 * If the interface is known to support monitor mode, indicate
426 * whether these are the data link types available when not in
427 * monitor mode, if -I wasn't specified, or when in monitor mode,
428 * when -I was specified (the link-layer types available in
429 * monitor mode might be different from the ones available when
430 * not in monitor mode).
432 if (supports_monitor_mode)
433 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
435 Iflag ? "when in monitor mode" : "when not in monitor mode");
437 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
440 while (--n_dlts >= 0) {
441 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
442 if (dlt_name != NULL) {
443 (void) fprintf(stderr, " %s (%s)", dlt_name,
444 pcap_datalink_val_to_description(dlts[n_dlts]));
447 * OK, does tcpdump handle that type?
449 if (lookup_printer(dlts[n_dlts]) == NULL
450 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
451 (void) fprintf(stderr, " (printing not supported)");
452 fprintf(stderr, "\n");
454 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
458 pcap_free_datalinks(dlts);
463 * Set up flags that might or might not be supported depending on the
464 * version of libpcap we're using.
466 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
468 #define B_FLAG_USAGE " [ -B size ]"
469 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
472 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
474 #ifdef HAVE_PCAP_CREATE
476 #else /* HAVE_PCAP_CREATE */
478 #endif /* HAVE_PCAP_CREATE */
480 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
482 #define j_FLAG_USAGE " [ -j tstamptype ]"
484 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
488 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
490 #ifdef HAVE_PCAP_FINDALLDEVS
491 #ifndef HAVE_PCAP_IF_T
492 #undef HAVE_PCAP_FINDALLDEVS
496 #ifdef HAVE_PCAP_FINDALLDEVS
502 #ifdef HAVE_PCAP_DUMP_FLUSH
509 /* Drop root privileges and chroot if necessary */
511 droproot(const char *username, const char *chroot_dir)
513 struct passwd *pw = NULL;
515 if (chroot_dir && !username) {
516 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
520 pw = getpwnam(username);
523 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
524 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
525 chroot_dir, pcap_strerror(errno));
529 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
530 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
531 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
533 (unsigned long)pw->pw_uid,
534 (unsigned long)pw->pw_gid,
535 pcap_strerror(errno));
540 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
563 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
565 char *filename = malloc(NAME_MAX + 1);
567 /* Process with strftime if Gflag is set. */
571 /* Convert Gflag_time to a usable format */
572 if ((local_tm = localtime(&Gflag_time)) == NULL) {
573 error("MakeTimedFilename: localtime");
576 /* There's no good way to detect an error in strftime since a return
577 * value of 0 isn't necessarily failure.
579 strftime(filename, NAME_MAX, orig_name, local_tm);
581 strncpy(filename, orig_name, NAME_MAX);
584 if (cnt == 0 && max_chars == 0)
585 strncpy(buffer, filename, NAME_MAX + 1);
587 if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
588 /* Report an error if the filename is too large */
589 error("too many output files or filename is too long (> %d)", NAME_MAX);
593 static int tcpdump_printf(netdissect_options *ndo _U_,
594 const char *fmt, ...)
601 ret=vfprintf(stdout, fmt, args);
608 main(int argc, char **argv)
610 register int cnt, op, i;
611 bpf_u_int32 localnet, netmask;
612 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
613 pcap_handler callback;
615 struct bpf_program fcode;
617 RETSIGTYPE (*oldhandler)(int);
619 struct print_info printinfo;
620 struct dump_info dumpinfo;
621 u_char *pcap_userdata;
622 char ebuf[PCAP_ERRBUF_SIZE];
623 char *username = NULL;
624 char *chroot_dir = NULL;
625 #ifdef HAVE_PCAP_FINDALLDEVS
626 pcap_if_t *devpointer;
631 if(wsockinit() != 0) return 1;
634 jflag=-1; /* not set */
638 gndo->ndo_default_print=ndo_default_print;
639 gndo->ndo_printf=tcpdump_printf;
640 gndo->ndo_error=ndo_error;
641 gndo->ndo_warning=ndo_warning;
642 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
649 if ((cp = strrchr(argv[0], '/')) != NULL)
650 program_name = cp + 1;
652 program_name = argv[0];
654 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
662 (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)
666 /* compatibility for old -a */
677 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
679 Bflag = atoi(optarg)*1024;
681 error("invalid packet buffer size %s", optarg);
683 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
688 error("invalid packet count %s", optarg);
692 Cflag = atoi(optarg) * 1000000;
694 error("invalid file size %s", optarg);
701 #ifdef HAVE_PCAP_FINDALLDEVS
703 if (pcap_findalldevs(&devpointer, ebuf) < 0)
706 for (i = 0; devpointer != 0; i++) {
707 printf("%d.%s", i+1, devpointer->name);
708 if (devpointer->description != NULL)
709 printf(" (%s)", devpointer->description);
711 devpointer = devpointer->next;
715 #endif /* HAVE_PCAP_FINDALLDEVS */
726 #ifndef HAVE_LIBCRYPTO
727 warning("crypto code not compiled in");
729 gndo->ndo_espsecret = optarg;
741 Gflag = atoi(optarg);
743 error("invalid number of seconds %s", optarg);
745 /* We will create one file initially. */
748 /* Grab the current time for rotation use. */
749 if ((Gflag_time = time(NULL)) == (time_t)-1) {
750 error("main: can't get current time: %s",
751 pcap_strerror(errno));
764 if (optarg[0] == '0' && optarg[1] == 0)
765 error("Invalid adapter index");
767 #ifdef HAVE_PCAP_FINDALLDEVS
769 * If the argument is a number, treat it as
770 * an index into the list of adapters, as
771 * printed by "tcpdump -D".
773 * This should be OK on UNIX systems, as interfaces
774 * shouldn't have names that begin with digits.
775 * It can be useful on Windows, where more than
776 * one interface can have the same name.
778 if ((devnum = atoi(optarg)) != 0) {
780 error("Invalid adapter index");
782 if (pcap_findalldevs(&devpointer, ebuf) < 0)
786 * Look for the devnum-th entry
787 * in the list of devices
791 i < devnum-1 && devpointer != NULL;
792 i++, devpointer = devpointer->next)
794 if (devpointer == NULL)
795 error("Invalid adapter index");
797 device = devpointer->name;
800 #endif /* HAVE_PCAP_FINDALLDEVS */
804 #ifdef HAVE_PCAP_CREATE
808 #endif /* HAVE_PCAP_CREATE */
810 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
812 jflag = pcap_tstamp_type_name_to_val(optarg);
814 error("invalid time stamp type %s", optarg);
825 * _IOLBF is the same as _IOFBF in Microsoft's C
826 * libraries; the only alternative they offer
829 * XXX - this should really be checking for MSVC++,
830 * not WIN32, if, for example, MinGW has its own
831 * C library that is more UNIX-compatible.
833 setvbuf(stdout, NULL, _IONBF, 0);
835 #ifdef HAVE_SETLINEBUF
838 setvbuf(stdout, NULL, _IOLBF, 0);
849 if (smiLoadModule(optarg) == 0) {
850 error("could not load MIB module %s", optarg);
854 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
855 program_name, optarg);
856 (void)fprintf(stderr, "(no libsmi support)\n");
861 /* TCP-MD5 shared secret */
862 #ifndef HAVE_LIBCRYPTO
863 warning("crypto code not compiled in");
886 ++suppress_default_print;
900 snaplen = strtol(optarg, &end, 0);
901 if (optarg == end || *end != '\0'
902 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
903 error("invalid snaplen %s", optarg);
904 else if (snaplen == 0)
905 snaplen = MAXIMUM_SNAPLEN;
918 if (strcasecmp(optarg, "vat") == 0)
920 else if (strcasecmp(optarg, "wb") == 0)
922 else if (strcasecmp(optarg, "rpc") == 0)
924 else if (strcasecmp(optarg, "rtp") == 0)
926 else if (strcasecmp(optarg, "rtcp") == 0)
927 packettype = PT_RTCP;
928 else if (strcasecmp(optarg, "snmp") == 0)
929 packettype = PT_SNMP;
930 else if (strcasecmp(optarg, "cnfp") == 0)
931 packettype = PT_CNFP;
932 else if (strcasecmp(optarg, "tftp") == 0)
933 packettype = PT_TFTP;
934 else if (strcasecmp(optarg, "aodv") == 0)
935 packettype = PT_AODV;
936 else if (strcasecmp(optarg, "carp") == 0)
937 packettype = PT_CARP;
939 error("unknown packet type `%s'", optarg);
946 #ifdef HAVE_PCAP_DUMP_FLUSH
961 Wflag = atoi(optarg);
963 error("invalid number of output files %s", optarg);
964 WflagChars = getWflagChars(Wflag);
969 ++suppress_default_print;
974 ++suppress_default_print;
978 gndo->ndo_dltname = optarg;
980 pcap_datalink_name_to_val(gndo->ndo_dltname);
981 if (gndo->ndo_dlt < 0)
982 error("invalid data link type %s", gndo->ndo_dltname);
985 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
988 /* Undocumented flag */
989 #ifdef HAVE_PCAP_DEBUG
990 extern int pcap_debug;
1001 zflag = strdup(optarg);
1010 username = strdup(optarg);
1025 case 0: /* Default */
1026 case 4: /* Default + Date*/
1027 thiszone = gmt2local(0);
1030 case 1: /* No time stamp */
1031 case 2: /* Unix timeval style */
1032 case 3: /* Microseconds since previous packet */
1033 case 5: /* Microseconds since first packet */
1036 default: /* Not supported */
1037 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1042 /* if run as root, prepare for chrooting */
1043 if (getuid() == 0 || geteuid() == 0) {
1044 /* future extensibility for cmd-line arguments */
1046 chroot_dir = WITH_CHROOT;
1051 /* if run as root, prepare for dropping root privileges */
1052 if (getuid() == 0 || geteuid() == 0) {
1053 /* Run with '-Z root' to restore old behaviour */
1055 username = WITH_USER;
1059 if (RFileName != NULL) {
1061 const char *dlt_name;
1065 * We don't need network access, so relinquish any set-UID
1066 * or set-GID privileges we have (if any).
1068 * We do *not* want set-UID privileges when opening a
1069 * trace file, as that might let the user read other
1070 * people's trace files (especially if we're set-UID
1073 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1074 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1076 pd = pcap_open_offline(RFileName, ebuf);
1079 dlt = pcap_datalink(pd);
1080 dlt_name = pcap_datalink_val_to_name(dlt);
1081 if (dlt_name == NULL) {
1082 fprintf(stderr, "reading from file %s, link-type %u\n",
1086 "reading from file %s, link-type %s (%s)\n",
1087 RFileName, dlt_name,
1088 pcap_datalink_val_to_description(dlt));
1093 error("-f and -r options are incompatible");
1095 if (device == NULL) {
1096 device = pcap_lookupdev(ebuf);
1101 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1102 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1103 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1107 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1112 #ifdef HAVE_PCAP_CREATE
1113 pd = pcap_create(device, ebuf);
1116 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1118 show_tstamp_types_and_exit(device, pd);
1121 * Is this an interface that supports monitor mode?
1123 if (pcap_can_set_rfmon(pd) == 1)
1124 supports_monitor_mode = 1;
1126 supports_monitor_mode = 0;
1127 status = pcap_set_snaplen(pd, snaplen);
1129 error("%s: Can't set snapshot length: %s",
1130 device, pcap_statustostr(status));
1131 status = pcap_set_promisc(pd, !pflag);
1133 error("%s: Can't set promiscuous mode: %s",
1134 device, pcap_statustostr(status));
1136 status = pcap_set_rfmon(pd, 1);
1138 error("%s: Can't set monitor mode: %s",
1139 device, pcap_statustostr(status));
1141 status = pcap_set_timeout(pd, 1000);
1143 error("%s: pcap_set_timeout failed: %s",
1144 device, pcap_statustostr(status));
1146 status = pcap_set_buffer_size(pd, Bflag);
1148 error("%s: Can't set buffer size: %s",
1149 device, pcap_statustostr(status));
1151 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1153 status = pcap_set_tstamp_type(pd, jflag);
1155 error("%s: Can't set time stamp type: %s",
1156 device, pcap_statustostr(status));
1159 status = pcap_activate(pd);
1162 * pcap_activate() failed.
1164 cp = pcap_geterr(pd);
1165 if (status == PCAP_ERROR)
1167 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1168 status == PCAP_ERROR_PERM_DENIED) &&
1170 error("%s: %s\n(%s)", device,
1171 pcap_statustostr(status), cp);
1173 error("%s: %s", device,
1174 pcap_statustostr(status));
1175 } else if (status > 0) {
1177 * pcap_activate() succeeded, but it's warning us
1178 * of a problem it had.
1180 cp = pcap_geterr(pd);
1181 if (status == PCAP_WARNING)
1183 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1185 warning("%s: %s\n(%s)", device,
1186 pcap_statustostr(status), cp);
1188 warning("%s: %s", device,
1189 pcap_statustostr(status));
1193 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1197 warning("%s", ebuf);
1198 #endif /* HAVE_PCAP_CREATE */
1200 * Let user own process after socket has been opened.
1203 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1204 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1206 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1208 if(pcap_setbuff(pd, Bflag)==-1){
1209 error("%s", pcap_geterr(pd));
1211 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1213 show_dlts_and_exit(device, pd);
1214 if (gndo->ndo_dlt >= 0) {
1215 #ifdef HAVE_PCAP_SET_DATALINK
1216 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1217 error("%s", pcap_geterr(pd));
1220 * We don't actually support changing the
1221 * data link type, so we only let them
1222 * set it to what it already is.
1224 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1225 error("%s is not one of the DLTs supported by this device\n",
1229 (void)fprintf(stderr, "%s: data link type %s\n",
1230 program_name, gndo->ndo_dltname);
1231 (void)fflush(stderr);
1233 i = pcap_snapshot(pd);
1235 warning("snaplen raised from %d to %d", snaplen, i);
1238 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1241 warning("%s", ebuf);
1245 cmdbuf = read_infile(infile);
1247 cmdbuf = copy_argv(&argv[optind]);
1249 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1250 error("%s", pcap_geterr(pd));
1253 bpf_dump(&fcode, dflag);
1257 init_addrtoname(localnet, netmask);
1261 (void)setsignal(SIGPIPE, cleanup);
1262 (void)setsignal(SIGTERM, cleanup);
1263 (void)setsignal(SIGINT, cleanup);
1265 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1266 (void)setsignal(SIGCHLD, child_cleanup);
1268 /* Cooperate with nohup(1) */
1270 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1271 (void)setsignal(SIGHUP, oldhandler);
1276 * If a user name was specified with "-Z", attempt to switch to
1277 * that user's UID. This would probably be used with sudo,
1278 * to allow tcpdump to be run in a special restricted
1279 * account (if you just want to allow users to open capture
1280 * devices, and can't just give users that permission,
1281 * you'd make tcpdump set-UID or set-GID).
1283 * Tcpdump doesn't necessarily write only to one savefile;
1284 * the general only way to allow a -Z instance to write to
1285 * savefiles as the user under whose UID it's run, rather
1286 * than as the user specified with -Z, would thus be to switch
1287 * to the original user ID before opening a capture file and
1288 * then switch back to the -Z user ID after opening the savefile.
1289 * Switching to the -Z user ID only after opening the first
1290 * savefile doesn't handle the general case.
1292 if (getuid() == 0 || geteuid() == 0) {
1293 if (username || chroot_dir)
1294 droproot(username, chroot_dir);
1298 if (pcap_setfilter(pd, &fcode) < 0)
1299 error("%s", pcap_geterr(pd));
1302 /* Do not exceed the default NAME_MAX for files. */
1303 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1305 if (dumpinfo.CurrentFileName == NULL)
1306 error("malloc of dumpinfo.CurrentFileName");
1308 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1310 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1312 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1314 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1316 error("%s", pcap_geterr(pd));
1317 if (Cflag != 0 || Gflag != 0) {
1318 callback = dump_packet_and_trunc;
1319 dumpinfo.WFileName = WFileName;
1322 pcap_userdata = (u_char *)&dumpinfo;
1324 callback = dump_packet;
1325 pcap_userdata = (u_char *)p;
1327 #ifdef HAVE_PCAP_DUMP_FLUSH
1332 type = pcap_datalink(pd);
1333 printinfo.ndo_type = 1;
1334 printinfo.ndo = gndo;
1335 printinfo.p.ndo_printer = lookup_ndo_printer(type);
1336 if (printinfo.p.ndo_printer == NULL) {
1337 printinfo.p.printer = lookup_printer(type);
1338 printinfo.ndo_type = 0;
1339 if (printinfo.p.printer == NULL) {
1340 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1341 if (gndo->ndo_dltname != NULL)
1342 error("packet printing is not supported for link type %s: use -w",
1345 error("packet printing is not supported for link type %d: use -w", type);
1348 callback = print_packet;
1349 pcap_userdata = (u_char *)&printinfo;
1354 * We can't get statistics when reading from a file rather
1355 * than capturing from a device.
1357 if (RFileName == NULL)
1358 (void)setsignal(SIGINFO, requestinfo);
1361 if (vflag > 0 && WFileName) {
1363 * When capturing to a file, "-v" means tcpdump should,
1364 * every 10 secodns, "v"erbosely report the number of
1367 #ifdef USE_WIN32_MM_TIMER
1368 /* call verbose_stats_dump() each 1000 +/-100msec */
1369 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1370 setvbuf(stderr, NULL, _IONBF, 0);
1371 #elif defined(HAVE_ALARM)
1372 (void)setsignal(SIGALRM, verbose_stats_dump);
1378 if (RFileName == NULL) {
1380 const char *dlt_name;
1382 if (!vflag && !WFileName) {
1383 (void)fprintf(stderr,
1384 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1387 (void)fprintf(stderr, "%s: ", program_name);
1388 dlt = pcap_datalink(pd);
1389 dlt_name = pcap_datalink_val_to_name(dlt);
1390 if (dlt_name == NULL) {
1391 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1392 device, dlt, snaplen);
1394 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1396 pcap_datalink_val_to_description(dlt), snaplen);
1398 (void)fflush(stderr);
1401 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1402 if (WFileName == NULL) {
1404 * We're printing packets. Flush the printed output,
1405 * so it doesn't get intermingled with error output.
1409 * We got interrupted, so perhaps we didn't
1410 * manage to finish a line we were printing.
1411 * Print an extra newline, just in case.
1415 (void)fflush(stdout);
1421 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1422 program_name, pcap_geterr(pd));
1424 if (RFileName == NULL) {
1426 * We're doing a live capture. Report the capture
1432 exit(status == -1 ? 1 : 0);
1435 /* make a clean exit on interrupts */
1437 cleanup(int signo _U_)
1439 #ifdef USE_WIN32_MM_TIMER
1441 timeKillEvent(timer_id);
1443 #elif defined(HAVE_ALARM)
1447 #ifdef HAVE_PCAP_BREAKLOOP
1449 * We have "pcap_breakloop()"; use it, so that we do as little
1450 * as possible in the signal handler (it's probably not safe
1451 * to do anything with standard I/O streams in a signal handler -
1452 * the ANSI C standard doesn't say it is).
1457 * We don't have "pcap_breakloop()"; this isn't safe, but
1458 * it's the best we can do. Print the summary if we're
1459 * not reading from a savefile - i.e., if we're doing a
1460 * live capture - and exit.
1462 if (pd != NULL && pcap_file(pd) == NULL) {
1464 * We got interrupted, so perhaps we didn't
1465 * manage to finish a line we were printing.
1466 * Print an extra newline, just in case.
1469 (void)fflush(stdout);
1477 On windows, we do not use a fork, so we do not care less about
1478 waiting a child processes to die
1480 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1482 child_cleanup(int signo _U_)
1486 #endif /* HAVE_FORK && HAVE_VFORK */
1489 info(register int verbose)
1491 struct pcap_stat stat;
1494 * Older versions of libpcap didn't set ps_ifdrop on some
1495 * platforms; initialize it to 0 to handle that.
1498 if (pcap_stats(pd, &stat) < 0) {
1499 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1505 fprintf(stderr, "%s: ", program_name);
1507 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1508 PLURAL_SUFFIX(packets_captured));
1510 fputs(", ", stderr);
1513 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1514 PLURAL_SUFFIX(stat.ps_recv));
1516 fputs(", ", stderr);
1519 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1520 PLURAL_SUFFIX(stat.ps_drop));
1521 if (stat.ps_ifdrop != 0) {
1523 fputs(", ", stderr);
1526 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1527 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1533 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1535 compress_savefile(const char *filename)
1544 * Set to lowest priority so that this doesn't disturb the capture
1547 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1549 setpriority(PRIO_PROCESS, 0, 19);
1551 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1553 "compress_savefile:execlp(%s, %s): %s\n",
1563 #else /* HAVE_FORK && HAVE_VFORK */
1565 compress_savefile(const char *filename)
1568 "compress_savefile failed. Functionality not implemented under your system\n");
1570 #endif /* HAVE_FORK && HAVE_VFORK */
1573 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1575 struct dump_info *dump_info;
1581 dump_info = (struct dump_info *)user;
1584 * XXX - this won't force the file to rotate on the specified time
1585 * boundary, but it will rotate on the first packet received after the
1586 * specified Gflag number of seconds. Note: if a Gflag time boundary
1587 * and a Cflag size boundary coincide, the time rotation will occur
1588 * first thereby cancelling the Cflag boundary (since the file should
1592 /* Check if it is time to rotate */
1595 /* Get the current time */
1596 if ((t = time(NULL)) == (time_t)-1) {
1597 error("dump_and_trunc_packet: can't get current_time: %s",
1598 pcap_strerror(errno));
1602 /* If the time is greater than the specified window, rotate */
1603 if (t - Gflag_time >= Gflag) {
1604 /* Update the Gflag_time */
1606 /* Update Gflag_count */
1609 * Close the current file and open a new one.
1611 pcap_dump_close(dump_info->p);
1614 * Compress the file we just closed, if the user asked for it
1617 compress_savefile(dump_info->CurrentFileName);
1620 * Check to see if we've exceeded the Wflag (when
1623 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1624 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1629 if (dump_info->CurrentFileName != NULL)
1630 free(dump_info->CurrentFileName);
1631 /* Allocate space for max filename + \0. */
1632 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1633 if (dump_info->CurrentFileName == NULL)
1634 error("dump_packet_and_trunc: malloc");
1636 * This is always the first file in the Cflag
1638 * We also don't need numbering if Cflag is not set.
1641 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1644 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1646 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1647 if (dump_info->p == NULL)
1648 error("%s", pcap_geterr(pd));
1653 * XXX - this won't prevent capture files from getting
1654 * larger than Cflag - the last packet written to the
1655 * file could put it over Cflag.
1657 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1659 * Close the current file and open a new one.
1661 pcap_dump_close(dump_info->p);
1664 * Compress the file we just closed, if the user asked for it
1667 compress_savefile(dump_info->CurrentFileName);
1671 if (Cflag_count >= Wflag)
1674 if (dump_info->CurrentFileName != NULL)
1675 free(dump_info->CurrentFileName);
1676 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1677 if (dump_info->CurrentFileName == NULL)
1678 error("dump_packet_and_trunc: malloc");
1679 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1680 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1681 if (dump_info->p == NULL)
1682 error("%s", pcap_geterr(pd));
1685 pcap_dump((u_char *)dump_info->p, h, sp);
1686 #ifdef HAVE_PCAP_DUMP_FLUSH
1688 pcap_dump_flush(dump_info->p);
1697 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1703 pcap_dump(user, h, sp);
1704 #ifdef HAVE_PCAP_DUMP_FLUSH
1706 pcap_dump_flush((pcap_dumper_t *)user);
1715 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1717 struct print_info *print_info;
1725 print_info = (struct print_info *)user;
1728 * Some printers want to check that they're not walking off the
1729 * end of the packet.
1730 * Rather than pass it all the way down, we set this global.
1732 snapend = sp + h->caplen;
1734 if(print_info->ndo_type) {
1735 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1737 hdrlen = (*print_info->p.printer)(h, sp);
1742 * Print the raw packet data in hex and ASCII.
1746 * Include the link-layer header.
1748 hex_and_ascii_print("\n\t", sp, h->caplen);
1751 * Don't include the link-layer header - and if
1752 * we have nothing past the link-layer header,
1755 if (h->caplen > hdrlen)
1756 hex_and_ascii_print("\n\t", sp + hdrlen,
1757 h->caplen - hdrlen);
1761 * Print the raw packet data in hex.
1765 * Include the link-layer header.
1767 hex_print("\n\t", sp, h->caplen);
1770 * Don't include the link-layer header - and if
1771 * we have nothing past the link-layer header,
1774 if (h->caplen > hdrlen)
1775 hex_print("\n\t", sp + hdrlen,
1776 h->caplen - hdrlen);
1780 * Print the raw packet data in ASCII.
1784 * Include the link-layer header.
1786 ascii_print(sp, h->caplen);
1789 * Don't include the link-layer header - and if
1790 * we have nothing past the link-layer header,
1793 if (h->caplen > hdrlen)
1794 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1807 * XXX - there should really be libpcap calls to get the version
1808 * number as a string (the string would be generated from #defines
1809 * at run time, so that it's not generated from string constants
1810 * in the library, as, on many UNIX systems, those constants would
1811 * be statically linked into the application executable image, and
1812 * would thus reflect the version of libpcap on the system on
1813 * which the application was *linked*, not the system on which it's
1816 * That routine should be documented, unlike the "version[]"
1817 * string, so that UNIX vendors providing their own libpcaps
1818 * don't omit it (as a couple of vendors have...).
1820 * Packet.dll should perhaps also export a routine to return the
1821 * version number of the Packet.dll code, to supply the
1822 * "Wpcap_version" information on Windows.
1824 char WDversion[]="current-cvs.tcpdump.org";
1825 #if !defined(HAVE_GENERATED_VERSION)
1826 char version[]="current-cvs.tcpdump.org";
1828 char pcap_version[]="current-cvs.tcpdump.org";
1829 char Wpcap_version[]="3.1";
1833 * By default, print the specified data out in hex and ASCII.
1836 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1838 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1842 default_print(const u_char *bp, u_int length)
1844 ndo_default_print(gndo, bp, length);
1848 RETSIGTYPE requestinfo(int signo _U_)
1858 * Called once each second in verbose mode while dumping to file
1860 #ifdef USE_WIN32_MM_TIMER
1861 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1862 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1864 struct pcap_stat stat;
1866 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1867 fprintf(stderr, "Got %u\r", packets_captured);
1869 #elif defined(HAVE_ALARM)
1870 static void verbose_stats_dump(int sig _U_)
1872 struct pcap_stat stat;
1874 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1875 fprintf(stderr, "Got %u\r", packets_captured);
1883 extern char version[];
1884 #ifndef HAVE_PCAP_LIB_VERSION
1885 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1886 extern char pcap_version[];
1887 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1888 static char pcap_version[] = "unknown";
1889 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1890 #endif /* HAVE_PCAP_LIB_VERSION */
1892 #ifdef HAVE_PCAP_LIB_VERSION
1894 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1896 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1898 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1899 #else /* HAVE_PCAP_LIB_VERSION */
1901 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1902 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1904 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1905 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1907 #endif /* HAVE_PCAP_LIB_VERSION */
1908 (void)fprintf(stderr,
1909 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1910 (void)fprintf(stderr,
1911 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1912 (void)fprintf(stderr,
1913 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
1914 (void)fprintf(stderr,
1915 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
1916 (void)fprintf(stderr,
1917 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
1918 (void)fprintf(stderr,
1919 "\t\t[ -Z user ] [ expression ]\n");
1927 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1931 (void)fprintf(stderr, "%s: ", program_name);
1933 (void)vfprintf(stderr, fmt, ap);
1937 if (fmt[-1] != '\n')
1938 (void)fputc('\n', stderr);
1946 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1950 (void)fprintf(stderr, "%s: WARNING: ", program_name);
1952 (void)vfprintf(stderr, fmt, ap);
1956 if (fmt[-1] != '\n')
1957 (void)fputc('\n', stderr);