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 */
134 * This is exported because, in some versions of libpcap, if libpcap
135 * is built with optimizer debugging code (which is *NOT* the default
136 * configuration!), the library *imports*(!) a variable named dflag,
137 * under the expectation that tcpdump is exporting it, to govern
138 * how much debugging information to print when optimizing
139 * the generated BPF code.
141 * This is a horrible hack; newer versions of libpcap don't import
142 * dflag but, instead, *if* built with optimizer debugging code,
143 * *export* a routine to set that flag.
145 int dflag
; /* print filter code */
146 static int Gflag
; /* rotate dump files after this many seconds */
147 static int Gflag_count
; /* number of files created with Gflag rotation */
148 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
149 static int Lflag
; /* list available data link types and exit */
150 static int Iflag
; /* rfmon (monitor) mode */
151 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
152 static int Jflag
; /* list available time stamp types */
154 #ifdef HAVE_PCAP_SETDIRECTION
155 int Qflag
= -1; /* restrict captured packet by send/receive direction */
157 static int Uflag
; /* "unbuffered" output of dump files */
158 static int Wflag
; /* recycle output files after this number of files */
159 static int WflagChars
;
160 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
162 static int infodelay
;
163 static int infoprint
;
168 static RETSIGTYPE
cleanup(int);
169 static RETSIGTYPE
child_cleanup(int);
170 static void print_version(void);
171 static void print_usage(void);
172 static void show_tstamp_types_and_exit(const char *device
) __attribute__((noreturn
));
173 static void show_dlts_and_exit(const char *device
) __attribute__((noreturn
));
175 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
176 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
177 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
178 static void droproot(const char *, const char *);
180 #ifdef SIGNAL_REQ_INFO
181 RETSIGTYPE
requestinfo(int);
184 #if defined(USE_WIN32_MM_TIMER)
185 #include <MMsystem.h>
186 static UINT timer_id
;
187 static void CALLBACK
verbose_stats_dump(UINT
, UINT
, DWORD_PTR
, DWORD_PTR
, DWORD_PTR
);
188 #elif defined(HAVE_ALARM)
189 static void verbose_stats_dump(int sig
);
192 static void info(int);
193 static u_int packets_captured
;
195 static const struct tok status_flags
[] = {
197 { PCAP_IF_UP
, "Up" },
199 #ifdef PCAP_IF_RUNNING
200 { PCAP_IF_RUNNING
, "Running" },
202 { PCAP_IF_LOOPBACK
, "Loopback" },
208 static int supports_monitor_mode
;
216 char *CurrentFileName
;
224 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
226 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
227 * by any libpcap header, because it's a special hack, only available if
228 * libpcap was configured to include it, and only intended for use by
229 * libpcap developers trying to debug the parser for filter expressions).
232 __declspec(dllimport
)
236 void pcap_set_parser_debug(int);
237 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
239 * We don't have pcap_set_parser_debug() in libpcap, but we do have
240 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
241 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
244 pcap_set_parser_debug(int value
)
246 #ifdef HAVE_PCAP_DEBUG
247 extern int pcap_debug
;
250 #else /* HAVE_PCAP_DEBUG */
254 #endif /* HAVE_PCAP_DEBUG */
257 #define HAVE_PCAP_SET_PARSER_DEBUG
260 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
262 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
263 * by any libpcap header, because it's a special hack, only available if
264 * libpcap was configured to include it, and only intended for use by
265 * libpcap developers trying to debug the optimizer for filter expressions).
268 __declspec(dllimport
)
272 void pcap_set_optimizer_debug(int);
275 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
277 show_tstamp_types_and_exit(const char *device
)
280 int *tstamp_types
= 0;
281 const char *tstamp_type_name
;
284 n_tstamp_types
= pcap_list_tstamp_types(pd
, &tstamp_types
);
285 if (n_tstamp_types
< 0)
286 error("%s", pcap_geterr(pd
));
288 if (n_tstamp_types
== 0) {
289 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
293 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
295 for (i
= 0; i
< n_tstamp_types
; i
++) {
296 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
297 if (tstamp_type_name
!= NULL
) {
298 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
299 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
301 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
304 pcap_free_tstamp_types(tstamp_types
);
310 show_dlts_and_exit(const char *device
)
314 const char *dlt_name
;
316 n_dlts
= pcap_list_datalinks(pd
, &dlts
);
318 error("%s", pcap_geterr(pd
));
319 else if (n_dlts
== 0 || !dlts
)
320 error("No data link types.");
323 * If the interface is known to support monitor mode, indicate
324 * whether these are the data link types available when not in
325 * monitor mode, if -I wasn't specified, or when in monitor mode,
326 * when -I was specified (the link-layer types available in
327 * monitor mode might be different from the ones available when
328 * not in monitor mode).
330 if (supports_monitor_mode
)
331 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
333 Iflag
? "when in monitor mode" : "when not in monitor mode");
335 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
338 for (i
= 0; i
< n_dlts
; i
++) {
339 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
340 if (dlt_name
!= NULL
) {
341 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
342 pcap_datalink_val_to_description(dlts
[i
]));
345 * OK, does tcpdump handle that type?
347 if (!has_printer(dlts
[i
]))
348 (void) fprintf(stderr
, " (printing not supported)");
349 fprintf(stderr
, "\n");
351 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
355 #ifdef HAVE_PCAP_FREE_DATALINKS
356 pcap_free_datalinks(dlts
);
361 #ifdef HAVE_PCAP_FINDALLDEVS
363 show_devices_and_exit (void)
365 pcap_if_t
*dev
, *devlist
;
366 char ebuf
[PCAP_ERRBUF_SIZE
];
369 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
371 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
372 printf("%d.%s", i
+1, dev
->name
);
373 if (dev
->description
!= NULL
)
374 printf(" (%s)", dev
->description
);
376 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
379 pcap_freealldevs(devlist
);
382 #endif /* HAVE_PCAP_FINDALLDEVS */
387 * Note that there we use all letters for short options except for g, k,
388 * o, and P, and those are used by other versions of tcpdump, and we should
389 * only use them for the same purposes that the other versions of tcpdump
392 * OS X tcpdump uses -g to force non--v output for IP to be on one
393 * line, making it more "g"repable;
395 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
398 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
399 * for hosts sending TCP SYN packets;
401 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
404 * OS X tcpdump also uses -Q to specify expressions that match packet
405 * metadata, including but not limited to the packet direction.
406 * The expression syntax is different from a simple "in|out|inout",
407 * and those expressions aren't accepted by OS X tcpdump, but the
408 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
409 * "inout" = "dir=in or dir=out", and the parser could conceivably
410 * special-case "in", "out", and "inout" as expressions for backwards
411 * compatibility, so all is not (yet) lost.
415 * Set up flags that might or might not be supported depending on the
416 * version of libpcap we're using.
418 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
420 #define B_FLAG_USAGE " [ -B size ]"
421 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
424 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
426 #ifdef HAVE_PCAP_CREATE
428 #else /* HAVE_PCAP_CREATE */
430 #endif /* HAVE_PCAP_CREATE */
432 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
434 #define j_FLAG_USAGE " [ -j tstamptype ]"
436 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
440 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
442 #ifdef HAVE_PCAP_FINDALLDEVS
448 #ifdef HAVE_PCAP_DUMP_FLUSH
454 #ifdef HAVE_PCAP_SETDIRECTION
460 #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:#"
465 * We do not currently have long options corresponding to all short
466 * options; we should probably pick appropriate option names for them.
468 * However, the short options where the number of times the option is
469 * specified matters, such as -v and -d and -t, should probably not
470 * just map to a long option, as saying
472 * tcpdump --verbose --verbose
474 * doesn't make sense; it should be --verbosity={N} or something such
477 * For long options with no corresponding short options, we define values
478 * outside the range of ASCII graphic characters, make that the last
479 * component of the entry for the long option, and have a case for that
480 * option in the switch statement.
482 #define OPTION_VERSION 128
483 #define OPTION_TSTAMP_PRECISION 129
484 #define OPTION_IMMEDIATE_MODE 130
486 static const struct option longopts
[] = {
487 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
488 { "buffer-size", required_argument
, NULL
, 'B' },
490 { "list-interfaces", no_argument
, NULL
, 'D' },
491 { "help", no_argument
, NULL
, 'h' },
492 { "interface", required_argument
, NULL
, 'i' },
493 #ifdef HAVE_PCAP_CREATE
494 { "monitor-mode", no_argument
, NULL
, 'I' },
496 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
497 { "time-stamp-type", required_argument
, NULL
, 'j' },
498 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
500 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
501 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
503 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
504 { "list-data-link-types", no_argument
, NULL
, 'L' },
505 { "no-optimize", no_argument
, NULL
, 'O' },
506 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
507 #ifdef HAVE_PCAP_SETDIRECTION
508 { "direction", required_argument
, NULL
, 'Q' },
510 { "snapshot-length", required_argument
, NULL
, 's' },
511 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
512 #ifdef HAVE_PCAP_DUMP_FLUSH
513 { "packet-buffered", no_argument
, NULL
, 'U' },
515 { "linktype", required_argument
, NULL
, 'y' },
516 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
517 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
519 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
520 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
522 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
523 { "number", no_argument
, NULL
, '#' },
524 { "version", no_argument
, NULL
, OPTION_VERSION
},
529 /* Drop root privileges and chroot if necessary */
531 droproot(const char *username
, const char *chroot_dir
)
533 struct passwd
*pw
= NULL
;
535 if (chroot_dir
&& !username
) {
536 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
541 pw
= getpwnam(username
);
544 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
545 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
546 program_name
, chroot_dir
, pcap_strerror(errno
));
550 #ifdef HAVE_LIBCAP_NG
552 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
554 fprintf(stderr
, "error : ret %d\n", ret
);
556 fprintf(stderr
, "dropped privs to %s\n", username
);
560 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
561 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
562 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
563 program_name
, username
,
564 (unsigned long)pw
->pw_uid
,
565 (unsigned long)pw
->pw_gid
,
566 pcap_strerror(errno
));
570 fprintf(stderr
, "dropped privs to %s\n", username
);
572 #endif /* HAVE_LIBCAP_NG */
575 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
576 program_name
, username
);
579 #ifdef HAVE_LIBCAP_NG
580 /* We don't need CAP_SETUID and CAP_SETGID any more. */
583 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
587 capng_apply(CAPNG_SELECT_BOTH
);
588 #endif /* HAVE_LIBCAP_NG */
609 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
611 char *filename
= malloc(PATH_MAX
+ 1);
612 if (filename
== NULL
)
613 error("Makefilename: malloc");
615 /* Process with strftime if Gflag is set. */
619 /* Convert Gflag_time to a usable format */
620 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
621 error("MakeTimedFilename: localtime");
624 /* There's no good way to detect an error in strftime since a return
625 * value of 0 isn't necessarily failure.
627 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
629 strncpy(filename
, orig_name
, PATH_MAX
);
632 if (cnt
== 0 && max_chars
== 0)
633 strncpy(buffer
, filename
, PATH_MAX
+ 1);
635 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
636 /* Report an error if the filename is too large */
637 error("too many output files or filename is too long (> %d)", PATH_MAX
);
642 get_next_file(FILE *VFile
, char *ptr
)
646 ret
= fgets(ptr
, PATH_MAX
, VFile
);
650 if (ptr
[strlen(ptr
) - 1] == '\n')
651 ptr
[strlen(ptr
) - 1] = '\0';
656 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
658 tstamp_precision_from_string(const char *precision
)
660 if (strncmp(precision
, "nano", strlen("nano")) == 0)
661 return PCAP_TSTAMP_PRECISION_NANO
;
663 if (strncmp(precision
, "micro", strlen("micro")) == 0)
664 return PCAP_TSTAMP_PRECISION_MICRO
;
670 tstamp_precision_to_string(int precision
)
674 case PCAP_TSTAMP_PRECISION_MICRO
:
677 case PCAP_TSTAMP_PRECISION_NANO
:
688 * Ensure that, on a dump file's descriptor, we have all the rights
689 * necessary to make the standard I/O library work with an fdopen()ed
690 * FILE * from that descriptor.
692 * A long time ago, in a galaxy far far away, AT&T decided that, instead
693 * of providing separate APIs for getting and setting the FD_ flags on a
694 * descriptor, getting and setting the O_ flags on a descriptor, and
695 * locking files, they'd throw them all into a kitchen-sink fcntl() call
696 * along the lines of ioctl(), the fact that ioctl() operations are
697 * largely specific to particular character devices but fcntl() operations
698 * are either generic to all descriptors or generic to all descriptors for
699 * regular files nonwithstanding.
701 * The Capsicum people decided that fine-grained control of descriptor
702 * operations was required, so that you need to grant permission for
703 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
704 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
705 * collection of things, so there are *individual* fcntls for which
706 * permission needs to be granted.
708 * The FreeBSD standard I/O people implemented some optimizations that
709 * requires that the standard I/O routines be able to determine whether
710 * the descriptor for the FILE * is open append-only or not; as that
711 * descriptor could have come from an open() rather than an fopen(),
712 * that requires that it be able to do an F_GETFL fcntl() to read
715 * Tcpdump uses ftell() to determine how much data has been written
716 * to a file in order to, when used with -C, determine when it's time
717 * to rotate capture files. ftell() therefore needs to do an lseek()
718 * to find out the file offset and must, thanks to the aforementioned
719 * optimization, also know whether the descriptor is open append-only
722 * The net result of all the above is that we need to grant CAP_SEEK,
723 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
725 * Perhaps this is the universe's way of saying that either
727 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
728 * using it, so that Capsicum-capable tcpdump wouldn't need to do
733 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
734 * I/O library that knows what rights are needed by the standard
735 * I/O library, based on the open mode, and assigns them, perhaps
736 * with an additional argument indicating, for example, whether
737 * seeking should be allowed, so that tcpdump doesn't need to know
738 * what the standard I/O library happens to require this week.
741 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
743 int fd
= fileno(pcap_dump_file(p
));
746 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
747 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
748 error("unable to limit dump descriptor");
750 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
751 error("unable to limit dump descriptor fcntls");
757 main(int argc
, char **argv
)
759 register int cnt
, op
, i
;
760 bpf_u_int32 localnet
=0 , netmask
= 0;
761 int timezone_offset
= 0;
762 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
763 pcap_handler callback
;
765 const char *dlt_name
;
766 struct bpf_program fcode
;
768 RETSIGTYPE (*oldhandler
)(int);
770 struct dump_info dumpinfo
;
771 u_char
*pcap_userdata
;
772 char ebuf
[PCAP_ERRBUF_SIZE
];
773 char VFileLine
[PATH_MAX
+ 1];
774 char *username
= NULL
;
775 char *chroot_dir
= NULL
;
778 #ifdef HAVE_PCAP_FINDALLDEVS
779 pcap_if_t
*dev
, *devlist
;
787 #endif /* HAVE_CAPSICUM */
788 int Bflag
= 0; /* buffer size */
789 int jflag
= -1; /* packet time stamp source */
790 int Oflag
= 1; /* run filter code optimizer */
791 int pflag
= 0; /* don't go promiscuous */
793 const char *yflag_dlt_name
= NULL
;
795 netdissect_options Ndo
;
796 netdissect_options
*ndo
= &Ndo
;
797 int immediate_mode
= 0;
799 memset(ndo
, 0, sizeof(*ndo
));
800 ndo_set_function_pointers(ndo
);
801 ndo
->ndo_snaplen
= DEFAULT_SNAPLEN
;
811 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
812 ndo
->program_name
= program_name
= cp
+ 1;
814 ndo
->program_name
= program_name
= argv
[0];
817 if (pcap_wsockinit() != 0)
818 error("Attempting to initialize Winsock failed");
822 * On platforms where the CPU doesn't support unaligned loads,
823 * force unaligned accesses to abort with SIGBUS, rather than
824 * being fixed up (slowly) by the OS kernel; on those platforms,
825 * misaligned accesses are bugs, and we want tcpdump to crash so
826 * that the bugs are reported.
828 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
836 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
840 /* compatibility for old -a */
851 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
853 Bflag
= atoi(optarg
)*1024;
855 error("invalid packet buffer size %s", optarg
);
857 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
862 error("invalid packet count %s", optarg
);
866 Cflag
= atoi(optarg
) * 1000000;
868 error("invalid file size %s", optarg
);
888 #ifndef HAVE_LIBCRYPTO
889 warning("crypto code not compiled in");
891 ndo
->ndo_espsecret
= optarg
;
903 Gflag
= atoi(optarg
);
905 error("invalid number of seconds %s", optarg
);
907 /* We will create one file initially. */
910 /* Grab the current time for rotation use. */
911 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
912 error("main: can't get current time: %s",
913 pcap_strerror(errno
));
927 if (optarg
[0] == '0' && optarg
[1] == 0)
928 error("Invalid adapter index");
930 #ifdef HAVE_PCAP_FINDALLDEVS
932 * If the argument is a number, treat it as
933 * an index into the list of adapters, as
934 * printed by "tcpdump -D".
936 * This should be OK on UNIX systems, as interfaces
937 * shouldn't have names that begin with digits.
938 * It can be useful on Windows, where more than
939 * one interface can have the same name.
941 devnum
= strtol(optarg
, &end
, 10);
942 if (optarg
!= end
&& *end
== '\0') {
944 error("Invalid adapter index");
946 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
949 * Look for the devnum-th entry in the
950 * list of devices (1-based).
952 for (i
= 0, dev
= devlist
;
953 i
< devnum
-1 && dev
!= NULL
;
954 i
++, dev
= dev
->next
)
957 error("Invalid adapter index");
958 device
= strdup(dev
->name
);
959 pcap_freealldevs(devlist
);
962 #endif /* HAVE_PCAP_FINDALLDEVS */
966 #ifdef HAVE_PCAP_CREATE
970 #endif /* HAVE_PCAP_CREATE */
972 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
974 jflag
= pcap_tstamp_type_name_to_val(optarg
);
976 error("invalid time stamp type %s", optarg
);
987 * _IOLBF is the same as _IOFBF in Microsoft's C
988 * libraries; the only alternative they offer
991 * XXX - this should really be checking for MSVC++,
992 * not _WIN32, if, for example, MinGW has its own
993 * C library that is more UNIX-compatible.
995 setvbuf(stdout
, NULL
, _IONBF
, 0);
997 #ifdef HAVE_SETLINEBUF
1000 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1011 if (smiLoadModule(optarg
) == 0) {
1012 error("could not load MIB module %s", optarg
);
1016 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1017 program_name
, optarg
);
1018 (void)fprintf(stderr
, "(no libsmi support)\n");
1023 /* TCP-MD5 shared secret */
1024 #ifndef HAVE_LIBCRYPTO
1025 warning("crypto code not compiled in");
1027 ndo
->ndo_sigsecret
= optarg
;
1048 ++ndo
->ndo_suppress_default_print
;
1051 #ifdef HAVE_PCAP_SETDIRECTION
1053 if (ascii_strcasecmp(optarg
, "in") == 0)
1055 else if (ascii_strcasecmp(optarg
, "out") == 0)
1057 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1058 Qflag
= PCAP_D_INOUT
;
1060 error("unknown capture direction `%s'", optarg
);
1062 #endif /* HAVE_PCAP_SETDIRECTION */
1069 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1070 if (optarg
== end
|| *end
!= '\0'
1071 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1072 error("invalid snaplen %s", optarg
);
1073 else if (ndo
->ndo_snaplen
== 0)
1074 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
1086 if (ascii_strcasecmp(optarg
, "vat") == 0)
1087 ndo
->ndo_packettype
= PT_VAT
;
1088 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1089 ndo
->ndo_packettype
= PT_WB
;
1090 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1091 ndo
->ndo_packettype
= PT_RPC
;
1092 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1093 ndo
->ndo_packettype
= PT_RTP
;
1094 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1095 ndo
->ndo_packettype
= PT_RTCP
;
1096 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1097 ndo
->ndo_packettype
= PT_SNMP
;
1098 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1099 ndo
->ndo_packettype
= PT_CNFP
;
1100 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1101 ndo
->ndo_packettype
= PT_TFTP
;
1102 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1103 ndo
->ndo_packettype
= PT_AODV
;
1104 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1105 ndo
->ndo_packettype
= PT_CARP
;
1106 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1107 ndo
->ndo_packettype
= PT_RADIUS
;
1108 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1109 ndo
->ndo_packettype
= PT_ZMTP1
;
1110 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1111 ndo
->ndo_packettype
= PT_VXLAN
;
1112 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1113 ndo
->ndo_packettype
= PT_PGM
;
1114 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1115 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1116 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1117 ndo
->ndo_packettype
= PT_LMP
;
1118 else if (strcasecmp(optarg
, "resp") == 0)
1119 ndo
->ndo_packettype
= PT_RESP
;
1121 error("unknown packet type `%s'", optarg
);
1128 #ifdef HAVE_PCAP_DUMP_FLUSH
1147 Wflag
= atoi(optarg
);
1149 error("invalid number of output files %s", optarg
);
1150 WflagChars
= getWflagChars(Wflag
);
1155 ++ndo
->ndo_suppress_default_print
;
1160 ++ndo
->ndo_suppress_default_print
;
1164 yflag_dlt_name
= optarg
;
1166 pcap_datalink_name_to_val(yflag_dlt_name
);
1168 error("invalid data link type %s", yflag_dlt_name
);
1171 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1174 /* Undocumented flag */
1175 pcap_set_parser_debug(1);
1188 ndo
->ndo_packet_number
= 1;
1191 case OPTION_VERSION
:
1196 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1197 case OPTION_TSTAMP_PRECISION
:
1198 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1199 if (ndo
->ndo_tstamp_precision
< 0)
1200 error("unsupported time stamp precision");
1204 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1205 case OPTION_IMMEDIATE_MODE
:
1216 #ifdef HAVE_PCAP_FINDALLDEVS
1218 show_devices_and_exit();
1221 switch (ndo
->ndo_tflag
) {
1223 case 0: /* Default */
1224 case 4: /* Default + Date*/
1225 timezone_offset
= gmt2local(0);
1228 case 1: /* No time stamp */
1229 case 2: /* Unix timeval style */
1230 case 3: /* Microseconds since previous packet */
1231 case 5: /* Microseconds since first packet */
1234 default: /* Not supported */
1235 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1239 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1240 error("-f can not be used with -V or -r");
1242 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1243 error("-V and -r are mutually exclusive.");
1245 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1247 * If we're printing dissected packets to the standard output
1248 * rather than saving raw packets to a file, and the standard
1249 * output is a terminal, use immediate mode, as the user's
1250 * probably expecting to see packets pop up immediately.
1252 if (WFileName
== NULL
&& isatty(1))
1257 /* if run as root, prepare for chrooting */
1258 if (getuid() == 0 || geteuid() == 0) {
1259 /* future extensibility for cmd-line arguments */
1261 chroot_dir
= WITH_CHROOT
;
1266 /* if run as root, prepare for dropping root privileges */
1267 if (getuid() == 0 || geteuid() == 0) {
1268 /* Run with '-Z root' to restore old behaviour */
1270 username
= WITH_USER
;
1274 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1276 * If RFileName is non-null, it's the pathname of a
1277 * savefile to read. If VFileName is non-null, it's
1278 * the pathname of a file containing a list of pathnames
1279 * (one per line) of savefiles to read.
1281 * In either case, we're reading a savefile, not doing
1286 * We don't need network access, so relinquish any set-UID
1287 * or set-GID privileges we have (if any).
1289 * We do *not* want set-UID privileges when opening a
1290 * trace file, as that might let the user read other
1291 * people's trace files (especially if we're set-UID
1294 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1295 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1297 if (VFileName
!= NULL
) {
1298 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1301 VFile
= fopen(VFileName
, "r");
1304 error("Unable to open file: %s\n", pcap_strerror(errno
));
1306 ret
= get_next_file(VFile
, VFileLine
);
1308 error("Nothing in %s\n", VFileName
);
1309 RFileName
= VFileLine
;
1312 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1313 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1314 ndo
->ndo_tstamp_precision
, ebuf
);
1316 pd
= pcap_open_offline(RFileName
, ebuf
);
1321 #ifdef HAVE_CAPSICUM
1322 cap_rights_init(&rights
, CAP_READ
);
1323 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1325 error("unable to limit pcap descriptor");
1328 dlt
= pcap_datalink(pd
);
1329 dlt_name
= pcap_datalink_val_to_name(dlt
);
1330 if (dlt_name
== NULL
) {
1331 fprintf(stderr
, "reading from file %s, link-type %u\n",
1335 "reading from file %s, link-type %s (%s)\n",
1336 RFileName
, dlt_name
,
1337 pcap_datalink_val_to_description(dlt
));
1341 * We're doing a live capture.
1343 if (device
== NULL
) {
1344 #ifdef HAVE_PCAP_FINDALLDEVS
1345 if (pcap_findalldevs(&devlist
, ebuf
) >= 0 &&
1347 device
= strdup(devlist
->name
);
1348 pcap_freealldevs(devlist
);
1350 #else /* HAVE_PCAP_FINDALLDEVS */
1351 device
= pcap_lookupdev(ebuf
);
1358 * Print a message to the standard error on Windows.
1359 * XXX - why do it here, with a different message?
1361 if(strlen(device
) == 1) /* we assume that an ASCII string is always longer than 1 char */
1362 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1363 fprintf(stderr
, "%s: listening on %ws\n", program_name
, device
);
1367 fprintf(stderr
, "%s: listening on %s\n", program_name
, device
);
1372 #ifdef HAVE_PCAP_CREATE
1373 pd
= pcap_create(device
, ebuf
);
1376 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1378 show_tstamp_types_and_exit(device
);
1380 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1381 status
= pcap_set_tstamp_precision(pd
, ndo
->ndo_tstamp_precision
);
1383 error("%s: Can't set %ssecond time stamp precision: %s",
1385 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1386 pcap_statustostr(status
));
1389 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1390 if (immediate_mode
) {
1391 status
= pcap_set_immediate_mode(pd
, 1);
1393 error("%s: Can't set immediate mode: %s",
1395 pcap_statustostr(status
));
1399 * Is this an interface that supports monitor mode?
1401 if (pcap_can_set_rfmon(pd
) == 1)
1402 supports_monitor_mode
= 1;
1404 supports_monitor_mode
= 0;
1405 status
= pcap_set_snaplen(pd
, ndo
->ndo_snaplen
);
1407 error("%s: Can't set snapshot length: %s",
1408 device
, pcap_statustostr(status
));
1409 status
= pcap_set_promisc(pd
, !pflag
);
1411 error("%s: Can't set promiscuous mode: %s",
1412 device
, pcap_statustostr(status
));
1414 status
= pcap_set_rfmon(pd
, 1);
1416 error("%s: Can't set monitor mode: %s",
1417 device
, pcap_statustostr(status
));
1419 status
= pcap_set_timeout(pd
, 1000);
1421 error("%s: pcap_set_timeout failed: %s",
1422 device
, pcap_statustostr(status
));
1424 status
= pcap_set_buffer_size(pd
, Bflag
);
1426 error("%s: Can't set buffer size: %s",
1427 device
, pcap_statustostr(status
));
1429 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1431 status
= pcap_set_tstamp_type(pd
, jflag
);
1433 error("%s: Can't set time stamp type: %s",
1434 device
, pcap_statustostr(status
));
1437 status
= pcap_activate(pd
);
1440 * pcap_activate() failed.
1442 cp
= pcap_geterr(pd
);
1443 if (status
== PCAP_ERROR
)
1445 else if ((status
== PCAP_ERROR_NO_SUCH_DEVICE
||
1446 status
== PCAP_ERROR_PERM_DENIED
) &&
1448 error("%s: %s\n(%s)", device
,
1449 pcap_statustostr(status
), cp
);
1451 error("%s: %s", device
,
1452 pcap_statustostr(status
));
1453 } else if (status
> 0) {
1455 * pcap_activate() succeeded, but it's warning us
1456 * of a problem it had.
1458 cp
= pcap_geterr(pd
);
1459 if (status
== PCAP_WARNING
)
1461 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1463 warning("%s: %s\n(%s)", device
,
1464 pcap_statustostr(status
), cp
);
1466 warning("%s: %s", device
,
1467 pcap_statustostr(status
));
1469 #ifdef HAVE_PCAP_SETDIRECTION
1471 status
= pcap_setdirection(pd
, Qflag
);
1473 error("%s: pcap_setdirection() failed: %s",
1474 device
, pcap_geterr(pd
));
1476 #endif /* HAVE_PCAP_SETDIRECTION */
1479 pd
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000,
1484 warning("%s", ebuf
);
1485 #endif /* HAVE_PCAP_CREATE */
1487 * Let user own process after socket has been opened.
1490 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1491 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1493 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1495 if(pcap_setbuff(pd
, Bflag
)==-1){
1496 error("%s", pcap_geterr(pd
));
1498 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1500 show_dlts_and_exit(device
);
1501 if (yflag_dlt
>= 0) {
1502 #ifdef HAVE_PCAP_SET_DATALINK
1503 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1504 error("%s", pcap_geterr(pd
));
1507 * We don't actually support changing the
1508 * data link type, so we only let them
1509 * set it to what it already is.
1511 if (yflag_dlt
!= pcap_datalink(pd
)) {
1512 error("%s is not one of the DLTs supported by this device\n",
1516 (void)fprintf(stderr
, "%s: data link type %s\n",
1517 program_name
, yflag_dlt_name
);
1518 (void)fflush(stderr
);
1520 i
= pcap_snapshot(pd
);
1521 if (ndo
->ndo_snaplen
< i
) {
1522 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1523 ndo
->ndo_snaplen
= i
;
1525 if(ndo
->ndo_fflag
!= 0) {
1526 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1527 warning("foreign (-f) flag used but: %s", ebuf
);
1533 cmdbuf
= read_infile(infile
);
1535 cmdbuf
= copy_argv(&argv
[optind
]);
1537 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1538 pcap_set_optimizer_debug(dflag
);
1540 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1541 error("%s", pcap_geterr(pd
));
1543 bpf_dump(&fcode
, dflag
);
1546 pcap_freecode(&fcode
);
1549 init_print(ndo
, localnet
, netmask
, timezone_offset
);
1552 (void)setsignal(SIGPIPE
, cleanup
);
1553 (void)setsignal(SIGTERM
, cleanup
);
1554 (void)setsignal(SIGINT
, cleanup
);
1556 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1557 (void)setsignal(SIGCHLD
, child_cleanup
);
1559 /* Cooperate with nohup(1) */
1561 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
1562 (void)setsignal(SIGHUP
, oldhandler
);
1567 * If a user name was specified with "-Z", attempt to switch to
1568 * that user's UID. This would probably be used with sudo,
1569 * to allow tcpdump to be run in a special restricted
1570 * account (if you just want to allow users to open capture
1571 * devices, and can't just give users that permission,
1572 * you'd make tcpdump set-UID or set-GID).
1574 * Tcpdump doesn't necessarily write only to one savefile;
1575 * the general only way to allow a -Z instance to write to
1576 * savefiles as the user under whose UID it's run, rather
1577 * than as the user specified with -Z, would thus be to switch
1578 * to the original user ID before opening a capture file and
1579 * then switch back to the -Z user ID after opening the savefile.
1580 * Switching to the -Z user ID only after opening the first
1581 * savefile doesn't handle the general case.
1584 if (getuid() == 0 || geteuid() == 0) {
1585 #ifdef HAVE_LIBCAP_NG
1586 /* Initialize capng */
1587 capng_clear(CAPNG_SELECT_BOTH
);
1591 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1600 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1604 capng_apply(CAPNG_SELECT_BOTH
);
1605 #endif /* HAVE_LIBCAP_NG */
1606 if (username
|| chroot_dir
)
1607 droproot(username
, chroot_dir
);
1612 if (pcap_setfilter(pd
, &fcode
) < 0)
1613 error("%s", pcap_geterr(pd
));
1614 #ifdef HAVE_CAPSICUM
1615 if (RFileName
== NULL
&& VFileName
== NULL
) {
1616 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
1618 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
);
1619 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
1621 error("unable to limit pcap descriptor");
1623 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
1624 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
1625 error("unable to limit ioctls on pcap descriptor");
1631 /* Do not exceed the default PATH_MAX for files. */
1632 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1634 if (dumpinfo
.CurrentFileName
== NULL
)
1635 error("malloc of dumpinfo.CurrentFileName");
1637 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1639 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
1641 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
1643 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
1644 #ifdef HAVE_LIBCAP_NG
1645 /* Give up CAP_DAC_OVERRIDE capability.
1646 * Only allow it to be restored if the -C or -G flag have been
1647 * set since we may need to create more files later on.
1651 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
1655 capng_apply(CAPNG_SELECT_BOTH
);
1656 #endif /* HAVE_LIBCAP_NG */
1658 error("%s", pcap_geterr(pd
));
1659 #ifdef HAVE_CAPSICUM
1660 set_dumper_capsicum_rights(p
);
1662 if (Cflag
!= 0 || Gflag
!= 0) {
1663 #ifdef HAVE_CAPSICUM
1664 dumpinfo
.WFileName
= strdup(basename(WFileName
));
1665 if (dumpinfo
.WFileName
== NULL
) {
1666 error("Unable to allocate memory for file %s",
1669 dumpinfo
.dirfd
= open(dirname(WFileName
),
1670 O_DIRECTORY
| O_RDONLY
);
1671 if (dumpinfo
.dirfd
< 0) {
1672 error("unable to open directory %s",
1673 dirname(WFileName
));
1675 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
1676 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
1677 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
1679 error("unable to limit directory rights");
1681 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
1683 error("unable to limit dump descriptor fcntls");
1685 #else /* !HAVE_CAPSICUM */
1686 dumpinfo
.WFileName
= WFileName
;
1688 callback
= dump_packet_and_trunc
;
1691 pcap_userdata
= (u_char
*)&dumpinfo
;
1693 callback
= dump_packet
;
1694 pcap_userdata
= (u_char
*)p
;
1696 #ifdef HAVE_PCAP_DUMP_FLUSH
1701 dlt
= pcap_datalink(pd
);
1702 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1703 callback
= print_packet
;
1704 pcap_userdata
= (u_char
*)ndo
;
1707 #ifdef SIGNAL_REQ_INFO
1709 * We can't get statistics when reading from a file rather
1710 * than capturing from a device.
1712 if (RFileName
== NULL
)
1713 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
1716 if (ndo
->ndo_vflag
> 0 && WFileName
) {
1718 * When capturing to a file, "-v" means tcpdump should,
1719 * every 10 seconds, "v"erbosely report the number of
1722 #ifdef USE_WIN32_MM_TIMER
1723 /* call verbose_stats_dump() each 1000 +/-100msec */
1724 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
1725 setvbuf(stderr
, NULL
, _IONBF
, 0);
1726 #elif defined(HAVE_ALARM)
1727 (void)setsignal(SIGALRM
, verbose_stats_dump
);
1733 if (RFileName
== NULL
) {
1735 * Live capture (if -V was specified, we set RFileName
1736 * to a file from the -V file). Print a message to
1737 * the standard error on UN*X.
1739 if (!ndo
->ndo_vflag
&& !WFileName
) {
1740 (void)fprintf(stderr
,
1741 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1744 (void)fprintf(stderr
, "%s: ", program_name
);
1745 dlt
= pcap_datalink(pd
);
1746 dlt_name
= pcap_datalink_val_to_name(dlt
);
1747 if (dlt_name
== NULL
) {
1748 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
1749 device
, dlt
, ndo
->ndo_snaplen
);
1751 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1753 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
1755 (void)fflush(stderr
);
1759 #ifdef HAVE_CAPSICUM
1760 cansandbox
= (ndo
->ndo_nflag
&& VFileName
== NULL
&& zflag
== NULL
);
1761 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
1762 error("unable to enter the capability mode");
1763 #endif /* HAVE_CAPSICUM */
1766 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
1767 if (WFileName
== NULL
) {
1769 * We're printing packets. Flush the printed output,
1770 * so it doesn't get intermingled with error output.
1774 * We got interrupted, so perhaps we didn't
1775 * manage to finish a line we were printing.
1776 * Print an extra newline, just in case.
1780 (void)fflush(stdout
);
1784 * We got interrupted. If we are reading multiple
1785 * files (via -V) set these so that we stop.
1794 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
1795 program_name
, pcap_geterr(pd
));
1797 if (RFileName
== NULL
) {
1799 * We're doing a live capture. Report the capture
1805 if (VFileName
!= NULL
) {
1806 ret
= get_next_file(VFile
, VFileLine
);
1810 RFileName
= VFileLine
;
1811 pd
= pcap_open_offline(RFileName
, ebuf
);
1814 #ifdef HAVE_CAPSICUM
1815 cap_rights_init(&rights
, CAP_READ
);
1816 if (cap_rights_limit(fileno(pcap_file(pd
)),
1817 &rights
) < 0 && errno
!= ENOSYS
) {
1818 error("unable to limit pcap descriptor");
1821 new_dlt
= pcap_datalink(pd
);
1822 if (new_dlt
!= dlt
) {
1824 * The new file has a different
1825 * link-layer header type from the
1828 if (WFileName
!= NULL
) {
1830 * We're writing raw packets
1831 * that match the filter to
1832 * a pcap file. pcap files
1833 * don't support multiple
1834 * different link-layer
1835 * header types, so we fail
1838 error("%s: new dlt does not match original", RFileName
);
1842 * We're printing the decoded packets;
1843 * switch to the new DLT.
1845 * To do that, we need to change
1846 * the printer, change the DLT name,
1847 * and recompile the filter with
1851 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1852 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1853 error("%s", pcap_geterr(pd
));
1857 * Set the filter on the new file.
1859 if (pcap_setfilter(pd
, &fcode
) < 0)
1860 error("%s", pcap_geterr(pd
));
1863 * Report the new file.
1865 dlt_name
= pcap_datalink_val_to_name(dlt
);
1866 if (dlt_name
== NULL
) {
1867 fprintf(stderr
, "reading from file %s, link-type %u\n",
1871 "reading from file %s, link-type %s (%s)\n",
1872 RFileName
, dlt_name
,
1873 pcap_datalink_val_to_description(dlt
));
1878 while (ret
!= NULL
);
1881 pcap_freecode(&fcode
);
1882 exit(status
== -1 ? 1 : 0);
1885 /* make a clean exit on interrupts */
1887 cleanup(int signo _U_
)
1889 #ifdef USE_WIN32_MM_TIMER
1891 timeKillEvent(timer_id
);
1893 #elif defined(HAVE_ALARM)
1897 #ifdef HAVE_PCAP_BREAKLOOP
1899 * We have "pcap_breakloop()"; use it, so that we do as little
1900 * as possible in the signal handler (it's probably not safe
1901 * to do anything with standard I/O streams in a signal handler -
1902 * the ANSI C standard doesn't say it is).
1907 * We don't have "pcap_breakloop()"; this isn't safe, but
1908 * it's the best we can do. Print the summary if we're
1909 * not reading from a savefile - i.e., if we're doing a
1910 * live capture - and exit.
1912 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
1914 * We got interrupted, so perhaps we didn't
1915 * manage to finish a line we were printing.
1916 * Print an extra newline, just in case.
1919 (void)fflush(stdout
);
1927 On windows, we do not use a fork, so we do not care less about
1928 waiting a child processes to die
1930 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1932 child_cleanup(int signo _U_
)
1936 #endif /* HAVE_FORK && HAVE_VFORK */
1939 info(register int verbose
)
1941 struct pcap_stat stats
;
1944 * Older versions of libpcap didn't set ps_ifdrop on some
1945 * platforms; initialize it to 0 to handle that.
1947 stats
.ps_ifdrop
= 0;
1948 if (pcap_stats(pd
, &stats
) < 0) {
1949 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
1955 fprintf(stderr
, "%s: ", program_name
);
1957 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
1958 PLURAL_SUFFIX(packets_captured
));
1960 fputs(", ", stderr
);
1963 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
1964 PLURAL_SUFFIX(stats
.ps_recv
));
1966 fputs(", ", stderr
);
1969 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
1970 PLURAL_SUFFIX(stats
.ps_drop
));
1971 if (stats
.ps_ifdrop
!= 0) {
1973 fputs(", ", stderr
);
1976 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
1977 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
1983 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1985 #define fork_subprocess() fork()
1987 #define fork_subprocess() vfork()
1990 compress_savefile(const char *filename
)
1994 child
= fork_subprocess();
1997 "compress_savefile: fork failed: %s\n",
1998 pcap_strerror(errno
));
2002 /* Parent process. */
2008 * Set to lowest priority so that this doesn't disturb the capture.
2011 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2013 setpriority(PRIO_PROCESS
, 0, 19);
2015 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2017 "compress_savefile: execlp(%s, %s) failed: %s\n",
2020 pcap_strerror(errno
));
2027 #else /* HAVE_FORK && HAVE_VFORK */
2029 compress_savefile(const char *filename
)
2032 "compress_savefile failed. Functionality not implemented under your system\n");
2034 #endif /* HAVE_FORK && HAVE_VFORK */
2037 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2039 struct dump_info
*dump_info
;
2045 dump_info
= (struct dump_info
*)user
;
2048 * XXX - this won't force the file to rotate on the specified time
2049 * boundary, but it will rotate on the first packet received after the
2050 * specified Gflag number of seconds. Note: if a Gflag time boundary
2051 * and a Cflag size boundary coincide, the time rotation will occur
2052 * first thereby cancelling the Cflag boundary (since the file should
2056 /* Check if it is time to rotate */
2059 /* Get the current time */
2060 if ((t
= time(NULL
)) == (time_t)-1) {
2061 error("dump_and_trunc_packet: can't get current_time: %s",
2062 pcap_strerror(errno
));
2066 /* If the time is greater than the specified window, rotate */
2067 if (t
- Gflag_time
>= Gflag
) {
2068 #ifdef HAVE_CAPSICUM
2073 /* Update the Gflag_time */
2075 /* Update Gflag_count */
2078 * Close the current file and open a new one.
2080 pcap_dump_close(dump_info
->p
);
2083 * Compress the file we just closed, if the user asked for it
2086 compress_savefile(dump_info
->CurrentFileName
);
2089 * Check to see if we've exceeded the Wflag (when
2092 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2093 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2098 if (dump_info
->CurrentFileName
!= NULL
)
2099 free(dump_info
->CurrentFileName
);
2100 /* Allocate space for max filename + \0. */
2101 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2102 if (dump_info
->CurrentFileName
== NULL
)
2103 error("dump_packet_and_trunc: malloc");
2105 * Gflag was set otherwise we wouldn't be here. Reset the count
2106 * so multiple files would end with 1,2,3 in the filename.
2107 * The counting is handled with the -C flow after this.
2112 * This is always the first file in the Cflag
2114 * We also don't need numbering if Cflag is not set.
2117 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2120 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2122 #ifdef HAVE_LIBCAP_NG
2123 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2124 capng_apply(CAPNG_SELECT_BOTH
);
2125 #endif /* HAVE_LIBCAP_NG */
2126 #ifdef HAVE_CAPSICUM
2127 fd
= openat(dump_info
->dirfd
,
2128 dump_info
->CurrentFileName
,
2129 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2131 error("unable to open file %s",
2132 dump_info
->CurrentFileName
);
2134 fp
= fdopen(fd
, "w");
2136 error("unable to fdopen file %s",
2137 dump_info
->CurrentFileName
);
2139 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2140 #else /* !HAVE_CAPSICUM */
2141 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2143 #ifdef HAVE_LIBCAP_NG
2144 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2145 capng_apply(CAPNG_SELECT_BOTH
);
2146 #endif /* HAVE_LIBCAP_NG */
2147 if (dump_info
->p
== NULL
)
2148 error("%s", pcap_geterr(pd
));
2149 #ifdef HAVE_CAPSICUM
2150 set_dumper_capsicum_rights(dump_info
->p
);
2156 * XXX - this won't prevent capture files from getting
2157 * larger than Cflag - the last packet written to the
2158 * file could put it over Cflag.
2161 long size
= pcap_dump_ftell(dump_info
->p
);
2164 error("ftell fails on output file");
2166 #ifdef HAVE_CAPSICUM
2172 * Close the current file and open a new one.
2174 pcap_dump_close(dump_info
->p
);
2177 * Compress the file we just closed, if the user
2181 compress_savefile(dump_info
->CurrentFileName
);
2185 if (Cflag_count
>= Wflag
)
2188 if (dump_info
->CurrentFileName
!= NULL
)
2189 free(dump_info
->CurrentFileName
);
2190 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2191 if (dump_info
->CurrentFileName
== NULL
)
2192 error("dump_packet_and_trunc: malloc");
2193 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2194 #ifdef HAVE_LIBCAP_NG
2195 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2196 capng_apply(CAPNG_SELECT_BOTH
);
2197 #endif /* HAVE_LIBCAP_NG */
2198 #ifdef HAVE_CAPSICUM
2199 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2200 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2202 error("unable to open file %s",
2203 dump_info
->CurrentFileName
);
2205 fp
= fdopen(fd
, "w");
2207 error("unable to fdopen file %s",
2208 dump_info
->CurrentFileName
);
2210 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2211 #else /* !HAVE_CAPSICUM */
2212 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2214 #ifdef HAVE_LIBCAP_NG
2215 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2216 capng_apply(CAPNG_SELECT_BOTH
);
2217 #endif /* HAVE_LIBCAP_NG */
2218 if (dump_info
->p
== NULL
)
2219 error("%s", pcap_geterr(pd
));
2220 #ifdef HAVE_CAPSICUM
2221 set_dumper_capsicum_rights(dump_info
->p
);
2226 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2227 #ifdef HAVE_PCAP_DUMP_FLUSH
2229 pcap_dump_flush(dump_info
->p
);
2238 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2244 pcap_dump(user
, h
, sp
);
2245 #ifdef HAVE_PCAP_DUMP_FLUSH
2247 pcap_dump_flush((pcap_dumper_t
*)user
);
2256 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2262 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2271 * XXX - there should really be libpcap calls to get the version
2272 * number as a string (the string would be generated from #defines
2273 * at run time, so that it's not generated from string constants
2274 * in the library, as, on many UNIX systems, those constants would
2275 * be statically linked into the application executable image, and
2276 * would thus reflect the version of libpcap on the system on
2277 * which the application was *linked*, not the system on which it's
2280 * That routine should be documented, unlike the "version[]"
2281 * string, so that UNIX vendors providing their own libpcaps
2282 * don't omit it (as a couple of vendors have...).
2284 * Packet.dll should perhaps also export a routine to return the
2285 * version number of the Packet.dll code, to supply the
2286 * "Wpcap_version" information on Windows.
2288 char WDversion
[]="current-git.tcpdump.org";
2289 #if !defined(HAVE_GENERATED_VERSION)
2290 char version
[]="current-git.tcpdump.org";
2292 char pcap_version
[]="current-git.tcpdump.org";
2293 char Wpcap_version
[]="3.1";
2296 #ifdef SIGNAL_REQ_INFO
2297 RETSIGTYPE
requestinfo(int signo _U_
)
2307 * Called once each second in verbose mode while dumping to file
2309 #ifdef USE_WIN32_MM_TIMER
2310 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2311 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2314 fprintf(stderr
, "Got %u\r", packets_captured
);
2316 #elif defined(HAVE_ALARM)
2317 static void verbose_stats_dump(int sig _U_
)
2320 fprintf(stderr
, "Got %u\r", packets_captured
);
2325 USES_APPLE_DEPRECATED_API
2329 extern char version
[];
2330 #ifndef HAVE_PCAP_LIB_VERSION
2331 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2332 extern char pcap_version
[];
2333 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2334 static char pcap_version
[] = "unknown";
2335 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2336 #endif /* HAVE_PCAP_LIB_VERSION */
2338 #ifdef HAVE_PCAP_LIB_VERSION
2340 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2342 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2344 (void)fprintf(stderr
, "%s\n",pcap_lib_version());
2345 #else /* HAVE_PCAP_LIB_VERSION */
2347 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2348 (void)fprintf(stderr
, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version
, pcap_version
);
2350 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2351 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2353 #endif /* HAVE_PCAP_LIB_VERSION */
2355 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2356 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2360 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2369 (void)fprintf(stderr
,
2370 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2371 (void)fprintf(stderr
,
2372 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2373 (void)fprintf(stderr
,
2374 "\t\t[ -i interface ]" j_FLAG_USAGE
" [ -M secret ] [ --number ]\n");
2375 #ifdef HAVE_PCAP_SETDIRECTION
2376 (void)fprintf(stderr
,
2377 "\t\t[ -Q in|out|inout ]\n");
2379 (void)fprintf(stderr
,
2380 "\t\t[ -r file ] [ -s snaplen ] ");
2381 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2382 (void)fprintf(stderr
, "[ --time-stamp-precision precision ]\n");
2383 (void)fprintf(stderr
,
2386 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2387 (void)fprintf(stderr
, "[ --immediate-mode ] ");
2389 (void)fprintf(stderr
, "[ -T type ] [ --version ] [ -V file ]\n");
2390 (void)fprintf(stderr
,
2391 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2392 (void)fprintf(stderr
,
2393 "\t\t[ -Z user ] [ expression ]\n");
2397 * c-style: whitesmith