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 <tcpdump-stdinc.h>
71 #include <openssl/crypto.h>
74 #ifdef HAVE_GETOPT_LONG
77 #include "getopt_long.h"
79 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
80 * to compile if <pcap.h> has already been included; including the headers
81 * in the opposite order works fine.
84 #include <sys/capability.h>
85 #include <sys/ioccom.h>
89 #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 Cflag
; /* rotate dump files after this many bytes */
138 static int Cflag_count
; /* Keep track of which file number we're writing */
139 static int Dflag
; /* list available devices and exit */
140 static int dflag
; /* print filter code */
141 static int Gflag
; /* rotate dump files after this many seconds */
142 static int Gflag_count
; /* number of files created with Gflag rotation */
143 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
144 static int Lflag
; /* list available data link types and exit */
145 static int Iflag
; /* rfmon (monitor) mode */
146 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
147 static int Jflag
; /* list available time stamp types */
149 #ifdef HAVE_PCAP_SETDIRECTION
150 int Qflag
= -1; /* restrict captured packet by send/receive direction */
152 static int Uflag
; /* "unbuffered" output of dump files */
153 static int Wflag
; /* recycle output files after this number of files */
154 static int WflagChars
;
155 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
157 static int infodelay
;
158 static int infoprint
;
163 static RETSIGTYPE
cleanup(int);
164 static RETSIGTYPE
child_cleanup(int);
165 static void print_version(void);
166 static void print_usage(void);
167 static void show_tstamp_types_and_exit(const char *device
) __attribute__((noreturn
));
168 static void show_dlts_and_exit(const char *device
) __attribute__((noreturn
));
170 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
171 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
172 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
173 static void droproot(const char *, const char *);
175 #ifdef SIGNAL_REQ_INFO
176 RETSIGTYPE
requestinfo(int);
179 #if defined(USE_WIN32_MM_TIMER)
180 #include <MMsystem.h>
181 static UINT timer_id
;
182 static void CALLBACK
verbose_stats_dump(UINT
, UINT
, DWORD_PTR
, DWORD_PTR
, DWORD_PTR
);
183 #elif defined(HAVE_ALARM)
184 static void verbose_stats_dump(int sig
);
187 static void info(int);
188 static u_int packets_captured
;
190 static const struct tok status_flags
[] = {
192 { PCAP_IF_UP
, "Up" },
194 #ifdef PCAP_IF_RUNNING
195 { PCAP_IF_RUNNING
, "Running" },
197 { PCAP_IF_LOOPBACK
, "Loopback" },
203 static int supports_monitor_mode
;
211 char *CurrentFileName
;
219 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
221 show_tstamp_types_and_exit(const char *device
)
224 int *tstamp_types
= 0;
225 const char *tstamp_type_name
;
228 n_tstamp_types
= pcap_list_tstamp_types(pd
, &tstamp_types
);
229 if (n_tstamp_types
< 0)
230 error("%s", pcap_geterr(pd
));
232 if (n_tstamp_types
== 0) {
233 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
237 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
239 for (i
= 0; i
< n_tstamp_types
; i
++) {
240 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
241 if (tstamp_type_name
!= NULL
) {
242 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
243 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
245 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
248 pcap_free_tstamp_types(tstamp_types
);
254 show_dlts_and_exit(const char *device
)
258 const char *dlt_name
;
260 n_dlts
= pcap_list_datalinks(pd
, &dlts
);
262 error("%s", pcap_geterr(pd
));
263 else if (n_dlts
== 0 || !dlts
)
264 error("No data link types.");
267 * If the interface is known to support monitor mode, indicate
268 * whether these are the data link types available when not in
269 * monitor mode, if -I wasn't specified, or when in monitor mode,
270 * when -I was specified (the link-layer types available in
271 * monitor mode might be different from the ones available when
272 * not in monitor mode).
274 if (supports_monitor_mode
)
275 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
277 Iflag
? "when in monitor mode" : "when not in monitor mode");
279 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
282 for (i
= 0; i
< n_dlts
; i
++) {
283 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
284 if (dlt_name
!= NULL
) {
285 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
286 pcap_datalink_val_to_description(dlts
[i
]));
289 * OK, does tcpdump handle that type?
291 if (!has_printer(dlts
[i
]))
292 (void) fprintf(stderr
, " (printing not supported)");
293 fprintf(stderr
, "\n");
295 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
299 #ifdef HAVE_PCAP_FREE_DATALINKS
300 pcap_free_datalinks(dlts
);
305 #ifdef HAVE_PCAP_FINDALLDEVS
307 show_devices_and_exit (void)
309 pcap_if_t
*devpointer
;
310 char ebuf
[PCAP_ERRBUF_SIZE
];
313 if (pcap_findalldevs(&devpointer
, ebuf
) < 0)
316 for (i
= 0; devpointer
!= NULL
; i
++) {
317 printf("%d.%s", i
+1, devpointer
->name
);
318 if (devpointer
->description
!= NULL
)
319 printf(" (%s)", devpointer
->description
);
320 if (devpointer
->flags
!= 0)
321 printf(" [%s]", bittok2str(status_flags
, "none", devpointer
->flags
));
323 devpointer
= devpointer
->next
;
328 #endif /* HAVE_PCAP_FINDALLDEVS */
333 * Note that there we use all letters for short options except for g, k,
334 * o, and P, and those are used by other versions of tcpdump, and we should
335 * only use them for the same purposes that the other versions of tcpdump
338 * OS X tcpdump uses -g to force non--v output for IP to be on one
339 * line, making it more "g"repable;
341 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
344 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
345 * for hosts sending TCP SYN packets;
347 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
350 * OS X tcpdump also uses -Q to specify expressions that match packet
351 * metadata, including but not limited to the packet direction.
352 * The expression syntax is different from a simple "in|out|inout",
353 * and those expressions aren't accepted by OS X tcpdump, but the
354 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
355 * "inout" = "dir=in or dir=out", and the parser could conceivably
356 * special-case "in", "out", and "inout" as expressions for backwards
357 * compatibility, so all is not (yet) lost.
361 * Set up flags that might or might not be supported depending on the
362 * version of libpcap we're using.
364 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
366 #define B_FLAG_USAGE " [ -B size ]"
367 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
370 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
372 #ifdef HAVE_PCAP_CREATE
374 #else /* HAVE_PCAP_CREATE */
376 #endif /* HAVE_PCAP_CREATE */
378 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
380 #define j_FLAG_USAGE " [ -j tstamptype ]"
382 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
386 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
388 #ifdef HAVE_PCAP_FINDALLDEVS
394 #ifdef HAVE_PCAP_DUMP_FLUSH
400 #ifdef HAVE_PCAP_SETDIRECTION
406 #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:#"
411 * We do not currently have long options corresponding to all short
412 * options; we should probably pick appropriate option names for them.
414 * However, the short options where the number of times the option is
415 * specified matters, such as -v and -d and -t, should probably not
416 * just map to a long option, as saying
418 * tcpdump --verbose --verbose
420 * doesn't make sense; it should be --verbosity={N} or something such
423 * For long options with no corresponding short options, we define values
424 * outside the range of ASCII graphic characters, make that the last
425 * component of the entry for the long option, and have a case for that
426 * option in the switch statement.
428 #define OPTION_VERSION 128
429 #define OPTION_TSTAMP_PRECISION 129
430 #define OPTION_IMMEDIATE_MODE 130
432 static const struct option longopts
[] = {
433 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
434 { "buffer-size", required_argument
, NULL
, 'B' },
436 { "list-interfaces", no_argument
, NULL
, 'D' },
437 { "help", no_argument
, NULL
, 'h' },
438 { "interface", required_argument
, NULL
, 'i' },
439 #ifdef HAVE_PCAP_CREATE
440 { "monitor-mode", no_argument
, NULL
, 'I' },
442 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
443 { "time-stamp-type", required_argument
, NULL
, 'j' },
444 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
446 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
447 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
449 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
450 { "list-data-link-types", no_argument
, NULL
, 'L' },
451 { "no-optimize", no_argument
, NULL
, 'O' },
452 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
453 #ifdef HAVE_PCAP_SETDIRECTION
454 { "direction", required_argument
, NULL
, 'Q' },
456 { "snapshot-length", required_argument
, NULL
, 's' },
457 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
458 #ifdef HAVE_PCAP_DUMP_FLUSH
459 { "packet-buffered", no_argument
, NULL
, 'U' },
461 { "linktype", required_argument
, NULL
, 'y' },
462 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
463 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
465 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
466 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
468 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
469 { "number", no_argument
, NULL
, '#' },
470 { "version", no_argument
, NULL
, OPTION_VERSION
},
475 /* Drop root privileges and chroot if necessary */
477 droproot(const char *username
, const char *chroot_dir
)
479 struct passwd
*pw
= NULL
;
481 if (chroot_dir
&& !username
) {
482 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
487 pw
= getpwnam(username
);
490 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
491 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
492 program_name
, chroot_dir
, pcap_strerror(errno
));
496 #ifdef HAVE_LIBCAP_NG
498 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
500 fprintf(stderr
, "error : ret %d\n", ret
);
502 fprintf(stderr
, "dropped privs to %s\n", username
);
506 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
507 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
508 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
509 program_name
, username
,
510 (unsigned long)pw
->pw_uid
,
511 (unsigned long)pw
->pw_gid
,
512 pcap_strerror(errno
));
516 fprintf(stderr
, "dropped privs to %s\n", username
);
518 #endif /* HAVE_LIBCAP_NG */
521 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
522 program_name
, username
);
525 #ifdef HAVE_LIBCAP_NG
526 /* We don't need CAP_SETUID and CAP_SETGID any more. */
529 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
533 capng_apply(CAPNG_SELECT_BOTH
);
534 #endif /* HAVE_LIBCAP_NG */
555 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
557 char *filename
= malloc(PATH_MAX
+ 1);
558 if (filename
== NULL
)
559 error("Makefilename: malloc");
561 /* Process with strftime if Gflag is set. */
565 /* Convert Gflag_time to a usable format */
566 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
567 error("MakeTimedFilename: localtime");
570 /* There's no good way to detect an error in strftime since a return
571 * value of 0 isn't necessarily failure.
573 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
575 strncpy(filename
, orig_name
, PATH_MAX
);
578 if (cnt
== 0 && max_chars
== 0)
579 strncpy(buffer
, filename
, PATH_MAX
+ 1);
581 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
582 /* Report an error if the filename is too large */
583 error("too many output files or filename is too long (> %d)", PATH_MAX
);
588 get_next_file(FILE *VFile
, char *ptr
)
592 ret
= fgets(ptr
, PATH_MAX
, VFile
);
596 if (ptr
[strlen(ptr
) - 1] == '\n')
597 ptr
[strlen(ptr
) - 1] = '\0';
602 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
604 tstamp_precision_from_string(const char *precision
)
606 if (strncmp(precision
, "nano", strlen("nano")) == 0)
607 return PCAP_TSTAMP_PRECISION_NANO
;
609 if (strncmp(precision
, "micro", strlen("micro")) == 0)
610 return PCAP_TSTAMP_PRECISION_MICRO
;
616 tstamp_precision_to_string(int precision
)
620 case PCAP_TSTAMP_PRECISION_MICRO
:
623 case PCAP_TSTAMP_PRECISION_NANO
:
634 * Ensure that, on a dump file's descriptor, we have all the rights
635 * necessary to make the standard I/O library work with an fdopen()ed
636 * FILE * from that descriptor.
638 * A long time ago, in a galaxy far far away, AT&T decided that, instead
639 * of providing separate APIs for getting and setting the FD_ flags on a
640 * descriptor, getting and setting the O_ flags on a descriptor, and
641 * locking files, they'd throw them all into a kitchen-sink fcntl() call
642 * along the lines of ioctl(), the fact that ioctl() operations are
643 * largely specific to particular character devices but fcntl() operations
644 * are either generic to all descriptors or generic to all descriptors for
645 * regular files nonwithstanding.
647 * The Capsicum people decided that fine-grained control of descriptor
648 * operations was required, so that you need to grant permission for
649 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
650 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
651 * collection of things, so there are *individual* fcntls for which
652 * permission needs to be granted.
654 * The FreeBSD standard I/O people implemented some optimizations that
655 * requires that the standard I/O routines be able to determine whether
656 * the descriptor for the FILE * is open append-only or not; as that
657 * descriptor could have come from an open() rather than an fopen(),
658 * that requires that it be able to do an F_GETFL fcntl() to read
661 * Tcpdump uses ftell() to determine how much data has been written
662 * to a file in order to, when used with -C, determine when it's time
663 * to rotate capture files. ftell() therefore needs to do an lseek()
664 * to find out the file offset and must, thanks to the aforementioned
665 * optimization, also know whether the descriptor is open append-only
668 * The net result of all the above is that we need to grant CAP_SEEK,
669 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
671 * Perhaps this is the universe's way of saying that either
673 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
674 * using it, so that Capsicum-capable tcpdump wouldn't need to do
679 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
680 * I/O library that knows what rights are needed by the standard
681 * I/O library, based on the open mode, and assigns them, perhaps
682 * with an additional argument indicating, for example, whether
683 * seeking should be allowed, so that tcpdump doesn't need to know
684 * what the standard I/O library happens to require this week.
687 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
689 int fd
= fileno(pcap_dump_file(p
));
692 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
693 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
694 error("unable to limit dump descriptor");
696 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
697 error("unable to limit dump descriptor fcntls");
703 main(int argc
, char **argv
)
705 register int cnt
, op
, i
;
706 bpf_u_int32 localnet
=0 , netmask
= 0;
707 int timezone_offset
= 0;
708 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
709 pcap_handler callback
;
713 const char *dlt_name
;
714 struct bpf_program fcode
;
716 RETSIGTYPE (*oldhandler
)(int);
718 struct print_info printinfo
;
719 struct dump_info dumpinfo
;
720 u_char
*pcap_userdata
;
721 char ebuf
[PCAP_ERRBUF_SIZE
];
722 char VFileLine
[PATH_MAX
+ 1];
723 char *username
= NULL
;
724 char *chroot_dir
= NULL
;
727 #ifdef HAVE_PCAP_FINDALLDEVS
728 pcap_if_t
*devpointer
;
736 #endif /* HAVE_CAPSICUM */
737 int Bflag
=0; /* buffer size */
738 int jflag
=-1; /* packet time stamp source */
739 int Oflag
=1; /* run filter code optimizer */
740 int pflag
=0; /* don't go promiscuous */
741 netdissect_options Ndo
;
742 netdissect_options
*ndo
= &Ndo
;
745 if(wsockinit() != 0) return 1;
748 memset(ndo
, 0, sizeof(*ndo
));
750 ndo_set_function_pointers(ndo
);
751 ndo
->ndo_snaplen
= DEFAULT_SNAPLEN
;
752 ndo
->ndo_immediate
= 0;
762 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
763 ndo
->program_name
= program_name
= cp
+ 1;
765 ndo
->program_name
= program_name
= argv
[0];
768 * On platforms where the CPU doesn't support unaligned loads,
769 * force unaligned accesses to abort with SIGBUS, rather than
770 * being fixed up (slowly) by the OS kernel; on those platforms,
771 * misaligned accesses are bugs, and we want tcpdump to crash so
772 * that the bugs are reported.
774 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
782 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
786 /* compatibility for old -a */
797 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
799 Bflag
= atoi(optarg
)*1024;
801 error("invalid packet buffer size %s", optarg
);
803 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
808 error("invalid packet count %s", optarg
);
812 Cflag
= atoi(optarg
) * 1000000;
814 error("invalid file size %s", optarg
);
834 #ifndef HAVE_LIBCRYPTO
835 warning("crypto code not compiled in");
837 ndo
->ndo_espsecret
= optarg
;
849 Gflag
= atoi(optarg
);
851 error("invalid number of seconds %s", optarg
);
853 /* We will create one file initially. */
856 /* Grab the current time for rotation use. */
857 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
858 error("main: can't get current time: %s",
859 pcap_strerror(errno
));
873 if (optarg
[0] == '0' && optarg
[1] == 0)
874 error("Invalid adapter index");
876 #ifdef HAVE_PCAP_FINDALLDEVS
878 * If the argument is a number, treat it as
879 * an index into the list of adapters, as
880 * printed by "tcpdump -D".
882 * This should be OK on UNIX systems, as interfaces
883 * shouldn't have names that begin with digits.
884 * It can be useful on Windows, where more than
885 * one interface can have the same name.
887 devnum
= strtol(optarg
, &end
, 10);
888 if (optarg
!= end
&& *end
== '\0') {
890 error("Invalid adapter index");
892 if (pcap_findalldevs(&devpointer
, ebuf
) < 0)
896 * Look for the devnum-th entry
897 * in the list of devices
901 i
< devnum
-1 && devpointer
!= NULL
;
902 i
++, devpointer
= devpointer
->next
)
904 if (devpointer
== NULL
)
905 error("Invalid adapter index");
907 device
= devpointer
->name
;
910 #endif /* HAVE_PCAP_FINDALLDEVS */
914 #ifdef HAVE_PCAP_CREATE
918 #endif /* HAVE_PCAP_CREATE */
920 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
922 jflag
= pcap_tstamp_type_name_to_val(optarg
);
924 error("invalid time stamp type %s", optarg
);
935 * _IOLBF is the same as _IOFBF in Microsoft's C
936 * libraries; the only alternative they offer
939 * XXX - this should really be checking for MSVC++,
940 * not _WIN32, if, for example, MinGW has its own
941 * C library that is more UNIX-compatible.
943 setvbuf(stdout
, NULL
, _IONBF
, 0);
945 #ifdef HAVE_SETLINEBUF
948 setvbuf(stdout
, NULL
, _IOLBF
, 0);
959 if (smiLoadModule(optarg
) == 0) {
960 error("could not load MIB module %s", optarg
);
964 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
965 program_name
, optarg
);
966 (void)fprintf(stderr
, "(no libsmi support)\n");
971 /* TCP-MD5 shared secret */
972 #ifndef HAVE_LIBCRYPTO
973 warning("crypto code not compiled in");
975 ndo
->ndo_sigsecret
= optarg
;
996 ++ndo
->ndo_suppress_default_print
;
999 #ifdef HAVE_PCAP_SETDIRECTION
1001 if (ascii_strcasecmp(optarg
, "in") == 0)
1003 else if (ascii_strcasecmp(optarg
, "out") == 0)
1005 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1006 Qflag
= PCAP_D_INOUT
;
1008 error("unknown capture direction `%s'", optarg
);
1010 #endif /* HAVE_PCAP_SETDIRECTION */
1017 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1018 if (optarg
== end
|| *end
!= '\0'
1019 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1020 error("invalid snaplen %s", optarg
);
1021 else if (ndo
->ndo_snaplen
== 0)
1022 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
1034 if (ascii_strcasecmp(optarg
, "vat") == 0)
1035 ndo
->ndo_packettype
= PT_VAT
;
1036 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1037 ndo
->ndo_packettype
= PT_WB
;
1038 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1039 ndo
->ndo_packettype
= PT_RPC
;
1040 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1041 ndo
->ndo_packettype
= PT_RTP
;
1042 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1043 ndo
->ndo_packettype
= PT_RTCP
;
1044 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1045 ndo
->ndo_packettype
= PT_SNMP
;
1046 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1047 ndo
->ndo_packettype
= PT_CNFP
;
1048 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1049 ndo
->ndo_packettype
= PT_TFTP
;
1050 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1051 ndo
->ndo_packettype
= PT_AODV
;
1052 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1053 ndo
->ndo_packettype
= PT_CARP
;
1054 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1055 ndo
->ndo_packettype
= PT_RADIUS
;
1056 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1057 ndo
->ndo_packettype
= PT_ZMTP1
;
1058 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1059 ndo
->ndo_packettype
= PT_VXLAN
;
1060 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1061 ndo
->ndo_packettype
= PT_PGM
;
1062 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1063 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1064 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1065 ndo
->ndo_packettype
= PT_LMP
;
1067 error("unknown packet type `%s'", optarg
);
1074 #ifdef HAVE_PCAP_DUMP_FLUSH
1093 Wflag
= atoi(optarg
);
1095 error("invalid number of output files %s", optarg
);
1096 WflagChars
= getWflagChars(Wflag
);
1101 ++ndo
->ndo_suppress_default_print
;
1106 ++ndo
->ndo_suppress_default_print
;
1110 ndo
->ndo_dltname
= optarg
;
1112 pcap_datalink_name_to_val(ndo
->ndo_dltname
);
1113 if (ndo
->ndo_dlt
< 0)
1114 error("invalid data link type %s", ndo
->ndo_dltname
);
1117 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1120 /* Undocumented flag */
1121 #ifdef HAVE_PCAP_DEBUG
1122 extern int pcap_debug
;
1132 zflag
= strdup(optarg
);
1134 error("Unable to allocate memory for -z argument");
1138 username
= strdup(optarg
);
1139 if (username
== NULL
)
1140 error("Unable to allocate memory for -Z argument");
1144 ndo
->ndo_packet_number
= 1;
1147 case OPTION_VERSION
:
1152 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1153 case OPTION_TSTAMP_PRECISION
:
1154 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1155 if (ndo
->ndo_tstamp_precision
< 0)
1156 error("unsupported time stamp precision");
1160 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1161 case OPTION_IMMEDIATE_MODE
:
1162 ndo
->ndo_immediate
= 1;
1172 #ifdef HAVE_PCAP_FINDALLDEVS
1174 show_devices_and_exit();
1177 switch (ndo
->ndo_tflag
) {
1179 case 0: /* Default */
1180 case 4: /* Default + Date*/
1181 timezone_offset
= gmt2local(0);
1184 case 1: /* No time stamp */
1185 case 2: /* Unix timeval style */
1186 case 3: /* Microseconds since previous packet */
1187 case 5: /* Microseconds since first packet */
1190 default: /* Not supported */
1191 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1195 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1196 error("-f can not be used with -V or -r");
1198 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1199 error("-V and -r are mutually exclusive.");
1201 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1203 * If we're printing dissected packets to the standard output
1204 * rather than saving raw packets to a file, and the standard
1205 * output is a terminal, use immediate mode, as the user's
1206 * probably expecting to see packets pop up immediately.
1208 if (WFileName
== NULL
&& isatty(1))
1209 ndo
->ndo_immediate
= 1;
1213 /* if run as root, prepare for chrooting */
1214 if (getuid() == 0 || geteuid() == 0) {
1215 /* future extensibility for cmd-line arguments */
1217 chroot_dir
= WITH_CHROOT
;
1222 /* if run as root, prepare for dropping root privileges */
1223 if (getuid() == 0 || geteuid() == 0) {
1224 /* Run with '-Z root' to restore old behaviour */
1226 username
= WITH_USER
;
1230 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1232 * If RFileName is non-null, it's the pathname of a
1233 * savefile to read. If VFileName is non-null, it's
1234 * the pathname of a file containing a list of pathnames
1235 * (one per line) of savefiles to read.
1237 * In either case, we're reading a savefile, not doing
1242 * We don't need network access, so relinquish any set-UID
1243 * or set-GID privileges we have (if any).
1245 * We do *not* want set-UID privileges when opening a
1246 * trace file, as that might let the user read other
1247 * people's trace files (especially if we're set-UID
1250 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1251 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1253 if (VFileName
!= NULL
) {
1254 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1257 VFile
= fopen(VFileName
, "r");
1260 error("Unable to open file: %s\n", strerror(errno
));
1262 ret
= get_next_file(VFile
, VFileLine
);
1264 error("Nothing in %s\n", VFileName
);
1265 RFileName
= VFileLine
;
1268 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1269 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1270 ndo
->ndo_tstamp_precision
, ebuf
);
1272 pd
= pcap_open_offline(RFileName
, ebuf
);
1277 #ifdef HAVE_CAPSICUM
1278 cap_rights_init(&rights
, CAP_READ
);
1279 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1281 error("unable to limit pcap descriptor");
1284 dlt
= pcap_datalink(pd
);
1285 dlt_name
= pcap_datalink_val_to_name(dlt
);
1286 if (dlt_name
== NULL
) {
1287 fprintf(stderr
, "reading from file %s, link-type %u\n",
1291 "reading from file %s, link-type %s (%s)\n",
1292 RFileName
, dlt_name
,
1293 pcap_datalink_val_to_description(dlt
));
1297 * We're doing a live capture.
1299 if (device
== NULL
) {
1300 device
= pcap_lookupdev(ebuf
);
1306 * Print a message to the standard error on Windows.
1307 * XXX - why do it here, with a different message?
1309 if(strlen(device
) == 1) /* we assume that an ASCII string is always longer than 1 char */
1310 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1311 fprintf(stderr
, "%s: listening on %ws\n", program_name
, device
);
1315 fprintf(stderr
, "%s: listening on %s\n", program_name
, device
);
1320 #ifdef HAVE_PCAP_CREATE
1321 pd
= pcap_create(device
, ebuf
);
1324 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1326 show_tstamp_types_and_exit(device
);
1328 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1329 status
= pcap_set_tstamp_precision(pd
, ndo
->ndo_tstamp_precision
);
1331 error("%s: Can't set %ssecond time stamp precision: %s",
1333 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1334 pcap_statustostr(status
));
1337 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1338 if (ndo
->ndo_immediate
) {
1339 status
= pcap_set_immediate_mode(pd
, 1);
1341 error("%s: Can't set immediate mode: %s",
1343 pcap_statustostr(status
));
1347 * Is this an interface that supports monitor mode?
1349 if (pcap_can_set_rfmon(pd
) == 1)
1350 supports_monitor_mode
= 1;
1352 supports_monitor_mode
= 0;
1353 status
= pcap_set_snaplen(pd
, ndo
->ndo_snaplen
);
1355 error("%s: Can't set snapshot length: %s",
1356 device
, pcap_statustostr(status
));
1357 status
= pcap_set_promisc(pd
, !pflag
);
1359 error("%s: Can't set promiscuous mode: %s",
1360 device
, pcap_statustostr(status
));
1362 status
= pcap_set_rfmon(pd
, 1);
1364 error("%s: Can't set monitor mode: %s",
1365 device
, pcap_statustostr(status
));
1367 status
= pcap_set_timeout(pd
, 1000);
1369 error("%s: pcap_set_timeout failed: %s",
1370 device
, pcap_statustostr(status
));
1372 status
= pcap_set_buffer_size(pd
, Bflag
);
1374 error("%s: Can't set buffer size: %s",
1375 device
, pcap_statustostr(status
));
1377 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1379 status
= pcap_set_tstamp_type(pd
, jflag
);
1381 error("%s: Can't set time stamp type: %s",
1382 device
, pcap_statustostr(status
));
1385 status
= pcap_activate(pd
);
1388 * pcap_activate() failed.
1390 cp
= pcap_geterr(pd
);
1391 if (status
== PCAP_ERROR
)
1393 else if ((status
== PCAP_ERROR_NO_SUCH_DEVICE
||
1394 status
== PCAP_ERROR_PERM_DENIED
) &&
1396 error("%s: %s\n(%s)", device
,
1397 pcap_statustostr(status
), cp
);
1399 error("%s: %s", device
,
1400 pcap_statustostr(status
));
1401 } else if (status
> 0) {
1403 * pcap_activate() succeeded, but it's warning us
1404 * of a problem it had.
1406 cp
= pcap_geterr(pd
);
1407 if (status
== PCAP_WARNING
)
1409 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1411 warning("%s: %s\n(%s)", device
,
1412 pcap_statustostr(status
), cp
);
1414 warning("%s: %s", device
,
1415 pcap_statustostr(status
));
1417 #ifdef HAVE_PCAP_SETDIRECTION
1419 status
= pcap_setdirection(pd
, Qflag
);
1421 error("%s: pcap_setdirection() failed: %s",
1422 device
, pcap_geterr(pd
));
1424 #endif /* HAVE_PCAP_SETDIRECTION */
1427 pd
= pcap_open_live(device
, snaplen
, !pflag
, 1000, ebuf
);
1431 warning("%s", ebuf
);
1432 #endif /* HAVE_PCAP_CREATE */
1434 * Let user own process after socket has been opened.
1437 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1438 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1440 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1442 if(pcap_setbuff(pd
, Bflag
)==-1){
1443 error("%s", pcap_geterr(pd
));
1445 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1447 show_dlts_and_exit(device
);
1448 if (ndo
->ndo_dlt
>= 0) {
1449 #ifdef HAVE_PCAP_SET_DATALINK
1450 if (pcap_set_datalink(pd
, ndo
->ndo_dlt
) < 0)
1451 error("%s", pcap_geterr(pd
));
1454 * We don't actually support changing the
1455 * data link type, so we only let them
1456 * set it to what it already is.
1458 if (ndo
->ndo_dlt
!= pcap_datalink(pd
)) {
1459 error("%s is not one of the DLTs supported by this device\n",
1463 (void)fprintf(stderr
, "%s: data link type %s\n",
1464 program_name
, ndo
->ndo_dltname
);
1465 (void)fflush(stderr
);
1467 i
= pcap_snapshot(pd
);
1468 if (ndo
->ndo_snaplen
< i
) {
1469 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1470 ndo
->ndo_snaplen
= i
;
1472 if(ndo
->ndo_fflag
!= 0) {
1473 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1474 warning("foreign (-f) flag used but: %s", ebuf
);
1480 cmdbuf
= read_infile(infile
);
1482 cmdbuf
= copy_argv(&argv
[optind
]);
1484 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1485 error("%s", pcap_geterr(pd
));
1487 bpf_dump(&fcode
, dflag
);
1492 init_print(ndo
, localnet
, netmask
, timezone_offset
);
1495 (void)setsignal(SIGPIPE
, cleanup
);
1496 (void)setsignal(SIGTERM
, cleanup
);
1497 (void)setsignal(SIGINT
, cleanup
);
1499 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1500 (void)setsignal(SIGCHLD
, child_cleanup
);
1502 /* Cooperate with nohup(1) */
1504 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
1505 (void)setsignal(SIGHUP
, oldhandler
);
1510 * If a user name was specified with "-Z", attempt to switch to
1511 * that user's UID. This would probably be used with sudo,
1512 * to allow tcpdump to be run in a special restricted
1513 * account (if you just want to allow users to open capture
1514 * devices, and can't just give users that permission,
1515 * you'd make tcpdump set-UID or set-GID).
1517 * Tcpdump doesn't necessarily write only to one savefile;
1518 * the general only way to allow a -Z instance to write to
1519 * savefiles as the user under whose UID it's run, rather
1520 * than as the user specified with -Z, would thus be to switch
1521 * to the original user ID before opening a capture file and
1522 * then switch back to the -Z user ID after opening the savefile.
1523 * Switching to the -Z user ID only after opening the first
1524 * savefile doesn't handle the general case.
1527 if (getuid() == 0 || geteuid() == 0) {
1528 #ifdef HAVE_LIBCAP_NG
1529 /* Initialize capng */
1530 capng_clear(CAPNG_SELECT_BOTH
);
1534 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1543 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1547 capng_apply(CAPNG_SELECT_BOTH
);
1548 #endif /* HAVE_LIBCAP_NG */
1549 if (username
|| chroot_dir
)
1550 droproot(username
, chroot_dir
);
1555 if (pcap_setfilter(pd
, &fcode
) < 0)
1556 error("%s", pcap_geterr(pd
));
1557 #ifdef HAVE_CAPSICUM
1558 if (RFileName
== NULL
&& VFileName
== NULL
) {
1559 static const unsigned long cmds
[] = { BIOCGSTATS
};
1561 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
);
1562 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
1564 error("unable to limit pcap descriptor");
1566 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
1567 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
1568 error("unable to limit ioctls on pcap descriptor");
1574 /* Do not exceed the default PATH_MAX for files. */
1575 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1577 if (dumpinfo
.CurrentFileName
== NULL
)
1578 error("malloc of dumpinfo.CurrentFileName");
1580 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1582 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
1584 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
1586 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
1587 #ifdef HAVE_LIBCAP_NG
1588 /* Give up CAP_DAC_OVERRIDE capability.
1589 * Only allow it to be restored if the -C or -G flag have been
1590 * set since we may need to create more files later on.
1594 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
1598 capng_apply(CAPNG_SELECT_BOTH
);
1599 #endif /* HAVE_LIBCAP_NG */
1601 error("%s", pcap_geterr(pd
));
1602 #ifdef HAVE_CAPSICUM
1603 set_dumper_capsicum_rights(p
);
1605 if (Cflag
!= 0 || Gflag
!= 0) {
1606 #ifdef HAVE_CAPSICUM
1607 dumpinfo
.WFileName
= strdup(basename(WFileName
));
1608 if (dumpinfo
.WFileName
== NULL
) {
1609 error("Unable to allocate memory for file %s",
1612 dumpinfo
.dirfd
= open(dirname(WFileName
),
1613 O_DIRECTORY
| O_RDONLY
);
1614 if (dumpinfo
.dirfd
< 0) {
1615 error("unable to open directory %s",
1616 dirname(WFileName
));
1618 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
1619 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
1620 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
1622 error("unable to limit directory rights");
1624 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
1626 error("unable to limit dump descriptor fcntls");
1628 #else /* !HAVE_CAPSICUM */
1629 dumpinfo
.WFileName
= WFileName
;
1631 callback
= dump_packet_and_trunc
;
1634 pcap_userdata
= (u_char
*)&dumpinfo
;
1636 callback
= dump_packet
;
1637 pcap_userdata
= (u_char
*)p
;
1639 #ifdef HAVE_PCAP_DUMP_FLUSH
1644 type
= pcap_datalink(pd
);
1645 printinfo
= get_print_info(ndo
, type
);
1646 callback
= print_packet
;
1647 pcap_userdata
= (u_char
*)&printinfo
;
1650 #ifdef SIGNAL_REQ_INFO
1652 * We can't get statistics when reading from a file rather
1653 * than capturing from a device.
1655 if (RFileName
== NULL
)
1656 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
1659 if (ndo
->ndo_vflag
> 0 && WFileName
) {
1661 * When capturing to a file, "-v" means tcpdump should,
1662 * every 10 seconds, "v"erbosely report the number of
1665 #ifdef USE_WIN32_MM_TIMER
1666 /* call verbose_stats_dump() each 1000 +/-100msec */
1667 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
1668 setvbuf(stderr
, NULL
, _IONBF
, 0);
1669 #elif defined(HAVE_ALARM)
1670 (void)setsignal(SIGALRM
, verbose_stats_dump
);
1676 if (RFileName
== NULL
) {
1678 * Live capture (if -V was specified, we set RFileName
1679 * to a file from the -V file). Print a message to
1680 * the standard error on UN*X.
1682 if (!ndo
->ndo_vflag
&& !WFileName
) {
1683 (void)fprintf(stderr
,
1684 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1687 (void)fprintf(stderr
, "%s: ", program_name
);
1688 dlt
= pcap_datalink(pd
);
1689 dlt_name
= pcap_datalink_val_to_name(dlt
);
1690 if (dlt_name
== NULL
) {
1691 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
1692 device
, dlt
, ndo
->ndo_snaplen
);
1694 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1696 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
1698 (void)fflush(stderr
);
1702 #ifdef HAVE_CAPSICUM
1703 cansandbox
= (ndo
->ndo_nflag
&& VFileName
== NULL
&& zflag
== NULL
);
1704 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
1705 error("unable to enter the capability mode");
1706 #endif /* HAVE_CAPSICUM */
1709 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
1710 if (WFileName
== NULL
) {
1712 * We're printing packets. Flush the printed output,
1713 * so it doesn't get intermingled with error output.
1717 * We got interrupted, so perhaps we didn't
1718 * manage to finish a line we were printing.
1719 * Print an extra newline, just in case.
1723 (void)fflush(stdout
);
1727 * We got interrupted. If we are reading multiple
1728 * files (via -V) set these so that we stop.
1737 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
1738 program_name
, pcap_geterr(pd
));
1740 if (RFileName
== NULL
) {
1742 * We're doing a live capture. Report the capture
1748 if (VFileName
!= NULL
) {
1749 ret
= get_next_file(VFile
, VFileLine
);
1751 RFileName
= VFileLine
;
1752 pd
= pcap_open_offline(RFileName
, ebuf
);
1755 #ifdef HAVE_CAPSICUM
1756 cap_rights_init(&rights
, CAP_READ
);
1757 if (cap_rights_limit(fileno(pcap_file(pd
)),
1758 &rights
) < 0 && errno
!= ENOSYS
) {
1759 error("unable to limit pcap descriptor");
1762 new_dlt
= pcap_datalink(pd
);
1763 if (WFileName
&& new_dlt
!= dlt
)
1764 error("%s: new dlt does not match original", RFileName
);
1765 printinfo
= get_print_info(ndo
, new_dlt
);
1766 dlt_name
= pcap_datalink_val_to_name(new_dlt
);
1767 if (dlt_name
== NULL
) {
1768 fprintf(stderr
, "reading from file %s, link-type %u\n",
1769 RFileName
, new_dlt
);
1772 "reading from file %s, link-type %s (%s)\n",
1773 RFileName
, dlt_name
,
1774 pcap_datalink_val_to_description(new_dlt
));
1776 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1777 error("%s", pcap_geterr(pd
));
1778 if (pcap_setfilter(pd
, &fcode
) < 0)
1779 error("%s", pcap_geterr(pd
));
1783 while (ret
!= NULL
);
1786 exit(status
== -1 ? 1 : 0);
1789 /* make a clean exit on interrupts */
1791 cleanup(int signo _U_
)
1793 #ifdef USE_WIN32_MM_TIMER
1795 timeKillEvent(timer_id
);
1797 #elif defined(HAVE_ALARM)
1801 #ifdef HAVE_PCAP_BREAKLOOP
1803 * We have "pcap_breakloop()"; use it, so that we do as little
1804 * as possible in the signal handler (it's probably not safe
1805 * to do anything with standard I/O streams in a signal handler -
1806 * the ANSI C standard doesn't say it is).
1811 * We don't have "pcap_breakloop()"; this isn't safe, but
1812 * it's the best we can do. Print the summary if we're
1813 * not reading from a savefile - i.e., if we're doing a
1814 * live capture - and exit.
1816 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
1818 * We got interrupted, so perhaps we didn't
1819 * manage to finish a line we were printing.
1820 * Print an extra newline, just in case.
1823 (void)fflush(stdout
);
1831 On windows, we do not use a fork, so we do not care less about
1832 waiting a child processes to die
1834 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1836 child_cleanup(int signo _U_
)
1840 #endif /* HAVE_FORK && HAVE_VFORK */
1843 info(register int verbose
)
1845 struct pcap_stat stat
;
1848 * Older versions of libpcap didn't set ps_ifdrop on some
1849 * platforms; initialize it to 0 to handle that.
1852 if (pcap_stats(pd
, &stat
) < 0) {
1853 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
1859 fprintf(stderr
, "%s: ", program_name
);
1861 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
1862 PLURAL_SUFFIX(packets_captured
));
1864 fputs(", ", stderr
);
1867 (void)fprintf(stderr
, "%u packet%s received by filter", stat
.ps_recv
,
1868 PLURAL_SUFFIX(stat
.ps_recv
));
1870 fputs(", ", stderr
);
1873 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stat
.ps_drop
,
1874 PLURAL_SUFFIX(stat
.ps_drop
));
1875 if (stat
.ps_ifdrop
!= 0) {
1877 fputs(", ", stderr
);
1880 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
1881 stat
.ps_ifdrop
, PLURAL_SUFFIX(stat
.ps_ifdrop
));
1887 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1889 compress_savefile(const char *filename
)
1898 * Set to lowest priority so that this doesn't disturb the capture
1901 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
1903 setpriority(PRIO_PROCESS
, 0, 19);
1905 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
1907 "compress_savefile:execlp(%s, %s): %s\n",
1917 #else /* HAVE_FORK && HAVE_VFORK */
1919 compress_savefile(const char *filename
)
1922 "compress_savefile failed. Functionality not implemented under your system\n");
1924 #endif /* HAVE_FORK && HAVE_VFORK */
1927 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
1929 struct dump_info
*dump_info
;
1935 dump_info
= (struct dump_info
*)user
;
1938 * XXX - this won't force the file to rotate on the specified time
1939 * boundary, but it will rotate on the first packet received after the
1940 * specified Gflag number of seconds. Note: if a Gflag time boundary
1941 * and a Cflag size boundary coincide, the time rotation will occur
1942 * first thereby cancelling the Cflag boundary (since the file should
1946 /* Check if it is time to rotate */
1949 /* Get the current time */
1950 if ((t
= time(NULL
)) == (time_t)-1) {
1951 error("dump_and_trunc_packet: can't get current_time: %s",
1952 pcap_strerror(errno
));
1956 /* If the time is greater than the specified window, rotate */
1957 if (t
- Gflag_time
>= Gflag
) {
1958 #ifdef HAVE_CAPSICUM
1963 /* Update the Gflag_time */
1965 /* Update Gflag_count */
1968 * Close the current file and open a new one.
1970 pcap_dump_close(dump_info
->p
);
1973 * Compress the file we just closed, if the user asked for it
1976 compress_savefile(dump_info
->CurrentFileName
);
1979 * Check to see if we've exceeded the Wflag (when
1982 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
1983 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
1988 if (dump_info
->CurrentFileName
!= NULL
)
1989 free(dump_info
->CurrentFileName
);
1990 /* Allocate space for max filename + \0. */
1991 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1992 if (dump_info
->CurrentFileName
== NULL
)
1993 error("dump_packet_and_trunc: malloc");
1995 * Gflag was set otherwise we wouldn't be here. Reset the count
1996 * so multiple files would end with 1,2,3 in the filename.
1997 * The counting is handled with the -C flow after this.
2002 * This is always the first file in the Cflag
2004 * We also don't need numbering if Cflag is not set.
2007 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2010 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2012 #ifdef HAVE_LIBCAP_NG
2013 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2014 capng_apply(CAPNG_SELECT_BOTH
);
2015 #endif /* HAVE_LIBCAP_NG */
2016 #ifdef HAVE_CAPSICUM
2017 fd
= openat(dump_info
->dirfd
,
2018 dump_info
->CurrentFileName
,
2019 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2021 error("unable to open file %s",
2022 dump_info
->CurrentFileName
);
2024 fp
= fdopen(fd
, "w");
2026 error("unable to fdopen file %s",
2027 dump_info
->CurrentFileName
);
2029 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2030 #else /* !HAVE_CAPSICUM */
2031 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2033 #ifdef HAVE_LIBCAP_NG
2034 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2035 capng_apply(CAPNG_SELECT_BOTH
);
2036 #endif /* HAVE_LIBCAP_NG */
2037 if (dump_info
->p
== NULL
)
2038 error("%s", pcap_geterr(pd
));
2039 #ifdef HAVE_CAPSICUM
2040 set_dumper_capsicum_rights(dump_info
->p
);
2046 * XXX - this won't prevent capture files from getting
2047 * larger than Cflag - the last packet written to the
2048 * file could put it over Cflag.
2051 long size
= pcap_dump_ftell(dump_info
->p
);
2054 error("ftell fails on output file");
2056 #ifdef HAVE_CAPSICUM
2062 * Close the current file and open a new one.
2064 pcap_dump_close(dump_info
->p
);
2067 * Compress the file we just closed, if the user
2071 compress_savefile(dump_info
->CurrentFileName
);
2075 if (Cflag_count
>= Wflag
)
2078 if (dump_info
->CurrentFileName
!= NULL
)
2079 free(dump_info
->CurrentFileName
);
2080 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2081 if (dump_info
->CurrentFileName
== NULL
)
2082 error("dump_packet_and_trunc: malloc");
2083 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2084 #ifdef HAVE_LIBCAP_NG
2085 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2086 capng_apply(CAPNG_SELECT_BOTH
);
2087 #endif /* HAVE_LIBCAP_NG */
2088 #ifdef HAVE_CAPSICUM
2089 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2090 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2092 error("unable to open file %s",
2093 dump_info
->CurrentFileName
);
2095 fp
= fdopen(fd
, "w");
2097 error("unable to fdopen file %s",
2098 dump_info
->CurrentFileName
);
2100 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2101 #else /* !HAVE_CAPSICUM */
2102 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2104 #ifdef HAVE_LIBCAP_NG
2105 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2106 capng_apply(CAPNG_SELECT_BOTH
);
2107 #endif /* HAVE_LIBCAP_NG */
2108 if (dump_info
->p
== NULL
)
2109 error("%s", pcap_geterr(pd
));
2110 #ifdef HAVE_CAPSICUM
2111 set_dumper_capsicum_rights(dump_info
->p
);
2116 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2117 #ifdef HAVE_PCAP_DUMP_FLUSH
2119 pcap_dump_flush(dump_info
->p
);
2128 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2134 pcap_dump(user
, h
, sp
);
2135 #ifdef HAVE_PCAP_DUMP_FLUSH
2137 pcap_dump_flush((pcap_dumper_t
*)user
);
2146 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2148 struct print_info
*print_info
;
2154 print_info
= (struct print_info
*)user
;
2156 pretty_print_packet(print_info
, h
, sp
, packets_captured
);
2165 * XXX - there should really be libpcap calls to get the version
2166 * number as a string (the string would be generated from #defines
2167 * at run time, so that it's not generated from string constants
2168 * in the library, as, on many UNIX systems, those constants would
2169 * be statically linked into the application executable image, and
2170 * would thus reflect the version of libpcap on the system on
2171 * which the application was *linked*, not the system on which it's
2174 * That routine should be documented, unlike the "version[]"
2175 * string, so that UNIX vendors providing their own libpcaps
2176 * don't omit it (as a couple of vendors have...).
2178 * Packet.dll should perhaps also export a routine to return the
2179 * version number of the Packet.dll code, to supply the
2180 * "Wpcap_version" information on Windows.
2182 char WDversion
[]="current-git.tcpdump.org";
2183 #if !defined(HAVE_GENERATED_VERSION)
2184 char version
[]="current-git.tcpdump.org";
2186 char pcap_version
[]="current-git.tcpdump.org";
2187 char Wpcap_version
[]="3.1";
2190 #ifdef SIGNAL_REQ_INFO
2191 RETSIGTYPE
requestinfo(int signo _U_
)
2201 * Called once each second in verbose mode while dumping to file
2203 #ifdef USE_WIN32_MM_TIMER
2204 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2205 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2207 struct pcap_stat stat
;
2209 if (infodelay
== 0 && pcap_stats(pd
, &stat
) >= 0)
2210 fprintf(stderr
, "Got %u\r", packets_captured
);
2212 #elif defined(HAVE_ALARM)
2213 static void verbose_stats_dump(int sig _U_
)
2215 struct pcap_stat stat
;
2217 if (infodelay
== 0 && pcap_stats(pd
, &stat
) >= 0)
2218 fprintf(stderr
, "Got %u\r", packets_captured
);
2223 USES_APPLE_DEPRECATED_API
2227 extern char version
[];
2228 #ifndef HAVE_PCAP_LIB_VERSION
2229 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2230 extern char pcap_version
[];
2231 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2232 static char pcap_version
[] = "unknown";
2233 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2234 #endif /* HAVE_PCAP_LIB_VERSION */
2236 #ifdef HAVE_PCAP_LIB_VERSION
2238 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2240 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2242 (void)fprintf(stderr
, "%s\n",pcap_lib_version());
2243 #else /* HAVE_PCAP_LIB_VERSION */
2245 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2246 (void)fprintf(stderr
, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version
, pcap_version
);
2248 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2249 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2251 #endif /* HAVE_PCAP_LIB_VERSION */
2253 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2254 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2258 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2267 (void)fprintf(stderr
,
2268 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2269 (void)fprintf(stderr
,
2270 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2271 (void)fprintf(stderr
,
2272 "\t\t[ -i interface ]" j_FLAG_USAGE
" [ -M secret ] [ --number ]\n");
2273 #ifdef HAVE_PCAP_SETDIRECTION
2274 (void)fprintf(stderr
,
2275 "\t\t[ -Q in|out|inout ]\n");
2277 (void)fprintf(stderr
,
2278 "\t\t[ -r file ] [ -s snaplen ] ");
2279 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2280 (void)fprintf(stderr
, "[ --time-stamp-precision precision ]\n");
2281 (void)fprintf(stderr
,
2284 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2285 (void)fprintf(stderr
, "[ --immediate-mode ] ");
2287 (void)fprintf(stderr
, "[ -T type ] [ --version ] [ -V file ]\n");
2288 (void)fprintf(stderr
,
2289 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2290 (void)fprintf(stderr
,
2291 "\t\t[ -Z user ] [ expression ]\n");
2295 * c-style: whitesmith