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";
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>
52 extern int strcasecmp (const char *__s1, const char *__s2);
63 #include <openssl/crypto.h>
66 #ifdef HAVE_GETOPT_LONG
69 #include "getopt_long.h"
78 #include <sys/capsicum.h>
79 #include <sys/sysctl.h>
80 #endif /* __FreeBSD__ */
82 #include <libcapsicum.h>
83 #include <libcapsicum_dns.h>
84 #include <libcapsicum_service.h>
86 #include <sys/capability.h>
87 #include <sys/ioccom.h>
91 #endif /* HAVE_CAPSICUM */
94 #include <sys/resource.h>
99 /* capabilities convinience library */
102 #endif /* HAVE_CAP_NG_H */
104 #include "netdissect.h"
105 #include "interface.h"
106 #include "addrtoname.h"
108 #include "setsignal.h"
109 #include "gmt2local.h"
110 #include "pcap-missing.h"
113 #define PATH_MAX 1024
117 #define SIGNAL_REQ_INFO SIGINFO
119 #define SIGNAL_REQ_INFO SIGUSR1
122 netdissect_options Gndo;
123 netdissect_options *gndo = &Gndo;
125 static int Dflag; /* list available devices and exit */
126 static int dflag; /* print filter code */
127 static int Lflag; /* list available data link types and exit */
128 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
129 static int Jflag; /* list available time stamp types */
131 #ifdef HAVE_PCAP_SETDIRECTION
132 int Qflag = -1; /* restrict captured packet by send/receive direction */
134 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
136 static int infodelay;
137 static int infoprint;
142 cap_channel_t *capdns;
145 int32_t thiszone; /* seconds offset from gmt to local time */
148 static RETSIGTYPE cleanup(int);
149 static RETSIGTYPE child_cleanup(int);
150 static void print_version(void);
151 static void print_usage(void);
152 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
154 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
155 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
156 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
157 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
158 static void droproot(const char *, const char *);
159 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
160 __attribute__((noreturn))
161 #ifdef __ATTRIBUTE___FORMAT_OK
162 __attribute__((format (printf, 2, 3)))
163 #endif /* __ATTRIBUTE___FORMAT_OK */
165 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...)
166 #ifdef __ATTRIBUTE___FORMAT_OK
167 __attribute__((format (printf, 2, 3)))
168 #endif /* __ATTRIBUTE___FORMAT_OK */
171 #ifdef SIGNAL_REQ_INFO
172 RETSIGTYPE requestinfo(int);
175 #if defined(USE_WIN32_MM_TIMER)
176 #include <MMsystem.h>
177 static UINT timer_id;
178 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
179 #elif defined(HAVE_ALARM)
180 static void verbose_stats_dump(int sig);
183 static void info(int);
184 static u_int packets_captured;
198 static const struct printer printers[] = {
202 static const struct ndo_printer ndo_printers[] = {
203 { ether_if_print, DLT_EN10MB },
205 { ipnet_if_print, DLT_IPNET },
207 #ifdef DLT_IEEE802_15_4
208 { ieee802_15_4_if_print, DLT_IEEE802_15_4 },
210 #ifdef DLT_IEEE802_15_4_NOFCS
211 { ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
214 { ppi_if_print, DLT_PPI },
216 #ifdef DLT_NETANALYZER
217 { netanalyzer_if_print, DLT_NETANALYZER },
219 #ifdef DLT_NETANALYZER_TRANSPARENT
220 { netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
222 #if defined(DLT_NFLOG) && defined(HAVE_PCAP_NFLOG_H)
223 { nflog_if_print, DLT_NFLOG},
226 { cip_if_print, DLT_CIP },
229 { cip_if_print, DLT_ATM_CLIP },
231 #ifdef DLT_IP_OVER_FC
232 { ipfc_if_print, DLT_IP_OVER_FC },
234 { null_if_print, DLT_NULL },
236 { null_if_print, DLT_LOOP },
238 #ifdef DLT_APPLE_IP_OVER_IEEE1394
239 { ap1394_if_print, DLT_APPLE_IP_OVER_IEEE1394 },
241 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
242 { bt_if_print, DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
245 { lane_if_print, DLT_LANE8023 },
247 { arcnet_if_print, DLT_ARCNET },
248 #ifdef DLT_ARCNET_LINUX
249 { arcnet_linux_if_print, DLT_ARCNET_LINUX },
251 { raw_if_print, DLT_RAW },
253 { raw_if_print, DLT_IPV4 },
256 { raw_if_print, DLT_IPV6 },
258 #ifdef HAVE_PCAP_USB_H
260 { usb_linux_48_byte_print, DLT_USB_LINUX},
261 #endif /* DLT_USB_LINUX */
262 #ifdef DLT_USB_LINUX_MMAPPED
263 { usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
264 #endif /* DLT_USB_LINUX_MMAPPED */
265 #endif /* HAVE_PCAP_USB_H */
266 #ifdef DLT_SYMANTEC_FIREWALL
267 { symantec_if_print, DLT_SYMANTEC_FIREWALL },
270 { chdlc_if_print, DLT_C_HDLC },
273 { chdlc_if_print, DLT_HDLC },
276 { pppoe_if_print, DLT_PPP_ETHER },
278 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
279 { pflog_if_print, DLT_PFLOG },
281 { token_if_print, DLT_IEEE802 },
282 { fddi_if_print, DLT_FDDI },
284 { sll_if_print, DLT_LINUX_SLL },
287 { fr_if_print, DLT_FR },
290 { fr_if_print, DLT_FRELAY },
293 { mfr_if_print, DLT_MFR },
295 { atm_if_print, DLT_ATM_RFC1483 },
297 { sunatm_if_print, DLT_SUNATM },
300 { enc_if_print, DLT_ENC },
302 { sl_if_print, DLT_SLIP },
303 #ifdef DLT_SLIP_BSDOS
304 { sl_bsdos_if_print, DLT_SLIP_BSDOS },
307 { ltalk_if_print, DLT_LTALK },
309 #ifdef DLT_JUNIPER_ATM1
310 { juniper_atm1_print, DLT_JUNIPER_ATM1 },
312 #ifdef DLT_JUNIPER_ATM2
313 { juniper_atm2_print, DLT_JUNIPER_ATM2 },
315 #ifdef DLT_JUNIPER_MFR
316 { juniper_mfr_print, DLT_JUNIPER_MFR },
318 #ifdef DLT_JUNIPER_MLFR
319 { juniper_mlfr_print, DLT_JUNIPER_MLFR },
321 #ifdef DLT_JUNIPER_MLPPP
322 { juniper_mlppp_print, DLT_JUNIPER_MLPPP },
324 #ifdef DLT_JUNIPER_PPPOE
325 { juniper_pppoe_print, DLT_JUNIPER_PPPOE },
327 #ifdef DLT_JUNIPER_PPPOE_ATM
328 { juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
330 #ifdef DLT_JUNIPER_GGSN
331 { juniper_ggsn_print, DLT_JUNIPER_GGSN },
333 #ifdef DLT_JUNIPER_ES
334 { juniper_es_print, DLT_JUNIPER_ES },
336 #ifdef DLT_JUNIPER_MONITOR
337 { juniper_monitor_print, DLT_JUNIPER_MONITOR },
339 #ifdef DLT_JUNIPER_SERVICES
340 { juniper_services_print, DLT_JUNIPER_SERVICES },
342 #ifdef DLT_JUNIPER_ETHER
343 { juniper_ether_print, DLT_JUNIPER_ETHER },
345 #ifdef DLT_JUNIPER_PPP
346 { juniper_ppp_print, DLT_JUNIPER_PPP },
348 #ifdef DLT_JUNIPER_FRELAY
349 { juniper_frelay_print, DLT_JUNIPER_FRELAY },
351 #ifdef DLT_JUNIPER_CHDLC
352 { juniper_chdlc_print, DLT_JUNIPER_CHDLC },
355 { pktap_if_print, DLT_PKTAP },
357 #ifdef DLT_IEEE802_11_RADIO
358 { ieee802_11_radio_if_print, DLT_IEEE802_11_RADIO },
360 #ifdef DLT_IEEE802_11
361 { ieee802_11_if_print, DLT_IEEE802_11},
363 #ifdef DLT_IEEE802_11_RADIO_AVS
364 { ieee802_11_radio_avs_if_print, DLT_IEEE802_11_RADIO_AVS },
366 #ifdef DLT_PRISM_HEADER
367 { prism_if_print, DLT_PRISM_HEADER },
369 { ppp_if_print, DLT_PPP },
370 #ifdef DLT_PPP_WITHDIRECTION
371 { ppp_if_print, DLT_PPP_WITHDIRECTION },
374 { ppp_bsdos_if_print, DLT_PPP_BSDOS },
376 #ifdef DLT_PPP_SERIAL
377 { ppp_hdlc_if_print, DLT_PPP_SERIAL },
382 static const struct tok status_flags[] = {
384 { PCAP_IF_UP, "Up" },
386 #ifdef PCAP_IF_RUNNING
387 { PCAP_IF_RUNNING, "Running" },
389 { PCAP_IF_LOOPBACK, "Loopback" },
394 lookup_printer(int type)
396 const struct printer *p;
398 for (p = printers; p->f; ++p)
407 lookup_ndo_printer(int type)
409 const struct ndo_printer *p;
411 for (p = ndo_printers; p->f; ++p)
415 #if defined(DLT_USER2) && defined(DLT_PKTAP)
417 * Apple incorrectly chose to use DLT_USER2 for their PKTAP
420 * We map DLT_PKTAP, whether it's DLT_USER2 as it is on Darwin-
421 * based OSes or the same value as LINKTYPE_PKTAP as it is on
422 * other OSes, to LINKTYPE_PKTAP, so files written with
423 * this version of libpcap for a DLT_PKTAP capture have a link-
424 * layer header type of LINKTYPE_PKTAP.
426 * However, files written on OS X Mavericks for a DLT_PKTAP
427 * capture have a link-layer header type of LINKTYPE_USER2.
428 * If we don't have a printer for DLT_USER2, and type is
429 * DLT_USER2, we look up the printer for DLT_PKTAP and use
432 if (type == DLT_USER2) {
433 for (p = ndo_printers; p->f; ++p)
434 if (DLT_PKTAP == p->type)
445 static int supports_monitor_mode;
452 netdissect_options *ndo;
455 if_ndo_printer ndo_printer;
462 char *CurrentFileName;
470 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
472 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
475 int *tstamp_types = 0;
476 const char *tstamp_type_name;
479 n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
480 if (n_tstamp_types < 0)
481 error("%s", pcap_geterr(pd));
483 if (n_tstamp_types == 0) {
484 fprintf(stderr, "Time stamp type cannot be set for %s\n",
488 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
490 for (i = 0; i < n_tstamp_types; i++) {
491 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
492 if (tstamp_type_name != NULL) {
493 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
494 pcap_tstamp_type_val_to_description(tstamp_types[i]));
496 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
499 pcap_free_tstamp_types(tstamp_types);
505 show_dlts_and_exit(const char *device, pcap_t *pd)
509 const char *dlt_name;
511 n_dlts = pcap_list_datalinks(pd, &dlts);
513 error("%s", pcap_geterr(pd));
514 else if (n_dlts == 0 || !dlts)
515 error("No data link types.");
518 * If the interface is known to support monitor mode, indicate
519 * whether these are the data link types available when not in
520 * monitor mode, if -I wasn't specified, or when in monitor mode,
521 * when -I was specified (the link-layer types available in
522 * monitor mode might be different from the ones available when
523 * not in monitor mode).
525 if (supports_monitor_mode)
526 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
528 Iflag ? "when in monitor mode" : "when not in monitor mode");
530 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
533 while (--n_dlts >= 0) {
534 dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
535 if (dlt_name != NULL) {
536 (void) fprintf(stderr, " %s (%s)", dlt_name,
537 pcap_datalink_val_to_description(dlts[n_dlts]));
540 * OK, does tcpdump handle that type?
542 if (lookup_printer(dlts[n_dlts]) == NULL
543 && lookup_ndo_printer(dlts[n_dlts]) == NULL)
544 (void) fprintf(stderr, " (printing not supported)");
545 fprintf(stderr, "\n");
547 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
551 #ifdef HAVE_PCAP_FREE_DATALINKS
552 pcap_free_datalinks(dlts);
557 #ifdef HAVE_PCAP_FINDALLDEVS
559 show_devices_and_exit (void)
561 pcap_if_t *devpointer;
562 char ebuf[PCAP_ERRBUF_SIZE];
565 if (pcap_findalldevs(&devpointer, ebuf) < 0)
568 for (i = 0; devpointer != NULL; i++) {
569 printf("%d.%s", i+1, devpointer->name);
570 if (devpointer->description != NULL)
571 printf(" (%s)", devpointer->description);
572 if (devpointer->flags != 0)
573 printf(" [%s]", bittok2str(status_flags, "none", devpointer->flags));
575 devpointer = devpointer->next;
580 #endif /* HAVE_PCAP_FINDALLDEVS */
585 * Note that there we use all letters for short options except for g, k,
586 * o, and P, and those are used by other versions of tcpdump, and we should
587 * only use them for the same purposes that the other versions of tcpdump
590 * OS X tcpdump uses -g to force non--v output for IP to be on one
591 * line, making it more "g"repable;
593 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
596 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
597 * for hosts sending TCP SYN packets;
599 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
604 * Set up flags that might or might not be supported depending on the
605 * version of libpcap we're using.
607 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
609 #define B_FLAG_USAGE " [ -B size ]"
610 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
613 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
615 #ifdef HAVE_PCAP_CREATE
617 #else /* HAVE_PCAP_CREATE */
619 #endif /* HAVE_PCAP_CREATE */
621 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
623 #define j_FLAG_USAGE " [ -j tstamptype ]"
625 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
629 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
631 #ifdef HAVE_PCAP_FINDALLDEVS
632 #ifndef HAVE_PCAP_IF_T
633 #undef HAVE_PCAP_FINDALLDEVS
637 #ifdef HAVE_PCAP_FINDALLDEVS
643 #ifdef HAVE_PCAP_DUMP_FLUSH
649 #ifdef HAVE_PCAP_SETDIRECTION
658 * We do not currently have long options corresponding to all short
659 * options; we should probably pick appropriate option names for them.
661 * However, the short options where the number of times the option is
662 * specified matters, such as -v and -d and -t, should probably not
663 * just map to a long option, as saying
665 * tcpdump --verbose --verbose
667 * doesn't make sense; it should be --verbosity={N} or something such
670 * For long options with no corresponding short options, we define values
671 * outside the range of ASCII graphic characters, make that the last
672 * component of the entry for the long option, and have a case for that
673 * option in the switch statement.
675 #define OPTION_VERSION 128
676 #define OPTION_TSTAMP_PRECISION 129
678 static const struct option longopts[] = {
679 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
680 { "buffer-size", required_argument, NULL, 'B' },
682 { "list-interfaces", no_argument, NULL, 'D' },
683 { "help", no_argument, NULL, 'h' },
684 { "interface", required_argument, NULL, 'i' },
685 #ifdef HAVE_PCAP_CREATE
686 { "monitor-mode", no_argument, NULL, 'I' },
688 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
689 { "time-stamp-type", required_argument, NULL, 'j' },
690 { "list-time-stamp-types", no_argument, NULL, 'J' },
692 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
693 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
695 { "dont-verify-checksums", no_argument, NULL, 'K' },
696 { "list-data-link-types", no_argument, NULL, 'L' },
697 { "no-optimize", no_argument, NULL, 'O' },
698 { "no-promiscuous-mode", no_argument, NULL, 'p' },
699 #ifdef HAVE_PCAP_SETDIRECTION
700 { "direction", required_argument, NULL, 'Q' },
702 { "snapshot-length", required_argument, NULL, 's' },
703 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
704 #ifdef HAVE_PCAP_DUMP_FLUSH
705 { "packet-buffered", no_argument, NULL, 'U' },
707 { "linktype", required_argument, NULL, 'y' },
708 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
709 { "debug-filter-parser", no_argument, NULL, 'Y' },
711 { "relinquish-privileges", required_argument, NULL, 'Z' },
712 { "number", no_argument, NULL, '#' },
713 { "version", no_argument, NULL, OPTION_VERSION },
718 /* Drop root privileges and chroot if necessary */
720 droproot(const char *username, const char *chroot_dir)
722 struct passwd *pw = NULL;
724 if (chroot_dir && !username) {
725 fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
729 pw = getpwnam(username);
732 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
733 fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
734 chroot_dir, pcap_strerror(errno));
739 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
741 fprintf(stderr, "error : ret %d\n", ret);
744 printf("dropped privs to %s\n", username);
746 /* We don't need CAP_SETUID and CAP_SETGID */
747 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
748 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
749 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
750 capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
751 capng_apply(CAPNG_SELECT_BOTH);
754 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
755 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
756 fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
758 (unsigned long)pw->pw_uid,
759 (unsigned long)pw->pw_gid,
760 pcap_strerror(errno));
764 printf("dropped privs to %s\n", username);
766 #endif /* HAVE_CAP_NG_H */
769 fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
792 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
794 char *filename = malloc(PATH_MAX + 1);
795 if (filename == NULL)
796 error("Makefilename: malloc");
798 /* Process with strftime if Gflag is set. */
802 /* Convert Gflag_time to a usable format */
803 if ((local_tm = localtime(&Gflag_time)) == NULL) {
804 error("MakeTimedFilename: localtime");
807 /* There's no good way to detect an error in strftime since a return
808 * value of 0 isn't necessarily failure.
810 strftime(filename, PATH_MAX, orig_name, local_tm);
812 strncpy(filename, orig_name, PATH_MAX);
815 if (cnt == 0 && max_chars == 0)
816 strncpy(buffer, filename, PATH_MAX + 1);
818 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
819 /* Report an error if the filename is too large */
820 error("too many output files or filename is too long (> %d)", PATH_MAX);
824 static int tcpdump_printf(netdissect_options *ndo _U_,
825 const char *fmt, ...)
832 ret=vfprintf(stdout, fmt, args);
838 static struct print_info
839 get_print_info(int type)
841 struct print_info printinfo;
843 printinfo.ndo_type = 1;
844 printinfo.ndo = gndo;
845 printinfo.p.ndo_printer = lookup_ndo_printer(type);
846 if (printinfo.p.ndo_printer == NULL) {
847 printinfo.p.printer = lookup_printer(type);
848 printinfo.ndo_type = 0;
849 if (printinfo.p.printer == NULL) {
850 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
851 if (gndo->ndo_dltname != NULL)
852 error("packet printing is not supported for link type %s: use -w",
855 error("packet printing is not supported for link type %d: use -w", type);
862 get_next_file(FILE *VFile, char *ptr)
866 ret = fgets(ptr, PATH_MAX, VFile);
870 if (ptr[strlen(ptr) - 1] == '\n')
871 ptr[strlen(ptr) - 1] = '\0';
877 static cap_channel_t *
880 cap_channel_t *capcas, *capdnsloc;
881 const char *types[1];
885 if (capcas == NULL) {
886 warning("unable to contact casperd");
889 capdnsloc = cap_service_open(capcas, "system.dns");
890 /* Casper capability no longer needed. */
892 if (capdnsloc == NULL)
893 error("unable to open system.dns service");
894 /* Limit system.dns to reverse DNS lookups. */
896 if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
897 error("unable to limit access to system.dns service");
898 families[0] = AF_INET;
899 families[1] = AF_INET6;
900 if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
901 error("unable to limit access to system.dns service");
905 #endif /* HAVE_CAPSICUM */
907 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
909 tstamp_precision_from_string(const char *precision)
911 if (strncmp(precision, "nano", strlen("nano")) == 0)
912 return PCAP_TSTAMP_PRECISION_NANO;
914 if (strncmp(precision, "micro", strlen("micro")) == 0)
915 return PCAP_TSTAMP_PRECISION_MICRO;
921 tstamp_precision_to_string(int precision)
925 case PCAP_TSTAMP_PRECISION_MICRO:
928 case PCAP_TSTAMP_PRECISION_NANO:
938 main(int argc, char **argv)
940 register int cnt, op, i;
941 bpf_u_int32 localnet =0 , netmask = 0;
942 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
943 pcap_handler callback;
947 const char *dlt_name;
948 struct bpf_program fcode;
950 RETSIGTYPE (*oldhandler)(int);
952 struct print_info printinfo;
953 struct dump_info dumpinfo;
954 u_char *pcap_userdata;
955 char ebuf[PCAP_ERRBUF_SIZE];
956 char VFileLine[PATH_MAX + 1];
957 char *username = NULL;
958 char *chroot_dir = NULL;
961 #ifdef HAVE_PCAP_FINDALLDEVS
962 pcap_if_t *devpointer;
969 #endif /* HAVE_CAPSICUM */
973 if(wsockinit() != 0) return 1;
976 jflag=-1; /* not set */
980 gndo->ndo_default_print=ndo_default_print;
981 gndo->ndo_printf=tcpdump_printf;
982 gndo->ndo_error=ndo_error;
983 gndo->ndo_warning=ndo_warning;
984 gndo->ndo_snaplen = DEFAULT_SNAPLEN;
994 if ((cp = strrchr(argv[0], '/')) != NULL)
995 program_name = cp + 1;
997 program_name = argv[0];
999 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1007 (op = getopt_long(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:Rs:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#", longopts, NULL)) != -1)
1011 /* compatibility for old -a */
1022 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
1024 Bflag = atoi(optarg)*1024;
1026 error("invalid packet buffer size %s", optarg);
1028 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
1033 error("invalid packet count %s", optarg);
1037 Cflag = atoi(optarg) * 1000000;
1039 error("invalid file size %s", optarg);
1059 #ifndef HAVE_LIBCRYPTO
1060 warning("crypto code not compiled in");
1062 gndo->ndo_espsecret = optarg;
1074 Gflag = atoi(optarg);
1076 error("invalid number of seconds %s", optarg);
1078 /* We will create one file initially. */
1081 /* Grab the current time for rotation use. */
1082 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1083 error("main: can't get current time: %s",
1084 pcap_strerror(errno));
1098 if (optarg[0] == '0' && optarg[1] == 0)
1099 error("Invalid adapter index");
1101 #ifdef HAVE_PCAP_FINDALLDEVS
1103 * If the argument is a number, treat it as
1104 * an index into the list of adapters, as
1105 * printed by "tcpdump -D".
1107 * This should be OK on UNIX systems, as interfaces
1108 * shouldn't have names that begin with digits.
1109 * It can be useful on Windows, where more than
1110 * one interface can have the same name.
1112 devnum = strtol(optarg, &end, 10);
1113 if (optarg != end && *end == '\0') {
1115 error("Invalid adapter index");
1117 if (pcap_findalldevs(&devpointer, ebuf) < 0)
1121 * Look for the devnum-th entry
1122 * in the list of devices
1126 i < devnum-1 && devpointer != NULL;
1127 i++, devpointer = devpointer->next)
1129 if (devpointer == NULL)
1130 error("Invalid adapter index");
1132 device = devpointer->name;
1135 #endif /* HAVE_PCAP_FINDALLDEVS */
1139 #ifdef HAVE_PCAP_CREATE
1143 #endif /* HAVE_PCAP_CREATE */
1145 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1147 jflag = pcap_tstamp_type_name_to_val(optarg);
1149 error("invalid time stamp type %s", optarg);
1160 * _IOLBF is the same as _IOFBF in Microsoft's C
1161 * libraries; the only alternative they offer
1164 * XXX - this should really be checking for MSVC++,
1165 * not WIN32, if, for example, MinGW has its own
1166 * C library that is more UNIX-compatible.
1168 setvbuf(stdout, NULL, _IONBF, 0);
1170 #ifdef HAVE_SETLINEBUF
1173 setvbuf(stdout, NULL, _IOLBF, 0);
1184 if (smiLoadModule(optarg) == 0) {
1185 error("could not load MIB module %s", optarg);
1189 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1190 program_name, optarg);
1191 (void)fprintf(stderr, "(no libsmi support)\n");
1196 /* TCP-MD5 shared secret */
1197 #ifndef HAVE_LIBCRYPTO
1198 warning("crypto code not compiled in");
1221 ++suppress_default_print;
1224 #ifdef HAVE_PCAP_SETDIRECTION
1226 if (strcasecmp(optarg, "in") == 0)
1228 else if (strcasecmp(optarg, "out") == 0)
1230 else if (strcasecmp(optarg, "inout") == 0)
1231 Qflag = PCAP_D_INOUT;
1233 error("unknown capture direction `%s'", optarg);
1235 #endif /* HAVE_PCAP_SETDIRECTION */
1246 snaplen = strtol(optarg, &end, 0);
1247 if (optarg == end || *end != '\0'
1248 || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
1249 error("invalid snaplen %s", optarg);
1250 else if (snaplen == 0)
1251 snaplen = MAXIMUM_SNAPLEN;
1263 if (strcasecmp(optarg, "vat") == 0)
1264 packettype = PT_VAT;
1265 else if (strcasecmp(optarg, "wb") == 0)
1267 else if (strcasecmp(optarg, "rpc") == 0)
1268 packettype = PT_RPC;
1269 else if (strcasecmp(optarg, "rtp") == 0)
1270 packettype = PT_RTP;
1271 else if (strcasecmp(optarg, "rtcp") == 0)
1272 packettype = PT_RTCP;
1273 else if (strcasecmp(optarg, "snmp") == 0)
1274 packettype = PT_SNMP;
1275 else if (strcasecmp(optarg, "cnfp") == 0)
1276 packettype = PT_CNFP;
1277 else if (strcasecmp(optarg, "tftp") == 0)
1278 packettype = PT_TFTP;
1279 else if (strcasecmp(optarg, "aodv") == 0)
1280 packettype = PT_AODV;
1281 else if (strcasecmp(optarg, "carp") == 0)
1282 packettype = PT_CARP;
1283 else if (strcasecmp(optarg, "radius") == 0)
1284 packettype = PT_RADIUS;
1285 else if (strcasecmp(optarg, "zmtp1") == 0)
1286 packettype = PT_ZMTP1;
1287 else if (strcasecmp(optarg, "vxlan") == 0)
1288 packettype = PT_VXLAN;
1289 else if (strcasecmp(optarg, "pgm") == 0)
1290 packettype = PT_PGM;
1291 else if (strcasecmp(optarg, "pgm_zmtp1") == 0)
1292 packettype = PT_PGM_ZMTP1;
1293 else if (strcasecmp(optarg, "lmp") == 0)
1294 packettype = PT_LMP;
1296 error("unknown packet type `%s'", optarg);
1303 #ifdef HAVE_PCAP_DUMP_FLUSH
1322 Wflag = atoi(optarg);
1324 error("invalid number of output files %s", optarg);
1325 WflagChars = getWflagChars(Wflag);
1330 ++suppress_default_print;
1335 ++suppress_default_print;
1339 gndo->ndo_dltname = optarg;
1341 pcap_datalink_name_to_val(gndo->ndo_dltname);
1342 if (gndo->ndo_dlt < 0)
1343 error("invalid data link type %s", gndo->ndo_dltname);
1346 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1349 /* Undocumented flag */
1350 #ifdef HAVE_PCAP_DEBUG
1351 extern int pcap_debug;
1361 zflag = strdup(optarg);
1365 username = strdup(optarg);
1369 gndo->ndo_packet_number = 1;
1372 case OPTION_VERSION:
1377 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1378 case OPTION_TSTAMP_PRECISION:
1379 gndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1380 if (gndo->ndo_tstamp_precision < 0)
1381 error("unsupported time stamp precision");
1391 #ifdef HAVE_PCAP_FINDALLDEVS
1393 show_devices_and_exit();
1398 case 0: /* Default */
1399 case 4: /* Default + Date*/
1400 thiszone = gmt2local(0);
1403 case 1: /* No time stamp */
1404 case 2: /* Unix timeval style */
1405 case 3: /* Microseconds since previous packet */
1406 case 5: /* Microseconds since first packet */
1409 default: /* Not supported */
1410 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1414 if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1415 error("-f can not be used with -V or -r");
1417 if (VFileName != NULL && RFileName != NULL)
1418 error("-V and -r are mutually exclusive.");
1421 /* if run as root, prepare for chrooting */
1422 if (getuid() == 0 || geteuid() == 0) {
1423 /* future extensibility for cmd-line arguments */
1425 chroot_dir = WITH_CHROOT;
1430 /* if run as root, prepare for dropping root privileges */
1431 if (getuid() == 0 || geteuid() == 0) {
1432 /* Run with '-Z root' to restore old behaviour */
1434 username = WITH_USER;
1438 if (RFileName != NULL || VFileName != NULL) {
1440 * If RFileName is non-null, it's the pathname of a
1441 * savefile to read. If VFileName is non-null, it's
1442 * the pathname of a file containing a list of pathnames
1443 * (one per line) of savefiles to read.
1445 * In either case, we're reading a savefile, not doing
1450 * We don't need network access, so relinquish any set-UID
1451 * or set-GID privileges we have (if any).
1453 * We do *not* want set-UID privileges when opening a
1454 * trace file, as that might let the user read other
1455 * people's trace files (especially if we're set-UID
1458 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1459 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1461 if (VFileName != NULL) {
1462 if (VFileName[0] == '-' && VFileName[1] == '\0')
1465 VFile = fopen(VFileName, "r");
1468 error("Unable to open file: %s\n", strerror(errno));
1470 ret = get_next_file(VFile, VFileLine);
1472 error("Nothing in %s\n", VFileName);
1473 RFileName = VFileLine;
1476 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1477 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1478 gndo->ndo_tstamp_precision, ebuf);
1480 pd = pcap_open_offline(RFileName, ebuf);
1485 #ifdef HAVE_CAPSICUM
1486 cap_rights_init(&rights, CAP_READ);
1487 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1489 error("unable to limit pcap descriptor");
1492 dlt = pcap_datalink(pd);
1493 dlt_name = pcap_datalink_val_to_name(dlt);
1494 if (dlt_name == NULL) {
1495 fprintf(stderr, "reading from file %s, link-type %u\n",
1499 "reading from file %s, link-type %s (%s)\n",
1500 RFileName, dlt_name,
1501 pcap_datalink_val_to_description(dlt));
1505 * We're doing a live capture.
1507 if (device == NULL) {
1508 device = pcap_lookupdev(ebuf);
1514 * Print a message to the standard error on Windows.
1515 * XXX - why do it here, with a different message?
1517 if(strlen(device) == 1) /* we assume that an ASCII string is always longer than 1 char */
1518 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1519 fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1523 fprintf(stderr, "%s: listening on %s\n", program_name, device);
1528 #ifdef HAVE_PCAP_CREATE
1529 pd = pcap_create(device, ebuf);
1532 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1534 show_tstamp_types_and_exit(device, pd);
1536 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1537 status = pcap_set_tstamp_precision(pd, gndo->ndo_tstamp_precision);
1539 error("%s: Can't set %ssecond time stamp precision: %s",
1541 tstamp_precision_to_string(gndo->ndo_tstamp_precision),
1542 pcap_statustostr(status));
1546 * Is this an interface that supports monitor mode?
1548 if (pcap_can_set_rfmon(pd) == 1)
1549 supports_monitor_mode = 1;
1551 supports_monitor_mode = 0;
1552 status = pcap_set_snaplen(pd, snaplen);
1554 error("%s: Can't set snapshot length: %s",
1555 device, pcap_statustostr(status));
1556 status = pcap_set_promisc(pd, !pflag);
1558 error("%s: Can't set promiscuous mode: %s",
1559 device, pcap_statustostr(status));
1561 status = pcap_set_rfmon(pd, 1);
1563 error("%s: Can't set monitor mode: %s",
1564 device, pcap_statustostr(status));
1566 status = pcap_set_timeout(pd, 1000);
1568 error("%s: pcap_set_timeout failed: %s",
1569 device, pcap_statustostr(status));
1571 status = pcap_set_buffer_size(pd, Bflag);
1573 error("%s: Can't set buffer size: %s",
1574 device, pcap_statustostr(status));
1576 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1578 status = pcap_set_tstamp_type(pd, jflag);
1580 error("%s: Can't set time stamp type: %s",
1581 device, pcap_statustostr(status));
1584 status = pcap_activate(pd);
1587 * pcap_activate() failed.
1589 cp = pcap_geterr(pd);
1590 if (status == PCAP_ERROR)
1592 else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1593 status == PCAP_ERROR_PERM_DENIED) &&
1595 error("%s: %s\n(%s)", device,
1596 pcap_statustostr(status), cp);
1598 else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1599 strncmp(device, "wlan", 4) == 0) {
1600 char parent[8], newdev[8];
1602 size_t s = sizeof(parent);
1604 snprintf(sysctl, sizeof(sysctl),
1605 "net.wlan.%d.%%parent", atoi(device + 4));
1606 sysctlbyname(sysctl, parent, &s, NULL, 0);
1607 strlcpy(newdev, device, sizeof(newdev));
1608 /* Suggest a new wlan device. */
1609 newdev[strlen(newdev)-1]++;
1610 error("%s is not a monitor mode VAP\n"
1611 "To create a new monitor mode VAP use:\n"
1612 " ifconfig %s create wlandev %s wlanmode "
1613 "monitor\nand use %s as the tcpdump "
1614 "interface", device, newdev, parent,
1619 error("%s: %s", device,
1620 pcap_statustostr(status));
1621 } else if (status > 0) {
1623 * pcap_activate() succeeded, but it's warning us
1624 * of a problem it had.
1626 cp = pcap_geterr(pd);
1627 if (status == PCAP_WARNING)
1629 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1631 warning("%s: %s\n(%s)", device,
1632 pcap_statustostr(status), cp);
1634 warning("%s: %s", device,
1635 pcap_statustostr(status));
1637 #ifdef HAVE_PCAP_SETDIRECTION
1639 status = pcap_setdirection(pd, Qflag);
1641 error("%s: pcap_setdirection() failed: %s",
1642 device, pcap_geterr(pd));
1644 #endif /* HAVE_PCAP_SETDIRECTION */
1647 pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1651 warning("%s", ebuf);
1652 #endif /* HAVE_PCAP_CREATE */
1654 * Let user own process after socket has been opened.
1657 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1658 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1660 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1662 if(pcap_setbuff(pd, Bflag)==-1){
1663 error("%s", pcap_geterr(pd));
1665 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1667 show_dlts_and_exit(device, pd);
1668 if (gndo->ndo_dlt >= 0) {
1669 #ifdef HAVE_PCAP_SET_DATALINK
1670 if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1671 error("%s", pcap_geterr(pd));
1674 * We don't actually support changing the
1675 * data link type, so we only let them
1676 * set it to what it already is.
1678 if (gndo->ndo_dlt != pcap_datalink(pd)) {
1679 error("%s is not one of the DLTs supported by this device\n",
1683 (void)fprintf(stderr, "%s: data link type %s\n",
1684 program_name, gndo->ndo_dltname);
1685 (void)fflush(stderr);
1687 i = pcap_snapshot(pd);
1689 warning("snaplen raised from %d to %d", snaplen, i);
1693 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1694 warning("foreign (-f) flag used but: %s", ebuf);
1700 cmdbuf = read_infile(infile);
1702 cmdbuf = copy_argv(&argv[optind]);
1704 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1705 error("%s", pcap_geterr(pd));
1707 bpf_dump(&fcode, dflag);
1713 #ifdef HAVE_CAPSICUM
1715 capdns = capdns_setup();
1716 #endif /* HAVE_CAPSICUM */
1718 init_addrtoname(gndo, localnet, netmask);
1722 (void)setsignal(SIGPIPE, cleanup);
1723 (void)setsignal(SIGTERM, cleanup);
1724 (void)setsignal(SIGINT, cleanup);
1726 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1727 (void)setsignal(SIGCHLD, child_cleanup);
1729 /* Cooperate with nohup(1) */
1731 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1732 (void)setsignal(SIGHUP, oldhandler);
1737 * If a user name was specified with "-Z", attempt to switch to
1738 * that user's UID. This would probably be used with sudo,
1739 * to allow tcpdump to be run in a special restricted
1740 * account (if you just want to allow users to open capture
1741 * devices, and can't just give users that permission,
1742 * you'd make tcpdump set-UID or set-GID).
1744 * Tcpdump doesn't necessarily write only to one savefile;
1745 * the general only way to allow a -Z instance to write to
1746 * savefiles as the user under whose UID it's run, rather
1747 * than as the user specified with -Z, would thus be to switch
1748 * to the original user ID before opening a capture file and
1749 * then switch back to the -Z user ID after opening the savefile.
1750 * Switching to the -Z user ID only after opening the first
1751 * savefile doesn't handle the general case.
1754 #ifdef HAVE_CAP_NG_H
1755 /* We are running as root and we will be writing to savefile */
1756 if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1758 /* Drop all capabilities from effective set */
1759 capng_clear(CAPNG_EFFECTIVE);
1760 /* Add capabilities we will need*/
1761 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1762 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1763 capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1765 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1766 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1767 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1769 capng_apply(CAPNG_SELECT_BOTH);
1772 #endif /* HAVE_CAP_NG_H */
1774 if (getuid() == 0 || geteuid() == 0) {
1775 if (username || chroot_dir)
1776 droproot(username, chroot_dir);
1781 if (pcap_setfilter(pd, &fcode) < 0)
1782 error("%s", pcap_geterr(pd));
1783 #ifdef HAVE_CAPSICUM
1784 if (RFileName == NULL && VFileName == NULL) {
1785 static const unsigned long cmds[] = { BIOCGSTATS };
1787 cap_rights_init(&rights, CAP_IOCTL, CAP_READ);
1788 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1790 error("unable to limit pcap descriptor");
1792 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1793 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1794 error("unable to limit ioctls on pcap descriptor");
1800 /* Do not exceed the default PATH_MAX for files. */
1801 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1803 if (dumpinfo.CurrentFileName == NULL)
1804 error("malloc of dumpinfo.CurrentFileName");
1806 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1808 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1810 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1812 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1813 #ifdef HAVE_CAP_NG_H
1814 /* Give up capabilities, clear Effective set */
1815 capng_clear(CAPNG_EFFECTIVE);
1818 error("%s", pcap_geterr(pd));
1819 #ifdef HAVE_CAPSICUM
1820 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1821 if (cap_rights_limit(fileno(pcap_dump_file(p)), &rights) < 0 &&
1823 error("unable to limit dump descriptor");
1826 if (Cflag != 0 || Gflag != 0) {
1827 #ifdef HAVE_CAPSICUM
1828 dumpinfo.WFileName = strdup(basename(WFileName));
1829 dumpinfo.dirfd = open(dirname(WFileName),
1830 O_DIRECTORY | O_RDONLY);
1831 if (dumpinfo.dirfd < 0) {
1832 error("unable to open directory %s",
1833 dirname(WFileName));
1835 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1836 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1837 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1839 error("unable to limit directory rights");
1841 #else /* !HAVE_CAPSICUM */
1842 dumpinfo.WFileName = WFileName;
1844 callback = dump_packet_and_trunc;
1847 pcap_userdata = (u_char *)&dumpinfo;
1849 callback = dump_packet;
1850 pcap_userdata = (u_char *)p;
1852 #ifdef HAVE_PCAP_DUMP_FLUSH
1857 type = pcap_datalink(pd);
1858 printinfo = get_print_info(type);
1859 callback = print_packet;
1860 pcap_userdata = (u_char *)&printinfo;
1863 #ifdef SIGNAL_REQ_INFO
1865 * We can't get statistics when reading from a file rather
1866 * than capturing from a device.
1868 if (RFileName == NULL)
1869 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1872 if (vflag > 0 && WFileName) {
1874 * When capturing to a file, "-v" means tcpdump should,
1875 * every 10 secodns, "v"erbosely report the number of
1878 #ifdef USE_WIN32_MM_TIMER
1879 /* call verbose_stats_dump() each 1000 +/-100msec */
1880 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1881 setvbuf(stderr, NULL, _IONBF, 0);
1882 #elif defined(HAVE_ALARM)
1883 (void)setsignal(SIGALRM, verbose_stats_dump);
1889 if (RFileName == NULL) {
1891 * Live capture (if -V was specified, we set RFileName
1892 * to a file from the -V file). Print a message to
1893 * the standard error on UN*X.
1895 if (!vflag && !WFileName) {
1896 (void)fprintf(stderr,
1897 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1900 (void)fprintf(stderr, "%s: ", program_name);
1901 dlt = pcap_datalink(pd);
1902 dlt_name = pcap_datalink_val_to_name(dlt);
1903 if (dlt_name == NULL) {
1904 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1905 device, dlt, snaplen);
1907 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1909 pcap_datalink_val_to_description(dlt), snaplen);
1911 (void)fflush(stderr);
1916 cansandbox = (VFileName == NULL && zflag == NULL);
1917 #ifdef HAVE_CAPSICUM
1918 cansandbox = (cansandbox && (nflag || capdns != NULL));
1920 cansandbox = (cansandbox && nflag);
1922 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1923 error("unable to enter the capability mode");
1924 #endif /* __FreeBSD__ */
1927 status = pcap_loop(pd, cnt, callback, pcap_userdata);
1928 if (WFileName == NULL) {
1930 * We're printing packets. Flush the printed output,
1931 * so it doesn't get intermingled with error output.
1935 * We got interrupted, so perhaps we didn't
1936 * manage to finish a line we were printing.
1937 * Print an extra newline, just in case.
1941 (void)fflush(stdout);
1945 * We got interrupted. If we are reading multiple
1946 * files (via -V) set these so that we stop.
1955 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
1956 program_name, pcap_geterr(pd));
1958 if (RFileName == NULL) {
1960 * We're doing a live capture. Report the capture
1966 if (VFileName != NULL) {
1967 ret = get_next_file(VFile, VFileLine);
1969 RFileName = VFileLine;
1970 pd = pcap_open_offline(RFileName, ebuf);
1973 #ifdef HAVE_CAPSICUM
1974 cap_rights_init(&rights, CAP_READ);
1975 if (cap_rights_limit(fileno(pcap_file(pd)),
1976 &rights) < 0 && errno != ENOSYS) {
1977 error("unable to limit pcap descriptor");
1980 new_dlt = pcap_datalink(pd);
1981 if (WFileName && new_dlt != dlt)
1982 error("%s: new dlt does not match original", RFileName);
1983 printinfo = get_print_info(new_dlt);
1984 dlt_name = pcap_datalink_val_to_name(new_dlt);
1985 if (dlt_name == NULL) {
1986 fprintf(stderr, "reading from file %s, link-type %u\n",
1987 RFileName, new_dlt);
1990 "reading from file %s, link-type %s (%s)\n",
1991 RFileName, dlt_name,
1992 pcap_datalink_val_to_description(new_dlt));
1994 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1995 error("%s", pcap_geterr(pd));
1996 if (pcap_setfilter(pd, &fcode) < 0)
1997 error("%s", pcap_geterr(pd));
2001 while (ret != NULL);
2004 exit(status == -1 ? 1 : 0);
2007 /* make a clean exit on interrupts */
2009 cleanup(int signo _U_)
2011 #ifdef USE_WIN32_MM_TIMER
2013 timeKillEvent(timer_id);
2015 #elif defined(HAVE_ALARM)
2019 #ifdef HAVE_PCAP_BREAKLOOP
2021 * We have "pcap_breakloop()"; use it, so that we do as little
2022 * as possible in the signal handler (it's probably not safe
2023 * to do anything with standard I/O streams in a signal handler -
2024 * the ANSI C standard doesn't say it is).
2029 * We don't have "pcap_breakloop()"; this isn't safe, but
2030 * it's the best we can do. Print the summary if we're
2031 * not reading from a savefile - i.e., if we're doing a
2032 * live capture - and exit.
2034 if (pd != NULL && pcap_file(pd) == NULL) {
2036 * We got interrupted, so perhaps we didn't
2037 * manage to finish a line we were printing.
2038 * Print an extra newline, just in case.
2041 (void)fflush(stdout);
2049 On windows, we do not use a fork, so we do not care less about
2050 waiting a child processes to die
2052 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2054 child_cleanup(int signo _U_)
2058 #endif /* HAVE_FORK && HAVE_VFORK */
2061 info(register int verbose)
2063 struct pcap_stat stat;
2066 * Older versions of libpcap didn't set ps_ifdrop on some
2067 * platforms; initialize it to 0 to handle that.
2070 if (pcap_stats(pd, &stat) < 0) {
2071 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2077 fprintf(stderr, "%s: ", program_name);
2079 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2080 PLURAL_SUFFIX(packets_captured));
2082 fputs(", ", stderr);
2085 (void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
2086 PLURAL_SUFFIX(stat.ps_recv));
2088 fputs(", ", stderr);
2091 (void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
2092 PLURAL_SUFFIX(stat.ps_drop));
2093 if (stat.ps_ifdrop != 0) {
2095 fputs(", ", stderr);
2098 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2099 stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
2105 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2107 compress_savefile(const char *filename)
2116 * Set to lowest priority so that this doesn't disturb the capture
2119 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2121 setpriority(PRIO_PROCESS, 0, 19);
2123 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2125 "compress_savefile:execlp(%s, %s): %s\n",
2135 #else /* HAVE_FORK && HAVE_VFORK */
2137 compress_savefile(const char *filename)
2140 "compress_savefile failed. Functionality not implemented under your system\n");
2142 #endif /* HAVE_FORK && HAVE_VFORK */
2145 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2147 struct dump_info *dump_info;
2148 #ifdef HAVE_CAPSICUM
2149 cap_rights_t rights;
2156 dump_info = (struct dump_info *)user;
2159 * XXX - this won't force the file to rotate on the specified time
2160 * boundary, but it will rotate on the first packet received after the
2161 * specified Gflag number of seconds. Note: if a Gflag time boundary
2162 * and a Cflag size boundary coincide, the time rotation will occur
2163 * first thereby cancelling the Cflag boundary (since the file should
2167 /* Check if it is time to rotate */
2170 /* Get the current time */
2171 if ((t = time(NULL)) == (time_t)-1) {
2172 error("dump_and_trunc_packet: can't get current_time: %s",
2173 pcap_strerror(errno));
2177 /* If the time is greater than the specified window, rotate */
2178 if (t - Gflag_time >= Gflag) {
2179 #ifdef HAVE_CAPSICUM
2184 /* Update the Gflag_time */
2186 /* Update Gflag_count */
2189 * Close the current file and open a new one.
2191 pcap_dump_close(dump_info->p);
2194 * Compress the file we just closed, if the user asked for it
2197 compress_savefile(dump_info->CurrentFileName);
2200 * Check to see if we've exceeded the Wflag (when
2203 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2204 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2209 if (dump_info->CurrentFileName != NULL)
2210 free(dump_info->CurrentFileName);
2211 /* Allocate space for max filename + \0. */
2212 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2213 if (dump_info->CurrentFileName == NULL)
2214 error("dump_packet_and_trunc: malloc");
2216 * Gflag was set otherwise we wouldn't be here. Reset the count
2217 * so multiple files would end with 1,2,3 in the filename.
2218 * The counting is handled with the -C flow after this.
2223 * This is always the first file in the Cflag
2225 * We also don't need numbering if Cflag is not set.
2228 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2231 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2233 #ifdef HAVE_CAP_NG_H
2234 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2235 capng_apply(CAPNG_EFFECTIVE);
2236 #endif /* HAVE_CAP_NG_H */
2237 #ifdef HAVE_CAPSICUM
2238 fd = openat(dump_info->dirfd,
2239 dump_info->CurrentFileName,
2240 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2242 error("unable to open file %s",
2243 dump_info->CurrentFileName);
2245 fp = fdopen(fd, "w");
2247 error("unable to fdopen file %s",
2248 dump_info->CurrentFileName);
2250 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2251 #else /* !HAVE_CAPSICUM */
2252 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2254 #ifdef HAVE_CAP_NG_H
2255 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2256 capng_apply(CAPNG_EFFECTIVE);
2257 #endif /* HAVE_CAP_NG_H */
2258 if (dump_info->p == NULL)
2259 error("%s", pcap_geterr(pd));
2260 #ifdef HAVE_CAPSICUM
2261 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2262 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2263 &rights) < 0 && errno != ENOSYS) {
2264 error("unable to limit dump descriptor");
2271 * XXX - this won't prevent capture files from getting
2272 * larger than Cflag - the last packet written to the
2273 * file could put it over Cflag.
2275 if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
2276 #ifdef HAVE_CAPSICUM
2282 * Close the current file and open a new one.
2284 pcap_dump_close(dump_info->p);
2287 * Compress the file we just closed, if the user asked for it
2290 compress_savefile(dump_info->CurrentFileName);
2294 if (Cflag_count >= Wflag)
2297 if (dump_info->CurrentFileName != NULL)
2298 free(dump_info->CurrentFileName);
2299 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2300 if (dump_info->CurrentFileName == NULL)
2301 error("dump_packet_and_trunc: malloc");
2302 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2303 #ifdef HAVE_CAPSICUM
2304 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2305 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2307 error("unable to open file %s",
2308 dump_info->CurrentFileName);
2310 fp = fdopen(fd, "w");
2312 error("unable to fdopen file %s",
2313 dump_info->CurrentFileName);
2315 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2316 #else /* !HAVE_CAPSICUM */
2317 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2319 if (dump_info->p == NULL)
2320 error("%s", pcap_geterr(pd));
2321 #ifdef HAVE_CAPSICUM
2322 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2323 if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2324 &rights) < 0 && errno != ENOSYS) {
2325 error("unable to limit dump descriptor");
2330 pcap_dump((u_char *)dump_info->p, h, sp);
2331 #ifdef HAVE_PCAP_DUMP_FLUSH
2333 pcap_dump_flush(dump_info->p);
2342 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2348 pcap_dump(user, h, sp);
2349 #ifdef HAVE_PCAP_DUMP_FLUSH
2351 pcap_dump_flush((pcap_dumper_t *)user);
2360 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2362 struct print_info *print_info;
2364 netdissect_options *ndo;
2370 print_info = (struct print_info *)user;
2371 ndo = print_info->ndo;
2373 if(ndo->ndo_packet_number)
2374 ND_PRINT((ndo, "%5u ", packets_captured));
2376 ts_print(ndo, &h->ts);
2379 * Some printers want to check that they're not walking off the
2380 * end of the packet.
2381 * Rather than pass it all the way down, we set this global.
2383 ndo->ndo_snapend = sp + h->caplen;
2385 if(print_info->ndo_type) {
2386 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2388 hdrlen = (*print_info->p.printer)(h, sp);
2391 if (ndo->ndo_Xflag) {
2393 * Print the raw packet data in hex and ASCII.
2395 if (ndo->ndo_Xflag > 1) {
2397 * Include the link-layer header.
2399 hex_and_ascii_print(ndo, "\n\t", sp, h->caplen);
2402 * Don't include the link-layer header - and if
2403 * we have nothing past the link-layer header,
2406 if (h->caplen > hdrlen)
2407 hex_and_ascii_print(ndo, "\n\t", sp + hdrlen,
2408 h->caplen - hdrlen);
2410 } else if (ndo->ndo_xflag) {
2412 * Print the raw packet data in hex.
2414 if (ndo->ndo_xflag > 1) {
2416 * Include the link-layer header.
2418 hex_print(ndo, "\n\t", sp, h->caplen);
2421 * Don't include the link-layer header - and if
2422 * we have nothing past the link-layer header,
2425 if (h->caplen > hdrlen)
2426 hex_print(ndo, "\n\t", sp + hdrlen,
2427 h->caplen - hdrlen);
2429 } else if (ndo->ndo_Aflag) {
2431 * Print the raw packet data in ASCII.
2433 if (ndo->ndo_Aflag > 1) {
2435 * Include the link-layer header.
2437 ascii_print(ndo, sp, h->caplen);
2440 * Don't include the link-layer header - and if
2441 * we have nothing past the link-layer header,
2444 if (h->caplen > hdrlen)
2445 ascii_print(ndo, sp + hdrlen, h->caplen - hdrlen);
2458 * XXX - there should really be libpcap calls to get the version
2459 * number as a string (the string would be generated from #defines
2460 * at run time, so that it's not generated from string constants
2461 * in the library, as, on many UNIX systems, those constants would
2462 * be statically linked into the application executable image, and
2463 * would thus reflect the version of libpcap on the system on
2464 * which the application was *linked*, not the system on which it's
2467 * That routine should be documented, unlike the "version[]"
2468 * string, so that UNIX vendors providing their own libpcaps
2469 * don't omit it (as a couple of vendors have...).
2471 * Packet.dll should perhaps also export a routine to return the
2472 * version number of the Packet.dll code, to supply the
2473 * "Wpcap_version" information on Windows.
2475 char WDversion[]="current-git.tcpdump.org";
2476 #if !defined(HAVE_GENERATED_VERSION)
2477 char version[]="current-git.tcpdump.org";
2479 char pcap_version[]="current-git.tcpdump.org";
2480 char Wpcap_version[]="3.1";
2484 * By default, print the specified data out in hex and ASCII.
2487 ndo_default_print(netdissect_options *ndo, const u_char *bp, u_int length)
2489 hex_and_ascii_print(ndo, "\n\t", bp, length); /* pass on lf and identation string */
2493 default_print(const u_char *bp, u_int length)
2495 ndo_default_print(gndo, bp, length);
2498 #ifdef SIGNAL_REQ_INFO
2499 RETSIGTYPE requestinfo(int signo _U_)
2509 * Called once each second in verbose mode while dumping to file
2511 #ifdef USE_WIN32_MM_TIMER
2512 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2513 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2515 struct pcap_stat stat;
2517 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2518 fprintf(stderr, "Got %u\r", packets_captured);
2520 #elif defined(HAVE_ALARM)
2521 static void verbose_stats_dump(int sig _U_)
2523 struct pcap_stat stat;
2525 if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2526 fprintf(stderr, "Got %u\r", packets_captured);
2531 USES_APPLE_DEPRECATED_API
2535 extern char version[];
2536 #ifndef HAVE_PCAP_LIB_VERSION
2537 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2538 extern char pcap_version[];
2539 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2540 static char pcap_version[] = "unknown";
2541 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2542 #endif /* HAVE_PCAP_LIB_VERSION */
2544 #ifdef HAVE_PCAP_LIB_VERSION
2546 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2548 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2550 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2551 #else /* HAVE_PCAP_LIB_VERSION */
2553 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2554 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2556 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2557 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2559 #endif /* HAVE_PCAP_LIB_VERSION */
2561 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2562 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2566 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2575 (void)fprintf(stderr,
2576 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2577 (void)fprintf(stderr,
2578 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2579 (void)fprintf(stderr,
2580 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2581 #ifdef HAVE_PCAP_SETDIRECTION
2582 (void)fprintf(stderr,
2583 "\t\t[ -Q in|out|inout ]\n");
2585 (void)fprintf(stderr,
2586 "\t\t[ -r file ] [ -s snaplen ] ");
2587 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2588 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2589 (void)fprintf(stderr,
2592 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2593 (void)fprintf(stderr,
2594 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2595 (void)fprintf(stderr,
2596 "\t\t[ -Z user ] [ expression ]\n");
2603 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2607 (void)fprintf(stderr, "%s: ", program_name);
2609 (void)vfprintf(stderr, fmt, ap);
2613 if (fmt[-1] != '\n')
2614 (void)fputc('\n', stderr);
2622 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2626 (void)fprintf(stderr, "%s: WARNING: ", program_name);
2628 (void)vfprintf(stderr, fmt, ap);
2632 if (fmt[-1] != '\n')
2633 (void)fputc('\n', stderr);
2638 * c-style: whitesmith