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);
72 #include <sys/capability.h>
73 #include <sys/ioccom.h>
74 #include <sys/types.h>
75 #include <sys/sysctl.h>
79 #ifdef HAVE_LIBCAPSICUM
80 #include <libcapsicum.h>
81 #include <libcapsicum_dns.h>
82 #include <libcapsicum_service.h>
84 #endif /* HAVE_LIBCAPSICUM */
85 #endif /* __FreeBSD__ */
88 #include <sys/resource.h>
94 /* capabilities convinience library */
97 #endif /* HAVE_CAP_NG_H */
99 #include "netdissect.h"
100 #include "interface.h"
101 #include "addrtoname.h"
103 #include "setsignal.h"
104 #include "gmt2local.h"
105 #include "pcap-missing.h"
108 #define PATH_MAX 1024
112 #define SIGNAL_REQ_INFO SIGINFO
114 #define SIGNAL_REQ_INFO SIGUSR1
117 netdissect_options Gndo;
118 netdissect_options *gndo = &Gndo;
120 static int dflag; /* print filter code */
121 static int Lflag; /* list available data link types and exit */
122 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
123 static int Jflag; /* list available time stamp types */
125 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
127 static int infodelay;
128 static int infoprint;
132 #ifdef HAVE_LIBCAPSICUM
133 cap_channel_t *capdns;
136 int32_t thiszone; /* seconds offset from gmt to local time */
139 static RETSIGTYPE cleanup(int);
140 static RETSIGTYPE child_cleanup(int);
141 static void usage(void) __attribute__((noreturn));
142 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
144 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
145 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
146 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
147 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
148 static void droproot(const char *, const char *);
149 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
150 __attribute__ ((noreturn, format (printf, 2, 3)));
151 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
153 #ifdef SIGNAL_REQ_INFO
154 RETSIGTYPE requestinfo(int);
157 #if defined(USE_WIN32_MM_TIMER)
158 #include <MMsystem.h>
159 static UINT timer_id;
160 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
161 #elif defined(HAVE_ALARM)
162 static void verbose_stats_dump(int sig);
165 static void info(int);
166 static u_int packets_captured;
180 static struct printer printers[] = {
181 { arcnet_if_print, DLT_ARCNET },
182 #ifdef DLT_ARCNET_LINUX
183 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
185 { token_if_print, DLT_IEEE802 },
187 { lane_if_print, DLT_LANE8023 },
190 { cip_if_print, DLT_CIP },
193 { cip_if_print, DLT_ATM_CLIP },
195 { sl_if_print, DLT_SLIP },
196 #ifdef DLT_SLIP_BSDOS
197 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
199 { ppp_if_print, DLT_PPP },
200 #ifdef DLT_PPP_WITHDIRECTION
201 { ppp_if_print, DLT_PPP_WITHDIRECTION },
204 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
206 { fddi_if_print, DLT_FDDI },
207 { null_if_print, DLT_NULL },
209 { null_if_print, DLT_LOOP },
211 { raw_if_print, DLT_RAW },
212 { atm_if_print, DLT_ATM_RFC1483 },
214 { chdlc_if_print, DLT_C_HDLC },
217 { chdlc_if_print, DLT_HDLC },
219 #ifdef DLT_PPP_SERIAL
220 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
223 { pppoe_if_print, DLT_PPP_ETHER },
226 { sll_if_print, DLT_LINUX_SLL },
228 #ifdef DLT_IEEE802_11
229 { ieee802_11_if_print, DLT_IEEE802_11},
232 { ltalk_if_print, DLT_LTALK },
234 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
235 { pflog_if_print, DLT_PFLOG },
238 { fr_if_print, DLT_FR },
241 { fr_if_print, DLT_FRELAY },
244 { sunatm_if_print, DLT_SUNATM },
246 #ifdef DLT_IP_OVER_FC
247 { ipfc_if_print, DLT_IP_OVER_FC },
249 #ifdef DLT_PRISM_HEADER
250 { prism_if_print, DLT_PRISM_HEADER },
252 #ifdef DLT_IEEE802_11_RADIO
253 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
256 { enc_if_print, DLT_ENC },
258 #ifdef DLT_SYMANTEC_FIREWALL
259 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
261 #ifdef DLT_APPLE_IP_OVER_IEEE1394
262 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
264 #ifdef DLT_IEEE802_11_RADIO_AVS
265 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
267 #ifdef DLT_JUNIPER_ATM1
268 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
270 #ifdef DLT_JUNIPER_ATM2
271 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
273 #ifdef DLT_JUNIPER_MFR
274 { juniper_mfr_print, DLT_JUNIPER_MFR },
276 #ifdef DLT_JUNIPER_MLFR
277 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
279 #ifdef DLT_JUNIPER_MLPPP
280 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
282 #ifdef DLT_JUNIPER_PPPOE
283 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
285 #ifdef DLT_JUNIPER_PPPOE_ATM
286 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
288 #ifdef DLT_JUNIPER_GGSN
289 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
291 #ifdef DLT_JUNIPER_ES
292 { juniper_es_print, DLT_JUNIPER_ES },
294 #ifdef DLT_JUNIPER_MONITOR
295 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
297 #ifdef DLT_JUNIPER_SERVICES
298 { juniper_services_print, DLT_JUNIPER_SERVICES },
300 #ifdef DLT_JUNIPER_ETHER
301 { juniper_ether_print, DLT_JUNIPER_ETHER },
303 #ifdef DLT_JUNIPER_PPP
304 { juniper_ppp_print, DLT_JUNIPER_PPP },
306 #ifdef DLT_JUNIPER_FRELAY
307 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
309 #ifdef DLT_JUNIPER_CHDLC
310 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
313 { mfr_if_print, DLT_MFR },
315 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
316 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
318 #ifdef HAVE_PCAP_USB_H
320 { usb_linux_48_byte_print, DLT_USB_LINUX},
321 #endif /* DLT_USB_LINUX */
322 #ifdef DLT_USB_LINUX_MMAPPED
323 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
324 #endif /* DLT_USB_LINUX_MMAPPED */
325 #endif /* HAVE_PCAP_USB_H */
327 { raw_if_print, DLT_IPV4 },
330 { raw_if_print, DLT_IPV6 },
335 static struct ndo_printer ndo_printers[] = {
336 { ether_if_print, DLT_EN10MB },
338 { ipnet_if_print, DLT_IPNET },
340 #ifdef DLT_IEEE802_15_4
341 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
343 #ifdef DLT_IEEE802_15_4_NOFCS
344 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
347 { ppi_if_print, DLT_PPI },
349 #ifdef DLT_NETANALYZER
350 { netanalyzer_if_print, DLT_NETANALYZER },
352 #ifdef DLT_NETANALYZER_TRANSPARENT
353 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
359 lookup_printer(int type)
363 for (p = printers; p->f; ++p)
372 lookup_ndo_printer(int type)
374 struct ndo_printer *p;
376 for (p = ndo_printers; p->f; ++p)
386 static int supports_monitor_mode;
393 netdissect_options *ndo;
396 if_ndo_printer ndo_printer;
403 char *CurrentFileName;
411 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
413 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
416 int *tstamp_types = 0;
417 const char *tstamp_type_name;
420 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
421 if (n_tstamp_types < 0)
422 error("%s", pcap_geterr(pd));
424 if (n_tstamp_types == 0) {
425 fprintf(stderr, "Time stamp type cannot be set for %s\n",
429 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
431 for (i = 0; i < n_tstamp_types; i++) {
432 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
433 if (tstamp_type_name != NULL) {
434 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
435 pcap_tstamp_type_val_to_description(tstamp_types[i]));
437 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
440 pcap_free_tstamp_types(tstamp_types);
446 show_dlts_and_exit(const char *device, pcap_t *pd)
450 const char *dlt_name;
452 n_dlts = pcap_list_datalinks(pd, &dlts);
454 error("%s", pcap_geterr(pd));
455 else if (n_dlts == 0 || !dlts)
456 error("No data link types.");
459 * If the interface is known to support monitor mode, indicate
460 * whether these are the data link types available when not in
461 * monitor mode, if -I wasn't specified, or when in monitor mode,
462 * when -I was specified (the link-layer types available in
463 * monitor mode might be different from the ones available when
464 * not in monitor mode).
466 if (supports_monitor_mode)
467 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
469 Iflag ? "when in monitor mode" : "when not in monitor mode");
471 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
474 while (--n_dlts >= 0) {
475 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
476 if (dlt_name != NULL) {
477 (void) fprintf(stderr, " %s (%s)", dlt_name,
478 pcap_datalink_val_to_description(dlts[n_dlts]));
481 * OK, does tcpdump handle that type?
483 if (lookup_printer(dlts[n_dlts]) == NULL
484 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
485 (void) fprintf(stderr, " (printing not supported)");
486 fprintf(stderr, "\n");
488 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
492 #ifdef HAVE_PCAP_FREE_DATALINKS
493 pcap_free_datalinks(dlts);
499 * Set up flags that might or might not be supported depending on the
500 * version of libpcap we're using.
502 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
504 #define B_FLAG_USAGE " [ -B size ]"
505 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
508 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
510 #ifdef HAVE_PCAP_CREATE
512 #else /* HAVE_PCAP_CREATE */
514 #endif /* HAVE_PCAP_CREATE */
516 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
518 #define j_FLAG_USAGE " [ -j tstamptype ]"
520 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
524 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
526 #ifdef HAVE_PCAP_FINDALLDEVS
527 #ifndef HAVE_PCAP_IF_T
528 #undef HAVE_PCAP_FINDALLDEVS
532 #ifdef HAVE_PCAP_FINDALLDEVS
538 #ifdef HAVE_PCAP_DUMP_FLUSH
545 /* Drop root privileges and chroot if necessary */
547 droproot(const char *username, const char *chroot_dir)
549 struct passwd *pw = NULL;
551 if (chroot_dir && !username) {
552 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
556 pw = getpwnam(username);
559 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
560 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
561 chroot_dir, pcap_strerror(errno));
566 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
568 printf("error : ret %d\n", ret);
570 /* We don't need CAP_SETUID and CAP_SETGID */
571 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
572 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
573 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
574 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
575 capng_apply(CAPNG_SELECT_BOTH);
578 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
579 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
580 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
582 (unsigned long)pw->pw_uid,
583 (unsigned long)pw->pw_gid,
584 pcap_strerror(errno));
587 #endif /* HAVE_CAP_NG_H */
590 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
613 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
615 char *filename = malloc(PATH_MAX + 1);
616 if (filename == NULL)
617 error("Makefilename: malloc");
619 /* Process with strftime if Gflag is set. */
623 /* Convert Gflag_time to a usable format */
624 if ((local_tm = localtime(&Gflag_time)) == NULL) {
625 error("MakeTimedFilename: localtime");
628 /* There's no good way to detect an error in strftime since a return
629 * value of 0 isn't necessarily failure.
631 strftime(filename, PATH_MAX, orig_name, local_tm);
633 strncpy(filename, orig_name, PATH_MAX);
636 if (cnt == 0 && max_chars == 0)
637 strncpy(buffer, filename, PATH_MAX + 1);
639 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
640 /* Report an error if the filename is too large */
641 error("too many output files or filename is too long (> %d)", PATH_MAX);
645 static int tcpdump_printf(netdissect_options *ndo _U_,
646 const char *fmt, ...)
653 ret=vfprintf(stdout, fmt, args);
659 static struct print_info
660 get_print_info(int type)
662 struct print_info printinfo;
664 printinfo.ndo_type = 1;
665 printinfo.ndo = gndo;
666 printinfo.p.ndo_printer = lookup_ndo_printer(type);
667 if (printinfo.p.ndo_printer == NULL) {
668 printinfo.p.printer = lookup_printer(type);
669 printinfo.ndo_type = 0;
670 if (printinfo.p.printer == NULL) {
671 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
672 if (gndo->ndo_dltname != NULL)
673 error("packet printing is not supported for link type %s: use -w",
676 error("packet printing is not supported for link type %d: use -w", type);
683 get_next_file(FILE *VFile, char *ptr)
687 ret = fgets(ptr, PATH_MAX, VFile);
691 if (ptr[strlen(ptr) - 1] == '\n')
692 ptr[strlen(ptr) - 1] = '\0';
697 #ifdef HAVE_LIBCAPSICUM
698 static cap_channel_t *
701 cap_channel_t *capcas, *capdnsloc;
702 const char *types[1];
706 if (capcas == NULL) {
707 warning("unable to contact casperd");
710 capdnsloc = cap_service_open(capcas, "system.dns");
711 /* Casper capability no longer needed. */
713 if (capdnsloc == NULL)
714 error("unable to open system.dns service");
715 /* Limit system.dns to reverse DNS lookups. */
717 if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
718 error("unable to limit access to system.dns service");
719 families[0] = AF_INET;
720 families[1] = AF_INET6;
721 if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
722 error("unable to limit access to system.dns service");
726 #endif /* HAVE_LIBCAPSICUM */
729 main(int argc, char **argv)
731 register int cnt, op, i;
732 bpf_u_int32 localnet, netmask;
733 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
734 pcap_handler callback;
738 const char *dlt_name;
739 struct bpf_program fcode;
741 RETSIGTYPE (*oldhandler)(int);
743 struct print_info printinfo;
744 struct dump_info dumpinfo;
745 u_char *pcap_userdata;
746 char ebuf[PCAP_ERRBUF_SIZE];
747 char VFileLine[PATH_MAX + 1];
748 char *username = NULL;
749 char *chroot_dir = NULL;
752 #ifdef HAVE_PCAP_FINDALLDEVS
753 pcap_if_t *devpointer;
761 #endif /* __FreeBSD__ */
764 if(wsockinit() != 0) return 1;
767 jflag=-1; /* not set */
771 gndo->ndo_default_print=ndo_default_print;
772 gndo->ndo_printf=tcpdump_printf;
773 gndo->ndo_error=ndo_error;
774 gndo->ndo_warning=ndo_warning;
775 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
785 if ((cp = strrchr(argv[0], '/')) != NULL)
786 program_name = cp + 1;
788 program_name = argv[0];
790 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
798 (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 "V:vw:W:xXy:Yz:Z:")) != -1)
802 /* compatibility for old -a */
813 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
815 Bflag = atoi(optarg)*1024;
817 error("invalid packet buffer size %s", optarg);
819 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
824 error("invalid packet count %s", optarg);
828 Cflag = atoi(optarg) * 1000000;
830 error("invalid file size %s", optarg);
837 #ifdef HAVE_PCAP_FINDALLDEVS
839 if (pcap_findalldevs(&devpointer, ebuf) < 0)
842 for (i = 0; devpointer != 0; i++) {
843 printf("%d.%s", i+1, devpointer->name);
844 if (devpointer->description != NULL)
845 printf(" (%s)", devpointer->description);
847 devpointer = devpointer->next;
851 #endif /* HAVE_PCAP_FINDALLDEVS */
862 #ifndef HAVE_LIBCRYPTO
863 warning("crypto code not compiled in");
865 gndo->ndo_espsecret = optarg;
877 Gflag = atoi(optarg);
879 error("invalid number of seconds %s", optarg);
881 /* We will create one file initially. */
884 /* Grab the current time for rotation use. */
885 if ((Gflag_time = time(NULL)) == (time_t)-1) {
886 error("main: can't get current time: %s",
887 pcap_strerror(errno));
900 if (optarg[0] == '0' && optarg[1] == 0)
901 error("Invalid adapter index");
903 #ifdef HAVE_PCAP_FINDALLDEVS
905 * If the argument is a number, treat it as
906 * an index into the list of adapters, as
907 * printed by "tcpdump -D".
909 * This should be OK on UNIX systems, as interfaces
910 * shouldn't have names that begin with digits.
911 * It can be useful on Windows, where more than
912 * one interface can have the same name.
914 devnum = strtol(optarg, &end, 10);
915 if (optarg != end && *end == '\0') {
917 error("Invalid adapter index");
919 if (pcap_findalldevs(&devpointer, ebuf) < 0)
923 * Look for the devnum-th entry
924 * in the list of devices
928 i < devnum-1 && devpointer != NULL;
929 i++, devpointer = devpointer->next)
931 if (devpointer == NULL)
932 error("Invalid adapter index");
934 device = devpointer->name;
937 #endif /* HAVE_PCAP_FINDALLDEVS */
941 #ifdef HAVE_PCAP_CREATE
945 #endif /* HAVE_PCAP_CREATE */
947 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
949 jflag = pcap_tstamp_type_name_to_val(optarg);
951 error("invalid time stamp type %s", optarg);
962 * _IOLBF is the same as _IOFBF in Microsoft's C
963 * libraries; the only alternative they offer
966 * XXX - this should really be checking for MSVC++,
967 * not WIN32, if, for example, MinGW has its own
968 * C library that is more UNIX-compatible.
970 setvbuf(stdout, NULL, _IONBF, 0);
972 #ifdef HAVE_SETLINEBUF
975 setvbuf(stdout, NULL, _IOLBF, 0);
986 if (smiLoadModule(optarg) == 0) {
987 error("could not load MIB module %s", optarg);
991 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
992 program_name, optarg);
993 (void)fprintf(stderr, "(no libsmi support)\n");
998 /* TCP-MD5 shared secret */
999 #ifndef HAVE_LIBCRYPTO
1000 warning("crypto code not compiled in");
1023 ++suppress_default_print;
1035 snaplen = strtol(optarg, &end, 0);
1036 if (optarg == end || *end != '\0'
1037 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
1038 error("invalid snaplen %s", optarg);
1039 else if (snaplen == 0)
1040 snaplen = MAXIMUM_SNAPLEN;
1052 if (strcasecmp(optarg, "vat") == 0)
1053 packettype = PT_VAT;
1054 else if (strcasecmp(optarg, "wb") == 0)
1056 else if (strcasecmp(optarg, "rpc") == 0)
1057 packettype = PT_RPC;
1058 else if (strcasecmp(optarg, "rtp") == 0)
1059 packettype = PT_RTP;
1060 else if (strcasecmp(optarg, "rtcp") == 0)
1061 packettype = PT_RTCP;
1062 else if (strcasecmp(optarg, "snmp") == 0)
1063 packettype = PT_SNMP;
1064 else if (strcasecmp(optarg, "cnfp") == 0)
1065 packettype = PT_CNFP;
1066 else if (strcasecmp(optarg, "tftp") == 0)
1067 packettype = PT_TFTP;
1068 else if (strcasecmp(optarg, "aodv") == 0)
1069 packettype = PT_AODV;
1070 else if (strcasecmp(optarg, "carp") == 0)
1071 packettype = PT_CARP;
1072 else if (strcasecmp(optarg, "radius") == 0)
1073 packettype = PT_RADIUS;
1074 else if (strcasecmp(optarg, "zmtp1") == 0)
1075 packettype = PT_ZMTP1;
1076 else if (strcasecmp(optarg, "vxlan") == 0)
1077 packettype = PT_VXLAN;
1079 error("unknown packet type `%s'", optarg);
1086 #ifdef HAVE_PCAP_DUMP_FLUSH
1105 Wflag = atoi(optarg);
1107 error("invalid number of output files %s", optarg);
1108 WflagChars = getWflagChars(Wflag);
1113 ++suppress_default_print;
1118 ++suppress_default_print;
1122 gndo->ndo_dltname = optarg;
1124 pcap_datalink_name_to_val(gndo->ndo_dltname);
1125 if (gndo->ndo_dlt < 0)
1126 error("invalid data link type %s", gndo->ndo_dltname);
1129 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1132 /* Undocumented flag */
1133 #ifdef HAVE_PCAP_DEBUG
1134 extern int pcap_debug;
1145 zflag = strdup(optarg);
1154 username = strdup(optarg);
1169 case 0: /* Default */
1170 case 4: /* Default + Date*/
1171 thiszone = gmt2local(0);
1174 case 1: /* No time stamp */
1175 case 2: /* Unix timeval style */
1176 case 3: /* Microseconds since previous packet */
1177 case 5: /* Microseconds since first packet */
1180 default: /* Not supported */
1181 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1185 if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1186 error("-f can not be used with -V or -r");
1188 if (VFileName != NULL && RFileName != NULL)
1189 error("-V and -r are mutually exclusive.");
1192 /* if run as root, prepare for chrooting */
1193 if (getuid() == 0 || geteuid() == 0) {
1194 /* future extensibility for cmd-line arguments */
1196 chroot_dir = WITH_CHROOT;
1201 /* if run as root, prepare for dropping root privileges */
1202 if (getuid() == 0 || geteuid() == 0) {
1203 /* Run with '-Z root' to restore old behaviour */
1205 username = WITH_USER;
1209 if (RFileName != NULL || VFileName != NULL) {
1211 * If RFileName is non-null, it's the pathname of a
1212 * savefile to read. If VFileName is non-null, it's
1213 * the pathname of a file containing a list of pathnames
1214 * (one per line) of savefiles to read.
1216 * In either case, we're reading a savefile, not doing
1221 * We don't need network access, so relinquish any set-UID
1222 * or set-GID privileges we have (if any).
1224 * We do *not* want set-UID privileges when opening a
1225 * trace file, as that might let the user read other
1226 * people's trace files (especially if we're set-UID
1229 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1230 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1232 if (VFileName != NULL) {
1233 if (VFileName[0] == '-' && VFileName[1] == '\0')
1236 VFile = fopen(VFileName, "r");
1239 error("Unable to open file: %s\n", strerror(errno));
1241 ret = get_next_file(VFile, VFileLine);
1243 error("Nothing in %s\n", VFileName);
1244 RFileName = VFileLine;
1247 pd = pcap_open_offline(RFileName, ebuf);
1251 cap_rights_init(&rights, CAP_READ);
1252 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1254 error("unable to limit pcap descriptor");
1257 dlt = pcap_datalink(pd);
1258 dlt_name = pcap_datalink_val_to_name(dlt);
1259 if (dlt_name == NULL) {
1260 fprintf(stderr, "reading from file %s, link-type %u\n",
1264 "reading from file %s, link-type %s (%s)\n",
1265 RFileName, dlt_name,
1266 pcap_datalink_val_to_description(dlt));
1272 * We're doing a live capture.
1274 if (device == NULL) {
1275 device = pcap_lookupdev(ebuf);
1281 * Print a message to the standard error on Windows.
1282 * XXX - why do it here, with a different message?
1284 if(strlen(device) == 1) //we assume that an ASCII string is always longer than 1 char
1285 { //a Unicode string has a \0 as second byte (so strlen() is 1)
1286 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1290 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1295 #ifdef HAVE_PCAP_CREATE
1296 pd = pcap_create(device, ebuf);
1299 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1301 show_tstamp_types_and_exit(device, pd);
1304 * Is this an interface that supports monitor mode?
1306 if (pcap_can_set_rfmon(pd) == 1)
1307 supports_monitor_mode = 1;
1309 supports_monitor_mode = 0;
1310 status = pcap_set_snaplen(pd, snaplen);
1312 error("%s: Can't set snapshot length: %s",
1313 device, pcap_statustostr(status));
1314 status = pcap_set_promisc(pd, !pflag);
1316 error("%s: Can't set promiscuous mode: %s",
1317 device, pcap_statustostr(status));
1319 status = pcap_set_rfmon(pd, 1);
1321 error("%s: Can't set monitor mode: %s",
1322 device, pcap_statustostr(status));
1324 status = pcap_set_timeout(pd, 1000);
1326 error("%s: pcap_set_timeout failed: %s",
1327 device, pcap_statustostr(status));
1329 status = pcap_set_buffer_size(pd, Bflag);
1331 error("%s: Can't set buffer size: %s",
1332 device, pcap_statustostr(status));
1334 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1336 status = pcap_set_tstamp_type(pd, jflag);
1338 error("%s: Can't set time stamp type: %s",
1339 device, pcap_statustostr(status));
1342 status = pcap_activate(pd);
1345 * pcap_activate() failed.
1347 cp = pcap_geterr(pd);
1348 if (status == PCAP_ERROR)
1350 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1351 status == PCAP_ERROR_PERM_DENIED) &&
1353 error("%s: %s\n(%s)", device,
1354 pcap_statustostr(status), cp);
1356 else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1357 strncmp(device, "wlan", 4) == 0) {
1358 char parent[8], newdev[8];
1360 size_t s = sizeof(parent);
1362 snprintf(sysctl, sizeof(sysctl),
1363 "net.wlan.%d.%%parent", atoi(device + 4));
1364 sysctlbyname(sysctl, parent, &s, NULL, 0);
1365 strlcpy(newdev, device, sizeof(newdev));
1366 /* Suggest a new wlan device. */
1367 newdev[strlen(newdev)-1]++;
1368 error("%s is not a monitor mode VAP\n"
1369 "To create a new monitor mode VAP use:\n"
1370 " ifconfig %s create wlandev %s wlanmode "
1371 "monitor\nand use %s as the tcpdump "
1372 "interface", device, newdev, parent,
1377 error("%s: %s", device,
1378 pcap_statustostr(status));
1379 } else if (status > 0) {
1381 * pcap_activate() succeeded, but it's warning us
1382 * of a problem it had.
1384 cp = pcap_geterr(pd);
1385 if (status == PCAP_WARNING)
1387 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1389 warning("%s: %s\n(%s)", device,
1390 pcap_statustostr(status), cp);
1392 warning("%s: %s", device,
1393 pcap_statustostr(status));
1397 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1401 warning("%s", ebuf);
1402 #endif /* HAVE_PCAP_CREATE */
1404 * Let user own process after socket has been opened.
1407 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1408 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1410 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1412 if(pcap_setbuff(pd, Bflag)==-1){
1413 error("%s", pcap_geterr(pd));
1415 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1417 show_dlts_and_exit(device, pd);
1418 if (gndo->ndo_dlt >= 0) {
1419 #ifdef HAVE_PCAP_SET_DATALINK
1420 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1421 error("%s", pcap_geterr(pd));
1424 * We don't actually support changing the
1425 * data link type, so we only let them
1426 * set it to what it already is.
1428 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1429 error("%s is not one of the DLTs supported by this device\n",
1433 (void)fprintf(stderr, "%s: data link type %s\n",
1434 program_name, gndo->ndo_dltname);
1435 (void)fflush(stderr);
1437 i = pcap_snapshot(pd);
1439 warning("snaplen raised from %d to %d", snaplen, i);
1442 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1445 warning("%s", ebuf);
1449 cmdbuf = read_infile(infile);
1451 cmdbuf = copy_argv(&argv[optind]);
1453 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1454 error("%s", pcap_geterr(pd));
1456 bpf_dump(&fcode, dflag);
1462 #ifdef HAVE_LIBCAPSICUM
1464 capdns = capdns_setup();
1465 #endif /* HAVE_LIBCAPSICUM */
1467 init_addrtoname(localnet, netmask);
1471 (void)setsignal(SIGPIPE, cleanup);
1472 (void)setsignal(SIGTERM, cleanup);
1473 (void)setsignal(SIGINT, cleanup);
1475 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1476 (void)setsignal(SIGCHLD, child_cleanup);
1478 /* Cooperate with nohup(1) */
1480 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1481 (void)setsignal(SIGHUP, oldhandler);
1486 * If a user name was specified with "-Z", attempt to switch to
1487 * that user's UID. This would probably be used with sudo,
1488 * to allow tcpdump to be run in a special restricted
1489 * account (if you just want to allow users to open capture
1490 * devices, and can't just give users that permission,
1491 * you'd make tcpdump set-UID or set-GID).
1493 * Tcpdump doesn't necessarily write only to one savefile;
1494 * the general only way to allow a -Z instance to write to
1495 * savefiles as the user under whose UID it's run, rather
1496 * than as the user specified with -Z, would thus be to switch
1497 * to the original user ID before opening a capture file and
1498 * then switch back to the -Z user ID after opening the savefile.
1499 * Switching to the -Z user ID only after opening the first
1500 * savefile doesn't handle the general case.
1503 #ifdef HAVE_CAP_NG_H
1504 /* We are running as root and we will be writing to savefile */
1505 if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1507 /* Drop all capabilities from effective set */
1508 capng_clear(CAPNG_EFFECTIVE);
1509 /* Add capabilities we will need*/
1510 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1511 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1512 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1514 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1515 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1516 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1518 capng_apply(CAPNG_SELECT_BOTH);
1521 #endif /* HAVE_CAP_NG_H */
1523 if (getuid() == 0 || geteuid() == 0) {
1524 if (username || chroot_dir)
1525 droproot(username, chroot_dir);
1530 if (pcap_setfilter(pd, &fcode) < 0)
1531 error("%s", pcap_geterr(pd));
1533 if (RFileName == NULL && VFileName == NULL) {
1534 static const unsigned long cmds[] = { BIOCGSTATS };
1536 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1537 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1539 error("unable to limit pcap descriptor");
1541 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1542 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1543 error("unable to limit ioctls on pcap descriptor");
1549 /* Do not exceed the default PATH_MAX for files. */
1550 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1552 if (dumpinfo.CurrentFileName == NULL)
1553 error("malloc of dumpinfo.CurrentFileName");
1555 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1557 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1559 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1561 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1562 #ifdef HAVE_CAP_NG_H
1563 /* Give up capabilities, clear Effective set */
1564 capng_clear(CAPNG_EFFECTIVE);
1567 error("%s", pcap_geterr(pd));
1569 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1570 if (cap_rights_limit(fileno(pcap_dump_file(p)), &rights) < 0 &&
1572 error("unable to limit dump descriptor");
1575 if (Cflag != 0 || Gflag != 0) {
1577 dumpinfo.WFileName = strdup(basename(WFileName));
1578 dumpinfo.dirfd = open(dirname(WFileName),
1579 O_DIRECTORY | O_RDONLY);
1580 if (dumpinfo.dirfd < 0) {
1581 error("unable to open directory %s",
1582 dirname(WFileName));
1584 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1585 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1586 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1588 error("unable to limit directory rights");
1590 #else /* !__FreeBSD__ */
1591 dumpinfo.WFileName = WFileName;
1593 callback = dump_packet_and_trunc;
1596 pcap_userdata = (u_char *)&dumpinfo;
1598 callback = dump_packet;
1599 pcap_userdata = (u_char *)p;
1601 #ifdef HAVE_PCAP_DUMP_FLUSH
1606 type = pcap_datalink(pd);
1607 printinfo = get_print_info(type);
1608 callback = print_packet;
1609 pcap_userdata = (u_char *)&printinfo;
1612 #ifdef SIGNAL_REQ_INFO
1614 * We can't get statistics when reading from a file rather
1615 * than capturing from a device.
1617 if (RFileName == NULL)
1618 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1621 if (vflag > 0 && WFileName) {
1623 * When capturing to a file, "-v" means tcpdump should,
1624 * every 10 secodns, "v"erbosely report the number of
1627 #ifdef USE_WIN32_MM_TIMER
1628 /* call verbose_stats_dump() each 1000 +/-100msec */
1629 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1630 setvbuf(stderr, NULL, _IONBF, 0);
1631 #elif defined(HAVE_ALARM)
1632 (void)setsignal(SIGALRM, verbose_stats_dump);
1638 if (RFileName == NULL) {
1640 * Live capture (if -V was specified, we set RFileName
1641 * to a file from the -V file). Print a message to
1642 * the standard error on UN*X.
1644 if (!vflag && !WFileName) {
1645 (void)fprintf(stderr,
1646 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1649 (void)fprintf(stderr, "%s: ", program_name);
1650 dlt = pcap_datalink(pd);
1651 dlt_name = pcap_datalink_val_to_name(dlt);
1652 if (dlt_name == NULL) {
1653 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1654 device, dlt, snaplen);
1656 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1658 pcap_datalink_val_to_description(dlt), snaplen);
1660 (void)fflush(stderr);
1665 cansandbox = (VFileName == NULL && zflag == NULL);
1666 #ifdef HAVE_LIBCAPSICUM
1667 cansandbox = (cansandbox && (nflag || capdns != NULL));
1669 cansandbox = (cansandbox && nflag);
1671 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1672 error("unable to enter the capability mode");
1673 if (cap_sandboxed())
1674 fprintf(stderr, "capability mode sandbox enabled\n");
1675 #endif /* __FreeBSD__ */
1678 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1679 if (WFileName == NULL) {
1681 * We're printing packets. Flush the printed output,
1682 * so it doesn't get intermingled with error output.
1686 * We got interrupted, so perhaps we didn't
1687 * manage to finish a line we were printing.
1688 * Print an extra newline, just in case.
1692 (void)fflush(stdout);
1698 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1699 program_name, pcap_geterr(pd));
1701 if (RFileName == NULL) {
1703 * We're doing a live capture. Report the capture
1709 if (VFileName != NULL) {
1710 ret = get_next_file(VFile, VFileLine);
1712 RFileName = VFileLine;
1713 pd = pcap_open_offline(RFileName, ebuf);
1717 cap_rights_init(&rights, CAP_READ);
1718 if (cap_rights_limit(fileno(pcap_file(pd)),
1719 &rights) < 0 && errno != ENOSYS) {
1720 error("unable to limit pcap descriptor");
1723 new_dlt = pcap_datalink(pd);
1724 if (WFileName && new_dlt != dlt)
1725 error("%s: new dlt does not match original", RFileName);
1726 printinfo = get_print_info(new_dlt);
1727 dlt_name = pcap_datalink_val_to_name(new_dlt);
1728 if (dlt_name == NULL) {
1729 fprintf(stderr, "reading from file %s, link-type %u\n",
1730 RFileName, new_dlt);
1733 "reading from file %s, link-type %s (%s)\n",
1734 RFileName, dlt_name,
1735 pcap_datalink_val_to_description(new_dlt));
1737 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1738 error("%s", pcap_geterr(pd));
1739 if (pcap_setfilter(pd, &fcode) < 0)
1740 error("%s", pcap_geterr(pd));
1744 while (ret != NULL);
1747 exit(status == -1 ? 1 : 0);
1750 /* make a clean exit on interrupts */
1752 cleanup(int signo _U_)
1754 #ifdef USE_WIN32_MM_TIMER
1756 timeKillEvent(timer_id);
1758 #elif defined(HAVE_ALARM)
1762 #ifdef HAVE_PCAP_BREAKLOOP
1764 * We have "pcap_breakloop()"; use it, so that we do as little
1765 * as possible in the signal handler (it's probably not safe
1766 * to do anything with standard I/O streams in a signal handler -
1767 * the ANSI C standard doesn't say it is).
1772 * We don't have "pcap_breakloop()"; this isn't safe, but
1773 * it's the best we can do. Print the summary if we're
1774 * not reading from a savefile - i.e., if we're doing a
1775 * live capture - and exit.
1777 if (pd != NULL && pcap_file(pd) == NULL) {
1779 * We got interrupted, so perhaps we didn't
1780 * manage to finish a line we were printing.
1781 * Print an extra newline, just in case.
1784 (void)fflush(stdout);
1792 On windows, we do not use a fork, so we do not care less about
1793 waiting a child processes to die
1795 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1797 child_cleanup(int signo _U_)
1801 #endif /* HAVE_FORK && HAVE_VFORK */
1804 info(register int verbose)
1806 struct pcap_stat stat;
1809 * Older versions of libpcap didn't set ps_ifdrop on some
1810 * platforms; initialize it to 0 to handle that.
1813 if (pcap_stats(pd, &stat) < 0) {
1814 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1820 fprintf(stderr, "%s: ", program_name);
1822 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
1823 PLURAL_SUFFIX(packets_captured));
1825 fputs(", ", stderr);
1828 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1829 PLURAL_SUFFIX(stat.ps_recv));
1831 fputs(", ", stderr);
1834 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1835 PLURAL_SUFFIX(stat.ps_drop));
1836 if (stat.ps_ifdrop != 0) {
1838 fputs(", ", stderr);
1841 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
1842 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1848 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1850 compress_savefile(const char *filename)
1859 * Set to lowest priority so that this doesn't disturb the capture
1862 setpriority(PRIO_PROCESS, 0, NZERO - 1);
1864 setpriority(PRIO_PROCESS, 0, 19);
1866 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1868 "compress_savefile:execlp(%s, %s): %s\n",
1878 #else /* HAVE_FORK && HAVE_VFORK */
1880 compress_savefile(const char *filename)
1883 "compress_savefile failed. Functionality not implemented under your system\n");
1885 #endif /* HAVE_FORK && HAVE_VFORK */
1888 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1890 struct dump_info *dump_info;
1892 cap_rights_t rights;
1899 dump_info = (struct dump_info *)user;
1902 * XXX - this won't force the file to rotate on the specified time
1903 * boundary, but it will rotate on the first packet received after the
1904 * specified Gflag number of seconds. Note: if a Gflag time boundary
1905 * and a Cflag size boundary coincide, the time rotation will occur
1906 * first thereby cancelling the Cflag boundary (since the file should
1910 /* Check if it is time to rotate */
1913 /* Get the current time */
1914 if ((t = time(NULL)) == (time_t)-1) {
1915 error("dump_and_trunc_packet: can't get current_time: %s",
1916 pcap_strerror(errno));
1920 /* If the time is greater than the specified window, rotate */
1921 if (t - Gflag_time >= Gflag) {
1927 /* Update the Gflag_time */
1929 /* Update Gflag_count */
1932 * Close the current file and open a new one.
1934 pcap_dump_close(dump_info->p);
1937 * Compress the file we just closed, if the user asked for it
1940 compress_savefile(dump_info->CurrentFileName);
1943 * Check to see if we've exceeded the Wflag (when
1946 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1947 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
1952 if (dump_info->CurrentFileName != NULL)
1953 free(dump_info->CurrentFileName);
1954 /* Allocate space for max filename + \0. */
1955 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
1956 if (dump_info->CurrentFileName == NULL)
1957 error("dump_packet_and_trunc: malloc");
1959 * This is always the first file in the Cflag
1961 * We also don't need numbering if Cflag is not set.
1964 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1967 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1969 #ifdef HAVE_CAP_NG_H
1970 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1971 capng_apply(CAPNG_EFFECTIVE);
1972 #endif /* HAVE_CAP_NG_H */
1974 fd = openat(dump_info->dirfd,
1975 dump_info->CurrentFileName,
1976 O_CREAT | O_WRONLY | O_TRUNC, 0644);
1978 error("unable to open file %s",
1979 dump_info->CurrentFileName);
1981 fp = fdopen(fd, "w");
1983 error("unable to fdopen file %s",
1984 dump_info->CurrentFileName);
1986 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
1987 #else /* !__FreeBSD__ */
1988 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1990 #ifdef HAVE_CAP_NG_H
1991 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1992 capng_apply(CAPNG_EFFECTIVE);
1993 #endif /* HAVE_CAP_NG_H */
1994 if (dump_info->p == NULL)
1995 error("%s", pcap_geterr(pd));
1997 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1998 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
1999 &rights) < 0 && errno != ENOSYS) {
2000 error("unable to limit dump descriptor");
2007 * XXX - this won't prevent capture files from getting
2008 * larger than Cflag - the last packet written to the
2009 * file could put it over Cflag.
2011 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
2018 * Close the current file and open a new one.
2020 pcap_dump_close(dump_info->p);
2023 * Compress the file we just closed, if the user asked for it
2026 compress_savefile(dump_info->CurrentFileName);
2030 if (Cflag_count >= Wflag)
2033 if (dump_info->CurrentFileName != NULL)
2034 free(dump_info->CurrentFileName);
2035 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2036 if (dump_info->CurrentFileName == NULL)
2037 error("dump_packet_and_trunc: malloc");
2038 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2040 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2041 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2043 error("unable to open file %s",
2044 dump_info->CurrentFileName);
2046 fp = fdopen(fd, "w");
2048 error("unable to fdopen file %s",
2049 dump_info->CurrentFileName);
2051 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2052 #else /* !__FreeBSD__ */
2053 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2055 if (dump_info->p == NULL)
2056 error("%s", pcap_geterr(pd));
2058 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2059 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2060 &rights) < 0 && errno != ENOSYS) {
2061 error("unable to limit dump descriptor");
2066 pcap_dump((u_char *)dump_info->p, h, sp);
2067 #ifdef HAVE_PCAP_DUMP_FLUSH
2069 pcap_dump_flush(dump_info->p);
2078 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2084 pcap_dump(user, h, sp);
2085 #ifdef HAVE_PCAP_DUMP_FLUSH
2087 pcap_dump_flush((pcap_dumper_t *)user);
2096 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2098 struct print_info *print_info;
2106 print_info = (struct print_info *)user;
2109 * Some printers want to check that they're not walking off the
2110 * end of the packet.
2111 * Rather than pass it all the way down, we set this global.
2113 snapend = sp + h->caplen;
2115 if(print_info->ndo_type) {
2116 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2118 hdrlen = (*print_info->p.printer)(h, sp);
2123 * Print the raw packet data in hex and ASCII.
2127 * Include the link-layer header.
2129 hex_and_ascii_print("\n\t", sp, h->caplen);
2132 * Don't include the link-layer header - and if
2133 * we have nothing past the link-layer header,
2136 if (h->caplen > hdrlen)
2137 hex_and_ascii_print("\n\t", sp + hdrlen,
2138 h->caplen - hdrlen);
2142 * Print the raw packet data in hex.
2146 * Include the link-layer header.
2148 hex_print("\n\t", sp, h->caplen);
2151 * Don't include the link-layer header - and if
2152 * we have nothing past the link-layer header,
2155 if (h->caplen > hdrlen)
2156 hex_print("\n\t", sp + hdrlen,
2157 h->caplen - hdrlen);
2161 * Print the raw packet data in ASCII.
2165 * Include the link-layer header.
2167 ascii_print(sp, h->caplen);
2170 * Don't include the link-layer header - and if
2171 * we have nothing past the link-layer header,
2174 if (h->caplen > hdrlen)
2175 ascii_print(sp + hdrlen, h->caplen - hdrlen);
2188 * XXX - there should really be libpcap calls to get the version
2189 * number as a string (the string would be generated from #defines
2190 * at run time, so that it's not generated from string constants
2191 * in the library, as, on many UNIX systems, those constants would
2192 * be statically linked into the application executable image, and
2193 * would thus reflect the version of libpcap on the system on
2194 * which the application was *linked*, not the system on which it's
2197 * That routine should be documented, unlike the "version[]"
2198 * string, so that UNIX vendors providing their own libpcaps
2199 * don't omit it (as a couple of vendors have...).
2201 * Packet.dll should perhaps also export a routine to return the
2202 * version number of the Packet.dll code, to supply the
2203 * "Wpcap_version" information on Windows.
2205 char WDversion[]="current-cvs.tcpdump.org";
2206 #if !defined(HAVE_GENERATED_VERSION)
2207 char version[]="current-cvs.tcpdump.org";
2209 char pcap_version[]="current-cvs.tcpdump.org";
2210 char Wpcap_version[]="3.1";
2214 * By default, print the specified data out in hex and ASCII.
2217 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
2219 hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
2223 default_print(const u_char *bp, u_int length)
2225 ndo_default_print(gndo, bp, length);
2228 #ifdef SIGNAL_REQ_INFO
2229 RETSIGTYPE requestinfo(int signo _U_)
2239 * Called once each second in verbose mode while dumping to file
2241 #ifdef USE_WIN32_MM_TIMER
2242 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2243 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2245 struct pcap_stat stat;
2247 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2248 fprintf(stderr, "Got %u\r", packets_captured);
2250 #elif defined(HAVE_ALARM)
2251 static void verbose_stats_dump(int sig _U_)
2253 struct pcap_stat stat;
2255 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2256 fprintf(stderr, "Got %u\r", packets_captured);
2264 extern char version[];
2265 #ifndef HAVE_PCAP_LIB_VERSION
2266 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2267 extern char pcap_version[];
2268 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2269 static char pcap_version[] = "unknown";
2270 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2271 #endif /* HAVE_PCAP_LIB_VERSION */
2273 #ifdef HAVE_PCAP_LIB_VERSION
2275 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2277 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2279 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2280 #else /* HAVE_PCAP_LIB_VERSION */
2282 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2283 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2285 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2286 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2288 #endif /* HAVE_PCAP_LIB_VERSION */
2289 (void)fprintf(stderr,
2290 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2291 (void)fprintf(stderr,
2292 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2293 (void)fprintf(stderr,
2294 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
2295 (void)fprintf(stderr,
2296 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -V file ] [ -w file ]\n");
2297 (void)fprintf(stderr,
2298 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2299 (void)fprintf(stderr,
2300 "\t\t[ -Z user ] [ expression ]\n");
2308 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2312 (void)fprintf(stderr, "%s: ", program_name);
2314 (void)vfprintf(stderr, fmt, ap);
2318 if (fmt[-1] != '\n')
2319 (void)fputc('\n', stderr);
2327 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2331 (void)fprintf(stderr, "%s: WARNING: ", program_name);
2333 (void)vfprintf(stderr, fmt, ap);
2337 if (fmt[-1] != '\n')
2338 (void)fputc('\n', stderr);