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.271.2.11 2008-09-25 21:50:04 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 int dflag; /* print filter code */
96 int Lflag; /* list available data link types and exit */
97 char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
100 static int infoprint;
104 int32_t thiszone; /* seconds offset from gmt to local time */
107 static RETSIGTYPE cleanup(int);
108 static RETSIGTYPE child_cleanup(int);
109 static void usage(void) __attribute__((noreturn));
110 static void show_dlts_and_exit(pcap_t *pd) __attribute__((noreturn));
112 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
113 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
114 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
115 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
116 static void droproot(const char *, const char *);
117 static void ndo_error(netdissect_options *ndo, const char *fmt, ...);
118 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
121 RETSIGTYPE requestinfo(int);
124 #if defined(USE_WIN32_MM_TIMER)
125 #include <MMsystem.h>
126 static UINT timer_id;
127 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
128 #elif defined(HAVE_ALARM)
129 static void verbose_stats_dump(int sig);
132 static void info(int);
133 static u_int packets_captured;
135 typedef u_int (*if_printer)(const struct pcap_pkthdr *, const u_char *);
142 static struct printer printers[] = {
143 { arcnet_if_print, DLT_ARCNET },
144 #ifdef DLT_ARCNET_LINUX
145 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
147 { ether_if_print, DLT_EN10MB },
148 { token_if_print, DLT_IEEE802 },
150 { lane_if_print, DLT_LANE8023 },
153 { cip_if_print, DLT_CIP },
156 { cip_if_print, DLT_ATM_CLIP },
158 { sl_if_print, DLT_SLIP },
159 #ifdef DLT_SLIP_BSDOS
160 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
162 { ppp_if_print, DLT_PPP },
163 #ifdef DLT_PPP_WITHDIRECTION
164 { ppp_if_print, DLT_PPP_WITHDIRECTION },
167 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
169 { fddi_if_print, DLT_FDDI },
170 { null_if_print, DLT_NULL },
172 { null_if_print, DLT_LOOP },
174 { raw_if_print, DLT_RAW },
175 { atm_if_print, DLT_ATM_RFC1483 },
177 { chdlc_if_print, DLT_C_HDLC },
180 { chdlc_if_print, DLT_HDLC },
182 #ifdef DLT_PPP_SERIAL
183 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
186 { pppoe_if_print, DLT_PPP_ETHER },
189 { sll_if_print, DLT_LINUX_SLL },
191 #ifdef DLT_IEEE802_11
192 { ieee802_11_if_print, DLT_IEEE802_11},
195 { ltalk_if_print, DLT_LTALK },
197 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
198 { pflog_if_print, DLT_PFLOG },
201 { fr_if_print, DLT_FR },
204 { fr_if_print, DLT_FRELAY },
207 { sunatm_if_print, DLT_SUNATM },
209 #ifdef DLT_IP_OVER_FC
210 { ipfc_if_print, DLT_IP_OVER_FC },
212 #ifdef DLT_PRISM_HEADER
213 { prism_if_print, DLT_PRISM_HEADER },
215 #ifdef DLT_IEEE802_11_RADIO
216 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
219 { enc_if_print, DLT_ENC },
221 #ifdef DLT_SYMANTEC_FIREWALL
222 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
224 #ifdef DLT_APPLE_IP_OVER_IEEE1394
225 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
227 #ifdef DLT_IEEE802_11_RADIO_AVS
228 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
230 #ifdef DLT_JUNIPER_ATM1
231 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
233 #ifdef DLT_JUNIPER_ATM2
234 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
236 #ifdef DLT_JUNIPER_MFR
237 { juniper_mfr_print, DLT_JUNIPER_MFR },
239 #ifdef DLT_JUNIPER_MLFR
240 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
242 #ifdef DLT_JUNIPER_MLPPP
243 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
245 #ifdef DLT_JUNIPER_PPPOE
246 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
248 #ifdef DLT_JUNIPER_PPPOE_ATM
249 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
251 #ifdef DLT_JUNIPER_GGSN
252 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
254 #ifdef DLT_JUNIPER_ES
255 { juniper_es_print, DLT_JUNIPER_ES },
257 #ifdef DLT_JUNIPER_MONITOR
258 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
260 #ifdef DLT_JUNIPER_SERVICES
261 { juniper_services_print, DLT_JUNIPER_SERVICES },
263 #ifdef DLT_JUNIPER_ETHER
264 { juniper_ether_print, DLT_JUNIPER_ETHER },
266 #ifdef DLT_JUNIPER_PPP
267 { juniper_ppp_print, DLT_JUNIPER_PPP },
269 #ifdef DLT_JUNIPER_FRELAY
270 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
272 #ifdef DLT_JUNIPER_CHDLC
273 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
276 { mfr_if_print, DLT_MFR },
278 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
279 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
285 lookup_printer(int type)
289 for (p = printers; p->f; ++p)
309 char *CurrentFileName;
315 show_dlts_and_exit(pcap_t *pd)
319 const char *dlt_name;
321 n_dlts = pcap_list_datalinks(pd, &dlts);
323 error("%s", pcap_geterr(pd));
324 else if (n_dlts == 0 || !dlts)
325 error("No data link types.");
327 (void) fprintf(stderr, "Data link types (use option -y to set):\n");
329 while (--n_dlts >= 0) {
330 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
331 if (dlt_name != NULL) {
332 (void) fprintf(stderr, " %s (%s)", dlt_name,
333 pcap_datalink_val_to_description(dlts[n_dlts]));
336 * OK, does tcpdump handle that type?
338 if (lookup_printer(dlts[n_dlts]) == NULL)
339 (void) fprintf(stderr, " (printing not supported)");
342 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
351 * Set up flags that might or might not be supported depending on the
352 * version of libpcap we're using.
354 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
356 #define B_FLAG_USAGE " [ -B size ]"
357 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
360 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
362 #ifdef HAVE_PCAP_CREATE
364 #else /* HAVE_PCAP_CREATE */
366 #endif /* HAVE_PCAP_CREATE */
368 #ifdef HAVE_PCAP_FINDALLDEVS
369 #ifndef HAVE_PCAP_IF_T
370 #undef HAVE_PCAP_FINDALLDEVS
374 #ifdef HAVE_PCAP_FINDALLDEVS
380 #ifdef HAVE_PCAP_DUMP_FLUSH
387 /* Drop root privileges and chroot if necessary */
389 droproot(const char *username, const char *chroot_dir)
391 struct passwd *pw = NULL;
393 if (chroot_dir && !username) {
394 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
398 pw = getpwnam(username);
401 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
402 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
403 chroot_dir, pcap_strerror(errno));
407 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
408 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
409 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
411 (unsigned long)pw->pw_uid,
412 (unsigned long)pw->pw_gid,
413 pcap_strerror(errno));
418 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
441 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
443 char *filename = malloc(NAME_MAX + 1);
445 /* Process with strftime if Gflag is set. */
449 /* Convert Gflag_time to a usable format */
450 if ((local_tm = localtime(&Gflag_time)) == NULL) {
451 error("MakeTimedFilename: localtime");
454 /* There's no good way to detect an error in strftime since a return
455 * value of 0 isn't necessarily failure.
457 strftime(filename, NAME_MAX, orig_name, local_tm);
459 strncpy(filename, orig_name, NAME_MAX);
462 if (cnt == 0 && max_chars == 0)
463 strncpy(buffer, filename, NAME_MAX + 1);
465 if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
466 /* Report an error if the filename is too large */
467 error("too many output files or filename is too long (> %d)", NAME_MAX);
471 static int tcpdump_printf(netdissect_options *ndo _U_,
472 const char *fmt, ...)
479 ret=vfprintf(stdout, fmt, args);
486 main(int argc, char **argv)
488 register int cnt, op, i;
489 bpf_u_int32 localnet, netmask;
490 register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
491 pcap_handler callback;
493 struct bpf_program fcode;
495 RETSIGTYPE (*oldhandler)(int);
497 struct print_info printinfo;
498 struct dump_info dumpinfo;
499 u_char *pcap_userdata;
500 char ebuf[PCAP_ERRBUF_SIZE];
501 char *username = NULL;
502 char *chroot_dir = NULL;
503 #ifdef HAVE_PCAP_FINDALLDEVS
504 pcap_if_t *devpointer;
509 if(wsockinit() != 0) return 1;
515 gndo->ndo_default_print=ndo_default_print;
516 gndo->ndo_printf=tcpdump_printf;
517 gndo->ndo_error=ndo_error;
518 gndo->ndo_warning=ndo_warning;
519 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
526 if ((cp = strrchr(argv[0], '/')) != NULL)
527 program_name = cp + 1;
529 program_name = argv[0];
531 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
540 (op = getopt(argc, argv, "aA" B_FLAG "c:C:d" D_FLAG "eE:fF:G:i:" I_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:Yz:Z:")) != -1)
544 /* compatibility for old -a */
551 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
553 Bflag = atoi(optarg)*1024;
555 error("invalid packet buffer size %s", optarg);
557 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
562 error("invalid packet count %s", optarg);
566 Cflag = atoi(optarg) * 1000000;
568 error("invalid file size %s", optarg);
575 #ifdef HAVE_PCAP_FINDALLDEVS
577 if (pcap_findalldevs(&devpointer, ebuf) < 0)
580 for (i = 0; devpointer != 0; i++) {
581 printf("%d.%s", i+1, devpointer->name);
582 if (devpointer->description != NULL)
583 printf(" (%s)", devpointer->description);
585 devpointer = devpointer->next;
589 #endif /* HAVE_PCAP_FINDALLDEVS */
600 #ifndef HAVE_LIBCRYPTO
601 warning("crypto code not compiled in");
603 gndo->ndo_espsecret = optarg;
615 Gflag = atoi(optarg);
617 error("invalid number of seconds %s", optarg);
619 /* We will create one file initially. */
622 /* Grab the current time for rotation use. */
623 if ((Gflag_time = time(NULL)) == (time_t)-1) {
624 error("main: can't get current time: %s",
625 pcap_strerror(errno));
630 if (optarg[0] == '0' && optarg[1] == 0)
631 error("Invalid adapter index");
633 #ifdef HAVE_PCAP_FINDALLDEVS
635 * If the argument is a number, treat it as
636 * an index into the list of adapters, as
637 * printed by "tcpdump -D".
639 * This should be OK on UNIX systems, as interfaces
640 * shouldn't have names that begin with digits.
641 * It can be useful on Windows, where more than
642 * one interface can have the same name.
644 if ((devnum = atoi(optarg)) != 0) {
646 error("Invalid adapter index");
648 if (pcap_findalldevs(&devpointer, ebuf) < 0)
651 for (i = 0; i < devnum-1; i++){
652 devpointer = devpointer->next;
653 if (devpointer == NULL)
654 error("Invalid adapter index");
657 device = devpointer->name;
660 #endif /* HAVE_PCAP_FINDALLDEVS */
664 #ifdef HAVE_PCAP_CREATE
668 #endif /* HAVE_PCAP_CREATE */
673 * _IOLBF is the same as _IOFBF in Microsoft's C
674 * libraries; the only alternative they offer
677 * XXX - this should really be checking for MSVC++,
678 * not WIN32, if, for example, MinGW has its own
679 * C library that is more UNIX-compatible.
681 setvbuf(stdout, NULL, _IONBF, 0);
683 #ifdef HAVE_SETLINEBUF
686 setvbuf(stdout, NULL, _IOLBF, 0);
697 if (smiLoadModule(optarg) == 0) {
698 error("could not load MIB module %s", optarg);
702 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
703 program_name, optarg);
704 (void)fprintf(stderr, "(no libsmi support)\n");
709 /* TCP-MD5 shared secret */
710 #ifndef HAVE_LIBCRYPTO
711 warning("crypto code not compiled in");
713 tcpmd5secret = optarg;
734 ++suppress_default_print;
748 snaplen = strtol(optarg, &end, 0);
749 if (optarg == end || *end != '\0'
750 || snaplen < 0 || snaplen > 65535)
751 error("invalid snaplen %s", optarg);
752 else if (snaplen == 0)
766 if (strcasecmp(optarg, "vat") == 0)
768 else if (strcasecmp(optarg, "wb") == 0)
770 else if (strcasecmp(optarg, "rpc") == 0)
772 else if (strcasecmp(optarg, "rtp") == 0)
774 else if (strcasecmp(optarg, "rtcp") == 0)
775 packettype = PT_RTCP;
776 else if (strcasecmp(optarg, "snmp") == 0)
777 packettype = PT_SNMP;
778 else if (strcasecmp(optarg, "cnfp") == 0)
779 packettype = PT_CNFP;
780 else if (strcasecmp(optarg, "tftp") == 0)
781 packettype = PT_TFTP;
782 else if (strcasecmp(optarg, "aodv") == 0)
783 packettype = PT_AODV;
785 error("unknown packet type `%s'", optarg);
792 #ifdef HAVE_PCAP_DUMP_FLUSH
807 Wflag = atoi(optarg);
809 error("invalid number of output files %s", optarg);
810 WflagChars = getWflagChars(Wflag);
815 ++suppress_default_print;
820 ++suppress_default_print;
824 gndo->ndo_dltname = optarg;
826 pcap_datalink_name_to_val(gndo->ndo_dltname);
827 if (gndo->ndo_dlt < 0)
828 error("invalid data link type %s", gndo->ndo_dltname);
831 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
834 /* Undocumented flag */
835 #ifdef HAVE_PCAP_DEBUG
836 extern int pcap_debug;
847 zflag = strdup(optarg);
856 username = strdup(optarg);
871 case 0: /* Default */
872 case 4: /* Default + Date*/
873 thiszone = gmt2local(0);
876 case 1: /* No time stamp */
877 case 2: /* Unix timeval style */
878 case 3: /* Microseconds since previous packet */
879 case 5: /* Microseconds since first packet */
882 default: /* Not supported */
883 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
888 /* if run as root, prepare for chrooting */
889 if (getuid() == 0 || geteuid() == 0) {
890 /* future extensibility for cmd-line arguments */
892 chroot_dir = WITH_CHROOT;
897 /* if run as root, prepare for dropping root privileges */
898 if (getuid() == 0 || geteuid() == 0) {
899 /* Run with '-Z root' to restore old behaviour */
901 username = WITH_USER;
905 if (RFileName != NULL) {
907 const char *dlt_name;
911 * We don't need network access, so relinquish any set-UID
912 * or set-GID privileges we have (if any).
914 * We do *not* want set-UID privileges when opening a
915 * trace file, as that might let the user read other
916 * people's trace files (especially if we're set-UID
919 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
920 fprintf(stderr, "Warning: setgid/setuid failed !\n");
922 pd = pcap_open_offline(RFileName, ebuf);
925 dlt = pcap_datalink(pd);
926 dlt_name = pcap_datalink_val_to_name(dlt);
927 if (dlt_name == NULL) {
928 fprintf(stderr, "reading from file %s, link-type %u\n",
932 "reading from file %s, link-type %s (%s)\n",
934 pcap_datalink_val_to_description(dlt));
939 error("-f and -r options are incompatible");
941 if (device == NULL) {
942 device = pcap_lookupdev(ebuf);
947 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
948 { //a Unicode string has a \0 as second byte (so strlen() is 1)
949 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
953 fprintf(stderr, "%s: listening on %s\n", program_name, device);
958 #ifdef HAVE_PCAP_CREATE
959 pd = pcap_create(device, ebuf);
962 status = pcap_set_snaplen(pd, snaplen);
964 error("%s: pcap_set_snaplen failed: %s",
965 device, pcap_statustostr(status));
966 status = pcap_set_promisc(pd, !pflag);
968 error("%s: pcap_set_promisc failed: %s",
969 device, pcap_statustostr(status));
971 status = pcap_set_rfmon(pd, 1);
973 error("%s: pcap_set_rfmon failed: %s",
974 device, pcap_statustostr(status));
976 status = pcap_set_timeout(pd, 1000);
978 error("%s: pcap_set_timeout failed: %s",
979 device, pcap_statustostr(status));
981 status = pcap_set_buffer_size(pd, Bflag);
983 error("%s: pcap_set_buffer_size failed: %s",
984 device, pcap_statustostr(status));
986 status = pcap_activate(pd);
989 * pcap_activate() failed.
991 cp = pcap_geterr(pd);
992 if (status == PCAP_ERROR)
994 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
995 status == PCAP_ERROR_PERM_DENIED) &&
997 error("%s: %s\n(%s)", device,
998 pcap_statustostr(status), cp);
1000 error("%s: %s", device,
1001 pcap_statustostr(status));
1002 } else if (status > 0) {
1004 * pcap_activate() succeeded, but it's warning us
1005 * of a problem it had.
1007 cp = pcap_geterr(pd);
1008 if (status == PCAP_WARNING)
1010 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1012 warning("%s: %s\n(%s)", device,
1013 pcap_statustostr(status), cp);
1015 warning("%s: %s", device,
1016 pcap_statustostr(status));
1020 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1024 warning("%s", ebuf);
1025 #endif /* HAVE_PCAP_CREATE */
1027 * Let user own process after socket has been opened.
1030 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1031 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1033 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1035 if(pcap_setbuff(pd, Bflag)==-1){
1036 error("%s", pcap_geterr(pd));
1038 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1040 show_dlts_and_exit(pd);
1041 if (gndo->ndo_dlt >= 0) {
1042 #ifdef HAVE_PCAP_SET_DATALINK
1043 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1044 error("%s", pcap_geterr(pd));
1047 * We don't actually support changing the
1048 * data link type, so we only let them
1049 * set it to what it already is.
1051 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1052 error("%s is not one of the DLTs supported by this device\n",
1056 (void)fprintf(stderr, "%s: data link type %s\n",
1057 program_name, gndo->ndo_dltname);
1058 (void)fflush(stderr);
1060 i = pcap_snapshot(pd);
1062 warning("snaplen raised from %d to %d", snaplen, i);
1065 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1068 warning("%s", ebuf);
1072 cmdbuf = read_infile(infile);
1074 cmdbuf = copy_argv(&argv[optind]);
1076 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1077 error("%s", pcap_geterr(pd));
1079 bpf_dump(&fcode, dflag);
1083 init_addrtoname(localnet, netmask);
1087 (void)setsignal(SIGPIPE, cleanup);
1088 (void)setsignal(SIGTERM, cleanup);
1089 (void)setsignal(SIGINT, cleanup);
1090 (void)setsignal(SIGCHLD, child_cleanup);
1092 /* Cooperate with nohup(1) */
1094 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1095 (void)setsignal(SIGHUP, oldhandler);
1098 if (pcap_setfilter(pd, &fcode) < 0)
1099 error("%s", pcap_geterr(pd));
1102 /* Do not exceed the default NAME_MAX for files. */
1103 dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1105 if (dumpinfo.CurrentFileName == NULL)
1106 error("malloc of dumpinfo.CurrentFileName");
1108 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1110 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1112 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1114 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1116 error("%s", pcap_geterr(pd));
1117 if (Cflag != 0 || Gflag != 0) {
1118 callback = dump_packet_and_trunc;
1119 dumpinfo.WFileName = WFileName;
1122 pcap_userdata = (u_char *)&dumpinfo;
1124 callback = dump_packet;
1125 pcap_userdata = (u_char *)p;
1128 type = pcap_datalink(pd);
1129 printinfo.printer = lookup_printer(type);
1130 if (printinfo.printer == NULL) {
1131 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1132 if (gndo->ndo_dltname != NULL)
1133 error("unsupported data link type %s",
1136 error("unsupported data link type %d", type);
1138 callback = print_packet;
1139 pcap_userdata = (u_char *)&printinfo;
1143 * We cannot do this earlier, because we want to be able to open
1144 * the file (if done) for writing before giving up permissions.
1146 if (getuid() == 0 || geteuid() == 0) {
1147 if (username || chroot_dir)
1148 droproot(username, chroot_dir);
1153 * We can't get statistics when reading from a file rather
1154 * than capturing from a device.
1156 if (RFileName == NULL)
1157 (void)setsignal(SIGINFO, requestinfo);
1160 if (vflag > 0 && WFileName) {
1162 * When capturing to a file, "-v" means tcpdump should,
1163 * every 10 secodns, "v"erbosely report the number of
1166 #ifdef USE_WIN32_MM_TIMER
1167 /* call verbose_stats_dump() each 1000 +/-100msec */
1168 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1169 setvbuf(stderr, NULL, _IONBF, 0);
1170 #elif defined(HAVE_ALARM)
1171 (void)setsignal(SIGALRM, verbose_stats_dump);
1177 if (RFileName == NULL) {
1179 const char *dlt_name;
1181 if (!vflag && !WFileName) {
1182 (void)fprintf(stderr,
1183 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1186 (void)fprintf(stderr, "%s: ", program_name);
1187 dlt = pcap_datalink(pd);
1188 dlt_name = pcap_datalink_val_to_name(dlt);
1189 if (dlt_name == NULL) {
1190 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1191 device, dlt, snaplen);
1193 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1195 pcap_datalink_val_to_description(dlt), snaplen);
1197 (void)fflush(stderr);
1200 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1201 if (WFileName == NULL) {
1203 * We're printing packets. Flush the printed output,
1204 * so it doesn't get intermingled with error output.
1208 * We got interrupted, so perhaps we didn't
1209 * manage to finish a line we were printing.
1210 * Print an extra newline, just in case.
1214 (void)fflush(stdout);
1220 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1221 program_name, pcap_geterr(pd));
1223 if (RFileName == NULL) {
1225 * We're doing a live capture. Report the capture
1231 exit(status == -1 ? 1 : 0);
1234 /* make a clean exit on interrupts */
1236 cleanup(int signo _U_)
1238 #ifdef USE_WIN32_MM_TIMER
1240 timeKillEvent(timer_id);
1242 #elif defined(HAVE_ALARM)
1246 #ifdef HAVE_PCAP_BREAKLOOP
1248 * We have "pcap_breakloop()"; use it, so that we do as little
1249 * as possible in the signal handler (it's probably not safe
1250 * to do anything with standard I/O streams in a signal handler -
1251 * the ANSI C standard doesn't say it is).
1256 * We don't have "pcap_breakloop()"; this isn't safe, but
1257 * it's the best we can do. Print the summary if we're
1258 * not reading from a savefile - i.e., if we're doing a
1259 * live capture - and exit.
1261 if (pd != NULL && pcap_file(pd) == NULL) {
1263 * We got interrupted, so perhaps we didn't
1264 * manage to finish a line we were printing.
1265 * Print an extra newline, just in case.
1268 (void)fflush(stdout);
1276 On windows, we do not use a fork, so we do not care less about
1277 waiting a child processes to die
1281 child_cleanup(int signo _U_)
1288 info(register int verbose)
1290 struct pcap_stat stat;
1292 if (pcap_stats(pd, &stat) < 0) {
1293 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1299 fprintf(stderr, "%s: ", program_name);
1301 (void)fprintf(stderr, "%u packets captured", packets_captured);
1303 fputs(", ", stderr);
1306 (void)fprintf(stderr, "%d packets received by filter", stat.ps_recv);
1308 fputs(", ", stderr);
1311 (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop);
1317 compress_savefile(const char *filename)
1322 * Set to lowest priority so that this doesn't disturb the capture
1325 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1327 setpriority(PRIO_PROCESS, 0, 19);
1329 if (execlp(zflag, zflag, filename, NULL) == -1)
1331 "compress_savefile:execlp(%s, %s): %s\n",
1338 compress_savefile(const char *filename)
1341 "compress_savefile failed. Functionality not implemented under windows\n");
1346 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1348 struct dump_info *dump_info;
1354 dump_info = (struct dump_info *)user;
1357 * XXX - this won't force the file to rotate on the specified time
1358 * boundary, but it will rotate on the first packet received after the
1359 * specified Gflag number of seconds. Note: if a Gflag time boundary
1360 * and a Cflag size boundary coincide, the time rotation will occur
1361 * first thereby cancelling the Cflag boundary (since the file should
1365 /* Check if it is time to rotate */
1368 /* Get the current time */
1369 if ((t = time(NULL)) == (time_t)-1) {
1370 error("dump_and_trunc_packet: can't get current_time: %s",
1371 pcap_strerror(errno));
1375 /* If the time is greater than the specified window, rotate */
1376 if (t - Gflag_time >= Gflag) {
1377 /* Update the Gflag_time */
1379 /* Update Gflag_count */
1382 * Close the current file and open a new one.
1384 pcap_dump_close(dump_info->p);
1387 * Compress the file we just closed, if the user asked for it
1390 compress_savefile(dump_info->CurrentFileName);
1393 * Check to see if we've exceeded the Wflag (when
1396 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1397 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1402 if (dump_info->CurrentFileName != NULL)
1403 free(dump_info->CurrentFileName);
1404 /* Allocate space for max filename + \0. */
1405 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1406 if (dump_info->CurrentFileName == NULL)
1407 error("dump_packet_and_trunc: malloc");
1409 * This is always the first file in the Cflag
1411 * We also don't need numbering if Cflag is not set.
1414 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1417 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1419 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1420 if (dump_info->p == NULL)
1421 error("%s", pcap_geterr(pd));
1426 * XXX - this won't prevent capture files from getting
1427 * larger than Cflag - the last packet written to the
1428 * file could put it over Cflag.
1430 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1432 * Close the current file and open a new one.
1434 pcap_dump_close(dump_info->p);
1437 * Compress the file we just closed, if the user asked for it
1440 compress_savefile(dump_info->CurrentFileName);
1444 if (Cflag_count >= Wflag)
1447 if (dump_info->CurrentFileName != NULL)
1448 free(dump_info->CurrentFileName);
1449 dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1450 if (dump_info->CurrentFileName == NULL)
1451 error("dump_packet_and_trunc: malloc");
1452 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1453 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1454 if (dump_info->p == NULL)
1455 error("%s", pcap_geterr(pd));
1458 pcap_dump((u_char *)dump_info->p, h, sp);
1459 #ifdef HAVE_PCAP_DUMP_FLUSH
1461 pcap_dump_flush(dump_info->p);
1470 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1476 pcap_dump(user, h, sp);
1477 #ifdef HAVE_PCAP_DUMP_FLUSH
1479 pcap_dump_flush((pcap_dumper_t *)user);
1488 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1490 struct print_info *print_info;
1498 print_info = (struct print_info *)user;
1501 * Some printers want to check that they're not walking off the
1502 * end of the packet.
1503 * Rather than pass it all the way down, we set this global.
1505 snapend = sp + h->caplen;
1507 hdrlen = (*print_info->printer)(h, sp);
1510 * Print the raw packet data in hex and ASCII.
1514 * Include the link-layer header.
1516 hex_and_ascii_print("\n\t", sp, h->caplen);
1519 * Don't include the link-layer header - and if
1520 * we have nothing past the link-layer header,
1523 if (h->caplen > hdrlen)
1524 hex_and_ascii_print("\n\t", sp + hdrlen,
1525 h->caplen - hdrlen);
1529 * Print the raw packet data in hex.
1533 * Include the link-layer header.
1535 hex_print("\n\t", sp, h->caplen);
1538 * Don't include the link-layer header - and if
1539 * we have nothing past the link-layer header,
1542 if (h->caplen > hdrlen)
1543 hex_print("\n\t", sp + hdrlen,
1544 h->caplen - hdrlen);
1548 * Print the raw packet data in ASCII.
1552 * Include the link-layer header.
1554 ascii_print(sp, h->caplen);
1557 * Don't include the link-layer header - and if
1558 * we have nothing past the link-layer header,
1561 if (h->caplen > hdrlen)
1562 ascii_print(sp + hdrlen, h->caplen - hdrlen);
1575 * XXX - there should really be libpcap calls to get the version
1576 * number as a string (the string would be generated from #defines
1577 * at run time, so that it's not generated from string constants
1578 * in the library, as, on many UNIX systems, those constants would
1579 * be statically linked into the application executable image, and
1580 * would thus reflect the version of libpcap on the system on
1581 * which the application was *linked*, not the system on which it's
1584 * That routine should be documented, unlike the "version[]"
1585 * string, so that UNIX vendors providing their own libpcaps
1586 * don't omit it (as a couple of vendors have...).
1588 * Packet.dll should perhaps also export a routine to return the
1589 * version number of the Packet.dll code, to supply the
1590 * "Wpcap_version" information on Windows.
1592 char WDversion[]="current-cvs.tcpdump.org";
1593 #if !defined(HAVE_GENERATED_VERSION)
1594 char version[]="current-cvs.tcpdump.org";
1596 char pcap_version[]="current-cvs.tcpdump.org";
1597 char Wpcap_version[]="3.1";
1601 * By default, print the specified data out in hex and ASCII.
1604 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1606 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1610 default_print(const u_char *bp, u_int length)
1612 ndo_default_print(gndo, bp, length);
1616 RETSIGTYPE requestinfo(int signo _U_)
1626 * Called once each second in verbose mode while dumping to file
1628 #ifdef USE_WIN32_MM_TIMER
1629 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1630 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1632 struct pcap_stat stat;
1634 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1635 fprintf(stderr, "Got %u\r", packets_captured);
1637 #elif defined(HAVE_ALARM)
1638 static void verbose_stats_dump(int sig _U_)
1640 struct pcap_stat stat;
1642 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1643 fprintf(stderr, "Got %u\r", packets_captured);
1651 extern char version[];
1652 #ifndef HAVE_PCAP_LIB_VERSION
1653 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1654 extern char pcap_version[];
1655 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1656 static char pcap_version[] = "unknown";
1657 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1658 #endif /* HAVE_PCAP_LIB_VERSION */
1660 #ifdef HAVE_PCAP_LIB_VERSION
1662 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1664 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1666 (void)fprintf(stderr, "%s\n",pcap_lib_version());
1667 #else /* HAVE_PCAP_LIB_VERSION */
1669 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1670 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1672 (void)fprintf(stderr, "%s version %s\n", program_name, version);
1673 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1675 #endif /* HAVE_PCAP_LIB_VERSION */
1676 (void)fprintf(stderr,
1677 "Usage: %s [-aAd" D_FLAG "ef" I_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1678 (void)fprintf(stderr,
1679 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1680 (void)fprintf(stderr,
1681 "\t\t[ -i interface ] [ -M secret ] [ -r file ]\n");
1682 (void)fprintf(stderr,
1683 "\t\t[ -s snaplen ] [ -T type ] [ -w file ] [ -W filecount ]\n");
1684 (void)fprintf(stderr,
1685 "\t\t[ -y datalinktype ] [ -z command ] [ -Z user ]\n");
1686 (void)fprintf(stderr,
1687 "\t\t[ expression ]\n");
1695 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1699 (void)fprintf(stderr, "%s: ", program_name);
1701 (void)vfprintf(stderr, fmt, ap);
1705 if (fmt[-1] != '\n')
1706 (void)fputc('\n', stderr);
1714 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1718 (void)fprintf(stderr, "%s: WARNING: ", program_name);
1720 (void)vfprintf(stderr, fmt, ap);
1724 if (fmt[-1] != '\n')
1725 (void)fputc('\n', stderr);