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";
35 * tcpdump - dump traffic on a network
37 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
38 * Mercilessly hacked and occasionally improved since then via the
39 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
47 * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
48 * 0.8. That means it has pcap_findalldevs() but the header doesn't
49 * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
51 #ifdef HAVE_PCAP_FINDALLDEVS
52 #ifndef HAVE_PCAP_IF_T
53 #undef HAVE_PCAP_FINDALLDEVS
57 #include <netdissect-stdinc.h>
66 #include <openssl/crypto.h>
69 #ifdef HAVE_GETOPT_LONG
72 #include "getopt_long.h"
74 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
75 * to compile if <pcap.h> has already been included; including the headers
76 * in the opposite order works fine.
79 #include <sys/capsicum.h>
81 #include <sys/ioccom.h>
85 #include <libcasper.h>
86 #include <casper/cap_dns.h>
87 #endif /* HAVE_CASPER */
88 #endif /* HAVE_CAPSICUM */
98 #include <sys/resource.h>
103 /* capabilities convenience library */
104 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
105 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
106 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
108 #ifdef HAVE_LIBCAP_NG
112 #undef HAVE_LIBCAP_NG
113 #endif /* HAVE_CAP_NG_H */
114 #endif /* HAVE_LIBCAP_NG */
116 #include "netdissect.h"
117 #include "interface.h"
118 #include "addrtoname.h"
120 #include "setsignal.h"
121 #include "gmt2local.h"
122 #include "pcap-missing.h"
123 #include "ascii_strcasecmp.h"
128 #define PATH_MAX 1024
132 #define SIGNAL_REQ_INFO SIGINFO
134 #define SIGNAL_REQ_INFO SIGUSR1
137 static int Bflag; /* buffer size */
138 static long Cflag; /* rotate dump files after this many bytes */
139 static int Cflag_count; /* Keep track of which file number we're writing */
140 static int Dflag; /* list available devices and exit */
142 * This is exported because, in some versions of libpcap, if libpcap
143 * is built with optimizer debugging code (which is *NOT* the default
144 * configuration!), the library *imports*(!) a variable named dflag,
145 * under the expectation that tcpdump is exporting it, to govern
146 * how much debugging information to print when optimizing
147 * the generated BPF code.
149 * This is a horrible hack; newer versions of libpcap don't import
150 * dflag but, instead, *if* built with optimizer debugging code,
151 * *export* a routine to set that flag.
153 int dflag; /* print filter code */
154 static int Gflag; /* rotate dump files after this many seconds */
155 static int Gflag_count; /* number of files created with Gflag rotation */
156 static time_t Gflag_time; /* The last time_t the dump file was rotated. */
157 static int Lflag; /* list available data link types and exit */
158 static int Iflag; /* rfmon (monitor) mode */
159 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
160 static int Jflag; /* list available time stamp types */
162 static int jflag = -1; /* packet time stamp source */
163 static int pflag; /* don't go promiscuous */
164 #ifdef HAVE_PCAP_SETDIRECTION
165 static int Qflag = -1; /* restrict captured packet by send/receive direction */
167 static int Uflag; /* "unbuffered" output of dump files */
168 static int Wflag; /* recycle output files after this number of files */
169 static int WflagChars;
170 static char *zflag = NULL; /* compress each savefile using a specified command (like gzip or bzip2) */
171 static int immediate_mode;
173 static int infodelay;
174 static int infoprint;
179 cap_channel_t *capdns;
183 static void error(FORMAT_STRING(const char *), ...) NORETURN PRINTFLIKE(1, 2);
184 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
185 static void exit_tcpdump(int) NORETURN;
186 static RETSIGTYPE cleanup(int);
187 static RETSIGTYPE child_cleanup(int);
188 static void print_version(void);
189 static void print_usage(void);
190 static void show_tstamp_types_and_exit(pcap_t *, const char *device) NORETURN;
191 static void show_dlts_and_exit(pcap_t *, const char *device) NORETURN;
192 #ifdef HAVE_PCAP_FINDALLDEVS
193 static void show_devices_and_exit (void) NORETURN;
196 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
197 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
198 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
199 static void droproot(const char *, const char *);
201 #ifdef SIGNAL_REQ_INFO
202 RETSIGTYPE requestinfo(int);
205 #if defined(USE_WIN32_MM_TIMER)
206 #include <MMsystem.h>
207 static UINT timer_id;
208 static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
209 #elif defined(HAVE_ALARM)
210 static void verbose_stats_dump(int sig);
213 static void info(int);
214 static u_int packets_captured;
216 #ifdef HAVE_PCAP_FINDALLDEVS
217 static const struct tok status_flags[] = {
219 { PCAP_IF_UP, "Up" },
221 #ifdef PCAP_IF_RUNNING
222 { PCAP_IF_RUNNING, "Running" },
224 { PCAP_IF_LOOPBACK, "Loopback" },
231 static int supports_monitor_mode;
239 char *CurrentFileName;
247 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
249 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
250 * by any libpcap header, because it's a special hack, only available if
251 * libpcap was configured to include it, and only intended for use by
252 * libpcap developers trying to debug the parser for filter expressions).
255 __declspec(dllimport)
259 void pcap_set_parser_debug(int);
260 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
262 * We don't have pcap_set_parser_debug() in libpcap, but we do have
263 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
264 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
267 pcap_set_parser_debug(int value)
269 #ifdef HAVE_PCAP_DEBUG
270 extern int pcap_debug;
273 #else /* HAVE_PCAP_DEBUG */
277 #endif /* HAVE_PCAP_DEBUG */
280 #define HAVE_PCAP_SET_PARSER_DEBUG
283 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
285 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
286 * by any libpcap header, because it's a special hack, only available if
287 * libpcap was configured to include it, and only intended for use by
288 * libpcap developers trying to debug the optimizer for filter expressions).
291 __declspec(dllimport)
295 void pcap_set_optimizer_debug(int);
300 error(const char *fmt, ...)
304 (void)fprintf(stderr, "%s: ", program_name);
306 (void)vfprintf(stderr, fmt, ap);
311 (void)fputc('\n', stderr);
319 warning(const char *fmt, ...)
323 (void)fprintf(stderr, "%s: WARNING: ", program_name);
325 (void)vfprintf(stderr, fmt, ap);
330 (void)fputc('\n', stderr);
335 exit_tcpdump(int status)
341 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
343 show_tstamp_types_and_exit(pcap_t *pc, const char *device)
346 int *tstamp_types = 0;
347 const char *tstamp_type_name;
350 n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types);
351 if (n_tstamp_types < 0)
352 error("%s", pcap_geterr(pc));
354 if (n_tstamp_types == 0) {
355 fprintf(stderr, "Time stamp type cannot be set for %s\n",
359 fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
361 for (i = 0; i < n_tstamp_types; i++) {
362 tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
363 if (tstamp_type_name != NULL) {
364 (void) fprintf(stderr, " %s (%s)\n", tstamp_type_name,
365 pcap_tstamp_type_val_to_description(tstamp_types[i]));
367 (void) fprintf(stderr, " %d\n", tstamp_types[i]);
370 pcap_free_tstamp_types(tstamp_types);
376 show_dlts_and_exit(pcap_t *pc, const char *device)
380 const char *dlt_name;
382 n_dlts = pcap_list_datalinks(pc, &dlts);
384 error("%s", pcap_geterr(pc));
385 else if (n_dlts == 0 || !dlts)
386 error("No data link types.");
389 * If the interface is known to support monitor mode, indicate
390 * whether these are the data link types available when not in
391 * monitor mode, if -I wasn't specified, or when in monitor mode,
392 * when -I was specified (the link-layer types available in
393 * monitor mode might be different from the ones available when
394 * not in monitor mode).
396 if (supports_monitor_mode)
397 (void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
399 Iflag ? "when in monitor mode" : "when not in monitor mode");
401 (void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
404 for (i = 0; i < n_dlts; i++) {
405 dlt_name = pcap_datalink_val_to_name(dlts[i]);
406 if (dlt_name != NULL) {
407 (void) fprintf(stderr, " %s (%s)", dlt_name,
408 pcap_datalink_val_to_description(dlts[i]));
411 * OK, does tcpdump handle that type?
413 if (!has_printer(dlts[i]))
414 (void) fprintf(stderr, " (printing not supported)");
415 fprintf(stderr, "\n");
417 (void) fprintf(stderr, " DLT %d (printing not supported)\n",
421 #ifdef HAVE_PCAP_FREE_DATALINKS
422 pcap_free_datalinks(dlts);
427 #ifdef HAVE_PCAP_FINDALLDEVS
429 show_devices_and_exit (void)
431 pcap_if_t *dev, *devlist;
432 char ebuf[PCAP_ERRBUF_SIZE];
435 if (pcap_findalldevs(&devlist, ebuf) < 0)
437 for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
438 printf("%d.%s", i+1, dev->name);
439 if (dev->description != NULL)
440 printf(" (%s)", dev->description);
442 printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
445 pcap_freealldevs(devlist);
448 #endif /* HAVE_PCAP_FINDALLDEVS */
453 * Note that there we use all letters for short options except for g, k,
454 * o, and P, and those are used by other versions of tcpdump, and we should
455 * only use them for the same purposes that the other versions of tcpdump
458 * OS X tcpdump uses -g to force non--v output for IP to be on one
459 * line, making it more "g"repable;
461 * OS X tcpdump uses -k to specify that packet comments in pcap-ng files
464 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
465 * for hosts sending TCP SYN packets;
467 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
470 * OS X tcpdump also uses -Q to specify expressions that match packet
471 * metadata, including but not limited to the packet direction.
472 * The expression syntax is different from a simple "in|out|inout",
473 * and those expressions aren't accepted by OS X tcpdump, but the
474 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
475 * "inout" = "dir=in or dir=out", and the parser could conceivably
476 * special-case "in", "out", and "inout" as expressions for backwards
477 * compatibility, so all is not (yet) lost.
481 * Set up flags that might or might not be supported depending on the
482 * version of libpcap we're using.
484 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
486 #define B_FLAG_USAGE " [ -B size ]"
487 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
490 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
492 #ifdef HAVE_PCAP_CREATE
494 #else /* HAVE_PCAP_CREATE */
496 #endif /* HAVE_PCAP_CREATE */
498 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
500 #define j_FLAG_USAGE " [ -j tstamptype ]"
502 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
506 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
508 #ifdef HAVE_PCAP_FINDALLDEVS
514 #ifdef HAVE_PCAP_DUMP_FLUSH
520 #ifdef HAVE_PCAP_SETDIRECTION
526 #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
531 * We do not currently have long options corresponding to all short
532 * options; we should probably pick appropriate option names for them.
534 * However, the short options where the number of times the option is
535 * specified matters, such as -v and -d and -t, should probably not
536 * just map to a long option, as saying
538 * tcpdump --verbose --verbose
540 * doesn't make sense; it should be --verbosity={N} or something such
543 * For long options with no corresponding short options, we define values
544 * outside the range of ASCII graphic characters, make that the last
545 * component of the entry for the long option, and have a case for that
546 * option in the switch statement.
548 #define OPTION_VERSION 128
549 #define OPTION_TSTAMP_PRECISION 129
550 #define OPTION_IMMEDIATE_MODE 130
552 static const struct option longopts[] = {
553 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
554 { "buffer-size", required_argument, NULL, 'B' },
556 { "list-interfaces", no_argument, NULL, 'D' },
557 { "help", no_argument, NULL, 'h' },
558 { "interface", required_argument, NULL, 'i' },
559 #ifdef HAVE_PCAP_CREATE
560 { "monitor-mode", no_argument, NULL, 'I' },
562 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
563 { "time-stamp-type", required_argument, NULL, 'j' },
564 { "list-time-stamp-types", no_argument, NULL, 'J' },
566 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
567 { "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
569 { "dont-verify-checksums", no_argument, NULL, 'K' },
570 { "list-data-link-types", no_argument, NULL, 'L' },
571 { "no-optimize", no_argument, NULL, 'O' },
572 { "no-promiscuous-mode", no_argument, NULL, 'p' },
573 #ifdef HAVE_PCAP_SETDIRECTION
574 { "direction", required_argument, NULL, 'Q' },
576 { "snapshot-length", required_argument, NULL, 's' },
577 { "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
578 #ifdef HAVE_PCAP_DUMP_FLUSH
579 { "packet-buffered", no_argument, NULL, 'U' },
581 { "linktype", required_argument, NULL, 'y' },
582 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
583 { "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
585 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
586 { "debug-filter-parser", no_argument, NULL, 'Y' },
588 { "relinquish-privileges", required_argument, NULL, 'Z' },
589 { "number", no_argument, NULL, '#' },
590 { "version", no_argument, NULL, OPTION_VERSION },
595 /* Drop root privileges and chroot if necessary */
597 droproot(const char *username, const char *chroot_dir)
599 struct passwd *pw = NULL;
601 if (chroot_dir && !username) {
602 fprintf(stderr, "%s: Chroot without dropping root is insecure\n",
607 pw = getpwnam(username);
610 if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
611 fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
612 program_name, chroot_dir, pcap_strerror(errno));
616 #ifdef HAVE_LIBCAP_NG
618 int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
620 error("capng_change_id(): return %d\n", ret);
622 fprintf(stderr, "dropped privs to %s\n", username);
625 if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
626 setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
627 fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
628 program_name, username,
629 (unsigned long)pw->pw_uid,
630 (unsigned long)pw->pw_gid,
631 pcap_strerror(errno));
635 fprintf(stderr, "dropped privs to %s\n", username);
637 #endif /* HAVE_LIBCAP_NG */
640 fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
641 program_name, username);
644 #ifdef HAVE_LIBCAP_NG
645 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
648 CAPNG_EFFECTIVE | CAPNG_PERMITTED,
653 capng_apply(CAPNG_SELECT_BOTH);
654 #endif /* HAVE_LIBCAP_NG */
675 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
677 char *filename = malloc(PATH_MAX + 1);
678 if (filename == NULL)
679 error("Makefilename: malloc");
681 /* Process with strftime if Gflag is set. */
685 /* Convert Gflag_time to a usable format */
686 if ((local_tm = localtime(&Gflag_time)) == NULL) {
687 error("MakeTimedFilename: localtime");
690 /* There's no good way to detect an error in strftime since a return
691 * value of 0 isn't necessarily failure.
693 strftime(filename, PATH_MAX, orig_name, local_tm);
695 strncpy(filename, orig_name, PATH_MAX);
698 if (cnt == 0 && max_chars == 0)
699 strncpy(buffer, filename, PATH_MAX + 1);
701 if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
702 /* Report an error if the filename is too large */
703 error("too many output files or filename is too long (> %d)", PATH_MAX);
708 get_next_file(FILE *VFile, char *ptr)
713 ret = fgets(ptr, PATH_MAX, VFile);
718 if (len > 0 && ptr[len - 1] == '\n')
725 static cap_channel_t *
728 cap_channel_t *capcas, *capdnsloc;
729 const char *types[1];
734 error("unable to create casper process");
735 capdnsloc = cap_service_open(capcas, "system.dns");
736 /* Casper capability no longer needed. */
738 if (capdnsloc == NULL)
739 error("unable to open system.dns service");
740 /* Limit system.dns to reverse DNS lookups. */
741 types[0] = "ADDR2NAME";
742 if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
743 error("unable to limit access to system.dns service");
744 families[0] = AF_INET;
745 families[1] = AF_INET6;
746 if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
747 error("unable to limit access to system.dns service");
751 #endif /* HAVE_CASPER */
753 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
755 tstamp_precision_from_string(const char *precision)
757 if (strncmp(precision, "nano", strlen("nano")) == 0)
758 return PCAP_TSTAMP_PRECISION_NANO;
760 if (strncmp(precision, "micro", strlen("micro")) == 0)
761 return PCAP_TSTAMP_PRECISION_MICRO;
767 tstamp_precision_to_string(int precision)
771 case PCAP_TSTAMP_PRECISION_MICRO:
774 case PCAP_TSTAMP_PRECISION_NANO:
785 * Ensure that, on a dump file's descriptor, we have all the rights
786 * necessary to make the standard I/O library work with an fdopen()ed
787 * FILE * from that descriptor.
789 * A long time ago, in a galaxy far far away, AT&T decided that, instead
790 * of providing separate APIs for getting and setting the FD_ flags on a
791 * descriptor, getting and setting the O_ flags on a descriptor, and
792 * locking files, they'd throw them all into a kitchen-sink fcntl() call
793 * along the lines of ioctl(), the fact that ioctl() operations are
794 * largely specific to particular character devices but fcntl() operations
795 * are either generic to all descriptors or generic to all descriptors for
796 * regular files nonwithstanding.
798 * The Capsicum people decided that fine-grained control of descriptor
799 * operations was required, so that you need to grant permission for
800 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
801 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
802 * collection of things, so there are *individual* fcntls for which
803 * permission needs to be granted.
805 * The FreeBSD standard I/O people implemented some optimizations that
806 * requires that the standard I/O routines be able to determine whether
807 * the descriptor for the FILE * is open append-only or not; as that
808 * descriptor could have come from an open() rather than an fopen(),
809 * that requires that it be able to do an F_GETFL fcntl() to read
812 * Tcpdump uses ftell() to determine how much data has been written
813 * to a file in order to, when used with -C, determine when it's time
814 * to rotate capture files. ftell() therefore needs to do an lseek()
815 * to find out the file offset and must, thanks to the aforementioned
816 * optimization, also know whether the descriptor is open append-only
819 * The net result of all the above is that we need to grant CAP_SEEK,
820 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
822 * Perhaps this is the universe's way of saying that either
824 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
825 * using it, so that Capsicum-capable tcpdump wouldn't need to do
830 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
831 * I/O library that knows what rights are needed by the standard
832 * I/O library, based on the open mode, and assigns them, perhaps
833 * with an additional argument indicating, for example, whether
834 * seeking should be allowed, so that tcpdump doesn't need to know
835 * what the standard I/O library happens to require this week.
838 set_dumper_capsicum_rights(pcap_dumper_t *p)
840 int fd = fileno(pcap_dump_file(p));
843 cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
844 if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
845 error("unable to limit dump descriptor");
847 if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
848 error("unable to limit dump descriptor fcntls");
854 * Copy arg vector into a new buffer, concatenating arguments with spaces.
857 copy_argv(register char **argv)
860 register u_int len = 0;
869 len += strlen(*p++) + 1;
871 buf = (char *)malloc(len);
873 error("copy_argv: malloc");
877 while ((src = *p++) != NULL) {
878 while ((*dst++ = *src++) != '\0')
888 * On Windows, we need to open the file in binary mode, so that
889 * we get all the bytes specified by the size we get from "fstat()".
890 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
891 * we define it as 0 if it's not defined, so it does nothing.
898 read_infile(char *fname)
900 register int i, fd, cc;
904 fd = open(fname, O_RDONLY|O_BINARY);
906 error("can't open %s: %s", fname, pcap_strerror(errno));
908 if (fstat(fd, &buf) < 0)
909 error("can't stat %s: %s", fname, pcap_strerror(errno));
911 cp = malloc((u_int)buf.st_size + 1);
913 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
914 fname, pcap_strerror(errno));
915 cc = read(fd, cp, (u_int)buf.st_size);
917 error("read %s: %s", fname, pcap_strerror(errno));
918 if (cc != buf.st_size)
919 error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
922 /* replace "# comment" with spaces */
923 for (i = 0; i < cc; i++) {
925 while (i < cc && cp[i] != '\n')
932 #ifdef HAVE_PCAP_FINDALLDEVS
934 parse_interface_number(const char *device)
939 devnum = strtol(device, &end, 10);
940 if (device != end && *end == '\0') {
942 * It's all-numeric, but is it a valid number?
946 * No, it's not an ordinal.
948 error("Invalid adapter index");
953 * It's not all-numeric; return -1, so our caller
961 find_interface_by_number(long devnum)
963 pcap_if_t *dev, *devlist;
965 char ebuf[PCAP_ERRBUF_SIZE];
968 if (pcap_findalldevs(&devlist, ebuf) < 0)
971 * Look for the devnum-th entry in the list of devices (1-based).
973 for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
974 i++, dev = dev->next)
977 error("Invalid adapter index");
978 device = strdup(dev->name);
979 pcap_freealldevs(devlist);
985 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
988 #ifdef HAVE_PCAP_CREATE
993 #ifdef HAVE_PCAP_CREATE
994 pc = pcap_create(device, ebuf);
997 * If this failed with "No such device", that means
998 * the interface doesn't exist; return NULL, so that
999 * the caller can see whether the device name is
1000 * actually an interface index.
1002 if (strstr(ebuf, "No such device") != NULL)
1006 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1008 show_tstamp_types_and_exit(pc, device);
1010 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1011 status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
1013 error("%s: Can't set %ssecond time stamp precision: %s",
1015 tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1016 pcap_statustostr(status));
1019 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1020 if (immediate_mode) {
1021 status = pcap_set_immediate_mode(pc, 1);
1023 error("%s: Can't set immediate mode: %s",
1025 pcap_statustostr(status));
1029 * Is this an interface that supports monitor mode?
1031 if (pcap_can_set_rfmon(pc) == 1)
1032 supports_monitor_mode = 1;
1034 supports_monitor_mode = 0;
1035 status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
1037 error("%s: Can't set snapshot length: %s",
1038 device, pcap_statustostr(status));
1039 status = pcap_set_promisc(pc, !pflag);
1041 error("%s: Can't set promiscuous mode: %s",
1042 device, pcap_statustostr(status));
1044 status = pcap_set_rfmon(pc, 1);
1046 error("%s: Can't set monitor mode: %s",
1047 device, pcap_statustostr(status));
1049 status = pcap_set_timeout(pc, 1000);
1051 error("%s: pcap_set_timeout failed: %s",
1052 device, pcap_statustostr(status));
1054 status = pcap_set_buffer_size(pc, Bflag);
1056 error("%s: Can't set buffer size: %s",
1057 device, pcap_statustostr(status));
1059 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1061 status = pcap_set_tstamp_type(pc, jflag);
1063 error("%s: Can't set time stamp type: %s",
1064 device, pcap_statustostr(status));
1065 else if (status > 0)
1066 warning("When trying to set timestamp type '%s' on %s: %s",
1067 pcap_tstamp_type_val_to_name(jflag), device,
1068 pcap_statustostr(status));
1071 status = pcap_activate(pc);
1074 * pcap_activate() failed.
1076 cp = pcap_geterr(pc);
1077 if (status == PCAP_ERROR)
1079 else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1081 * Return an error for our caller to handle.
1083 snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1084 device, pcap_statustostr(status), cp);
1087 } else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1088 error("%s: %s\n(%s)", device,
1089 pcap_statustostr(status), cp);
1091 error("%s: %s", device,
1092 pcap_statustostr(status));
1093 } else if (status > 0) {
1095 * pcap_activate() succeeded, but it's warning us
1096 * of a problem it had.
1098 cp = pcap_geterr(pc);
1099 if (status == PCAP_WARNING)
1101 else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1103 warning("%s: %s\n(%s)", device,
1104 pcap_statustostr(status), cp);
1106 warning("%s: %s", device,
1107 pcap_statustostr(status));
1109 #ifdef HAVE_PCAP_SETDIRECTION
1111 status = pcap_setdirection(pc, Qflag);
1113 error("%s: pcap_setdirection() failed: %s",
1114 device, pcap_geterr(pc));
1116 #endif /* HAVE_PCAP_SETDIRECTION */
1117 #else /* HAVE_PCAP_CREATE */
1119 pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf);
1122 * If this failed with "No such device", that means
1123 * the interface doesn't exist; return NULL, so that
1124 * the caller can see whether the device name is
1125 * actually an interface index.
1127 if (strstr(ebuf, "No such device") != NULL)
1132 warning("%s", ebuf);
1133 #endif /* HAVE_PCAP_CREATE */
1139 main(int argc, char **argv)
1141 register int cnt, op, i;
1142 bpf_u_int32 localnet =0 , netmask = 0;
1143 int timezone_offset = 0;
1144 register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1145 pcap_handler callback;
1147 const char *dlt_name;
1148 struct bpf_program fcode;
1150 RETSIGTYPE (*oldhandler)(int);
1152 struct dump_info dumpinfo;
1153 u_char *pcap_userdata;
1154 char ebuf[PCAP_ERRBUF_SIZE];
1155 char VFileLine[PATH_MAX + 1];
1156 char *username = NULL;
1157 char *chroot_dir = NULL;
1160 #ifdef HAVE_PCAP_FINDALLDEVS
1166 #ifdef HAVE_CAPSICUM
1167 cap_rights_t rights;
1169 #endif /* HAVE_CAPSICUM */
1170 int Oflag = 1; /* run filter code optimizer */
1172 const char *yflag_dlt_name = NULL;
1174 netdissect_options Ndo;
1175 netdissect_options *ndo = &Ndo;
1178 * Initialize the netdissect code.
1180 if (nd_init(ebuf, sizeof ebuf) == -1)
1183 memset(ndo, 0, sizeof(*ndo));
1184 ndo_set_function_pointers(ndo);
1185 ndo->ndo_snaplen = DEFAULT_SNAPLEN;
1195 if ((cp = strrchr(argv[0], '/')) != NULL)
1196 ndo->program_name = program_name = cp + 1;
1198 ndo->program_name = program_name = argv[0];
1201 if (pcap_wsockinit() != 0)
1202 error("Attempting to initialize Winsock failed");
1206 * On platforms where the CPU doesn't support unaligned loads,
1207 * force unaligned accesses to abort with SIGBUS, rather than
1208 * being fixed up (slowly) by the OS kernel; on those platforms,
1209 * misaligned accesses are bugs, and we want tcpdump to crash so
1210 * that the bugs are reported.
1212 if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1216 (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1220 /* compatibility for old -a */
1231 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1233 Bflag = atoi(optarg)*1024;
1235 error("invalid packet buffer size %s", optarg);
1237 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1242 error("invalid packet count %s", optarg);
1246 Cflag = atoi(optarg) * 1000000;
1248 error("invalid file size %s", optarg);
1268 #ifndef HAVE_LIBCRYPTO
1269 warning("crypto code not compiled in");
1271 ndo->ndo_espsecret = optarg;
1283 Gflag = atoi(optarg);
1285 error("invalid number of seconds %s", optarg);
1287 /* We will create one file initially. */
1290 /* Grab the current time for rotation use. */
1291 if ((Gflag_time = time(NULL)) == (time_t)-1) {
1292 error("main: can't get current time: %s",
1293 pcap_strerror(errno));
1310 #ifdef HAVE_PCAP_CREATE
1314 #endif /* HAVE_PCAP_CREATE */
1316 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1318 jflag = pcap_tstamp_type_name_to_val(optarg);
1320 error("invalid time stamp type %s", optarg);
1331 * _IOLBF is the same as _IOFBF in Microsoft's C
1332 * libraries; the only alternative they offer
1335 * XXX - this should really be checking for MSVC++,
1336 * not _WIN32, if, for example, MinGW has its own
1337 * C library that is more UNIX-compatible.
1339 setvbuf(stdout, NULL, _IONBF, 0);
1341 #ifdef HAVE_SETLINEBUF
1344 setvbuf(stdout, NULL, _IOLBF, 0);
1354 if (nd_have_smi_support()) {
1355 if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1)
1358 (void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1359 program_name, optarg);
1360 (void)fprintf(stderr, "(no libsmi support)\n");
1365 /* TCP-MD5 shared secret */
1366 #ifndef HAVE_LIBCRYPTO
1367 warning("crypto code not compiled in");
1369 ndo->ndo_sigsecret = optarg;
1390 ++ndo->ndo_suppress_default_print;
1393 #ifdef HAVE_PCAP_SETDIRECTION
1395 if (ascii_strcasecmp(optarg, "in") == 0)
1397 else if (ascii_strcasecmp(optarg, "out") == 0)
1399 else if (ascii_strcasecmp(optarg, "inout") == 0)
1400 Qflag = PCAP_D_INOUT;
1402 error("unknown capture direction `%s'", optarg);
1404 #endif /* HAVE_PCAP_SETDIRECTION */
1411 ndo->ndo_snaplen = strtol(optarg, &end, 0);
1412 if (optarg == end || *end != '\0'
1413 || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1414 error("invalid snaplen %s", optarg);
1415 else if (ndo->ndo_snaplen == 0)
1416 ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1428 if (ascii_strcasecmp(optarg, "vat") == 0)
1429 ndo->ndo_packettype = PT_VAT;
1430 else if (ascii_strcasecmp(optarg, "wb") == 0)
1431 ndo->ndo_packettype = PT_WB;
1432 else if (ascii_strcasecmp(optarg, "rpc") == 0)
1433 ndo->ndo_packettype = PT_RPC;
1434 else if (ascii_strcasecmp(optarg, "rtp") == 0)
1435 ndo->ndo_packettype = PT_RTP;
1436 else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1437 ndo->ndo_packettype = PT_RTCP;
1438 else if (ascii_strcasecmp(optarg, "snmp") == 0)
1439 ndo->ndo_packettype = PT_SNMP;
1440 else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1441 ndo->ndo_packettype = PT_CNFP;
1442 else if (ascii_strcasecmp(optarg, "tftp") == 0)
1443 ndo->ndo_packettype = PT_TFTP;
1444 else if (ascii_strcasecmp(optarg, "aodv") == 0)
1445 ndo->ndo_packettype = PT_AODV;
1446 else if (ascii_strcasecmp(optarg, "carp") == 0)
1447 ndo->ndo_packettype = PT_CARP;
1448 else if (ascii_strcasecmp(optarg, "radius") == 0)
1449 ndo->ndo_packettype = PT_RADIUS;
1450 else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1451 ndo->ndo_packettype = PT_ZMTP1;
1452 else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1453 ndo->ndo_packettype = PT_VXLAN;
1454 else if (ascii_strcasecmp(optarg, "pgm") == 0)
1455 ndo->ndo_packettype = PT_PGM;
1456 else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1457 ndo->ndo_packettype = PT_PGM_ZMTP1;
1458 else if (ascii_strcasecmp(optarg, "lmp") == 0)
1459 ndo->ndo_packettype = PT_LMP;
1460 else if (ascii_strcasecmp(optarg, "resp") == 0)
1461 ndo->ndo_packettype = PT_RESP;
1463 error("unknown packet type `%s'", optarg);
1470 #ifdef HAVE_PCAP_DUMP_FLUSH
1489 Wflag = atoi(optarg);
1491 error("invalid number of output files %s", optarg);
1492 WflagChars = getWflagChars(Wflag);
1497 ++ndo->ndo_suppress_default_print;
1502 ++ndo->ndo_suppress_default_print;
1506 yflag_dlt_name = optarg;
1508 pcap_datalink_name_to_val(yflag_dlt_name);
1510 error("invalid data link type %s", yflag_dlt_name);
1513 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1516 /* Undocumented flag */
1517 pcap_set_parser_debug(1);
1530 ndo->ndo_packet_number = 1;
1533 case OPTION_VERSION:
1538 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1539 case OPTION_TSTAMP_PRECISION:
1540 ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1541 if (ndo->ndo_tstamp_precision < 0)
1542 error("unsupported time stamp precision");
1546 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1547 case OPTION_IMMEDIATE_MODE:
1558 #ifdef HAVE_PCAP_FINDALLDEVS
1560 show_devices_and_exit();
1563 switch (ndo->ndo_tflag) {
1565 case 0: /* Default */
1566 case 4: /* Default + Date*/
1567 timezone_offset = gmt2local(0);
1570 case 1: /* No time stamp */
1571 case 2: /* Unix timeval style */
1572 case 3: /* Microseconds since previous packet */
1573 case 5: /* Microseconds since first packet */
1576 default: /* Not supported */
1577 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1581 if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1582 error("-f can not be used with -V or -r");
1584 if (VFileName != NULL && RFileName != NULL)
1585 error("-V and -r are mutually exclusive.");
1587 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1589 * If we're printing dissected packets to the standard output
1590 * rather than saving raw packets to a file, and the standard
1591 * output is a terminal, use immediate mode, as the user's
1592 * probably expecting to see packets pop up immediately.
1594 if (WFileName == NULL && isatty(1))
1599 /* if run as root, prepare for chrooting */
1600 if (getuid() == 0 || geteuid() == 0) {
1601 /* future extensibility for cmd-line arguments */
1603 chroot_dir = WITH_CHROOT;
1608 /* if run as root, prepare for dropping root privileges */
1609 if (getuid() == 0 || geteuid() == 0) {
1610 /* Run with '-Z root' to restore old behaviour */
1612 username = WITH_USER;
1616 if (RFileName != NULL || VFileName != NULL) {
1618 * If RFileName is non-null, it's the pathname of a
1619 * savefile to read. If VFileName is non-null, it's
1620 * the pathname of a file containing a list of pathnames
1621 * (one per line) of savefiles to read.
1623 * In either case, we're reading a savefile, not doing
1628 * We don't need network access, so relinquish any set-UID
1629 * or set-GID privileges we have (if any).
1631 * We do *not* want set-UID privileges when opening a
1632 * trace file, as that might let the user read other
1633 * people's trace files (especially if we're set-UID
1636 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1637 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1639 if (VFileName != NULL) {
1640 if (VFileName[0] == '-' && VFileName[1] == '\0')
1643 VFile = fopen(VFileName, "r");
1646 error("Unable to open file: %s\n", pcap_strerror(errno));
1648 ret = get_next_file(VFile, VFileLine);
1650 error("Nothing in %s\n", VFileName);
1651 RFileName = VFileLine;
1654 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1655 pd = pcap_open_offline_with_tstamp_precision(RFileName,
1656 ndo->ndo_tstamp_precision, ebuf);
1658 pd = pcap_open_offline(RFileName, ebuf);
1663 #ifdef HAVE_CAPSICUM
1664 cap_rights_init(&rights, CAP_READ);
1665 if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1667 error("unable to limit pcap descriptor");
1670 dlt = pcap_datalink(pd);
1671 dlt_name = pcap_datalink_val_to_name(dlt);
1672 if (dlt_name == NULL) {
1673 fprintf(stderr, "reading from file %s, link-type %u\n",
1677 "reading from file %s, link-type %s (%s)\n",
1678 RFileName, dlt_name,
1679 pcap_datalink_val_to_description(dlt));
1683 * We're doing a live capture.
1685 if (device == NULL) {
1687 * No interface was specified. Pick one.
1689 #ifdef HAVE_PCAP_FINDALLDEVS
1691 * Find the list of interfaces, and pick
1692 * the first interface.
1694 if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
1696 device = strdup(devlist->name);
1697 pcap_freealldevs(devlist);
1699 #else /* HAVE_PCAP_FINDALLDEVS */
1701 * Use whatever interface pcap_lookupdev()
1704 device = pcap_lookupdev(ebuf);
1711 * Try to open the interface with the specified name.
1713 pd = open_interface(device, ndo, ebuf);
1716 * That failed. If we can get a list of
1717 * interfaces, and the interface name
1718 * is purely numeric, try to use it as
1719 * a 1-based index in the list of
1722 #ifdef HAVE_PCAP_FINDALLDEVS
1723 devnum = parse_interface_number(device);
1726 * It's not a number; just report
1727 * the open error and fail.
1733 * OK, it's a number; try to find the
1734 * interface with that index, and try
1737 * find_interface_by_number() exits if it
1738 * couldn't be found.
1740 device = find_interface_by_number(devnum);
1741 pd = open_interface(device, ndo, ebuf);
1744 #else /* HAVE_PCAP_FINDALLDEVS */
1746 * We can't get a list of interfaces; just
1750 #endif /* HAVE_PCAP_FINDALLDEVS */
1754 * Let user own process after socket has been opened.
1757 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1758 fprintf(stderr, "Warning: setgid/setuid failed !\n");
1760 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1762 if(pcap_setbuff(pd, Bflag)==-1){
1763 error("%s", pcap_geterr(pd));
1765 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1767 show_dlts_and_exit(pd, device);
1768 if (yflag_dlt >= 0) {
1769 #ifdef HAVE_PCAP_SET_DATALINK
1770 if (pcap_set_datalink(pd, yflag_dlt) < 0)
1771 error("%s", pcap_geterr(pd));
1774 * We don't actually support changing the
1775 * data link type, so we only let them
1776 * set it to what it already is.
1778 if (yflag_dlt != pcap_datalink(pd)) {
1779 error("%s is not one of the DLTs supported by this device\n",
1783 (void)fprintf(stderr, "%s: data link type %s\n",
1784 program_name, yflag_dlt_name);
1785 (void)fflush(stderr);
1787 i = pcap_snapshot(pd);
1788 if (ndo->ndo_snaplen < i) {
1789 warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1790 ndo->ndo_snaplen = i;
1792 if(ndo->ndo_fflag != 0) {
1793 if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1794 warning("foreign (-f) flag used but: %s", ebuf);
1800 cmdbuf = read_infile(infile);
1802 cmdbuf = copy_argv(&argv[optind]);
1804 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1805 pcap_set_optimizer_debug(dflag);
1807 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1808 error("%s", pcap_geterr(pd));
1810 bpf_dump(&fcode, dflag);
1813 pcap_freecode(&fcode);
1818 if (!ndo->ndo_nflag)
1819 capdns = capdns_setup();
1820 #endif /* HAVE_CASPER */
1822 init_print(ndo, localnet, netmask, timezone_offset);
1825 (void)setsignal(SIGPIPE, cleanup);
1826 (void)setsignal(SIGTERM, cleanup);
1827 (void)setsignal(SIGINT, cleanup);
1829 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1830 (void)setsignal(SIGCHLD, child_cleanup);
1832 /* Cooperate with nohup(1) */
1834 if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1835 (void)setsignal(SIGHUP, oldhandler);
1840 * If a user name was specified with "-Z", attempt to switch to
1841 * that user's UID. This would probably be used with sudo,
1842 * to allow tcpdump to be run in a special restricted
1843 * account (if you just want to allow users to open capture
1844 * devices, and can't just give users that permission,
1845 * you'd make tcpdump set-UID or set-GID).
1847 * Tcpdump doesn't necessarily write only to one savefile;
1848 * the general only way to allow a -Z instance to write to
1849 * savefiles as the user under whose UID it's run, rather
1850 * than as the user specified with -Z, would thus be to switch
1851 * to the original user ID before opening a capture file and
1852 * then switch back to the -Z user ID after opening the savefile.
1853 * Switching to the -Z user ID only after opening the first
1854 * savefile doesn't handle the general case.
1857 if (getuid() == 0 || geteuid() == 0) {
1858 #ifdef HAVE_LIBCAP_NG
1859 /* Initialize capng */
1860 capng_clear(CAPNG_SELECT_BOTH);
1864 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1872 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1880 CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1884 capng_apply(CAPNG_SELECT_BOTH);
1885 #endif /* HAVE_LIBCAP_NG */
1886 if (username || chroot_dir)
1887 droproot(username, chroot_dir);
1892 if (pcap_setfilter(pd, &fcode) < 0)
1893 error("%s", pcap_geterr(pd));
1894 #ifdef HAVE_CAPSICUM
1895 if (RFileName == NULL && VFileName == NULL && pcap_fileno(pd) != -1) {
1896 static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1899 * The various libpcap devices use a combination of
1900 * read (bpf), ioctl (bpf, netmap), poll (netmap)
1901 * so we add the relevant access rights.
1903 cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
1904 if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1906 error("unable to limit pcap descriptor");
1908 if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1909 sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1910 error("unable to limit ioctls on pcap descriptor");
1916 /* Do not exceed the default PATH_MAX for files. */
1917 dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1919 if (dumpinfo.CurrentFileName == NULL)
1920 error("malloc of dumpinfo.CurrentFileName");
1922 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1924 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1926 MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1928 p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1929 #ifdef HAVE_LIBCAP_NG
1930 /* Give up CAP_DAC_OVERRIDE capability.
1931 * Only allow it to be restored if the -C or -G flag have been
1932 * set since we may need to create more files later on.
1936 (Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1940 capng_apply(CAPNG_SELECT_BOTH);
1941 #endif /* HAVE_LIBCAP_NG */
1943 error("%s", pcap_geterr(pd));
1944 #ifdef HAVE_CAPSICUM
1945 set_dumper_capsicum_rights(p);
1947 if (Cflag != 0 || Gflag != 0) {
1948 #ifdef HAVE_CAPSICUM
1949 dumpinfo.WFileName = strdup(basename(WFileName));
1950 if (dumpinfo.WFileName == NULL) {
1951 error("Unable to allocate memory for file %s",
1954 dumpinfo.dirfd = open(dirname(WFileName),
1955 O_DIRECTORY | O_RDONLY);
1956 if (dumpinfo.dirfd < 0) {
1957 error("unable to open directory %s",
1958 dirname(WFileName));
1960 cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1961 CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1962 if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1964 error("unable to limit directory rights");
1966 if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1968 error("unable to limit dump descriptor fcntls");
1970 #else /* !HAVE_CAPSICUM */
1971 dumpinfo.WFileName = WFileName;
1973 callback = dump_packet_and_trunc;
1976 pcap_userdata = (u_char *)&dumpinfo;
1978 callback = dump_packet;
1979 pcap_userdata = (u_char *)p;
1981 #ifdef HAVE_PCAP_DUMP_FLUSH
1986 dlt = pcap_datalink(pd);
1987 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1988 callback = print_packet;
1989 pcap_userdata = (u_char *)ndo;
1992 #ifdef SIGNAL_REQ_INFO
1994 * We can't get statistics when reading from a file rather
1995 * than capturing from a device.
1997 if (RFileName == NULL)
1998 (void)setsignal(SIGNAL_REQ_INFO, requestinfo);
2001 if (ndo->ndo_vflag > 0 && WFileName) {
2003 * When capturing to a file, "-v" means tcpdump should,
2004 * every 10 seconds, "v"erbosely report the number of
2007 #ifdef USE_WIN32_MM_TIMER
2008 /* call verbose_stats_dump() each 1000 +/-100msec */
2009 timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
2010 setvbuf(stderr, NULL, _IONBF, 0);
2011 #elif defined(HAVE_ALARM)
2012 (void)setsignal(SIGALRM, verbose_stats_dump);
2017 if (RFileName == NULL) {
2019 * Live capture (if -V was specified, we set RFileName
2020 * to a file from the -V file). Print a message to
2021 * the standard error on UN*X.
2023 if (!ndo->ndo_vflag && !WFileName) {
2024 (void)fprintf(stderr,
2025 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2028 (void)fprintf(stderr, "%s: ", program_name);
2029 dlt = pcap_datalink(pd);
2030 dlt_name = pcap_datalink_val_to_name(dlt);
2031 if (dlt_name == NULL) {
2032 (void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
2033 device, dlt, ndo->ndo_snaplen);
2035 (void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2037 pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
2039 (void)fflush(stderr);
2042 #ifdef HAVE_CAPSICUM
2043 cansandbox = (VFileName == NULL && zflag == NULL &&
2044 ndo->ndo_espsecret == NULL);
2046 cansandbox = (cansandbox && (ndo->ndo_nflag || capdns != NULL));
2048 cansandbox = (cansandbox && ndo->ndo_nflag);
2049 #endif /* HAVE_CASPER */
2050 cansandbox = (cansandbox && (pcap_fileno(pd) != -1 ||
2051 RFileName != NULL));
2053 if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2054 error("unable to enter the capability mode");
2055 #endif /* HAVE_CAPSICUM */
2058 status = pcap_loop(pd, cnt, callback, pcap_userdata);
2059 if (WFileName == NULL) {
2061 * We're printing packets. Flush the printed output,
2062 * so it doesn't get intermingled with error output.
2066 * We got interrupted, so perhaps we didn't
2067 * manage to finish a line we were printing.
2068 * Print an extra newline, just in case.
2072 (void)fflush(stdout);
2076 * We got interrupted. If we are reading multiple
2077 * files (via -V) set these so that we stop.
2086 (void)fprintf(stderr, "%s: pcap_loop: %s\n",
2087 program_name, pcap_geterr(pd));
2089 if (RFileName == NULL) {
2091 * We're doing a live capture. Report the capture
2097 if (VFileName != NULL) {
2098 ret = get_next_file(VFile, VFileLine);
2102 RFileName = VFileLine;
2103 pd = pcap_open_offline(RFileName, ebuf);
2106 #ifdef HAVE_CAPSICUM
2107 cap_rights_init(&rights, CAP_READ);
2108 if (cap_rights_limit(fileno(pcap_file(pd)),
2109 &rights) < 0 && errno != ENOSYS) {
2110 error("unable to limit pcap descriptor");
2113 new_dlt = pcap_datalink(pd);
2114 if (new_dlt != dlt) {
2116 * The new file has a different
2117 * link-layer header type from the
2120 if (WFileName != NULL) {
2122 * We're writing raw packets
2123 * that match the filter to
2124 * a pcap file. pcap files
2125 * don't support multiple
2126 * different link-layer
2127 * header types, so we fail
2130 error("%s: new dlt does not match original", RFileName);
2134 * We're printing the decoded packets;
2135 * switch to the new DLT.
2137 * To do that, we need to change
2138 * the printer, change the DLT name,
2139 * and recompile the filter with
2143 ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2144 if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2145 error("%s", pcap_geterr(pd));
2149 * Set the filter on the new file.
2151 if (pcap_setfilter(pd, &fcode) < 0)
2152 error("%s", pcap_geterr(pd));
2155 * Report the new file.
2157 dlt_name = pcap_datalink_val_to_name(dlt);
2158 if (dlt_name == NULL) {
2159 fprintf(stderr, "reading from file %s, link-type %u\n",
2163 "reading from file %s, link-type %s (%s)\n",
2164 RFileName, dlt_name,
2165 pcap_datalink_val_to_description(dlt));
2170 while (ret != NULL);
2173 pcap_freecode(&fcode);
2174 exit_tcpdump(status == -1 ? 1 : 0);
2177 /* make a clean exit on interrupts */
2179 cleanup(int signo _U_)
2181 #ifdef USE_WIN32_MM_TIMER
2183 timeKillEvent(timer_id);
2185 #elif defined(HAVE_ALARM)
2189 #ifdef HAVE_PCAP_BREAKLOOP
2191 * We have "pcap_breakloop()"; use it, so that we do as little
2192 * as possible in the signal handler (it's probably not safe
2193 * to do anything with standard I/O streams in a signal handler -
2194 * the ANSI C standard doesn't say it is).
2199 * We don't have "pcap_breakloop()"; this isn't safe, but
2200 * it's the best we can do. Print the summary if we're
2201 * not reading from a savefile - i.e., if we're doing a
2202 * live capture - and exit.
2204 if (pd != NULL && pcap_file(pd) == NULL) {
2206 * We got interrupted, so perhaps we didn't
2207 * manage to finish a line we were printing.
2208 * Print an extra newline, just in case.
2211 (void)fflush(stdout);
2219 On windows, we do not use a fork, so we do not care less about
2220 waiting a child processes to die
2222 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2224 child_cleanup(int signo _U_)
2228 #endif /* HAVE_FORK && HAVE_VFORK */
2231 info(register int verbose)
2233 struct pcap_stat stats;
2236 * Older versions of libpcap didn't set ps_ifdrop on some
2237 * platforms; initialize it to 0 to handle that.
2239 stats.ps_ifdrop = 0;
2240 if (pcap_stats(pd, &stats) < 0) {
2241 (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2247 fprintf(stderr, "%s: ", program_name);
2249 (void)fprintf(stderr, "%u packet%s captured", packets_captured,
2250 PLURAL_SUFFIX(packets_captured));
2252 fputs(", ", stderr);
2255 (void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
2256 PLURAL_SUFFIX(stats.ps_recv));
2258 fputs(", ", stderr);
2261 (void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
2262 PLURAL_SUFFIX(stats.ps_drop));
2263 if (stats.ps_ifdrop != 0) {
2265 fputs(", ", stderr);
2268 (void)fprintf(stderr, "%u packet%s dropped by interface\n",
2269 stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
2275 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2277 #define fork_subprocess() fork()
2279 #define fork_subprocess() vfork()
2282 compress_savefile(const char *filename)
2286 child = fork_subprocess();
2289 "compress_savefile: fork failed: %s\n",
2290 pcap_strerror(errno));
2294 /* Parent process. */
2300 * Set to lowest priority so that this doesn't disturb the capture.
2303 setpriority(PRIO_PROCESS, 0, NZERO - 1);
2305 setpriority(PRIO_PROCESS, 0, 19);
2307 if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2309 "compress_savefile: execlp(%s, %s) failed: %s\n",
2312 pcap_strerror(errno));
2319 #else /* HAVE_FORK && HAVE_VFORK */
2321 compress_savefile(const char *filename)
2324 "compress_savefile failed. Functionality not implemented under your system\n");
2326 #endif /* HAVE_FORK && HAVE_VFORK */
2329 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2331 struct dump_info *dump_info;
2337 dump_info = (struct dump_info *)user;
2340 * XXX - this won't force the file to rotate on the specified time
2341 * boundary, but it will rotate on the first packet received after the
2342 * specified Gflag number of seconds. Note: if a Gflag time boundary
2343 * and a Cflag size boundary coincide, the time rotation will occur
2344 * first thereby cancelling the Cflag boundary (since the file should
2348 /* Check if it is time to rotate */
2351 /* Get the current time */
2352 if ((t = time(NULL)) == (time_t)-1) {
2353 error("dump_and_trunc_packet: can't get current_time: %s",
2354 pcap_strerror(errno));
2358 /* If the time is greater than the specified window, rotate */
2359 if (t - Gflag_time >= Gflag) {
2360 #ifdef HAVE_CAPSICUM
2365 /* Update the Gflag_time */
2367 /* Update Gflag_count */
2370 * Close the current file and open a new one.
2372 pcap_dump_close(dump_info->p);
2375 * Compress the file we just closed, if the user asked for it
2378 compress_savefile(dump_info->CurrentFileName);
2381 * Check to see if we've exceeded the Wflag (when
2384 if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2385 (void)fprintf(stderr, "Maximum file limit reached: %d\n",
2391 if (dump_info->CurrentFileName != NULL)
2392 free(dump_info->CurrentFileName);
2393 /* Allocate space for max filename + \0. */
2394 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2395 if (dump_info->CurrentFileName == NULL)
2396 error("dump_packet_and_trunc: malloc");
2398 * Gflag was set otherwise we wouldn't be here. Reset the count
2399 * so multiple files would end with 1,2,3 in the filename.
2400 * The counting is handled with the -C flow after this.
2405 * This is always the first file in the Cflag
2407 * We also don't need numbering if Cflag is not set.
2410 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2413 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2415 #ifdef HAVE_LIBCAP_NG
2416 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2417 capng_apply(CAPNG_SELECT_BOTH);
2418 #endif /* HAVE_LIBCAP_NG */
2419 #ifdef HAVE_CAPSICUM
2420 fd = openat(dump_info->dirfd,
2421 dump_info->CurrentFileName,
2422 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2424 error("unable to open file %s",
2425 dump_info->CurrentFileName);
2427 fp = fdopen(fd, "w");
2429 error("unable to fdopen file %s",
2430 dump_info->CurrentFileName);
2432 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2433 #else /* !HAVE_CAPSICUM */
2434 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2436 #ifdef HAVE_LIBCAP_NG
2437 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2438 capng_apply(CAPNG_SELECT_BOTH);
2439 #endif /* HAVE_LIBCAP_NG */
2440 if (dump_info->p == NULL)
2441 error("%s", pcap_geterr(pd));
2442 #ifdef HAVE_CAPSICUM
2443 set_dumper_capsicum_rights(dump_info->p);
2449 * XXX - this won't prevent capture files from getting
2450 * larger than Cflag - the last packet written to the
2451 * file could put it over Cflag.
2454 long size = pcap_dump_ftell(dump_info->p);
2457 error("ftell fails on output file");
2459 #ifdef HAVE_CAPSICUM
2465 * Close the current file and open a new one.
2467 pcap_dump_close(dump_info->p);
2470 * Compress the file we just closed, if the user
2474 compress_savefile(dump_info->CurrentFileName);
2478 if (Cflag_count >= Wflag)
2481 if (dump_info->CurrentFileName != NULL)
2482 free(dump_info->CurrentFileName);
2483 dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2484 if (dump_info->CurrentFileName == NULL)
2485 error("dump_packet_and_trunc: malloc");
2486 MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2487 #ifdef HAVE_LIBCAP_NG
2488 capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2489 capng_apply(CAPNG_SELECT_BOTH);
2490 #endif /* HAVE_LIBCAP_NG */
2491 #ifdef HAVE_CAPSICUM
2492 fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2493 O_CREAT | O_WRONLY | O_TRUNC, 0644);
2495 error("unable to open file %s",
2496 dump_info->CurrentFileName);
2498 fp = fdopen(fd, "w");
2500 error("unable to fdopen file %s",
2501 dump_info->CurrentFileName);
2503 dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2504 #else /* !HAVE_CAPSICUM */
2505 dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2507 #ifdef HAVE_LIBCAP_NG
2508 capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2509 capng_apply(CAPNG_SELECT_BOTH);
2510 #endif /* HAVE_LIBCAP_NG */
2511 if (dump_info->p == NULL)
2512 error("%s", pcap_geterr(pd));
2513 #ifdef HAVE_CAPSICUM
2514 set_dumper_capsicum_rights(dump_info->p);
2519 pcap_dump((u_char *)dump_info->p, h, sp);
2520 #ifdef HAVE_PCAP_DUMP_FLUSH
2522 pcap_dump_flush(dump_info->p);
2531 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2537 pcap_dump(user, h, sp);
2538 #ifdef HAVE_PCAP_DUMP_FLUSH
2540 pcap_dump_flush((pcap_dumper_t *)user);
2549 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2555 pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2564 * XXX - there should really be libpcap calls to get the version
2565 * number as a string (the string would be generated from #defines
2566 * at run time, so that it's not generated from string constants
2567 * in the library, as, on many UNIX systems, those constants would
2568 * be statically linked into the application executable image, and
2569 * would thus reflect the version of libpcap on the system on
2570 * which the application was *linked*, not the system on which it's
2573 * That routine should be documented, unlike the "version[]"
2574 * string, so that UNIX vendors providing their own libpcaps
2575 * don't omit it (as a couple of vendors have...).
2577 * Packet.dll should perhaps also export a routine to return the
2578 * version number of the Packet.dll code, to supply the
2579 * "Wpcap_version" information on Windows.
2581 char WDversion[]="current-git.tcpdump.org";
2582 #if !defined(HAVE_GENERATED_VERSION)
2583 char version[]="current-git.tcpdump.org";
2585 char pcap_version[]="current-git.tcpdump.org";
2586 char Wpcap_version[]="3.1";
2589 #ifdef SIGNAL_REQ_INFO
2590 RETSIGTYPE requestinfo(int signo _U_)
2600 * Called once each second in verbose mode while dumping to file
2602 #ifdef USE_WIN32_MM_TIMER
2603 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2604 DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2607 fprintf(stderr, "Got %u\r", packets_captured);
2609 #elif defined(HAVE_ALARM)
2610 static void verbose_stats_dump(int sig _U_)
2613 fprintf(stderr, "Got %u\r", packets_captured);
2618 USES_APPLE_DEPRECATED_API
2622 extern char version[];
2623 #ifndef HAVE_PCAP_LIB_VERSION
2624 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2625 extern char pcap_version[];
2626 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2627 static char pcap_version[] = "unknown";
2628 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2629 #endif /* HAVE_PCAP_LIB_VERSION */
2630 const char *smi_version_string;
2632 #ifdef HAVE_PCAP_LIB_VERSION
2634 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2636 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2638 (void)fprintf(stderr, "%s\n",pcap_lib_version());
2639 #else /* HAVE_PCAP_LIB_VERSION */
2641 (void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2642 (void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2644 (void)fprintf(stderr, "%s version %s\n", program_name, version);
2645 (void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2647 #endif /* HAVE_PCAP_LIB_VERSION */
2649 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2650 (void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2653 smi_version_string = nd_smi_version_string();
2654 if (smi_version_string != NULL)
2655 (void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2657 #if defined(__SANITIZE_ADDRESS__)
2658 (void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n");
2659 #elif defined(__has_feature)
2660 # if __has_feature(address_sanitizer)
2661 (void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n");
2663 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2671 (void)fprintf(stderr,
2672 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2673 (void)fprintf(stderr,
2674 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2675 (void)fprintf(stderr,
2676 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2677 #ifdef HAVE_PCAP_SETDIRECTION
2678 (void)fprintf(stderr,
2679 "\t\t[ -Q in|out|inout ]\n");
2681 (void)fprintf(stderr,
2682 "\t\t[ -r file ] [ -s snaplen ] ");
2683 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2684 (void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2685 (void)fprintf(stderr,
2688 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2689 (void)fprintf(stderr, "[ --immediate-mode ] ");
2691 (void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2692 (void)fprintf(stderr,
2693 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2694 (void)fprintf(stderr,
2695 "\t\t[ -Z user ] [ expression ]\n");
2699 * c-style: whitesmith