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>
64 #include <openssl/crypto.h>
67 #ifdef HAVE_GETOPT_LONG
70 #include "getopt_long.h"
72 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
73 * to compile if <pcap.h> has already been included; including the headers
74 * in the opposite order works fine.
77 #include <sys/capability.h>
78 #include <sys/ioccom.h>
82 #endif /* HAVE_CAPSICUM */
91 #include <sys/resource.h>
96 /* capabilities convenience library */
97 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
98 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
99 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
101 #ifdef HAVE_LIBCAP_NG
105 #undef HAVE_LIBCAP_NG
106 #endif /* HAVE_CAP_NG_H */
107 #endif /* HAVE_LIBCAP_NG */
109 #include "netdissect.h"
110 #include "interface.h"
111 #include "addrtoname.h"
113 #include "setsignal.h"
114 #include "gmt2local.h"
115 #include "pcap-missing.h"
116 #include "ascii_strcasecmp.h"
121 #define PATH_MAX 1024
125 #define SIGNAL_REQ_INFO SIGINFO
127 #define SIGNAL_REQ_INFO SIGUSR1
130 static int Cflag
; /* rotate dump files after this many bytes */
131 static int Cflag_count
; /* Keep track of which file number we're writing */
132 static int Dflag
; /* list available devices and exit */
133 static int dflag
; /* print filter code */
134 static int Gflag
; /* rotate dump files after this many seconds */
135 static int Gflag_count
; /* number of files created with Gflag rotation */
136 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
137 static int Lflag
; /* list available data link types and exit */
138 static int Iflag
; /* rfmon (monitor) mode */
139 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
140 static int Jflag
; /* list available time stamp types */
142 #ifdef HAVE_PCAP_SETDIRECTION
143 int Qflag
= -1; /* restrict captured packet by send/receive direction */
145 static int Uflag
; /* "unbuffered" output of dump files */
146 static int Wflag
; /* recycle output files after this number of files */
147 static int WflagChars
;
148 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
150 static int infodelay
;
151 static int infoprint
;
156 static RETSIGTYPE
cleanup(int);
157 static RETSIGTYPE
child_cleanup(int);
158 static void print_version(void);
159 static void print_usage(void);
160 static void show_tstamp_types_and_exit(const char *device
) __attribute__((noreturn
));
161 static void show_dlts_and_exit(const char *device
) __attribute__((noreturn
));
163 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
164 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
165 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
166 static void droproot(const char *, const char *);
168 #ifdef SIGNAL_REQ_INFO
169 RETSIGTYPE
requestinfo(int);
172 #if defined(USE_WIN32_MM_TIMER)
173 #include <MMsystem.h>
174 static UINT timer_id
;
175 static void CALLBACK
verbose_stats_dump(UINT
, UINT
, DWORD_PTR
, DWORD_PTR
, DWORD_PTR
);
176 #elif defined(HAVE_ALARM)
177 static void verbose_stats_dump(int sig
);
180 static void info(int);
181 static u_int packets_captured
;
183 static const struct tok status_flags
[] = {
185 { PCAP_IF_UP
, "Up" },
187 #ifdef PCAP_IF_RUNNING
188 { PCAP_IF_RUNNING
, "Running" },
190 { PCAP_IF_LOOPBACK
, "Loopback" },
196 static int supports_monitor_mode
;
204 char *CurrentFileName
;
212 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
214 show_tstamp_types_and_exit(const char *device
)
217 int *tstamp_types
= 0;
218 const char *tstamp_type_name
;
221 n_tstamp_types
= pcap_list_tstamp_types(pd
, &tstamp_types
);
222 if (n_tstamp_types
< 0)
223 error("%s", pcap_geterr(pd
));
225 if (n_tstamp_types
== 0) {
226 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
230 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
232 for (i
= 0; i
< n_tstamp_types
; i
++) {
233 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
234 if (tstamp_type_name
!= NULL
) {
235 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
236 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
238 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
241 pcap_free_tstamp_types(tstamp_types
);
247 show_dlts_and_exit(const char *device
)
251 const char *dlt_name
;
253 n_dlts
= pcap_list_datalinks(pd
, &dlts
);
255 error("%s", pcap_geterr(pd
));
256 else if (n_dlts
== 0 || !dlts
)
257 error("No data link types.");
260 * If the interface is known to support monitor mode, indicate
261 * whether these are the data link types available when not in
262 * monitor mode, if -I wasn't specified, or when in monitor mode,
263 * when -I was specified (the link-layer types available in
264 * monitor mode might be different from the ones available when
265 * not in monitor mode).
267 if (supports_monitor_mode
)
268 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
270 Iflag
? "when in monitor mode" : "when not in monitor mode");
272 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
275 for (i
= 0; i
< n_dlts
; i
++) {
276 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
277 if (dlt_name
!= NULL
) {
278 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
279 pcap_datalink_val_to_description(dlts
[i
]));
282 * OK, does tcpdump handle that type?
284 if (!has_printer(dlts
[i
]))
285 (void) fprintf(stderr
, " (printing not supported)");
286 fprintf(stderr
, "\n");
288 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
292 #ifdef HAVE_PCAP_FREE_DATALINKS
293 pcap_free_datalinks(dlts
);
298 #ifdef HAVE_PCAP_FINDALLDEVS
300 show_devices_and_exit (void)
302 pcap_if_t
*dev
, *devlist
;
303 char ebuf
[PCAP_ERRBUF_SIZE
];
306 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
308 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
309 printf("%d.%s", i
+1, dev
->name
);
310 if (dev
->description
!= NULL
)
311 printf(" (%s)", dev
->description
);
313 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
316 pcap_freealldevs(devlist
);
319 #endif /* HAVE_PCAP_FINDALLDEVS */
324 * Note that there we use all letters for short options except for g, k,
325 * o, and P, and those are used by other versions of tcpdump, and we should
326 * only use them for the same purposes that the other versions of tcpdump
329 * OS X tcpdump uses -g to force non--v output for IP to be on one
330 * line, making it more "g"repable;
332 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
335 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
336 * for hosts sending TCP SYN packets;
338 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
341 * OS X tcpdump also uses -Q to specify expressions that match packet
342 * metadata, including but not limited to the packet direction.
343 * The expression syntax is different from a simple "in|out|inout",
344 * and those expressions aren't accepted by OS X tcpdump, but the
345 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
346 * "inout" = "dir=in or dir=out", and the parser could conceivably
347 * special-case "in", "out", and "inout" as expressions for backwards
348 * compatibility, so all is not (yet) lost.
352 * Set up flags that might or might not be supported depending on the
353 * version of libpcap we're using.
355 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
357 #define B_FLAG_USAGE " [ -B size ]"
358 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
361 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
363 #ifdef HAVE_PCAP_CREATE
365 #else /* HAVE_PCAP_CREATE */
367 #endif /* HAVE_PCAP_CREATE */
369 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
371 #define j_FLAG_USAGE " [ -j tstamptype ]"
373 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
377 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
379 #ifdef HAVE_PCAP_FINDALLDEVS
385 #ifdef HAVE_PCAP_DUMP_FLUSH
391 #ifdef HAVE_PCAP_SETDIRECTION
397 #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:#"
402 * We do not currently have long options corresponding to all short
403 * options; we should probably pick appropriate option names for them.
405 * However, the short options where the number of times the option is
406 * specified matters, such as -v and -d and -t, should probably not
407 * just map to a long option, as saying
409 * tcpdump --verbose --verbose
411 * doesn't make sense; it should be --verbosity={N} or something such
414 * For long options with no corresponding short options, we define values
415 * outside the range of ASCII graphic characters, make that the last
416 * component of the entry for the long option, and have a case for that
417 * option in the switch statement.
419 #define OPTION_VERSION 128
420 #define OPTION_TSTAMP_PRECISION 129
421 #define OPTION_IMMEDIATE_MODE 130
423 static const struct option longopts
[] = {
424 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
425 { "buffer-size", required_argument
, NULL
, 'B' },
427 { "list-interfaces", no_argument
, NULL
, 'D' },
428 { "help", no_argument
, NULL
, 'h' },
429 { "interface", required_argument
, NULL
, 'i' },
430 #ifdef HAVE_PCAP_CREATE
431 { "monitor-mode", no_argument
, NULL
, 'I' },
433 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
434 { "time-stamp-type", required_argument
, NULL
, 'j' },
435 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
437 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
438 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
440 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
441 { "list-data-link-types", no_argument
, NULL
, 'L' },
442 { "no-optimize", no_argument
, NULL
, 'O' },
443 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
444 #ifdef HAVE_PCAP_SETDIRECTION
445 { "direction", required_argument
, NULL
, 'Q' },
447 { "snapshot-length", required_argument
, NULL
, 's' },
448 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
449 #ifdef HAVE_PCAP_DUMP_FLUSH
450 { "packet-buffered", no_argument
, NULL
, 'U' },
452 { "linktype", required_argument
, NULL
, 'y' },
453 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
454 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
456 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
457 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
459 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
460 { "number", no_argument
, NULL
, '#' },
461 { "version", no_argument
, NULL
, OPTION_VERSION
},
466 /* Drop root privileges and chroot if necessary */
468 droproot(const char *username
, const char *chroot_dir
)
470 struct passwd
*pw
= NULL
;
472 if (chroot_dir
&& !username
) {
473 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
478 pw
= getpwnam(username
);
481 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
482 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
483 program_name
, chroot_dir
, pcap_strerror(errno
));
487 #ifdef HAVE_LIBCAP_NG
489 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
491 fprintf(stderr
, "error : ret %d\n", ret
);
493 fprintf(stderr
, "dropped privs to %s\n", username
);
497 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
498 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
499 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
500 program_name
, username
,
501 (unsigned long)pw
->pw_uid
,
502 (unsigned long)pw
->pw_gid
,
503 pcap_strerror(errno
));
507 fprintf(stderr
, "dropped privs to %s\n", username
);
509 #endif /* HAVE_LIBCAP_NG */
512 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
513 program_name
, username
);
516 #ifdef HAVE_LIBCAP_NG
517 /* We don't need CAP_SETUID and CAP_SETGID any more. */
520 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
524 capng_apply(CAPNG_SELECT_BOTH
);
525 #endif /* HAVE_LIBCAP_NG */
546 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
548 char *filename
= malloc(PATH_MAX
+ 1);
549 if (filename
== NULL
)
550 error("Makefilename: malloc");
552 /* Process with strftime if Gflag is set. */
556 /* Convert Gflag_time to a usable format */
557 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
558 error("MakeTimedFilename: localtime");
561 /* There's no good way to detect an error in strftime since a return
562 * value of 0 isn't necessarily failure.
564 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
566 strncpy(filename
, orig_name
, PATH_MAX
);
569 if (cnt
== 0 && max_chars
== 0)
570 strncpy(buffer
, filename
, PATH_MAX
+ 1);
572 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
573 /* Report an error if the filename is too large */
574 error("too many output files or filename is too long (> %d)", PATH_MAX
);
579 get_next_file(FILE *VFile
, char *ptr
)
583 ret
= fgets(ptr
, PATH_MAX
, VFile
);
587 if (ptr
[strlen(ptr
) - 1] == '\n')
588 ptr
[strlen(ptr
) - 1] = '\0';
593 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
595 tstamp_precision_from_string(const char *precision
)
597 if (strncmp(precision
, "nano", strlen("nano")) == 0)
598 return PCAP_TSTAMP_PRECISION_NANO
;
600 if (strncmp(precision
, "micro", strlen("micro")) == 0)
601 return PCAP_TSTAMP_PRECISION_MICRO
;
607 tstamp_precision_to_string(int precision
)
611 case PCAP_TSTAMP_PRECISION_MICRO
:
614 case PCAP_TSTAMP_PRECISION_NANO
:
625 * Ensure that, on a dump file's descriptor, we have all the rights
626 * necessary to make the standard I/O library work with an fdopen()ed
627 * FILE * from that descriptor.
629 * A long time ago, in a galaxy far far away, AT&T decided that, instead
630 * of providing separate APIs for getting and setting the FD_ flags on a
631 * descriptor, getting and setting the O_ flags on a descriptor, and
632 * locking files, they'd throw them all into a kitchen-sink fcntl() call
633 * along the lines of ioctl(), the fact that ioctl() operations are
634 * largely specific to particular character devices but fcntl() operations
635 * are either generic to all descriptors or generic to all descriptors for
636 * regular files nonwithstanding.
638 * The Capsicum people decided that fine-grained control of descriptor
639 * operations was required, so that you need to grant permission for
640 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
641 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
642 * collection of things, so there are *individual* fcntls for which
643 * permission needs to be granted.
645 * The FreeBSD standard I/O people implemented some optimizations that
646 * requires that the standard I/O routines be able to determine whether
647 * the descriptor for the FILE * is open append-only or not; as that
648 * descriptor could have come from an open() rather than an fopen(),
649 * that requires that it be able to do an F_GETFL fcntl() to read
652 * Tcpdump uses ftell() to determine how much data has been written
653 * to a file in order to, when used with -C, determine when it's time
654 * to rotate capture files. ftell() therefore needs to do an lseek()
655 * to find out the file offset and must, thanks to the aforementioned
656 * optimization, also know whether the descriptor is open append-only
659 * The net result of all the above is that we need to grant CAP_SEEK,
660 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
662 * Perhaps this is the universe's way of saying that either
664 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
665 * using it, so that Capsicum-capable tcpdump wouldn't need to do
670 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
671 * I/O library that knows what rights are needed by the standard
672 * I/O library, based on the open mode, and assigns them, perhaps
673 * with an additional argument indicating, for example, whether
674 * seeking should be allowed, so that tcpdump doesn't need to know
675 * what the standard I/O library happens to require this week.
678 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
680 int fd
= fileno(pcap_dump_file(p
));
683 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
684 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
685 error("unable to limit dump descriptor");
687 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
688 error("unable to limit dump descriptor fcntls");
694 main(int argc
, char **argv
)
696 register int cnt
, op
, i
;
697 bpf_u_int32 localnet
=0 , netmask
= 0;
698 int timezone_offset
= 0;
699 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
700 pcap_handler callback
;
703 const char *dlt_name
;
704 struct bpf_program fcode
;
706 RETSIGTYPE (*oldhandler
)(int);
708 struct dump_info dumpinfo
;
709 u_char
*pcap_userdata
;
710 char ebuf
[PCAP_ERRBUF_SIZE
];
711 char VFileLine
[PATH_MAX
+ 1];
712 char *username
= NULL
;
713 char *chroot_dir
= NULL
;
716 #ifdef HAVE_PCAP_FINDALLDEVS
717 pcap_if_t
*dev
, *devlist
;
725 #endif /* HAVE_CAPSICUM */
726 int Bflag
= 0; /* buffer size */
727 int jflag
= -1; /* packet time stamp source */
728 int Oflag
= 1; /* run filter code optimizer */
729 int pflag
= 0; /* don't go promiscuous */
731 const char *yflag_dlt_name
= NULL
;
733 netdissect_options Ndo
;
734 netdissect_options
*ndo
= &Ndo
;
735 int immediate_mode
= 0;
737 memset(ndo
, 0, sizeof(*ndo
));
738 ndo_set_function_pointers(ndo
);
739 ndo
->ndo_snaplen
= DEFAULT_SNAPLEN
;
749 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
750 ndo
->program_name
= program_name
= cp
+ 1;
752 ndo
->program_name
= program_name
= argv
[0];
755 if (pcap_wsockinit() != 0)
756 error("Attempting to initialize Winsock failed");
760 * On platforms where the CPU doesn't support unaligned loads,
761 * force unaligned accesses to abort with SIGBUS, rather than
762 * being fixed up (slowly) by the OS kernel; on those platforms,
763 * misaligned accesses are bugs, and we want tcpdump to crash so
764 * that the bugs are reported.
766 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
774 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
778 /* compatibility for old -a */
789 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
791 Bflag
= atoi(optarg
)*1024;
793 error("invalid packet buffer size %s", optarg
);
795 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
800 error("invalid packet count %s", optarg
);
804 Cflag
= atoi(optarg
) * 1000000;
806 error("invalid file size %s", optarg
);
826 #ifndef HAVE_LIBCRYPTO
827 warning("crypto code not compiled in");
829 ndo
->ndo_espsecret
= optarg
;
841 Gflag
= atoi(optarg
);
843 error("invalid number of seconds %s", optarg
);
845 /* We will create one file initially. */
848 /* Grab the current time for rotation use. */
849 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
850 error("main: can't get current time: %s",
851 pcap_strerror(errno
));
865 if (optarg
[0] == '0' && optarg
[1] == 0)
866 error("Invalid adapter index");
868 #ifdef HAVE_PCAP_FINDALLDEVS
870 * If the argument is a number, treat it as
871 * an index into the list of adapters, as
872 * printed by "tcpdump -D".
874 * This should be OK on UNIX systems, as interfaces
875 * shouldn't have names that begin with digits.
876 * It can be useful on Windows, where more than
877 * one interface can have the same name.
879 devnum
= strtol(optarg
, &end
, 10);
880 if (optarg
!= end
&& *end
== '\0') {
882 error("Invalid adapter index");
884 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
887 * Look for the devnum-th entry in the
888 * list of devices (1-based).
890 for (i
= 0, dev
= devlist
;
891 i
< devnum
-1 && dev
!= NULL
;
892 i
++, dev
= dev
->next
)
895 error("Invalid adapter index");
896 device
= strdup(dev
->name
);
897 pcap_freealldevs(devlist
);
900 #endif /* HAVE_PCAP_FINDALLDEVS */
904 #ifdef HAVE_PCAP_CREATE
908 #endif /* HAVE_PCAP_CREATE */
910 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
912 jflag
= pcap_tstamp_type_name_to_val(optarg
);
914 error("invalid time stamp type %s", optarg
);
925 * _IOLBF is the same as _IOFBF in Microsoft's C
926 * libraries; the only alternative they offer
929 * XXX - this should really be checking for MSVC++,
930 * not _WIN32, if, for example, MinGW has its own
931 * C library that is more UNIX-compatible.
933 setvbuf(stdout
, NULL
, _IONBF
, 0);
935 #ifdef HAVE_SETLINEBUF
938 setvbuf(stdout
, NULL
, _IOLBF
, 0);
949 if (smiLoadModule(optarg
) == 0) {
950 error("could not load MIB module %s", optarg
);
954 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
955 program_name
, optarg
);
956 (void)fprintf(stderr
, "(no libsmi support)\n");
961 /* TCP-MD5 shared secret */
962 #ifndef HAVE_LIBCRYPTO
963 warning("crypto code not compiled in");
965 ndo
->ndo_sigsecret
= optarg
;
986 ++ndo
->ndo_suppress_default_print
;
989 #ifdef HAVE_PCAP_SETDIRECTION
991 if (ascii_strcasecmp(optarg
, "in") == 0)
993 else if (ascii_strcasecmp(optarg
, "out") == 0)
995 else if (ascii_strcasecmp(optarg
, "inout") == 0)
996 Qflag
= PCAP_D_INOUT
;
998 error("unknown capture direction `%s'", optarg
);
1000 #endif /* HAVE_PCAP_SETDIRECTION */
1007 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1008 if (optarg
== end
|| *end
!= '\0'
1009 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1010 error("invalid snaplen %s", optarg
);
1011 else if (ndo
->ndo_snaplen
== 0)
1012 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
1024 if (ascii_strcasecmp(optarg
, "vat") == 0)
1025 ndo
->ndo_packettype
= PT_VAT
;
1026 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1027 ndo
->ndo_packettype
= PT_WB
;
1028 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1029 ndo
->ndo_packettype
= PT_RPC
;
1030 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1031 ndo
->ndo_packettype
= PT_RTP
;
1032 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1033 ndo
->ndo_packettype
= PT_RTCP
;
1034 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1035 ndo
->ndo_packettype
= PT_SNMP
;
1036 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1037 ndo
->ndo_packettype
= PT_CNFP
;
1038 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1039 ndo
->ndo_packettype
= PT_TFTP
;
1040 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1041 ndo
->ndo_packettype
= PT_AODV
;
1042 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1043 ndo
->ndo_packettype
= PT_CARP
;
1044 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1045 ndo
->ndo_packettype
= PT_RADIUS
;
1046 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1047 ndo
->ndo_packettype
= PT_ZMTP1
;
1048 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1049 ndo
->ndo_packettype
= PT_VXLAN
;
1050 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1051 ndo
->ndo_packettype
= PT_PGM
;
1052 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1053 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1054 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1055 ndo
->ndo_packettype
= PT_LMP
;
1057 error("unknown packet type `%s'", optarg
);
1064 #ifdef HAVE_PCAP_DUMP_FLUSH
1083 Wflag
= atoi(optarg
);
1085 error("invalid number of output files %s", optarg
);
1086 WflagChars
= getWflagChars(Wflag
);
1091 ++ndo
->ndo_suppress_default_print
;
1096 ++ndo
->ndo_suppress_default_print
;
1100 yflag_dlt_name
= optarg
;
1102 pcap_datalink_name_to_val(yflag_dlt_name
);
1104 error("invalid data link type %s", yflag_dlt_name
);
1107 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1110 /* Undocumented flag */
1111 #ifdef HAVE_PCAP_DEBUG
1112 extern int pcap_debug
;
1122 zflag
= strdup(optarg
);
1124 error("Unable to allocate memory for -z argument");
1128 username
= strdup(optarg
);
1129 if (username
== NULL
)
1130 error("Unable to allocate memory for -Z argument");
1134 ndo
->ndo_packet_number
= 1;
1137 case OPTION_VERSION
:
1142 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1143 case OPTION_TSTAMP_PRECISION
:
1144 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1145 if (ndo
->ndo_tstamp_precision
< 0)
1146 error("unsupported time stamp precision");
1150 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1151 case OPTION_IMMEDIATE_MODE
:
1162 #ifdef HAVE_PCAP_FINDALLDEVS
1164 show_devices_and_exit();
1167 switch (ndo
->ndo_tflag
) {
1169 case 0: /* Default */
1170 case 4: /* Default + Date*/
1171 timezone_offset
= gmt2local(0);
1174 case 1: /* No time stamp */
1175 case 2: /* Unix timeval style */
1176 case 3: /* Microseconds since previous packet */
1177 case 5: /* Microseconds since first packet */
1180 default: /* Not supported */
1181 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1185 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1186 error("-f can not be used with -V or -r");
1188 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1189 error("-V and -r are mutually exclusive.");
1191 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1193 * If we're printing dissected packets to the standard output
1194 * rather than saving raw packets to a file, and the standard
1195 * output is a terminal, use immediate mode, as the user's
1196 * probably expecting to see packets pop up immediately.
1198 if (WFileName
== NULL
&& isatty(1))
1203 /* if run as root, prepare for chrooting */
1204 if (getuid() == 0 || geteuid() == 0) {
1205 /* future extensibility for cmd-line arguments */
1207 chroot_dir
= WITH_CHROOT
;
1212 /* if run as root, prepare for dropping root privileges */
1213 if (getuid() == 0 || geteuid() == 0) {
1214 /* Run with '-Z root' to restore old behaviour */
1216 username
= WITH_USER
;
1220 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1222 * If RFileName is non-null, it's the pathname of a
1223 * savefile to read. If VFileName is non-null, it's
1224 * the pathname of a file containing a list of pathnames
1225 * (one per line) of savefiles to read.
1227 * In either case, we're reading a savefile, not doing
1232 * We don't need network access, so relinquish any set-UID
1233 * or set-GID privileges we have (if any).
1235 * We do *not* want set-UID privileges when opening a
1236 * trace file, as that might let the user read other
1237 * people's trace files (especially if we're set-UID
1240 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1241 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1243 if (VFileName
!= NULL
) {
1244 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1247 VFile
= fopen(VFileName
, "r");
1250 error("Unable to open file: %s\n", pcap_strerror(errno
));
1252 ret
= get_next_file(VFile
, VFileLine
);
1254 error("Nothing in %s\n", VFileName
);
1255 RFileName
= VFileLine
;
1258 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1259 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1260 ndo
->ndo_tstamp_precision
, ebuf
);
1262 pd
= pcap_open_offline(RFileName
, ebuf
);
1267 #ifdef HAVE_CAPSICUM
1268 cap_rights_init(&rights
, CAP_READ
);
1269 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1271 error("unable to limit pcap descriptor");
1274 dlt
= pcap_datalink(pd
);
1275 dlt_name
= pcap_datalink_val_to_name(dlt
);
1276 if (dlt_name
== NULL
) {
1277 fprintf(stderr
, "reading from file %s, link-type %u\n",
1281 "reading from file %s, link-type %s (%s)\n",
1282 RFileName
, dlt_name
,
1283 pcap_datalink_val_to_description(dlt
));
1287 * We're doing a live capture.
1289 if (device
== NULL
) {
1290 #ifdef HAVE_PCAP_FINDALLDEVS
1291 if (pcap_findalldevs(&devlist
, ebuf
) >= 0 &&
1293 device
= strdup(devlist
->name
);
1294 pcap_freealldevs(devlist
);
1296 #else /* HAVE_PCAP_FINDALLDEVS */
1297 device
= pcap_lookupdev(ebuf
);
1304 * Print a message to the standard error on Windows.
1305 * XXX - why do it here, with a different message?
1307 if(strlen(device
) == 1) /* we assume that an ASCII string is always longer than 1 char */
1308 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1309 fprintf(stderr
, "%s: listening on %ws\n", program_name
, device
);
1313 fprintf(stderr
, "%s: listening on %s\n", program_name
, device
);
1318 #ifdef HAVE_PCAP_CREATE
1319 pd
= pcap_create(device
, ebuf
);
1322 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1324 show_tstamp_types_and_exit(device
);
1326 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1327 status
= pcap_set_tstamp_precision(pd
, ndo
->ndo_tstamp_precision
);
1329 error("%s: Can't set %ssecond time stamp precision: %s",
1331 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1332 pcap_statustostr(status
));
1335 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1336 if (immediate_mode
) {
1337 status
= pcap_set_immediate_mode(pd
, 1);
1339 error("%s: Can't set immediate mode: %s",
1341 pcap_statustostr(status
));
1345 * Is this an interface that supports monitor mode?
1347 if (pcap_can_set_rfmon(pd
) == 1)
1348 supports_monitor_mode
= 1;
1350 supports_monitor_mode
= 0;
1351 status
= pcap_set_snaplen(pd
, ndo
->ndo_snaplen
);
1353 error("%s: Can't set snapshot length: %s",
1354 device
, pcap_statustostr(status
));
1355 status
= pcap_set_promisc(pd
, !pflag
);
1357 error("%s: Can't set promiscuous mode: %s",
1358 device
, pcap_statustostr(status
));
1360 status
= pcap_set_rfmon(pd
, 1);
1362 error("%s: Can't set monitor mode: %s",
1363 device
, pcap_statustostr(status
));
1365 status
= pcap_set_timeout(pd
, 1000);
1367 error("%s: pcap_set_timeout failed: %s",
1368 device
, pcap_statustostr(status
));
1370 status
= pcap_set_buffer_size(pd
, Bflag
);
1372 error("%s: Can't set buffer size: %s",
1373 device
, pcap_statustostr(status
));
1375 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1377 status
= pcap_set_tstamp_type(pd
, jflag
);
1379 error("%s: Can't set time stamp type: %s",
1380 device
, pcap_statustostr(status
));
1383 status
= pcap_activate(pd
);
1386 * pcap_activate() failed.
1388 cp
= pcap_geterr(pd
);
1389 if (status
== PCAP_ERROR
)
1391 else if ((status
== PCAP_ERROR_NO_SUCH_DEVICE
||
1392 status
== PCAP_ERROR_PERM_DENIED
) &&
1394 error("%s: %s\n(%s)", device
,
1395 pcap_statustostr(status
), cp
);
1397 error("%s: %s", device
,
1398 pcap_statustostr(status
));
1399 } else if (status
> 0) {
1401 * pcap_activate() succeeded, but it's warning us
1402 * of a problem it had.
1404 cp
= pcap_geterr(pd
);
1405 if (status
== PCAP_WARNING
)
1407 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1409 warning("%s: %s\n(%s)", device
,
1410 pcap_statustostr(status
), cp
);
1412 warning("%s: %s", device
,
1413 pcap_statustostr(status
));
1415 #ifdef HAVE_PCAP_SETDIRECTION
1417 status
= pcap_setdirection(pd
, Qflag
);
1419 error("%s: pcap_setdirection() failed: %s",
1420 device
, pcap_geterr(pd
));
1422 #endif /* HAVE_PCAP_SETDIRECTION */
1425 pd
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000,
1430 warning("%s", ebuf
);
1431 #endif /* HAVE_PCAP_CREATE */
1433 * Let user own process after socket has been opened.
1436 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1437 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1439 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1441 if(pcap_setbuff(pd
, Bflag
)==-1){
1442 error("%s", pcap_geterr(pd
));
1444 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1446 show_dlts_and_exit(device
);
1447 if (yflag_dlt
>= 0) {
1448 #ifdef HAVE_PCAP_SET_DATALINK
1449 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1450 error("%s", pcap_geterr(pd
));
1453 * We don't actually support changing the
1454 * data link type, so we only let them
1455 * set it to what it already is.
1457 if (yflag_dlt
!= pcap_datalink(pd
)) {
1458 error("%s is not one of the DLTs supported by this device\n",
1462 (void)fprintf(stderr
, "%s: data link type %s\n",
1463 program_name
, yflag_dlt_name
);
1464 (void)fflush(stderr
);
1466 i
= pcap_snapshot(pd
);
1467 if (ndo
->ndo_snaplen
< i
) {
1468 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1469 ndo
->ndo_snaplen
= i
;
1471 if(ndo
->ndo_fflag
!= 0) {
1472 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1473 warning("foreign (-f) flag used but: %s", ebuf
);
1479 cmdbuf
= read_infile(infile
);
1481 cmdbuf
= copy_argv(&argv
[optind
]);
1483 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1484 error("%s", pcap_geterr(pd
));
1486 bpf_dump(&fcode
, dflag
);
1491 init_print(ndo
, localnet
, netmask
, timezone_offset
);
1494 (void)setsignal(SIGPIPE
, cleanup
);
1495 (void)setsignal(SIGTERM
, cleanup
);
1496 (void)setsignal(SIGINT
, cleanup
);
1498 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1499 (void)setsignal(SIGCHLD
, child_cleanup
);
1501 /* Cooperate with nohup(1) */
1503 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
1504 (void)setsignal(SIGHUP
, oldhandler
);
1509 * If a user name was specified with "-Z", attempt to switch to
1510 * that user's UID. This would probably be used with sudo,
1511 * to allow tcpdump to be run in a special restricted
1512 * account (if you just want to allow users to open capture
1513 * devices, and can't just give users that permission,
1514 * you'd make tcpdump set-UID or set-GID).
1516 * Tcpdump doesn't necessarily write only to one savefile;
1517 * the general only way to allow a -Z instance to write to
1518 * savefiles as the user under whose UID it's run, rather
1519 * than as the user specified with -Z, would thus be to switch
1520 * to the original user ID before opening a capture file and
1521 * then switch back to the -Z user ID after opening the savefile.
1522 * Switching to the -Z user ID only after opening the first
1523 * savefile doesn't handle the general case.
1526 if (getuid() == 0 || geteuid() == 0) {
1527 #ifdef HAVE_LIBCAP_NG
1528 /* Initialize capng */
1529 capng_clear(CAPNG_SELECT_BOTH
);
1533 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1542 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1546 capng_apply(CAPNG_SELECT_BOTH
);
1547 #endif /* HAVE_LIBCAP_NG */
1548 if (username
|| chroot_dir
)
1549 droproot(username
, chroot_dir
);
1554 if (pcap_setfilter(pd
, &fcode
) < 0)
1555 error("%s", pcap_geterr(pd
));
1556 #ifdef HAVE_CAPSICUM
1557 if (RFileName
== NULL
&& VFileName
== NULL
) {
1558 static const unsigned long cmds
[] = { BIOCGSTATS
};
1560 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
);
1561 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
1563 error("unable to limit pcap descriptor");
1565 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
1566 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
1567 error("unable to limit ioctls on pcap descriptor");
1573 /* Do not exceed the default PATH_MAX for files. */
1574 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1576 if (dumpinfo
.CurrentFileName
== NULL
)
1577 error("malloc of dumpinfo.CurrentFileName");
1579 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1581 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
1583 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
1585 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
1586 #ifdef HAVE_LIBCAP_NG
1587 /* Give up CAP_DAC_OVERRIDE capability.
1588 * Only allow it to be restored if the -C or -G flag have been
1589 * set since we may need to create more files later on.
1593 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
1597 capng_apply(CAPNG_SELECT_BOTH
);
1598 #endif /* HAVE_LIBCAP_NG */
1600 error("%s", pcap_geterr(pd
));
1601 #ifdef HAVE_CAPSICUM
1602 set_dumper_capsicum_rights(p
);
1604 if (Cflag
!= 0 || Gflag
!= 0) {
1605 #ifdef HAVE_CAPSICUM
1606 dumpinfo
.WFileName
= strdup(basename(WFileName
));
1607 if (dumpinfo
.WFileName
== NULL
) {
1608 error("Unable to allocate memory for file %s",
1611 dumpinfo
.dirfd
= open(dirname(WFileName
),
1612 O_DIRECTORY
| O_RDONLY
);
1613 if (dumpinfo
.dirfd
< 0) {
1614 error("unable to open directory %s",
1615 dirname(WFileName
));
1617 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
1618 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
1619 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
1621 error("unable to limit directory rights");
1623 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
1625 error("unable to limit dump descriptor fcntls");
1627 #else /* !HAVE_CAPSICUM */
1628 dumpinfo
.WFileName
= WFileName
;
1630 callback
= dump_packet_and_trunc
;
1633 pcap_userdata
= (u_char
*)&dumpinfo
;
1635 callback
= dump_packet
;
1636 pcap_userdata
= (u_char
*)p
;
1638 #ifdef HAVE_PCAP_DUMP_FLUSH
1643 dlt
= pcap_datalink(pd
);
1644 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1645 callback
= print_packet
;
1646 pcap_userdata
= (u_char
*)ndo
;
1649 #ifdef SIGNAL_REQ_INFO
1651 * We can't get statistics when reading from a file rather
1652 * than capturing from a device.
1654 if (RFileName
== NULL
)
1655 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
1658 if (ndo
->ndo_vflag
> 0 && WFileName
) {
1660 * When capturing to a file, "-v" means tcpdump should,
1661 * every 10 seconds, "v"erbosely report the number of
1664 #ifdef USE_WIN32_MM_TIMER
1665 /* call verbose_stats_dump() each 1000 +/-100msec */
1666 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
1667 setvbuf(stderr
, NULL
, _IONBF
, 0);
1668 #elif defined(HAVE_ALARM)
1669 (void)setsignal(SIGALRM
, verbose_stats_dump
);
1675 if (RFileName
== NULL
) {
1677 * Live capture (if -V was specified, we set RFileName
1678 * to a file from the -V file). Print a message to
1679 * the standard error on UN*X.
1681 if (!ndo
->ndo_vflag
&& !WFileName
) {
1682 (void)fprintf(stderr
,
1683 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1686 (void)fprintf(stderr
, "%s: ", program_name
);
1687 dlt
= pcap_datalink(pd
);
1688 dlt_name
= pcap_datalink_val_to_name(dlt
);
1689 if (dlt_name
== NULL
) {
1690 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
1691 device
, dlt
, ndo
->ndo_snaplen
);
1693 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1695 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
1697 (void)fflush(stderr
);
1701 #ifdef HAVE_CAPSICUM
1702 cansandbox
= (ndo
->ndo_nflag
&& VFileName
== NULL
&& zflag
== NULL
);
1703 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
1704 error("unable to enter the capability mode");
1705 #endif /* HAVE_CAPSICUM */
1708 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
1709 if (WFileName
== NULL
) {
1711 * We're printing packets. Flush the printed output,
1712 * so it doesn't get intermingled with error output.
1716 * We got interrupted, so perhaps we didn't
1717 * manage to finish a line we were printing.
1718 * Print an extra newline, just in case.
1722 (void)fflush(stdout
);
1726 * We got interrupted. If we are reading multiple
1727 * files (via -V) set these so that we stop.
1736 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
1737 program_name
, pcap_geterr(pd
));
1739 if (RFileName
== NULL
) {
1741 * We're doing a live capture. Report the capture
1747 if (VFileName
!= NULL
) {
1748 ret
= get_next_file(VFile
, VFileLine
);
1750 RFileName
= VFileLine
;
1751 pd
= pcap_open_offline(RFileName
, ebuf
);
1754 #ifdef HAVE_CAPSICUM
1755 cap_rights_init(&rights
, CAP_READ
);
1756 if (cap_rights_limit(fileno(pcap_file(pd
)),
1757 &rights
) < 0 && errno
!= ENOSYS
) {
1758 error("unable to limit pcap descriptor");
1761 new_dlt
= pcap_datalink(pd
);
1762 if (WFileName
&& new_dlt
!= dlt
)
1763 error("%s: new dlt does not match original", RFileName
);
1764 ndo
->ndo_if_printer
= get_if_printer(ndo
, new_dlt
);
1765 dlt_name
= pcap_datalink_val_to_name(new_dlt
);
1766 if (dlt_name
== NULL
) {
1767 fprintf(stderr
, "reading from file %s, link-type %u\n",
1768 RFileName
, new_dlt
);
1771 "reading from file %s, link-type %s (%s)\n",
1772 RFileName
, dlt_name
,
1773 pcap_datalink_val_to_description(new_dlt
));
1775 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1776 error("%s", pcap_geterr(pd
));
1777 if (pcap_setfilter(pd
, &fcode
) < 0)
1778 error("%s", pcap_geterr(pd
));
1782 while (ret
!= NULL
);
1785 exit(status
== -1 ? 1 : 0);
1788 /* make a clean exit on interrupts */
1790 cleanup(int signo _U_
)
1792 #ifdef USE_WIN32_MM_TIMER
1794 timeKillEvent(timer_id
);
1796 #elif defined(HAVE_ALARM)
1800 #ifdef HAVE_PCAP_BREAKLOOP
1802 * We have "pcap_breakloop()"; use it, so that we do as little
1803 * as possible in the signal handler (it's probably not safe
1804 * to do anything with standard I/O streams in a signal handler -
1805 * the ANSI C standard doesn't say it is).
1810 * We don't have "pcap_breakloop()"; this isn't safe, but
1811 * it's the best we can do. Print the summary if we're
1812 * not reading from a savefile - i.e., if we're doing a
1813 * live capture - and exit.
1815 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
1817 * We got interrupted, so perhaps we didn't
1818 * manage to finish a line we were printing.
1819 * Print an extra newline, just in case.
1822 (void)fflush(stdout
);
1830 On windows, we do not use a fork, so we do not care less about
1831 waiting a child processes to die
1833 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1835 child_cleanup(int signo _U_
)
1839 #endif /* HAVE_FORK && HAVE_VFORK */
1842 info(register int verbose
)
1844 struct pcap_stat stats
;
1847 * Older versions of libpcap didn't set ps_ifdrop on some
1848 * platforms; initialize it to 0 to handle that.
1850 stats
.ps_ifdrop
= 0;
1851 if (pcap_stats(pd
, &stats
) < 0) {
1852 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
1858 fprintf(stderr
, "%s: ", program_name
);
1860 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
1861 PLURAL_SUFFIX(packets_captured
));
1863 fputs(", ", stderr
);
1866 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
1867 PLURAL_SUFFIX(stats
.ps_recv
));
1869 fputs(", ", stderr
);
1872 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
1873 PLURAL_SUFFIX(stats
.ps_drop
));
1874 if (stats
.ps_ifdrop
!= 0) {
1876 fputs(", ", stderr
);
1879 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
1880 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
1886 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1888 compress_savefile(const char *filename
)
1897 * Set to lowest priority so that this doesn't disturb the capture
1900 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
1902 setpriority(PRIO_PROCESS
, 0, 19);
1904 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
1906 "compress_savefile:execlp(%s, %s): %s\n",
1909 pcap_strerror(errno
));
1916 #else /* HAVE_FORK && HAVE_VFORK */
1918 compress_savefile(const char *filename
)
1921 "compress_savefile failed. Functionality not implemented under your system\n");
1923 #endif /* HAVE_FORK && HAVE_VFORK */
1926 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
1928 struct dump_info
*dump_info
;
1934 dump_info
= (struct dump_info
*)user
;
1937 * XXX - this won't force the file to rotate on the specified time
1938 * boundary, but it will rotate on the first packet received after the
1939 * specified Gflag number of seconds. Note: if a Gflag time boundary
1940 * and a Cflag size boundary coincide, the time rotation will occur
1941 * first thereby cancelling the Cflag boundary (since the file should
1945 /* Check if it is time to rotate */
1948 /* Get the current time */
1949 if ((t
= time(NULL
)) == (time_t)-1) {
1950 error("dump_and_trunc_packet: can't get current_time: %s",
1951 pcap_strerror(errno
));
1955 /* If the time is greater than the specified window, rotate */
1956 if (t
- Gflag_time
>= Gflag
) {
1957 #ifdef HAVE_CAPSICUM
1962 /* Update the Gflag_time */
1964 /* Update Gflag_count */
1967 * Close the current file and open a new one.
1969 pcap_dump_close(dump_info
->p
);
1972 * Compress the file we just closed, if the user asked for it
1975 compress_savefile(dump_info
->CurrentFileName
);
1978 * Check to see if we've exceeded the Wflag (when
1981 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
1982 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
1987 if (dump_info
->CurrentFileName
!= NULL
)
1988 free(dump_info
->CurrentFileName
);
1989 /* Allocate space for max filename + \0. */
1990 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1991 if (dump_info
->CurrentFileName
== NULL
)
1992 error("dump_packet_and_trunc: malloc");
1994 * Gflag was set otherwise we wouldn't be here. Reset the count
1995 * so multiple files would end with 1,2,3 in the filename.
1996 * The counting is handled with the -C flow after this.
2001 * This is always the first file in the Cflag
2003 * We also don't need numbering if Cflag is not set.
2006 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2009 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2011 #ifdef HAVE_LIBCAP_NG
2012 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2013 capng_apply(CAPNG_SELECT_BOTH
);
2014 #endif /* HAVE_LIBCAP_NG */
2015 #ifdef HAVE_CAPSICUM
2016 fd
= openat(dump_info
->dirfd
,
2017 dump_info
->CurrentFileName
,
2018 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2020 error("unable to open file %s",
2021 dump_info
->CurrentFileName
);
2023 fp
= fdopen(fd
, "w");
2025 error("unable to fdopen file %s",
2026 dump_info
->CurrentFileName
);
2028 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2029 #else /* !HAVE_CAPSICUM */
2030 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2032 #ifdef HAVE_LIBCAP_NG
2033 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2034 capng_apply(CAPNG_SELECT_BOTH
);
2035 #endif /* HAVE_LIBCAP_NG */
2036 if (dump_info
->p
== NULL
)
2037 error("%s", pcap_geterr(pd
));
2038 #ifdef HAVE_CAPSICUM
2039 set_dumper_capsicum_rights(dump_info
->p
);
2045 * XXX - this won't prevent capture files from getting
2046 * larger than Cflag - the last packet written to the
2047 * file could put it over Cflag.
2050 long size
= pcap_dump_ftell(dump_info
->p
);
2053 error("ftell fails on output file");
2055 #ifdef HAVE_CAPSICUM
2061 * Close the current file and open a new one.
2063 pcap_dump_close(dump_info
->p
);
2066 * Compress the file we just closed, if the user
2070 compress_savefile(dump_info
->CurrentFileName
);
2074 if (Cflag_count
>= Wflag
)
2077 if (dump_info
->CurrentFileName
!= NULL
)
2078 free(dump_info
->CurrentFileName
);
2079 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2080 if (dump_info
->CurrentFileName
== NULL
)
2081 error("dump_packet_and_trunc: malloc");
2082 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2083 #ifdef HAVE_LIBCAP_NG
2084 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2085 capng_apply(CAPNG_SELECT_BOTH
);
2086 #endif /* HAVE_LIBCAP_NG */
2087 #ifdef HAVE_CAPSICUM
2088 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2089 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2091 error("unable to open file %s",
2092 dump_info
->CurrentFileName
);
2094 fp
= fdopen(fd
, "w");
2096 error("unable to fdopen file %s",
2097 dump_info
->CurrentFileName
);
2099 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2100 #else /* !HAVE_CAPSICUM */
2101 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2103 #ifdef HAVE_LIBCAP_NG
2104 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2105 capng_apply(CAPNG_SELECT_BOTH
);
2106 #endif /* HAVE_LIBCAP_NG */
2107 if (dump_info
->p
== NULL
)
2108 error("%s", pcap_geterr(pd
));
2109 #ifdef HAVE_CAPSICUM
2110 set_dumper_capsicum_rights(dump_info
->p
);
2115 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2116 #ifdef HAVE_PCAP_DUMP_FLUSH
2118 pcap_dump_flush(dump_info
->p
);
2127 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2133 pcap_dump(user
, h
, sp
);
2134 #ifdef HAVE_PCAP_DUMP_FLUSH
2136 pcap_dump_flush((pcap_dumper_t
*)user
);
2145 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2151 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2160 * XXX - there should really be libpcap calls to get the version
2161 * number as a string (the string would be generated from #defines
2162 * at run time, so that it's not generated from string constants
2163 * in the library, as, on many UNIX systems, those constants would
2164 * be statically linked into the application executable image, and
2165 * would thus reflect the version of libpcap on the system on
2166 * which the application was *linked*, not the system on which it's
2169 * That routine should be documented, unlike the "version[]"
2170 * string, so that UNIX vendors providing their own libpcaps
2171 * don't omit it (as a couple of vendors have...).
2173 * Packet.dll should perhaps also export a routine to return the
2174 * version number of the Packet.dll code, to supply the
2175 * "Wpcap_version" information on Windows.
2177 char WDversion
[]="current-git.tcpdump.org";
2178 #if !defined(HAVE_GENERATED_VERSION)
2179 char version
[]="current-git.tcpdump.org";
2181 char pcap_version
[]="current-git.tcpdump.org";
2182 char Wpcap_version
[]="3.1";
2185 #ifdef SIGNAL_REQ_INFO
2186 RETSIGTYPE
requestinfo(int signo _U_
)
2196 * Called once each second in verbose mode while dumping to file
2198 #ifdef USE_WIN32_MM_TIMER
2199 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2200 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2203 fprintf(stderr
, "Got %u\r", packets_captured
);
2205 #elif defined(HAVE_ALARM)
2206 static void verbose_stats_dump(int sig _U_
)
2209 fprintf(stderr
, "Got %u\r", packets_captured
);
2214 USES_APPLE_DEPRECATED_API
2218 extern char version
[];
2219 #ifndef HAVE_PCAP_LIB_VERSION
2220 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2221 extern char pcap_version
[];
2222 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2223 static char pcap_version
[] = "unknown";
2224 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2225 #endif /* HAVE_PCAP_LIB_VERSION */
2227 #ifdef HAVE_PCAP_LIB_VERSION
2229 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2231 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2233 (void)fprintf(stderr
, "%s\n",pcap_lib_version());
2234 #else /* HAVE_PCAP_LIB_VERSION */
2236 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2237 (void)fprintf(stderr
, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version
, pcap_version
);
2239 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2240 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2242 #endif /* HAVE_PCAP_LIB_VERSION */
2244 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2245 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2249 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2258 (void)fprintf(stderr
,
2259 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2260 (void)fprintf(stderr
,
2261 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2262 (void)fprintf(stderr
,
2263 "\t\t[ -i interface ]" j_FLAG_USAGE
" [ -M secret ] [ --number ]\n");
2264 #ifdef HAVE_PCAP_SETDIRECTION
2265 (void)fprintf(stderr
,
2266 "\t\t[ -Q in|out|inout ]\n");
2268 (void)fprintf(stderr
,
2269 "\t\t[ -r file ] [ -s snaplen ] ");
2270 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2271 (void)fprintf(stderr
, "[ --time-stamp-precision precision ]\n");
2272 (void)fprintf(stderr
,
2275 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2276 (void)fprintf(stderr
, "[ --immediate-mode ] ");
2278 (void)fprintf(stderr
, "[ -T type ] [ --version ] [ -V file ]\n");
2279 (void)fprintf(stderr
,
2280 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2281 (void)fprintf(stderr
,
2282 "\t\t[ -Z user ] [ expression ]\n");
2286 * c-style: whitesmith