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
;
1119 error("unknown packet type `%s'", optarg
);
1126 #ifdef HAVE_PCAP_DUMP_FLUSH
1145 Wflag
= atoi(optarg
);
1147 error("invalid number of output files %s", optarg
);
1148 WflagChars
= getWflagChars(Wflag
);
1153 ++ndo
->ndo_suppress_default_print
;
1158 ++ndo
->ndo_suppress_default_print
;
1162 yflag_dlt_name
= optarg
;
1164 pcap_datalink_name_to_val(yflag_dlt_name
);
1166 error("invalid data link type %s", yflag_dlt_name
);
1169 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1172 /* Undocumented flag */
1173 pcap_set_parser_debug(1);
1186 ndo
->ndo_packet_number
= 1;
1189 case OPTION_VERSION
:
1194 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1195 case OPTION_TSTAMP_PRECISION
:
1196 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1197 if (ndo
->ndo_tstamp_precision
< 0)
1198 error("unsupported time stamp precision");
1202 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1203 case OPTION_IMMEDIATE_MODE
:
1214 #ifdef HAVE_PCAP_FINDALLDEVS
1216 show_devices_and_exit();
1219 switch (ndo
->ndo_tflag
) {
1221 case 0: /* Default */
1222 case 4: /* Default + Date*/
1223 timezone_offset
= gmt2local(0);
1226 case 1: /* No time stamp */
1227 case 2: /* Unix timeval style */
1228 case 3: /* Microseconds since previous packet */
1229 case 5: /* Microseconds since first packet */
1232 default: /* Not supported */
1233 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1237 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1238 error("-f can not be used with -V or -r");
1240 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1241 error("-V and -r are mutually exclusive.");
1243 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1245 * If we're printing dissected packets to the standard output
1246 * rather than saving raw packets to a file, and the standard
1247 * output is a terminal, use immediate mode, as the user's
1248 * probably expecting to see packets pop up immediately.
1250 if (WFileName
== NULL
&& isatty(1))
1255 /* if run as root, prepare for chrooting */
1256 if (getuid() == 0 || geteuid() == 0) {
1257 /* future extensibility for cmd-line arguments */
1259 chroot_dir
= WITH_CHROOT
;
1264 /* if run as root, prepare for dropping root privileges */
1265 if (getuid() == 0 || geteuid() == 0) {
1266 /* Run with '-Z root' to restore old behaviour */
1268 username
= WITH_USER
;
1272 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1274 * If RFileName is non-null, it's the pathname of a
1275 * savefile to read. If VFileName is non-null, it's
1276 * the pathname of a file containing a list of pathnames
1277 * (one per line) of savefiles to read.
1279 * In either case, we're reading a savefile, not doing
1284 * We don't need network access, so relinquish any set-UID
1285 * or set-GID privileges we have (if any).
1287 * We do *not* want set-UID privileges when opening a
1288 * trace file, as that might let the user read other
1289 * people's trace files (especially if we're set-UID
1292 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1293 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1295 if (VFileName
!= NULL
) {
1296 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1299 VFile
= fopen(VFileName
, "r");
1302 error("Unable to open file: %s\n", pcap_strerror(errno
));
1304 ret
= get_next_file(VFile
, VFileLine
);
1306 error("Nothing in %s\n", VFileName
);
1307 RFileName
= VFileLine
;
1310 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1311 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1312 ndo
->ndo_tstamp_precision
, ebuf
);
1314 pd
= pcap_open_offline(RFileName
, ebuf
);
1319 #ifdef HAVE_CAPSICUM
1320 cap_rights_init(&rights
, CAP_READ
);
1321 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1323 error("unable to limit pcap descriptor");
1326 dlt
= pcap_datalink(pd
);
1327 dlt_name
= pcap_datalink_val_to_name(dlt
);
1328 if (dlt_name
== NULL
) {
1329 fprintf(stderr
, "reading from file %s, link-type %u\n",
1333 "reading from file %s, link-type %s (%s)\n",
1334 RFileName
, dlt_name
,
1335 pcap_datalink_val_to_description(dlt
));
1339 * We're doing a live capture.
1341 if (device
== NULL
) {
1342 #ifdef HAVE_PCAP_FINDALLDEVS
1343 if (pcap_findalldevs(&devlist
, ebuf
) >= 0 &&
1345 device
= strdup(devlist
->name
);
1346 pcap_freealldevs(devlist
);
1348 #else /* HAVE_PCAP_FINDALLDEVS */
1349 device
= pcap_lookupdev(ebuf
);
1356 * Print a message to the standard error on Windows.
1357 * XXX - why do it here, with a different message?
1359 if(strlen(device
) == 1) /* we assume that an ASCII string is always longer than 1 char */
1360 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1361 fprintf(stderr
, "%s: listening on %ws\n", program_name
, device
);
1365 fprintf(stderr
, "%s: listening on %s\n", program_name
, device
);
1370 #ifdef HAVE_PCAP_CREATE
1371 pd
= pcap_create(device
, ebuf
);
1374 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1376 show_tstamp_types_and_exit(device
);
1378 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1379 status
= pcap_set_tstamp_precision(pd
, ndo
->ndo_tstamp_precision
);
1381 error("%s: Can't set %ssecond time stamp precision: %s",
1383 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1384 pcap_statustostr(status
));
1387 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1388 if (immediate_mode
) {
1389 status
= pcap_set_immediate_mode(pd
, 1);
1391 error("%s: Can't set immediate mode: %s",
1393 pcap_statustostr(status
));
1397 * Is this an interface that supports monitor mode?
1399 if (pcap_can_set_rfmon(pd
) == 1)
1400 supports_monitor_mode
= 1;
1402 supports_monitor_mode
= 0;
1403 status
= pcap_set_snaplen(pd
, ndo
->ndo_snaplen
);
1405 error("%s: Can't set snapshot length: %s",
1406 device
, pcap_statustostr(status
));
1407 status
= pcap_set_promisc(pd
, !pflag
);
1409 error("%s: Can't set promiscuous mode: %s",
1410 device
, pcap_statustostr(status
));
1412 status
= pcap_set_rfmon(pd
, 1);
1414 error("%s: Can't set monitor mode: %s",
1415 device
, pcap_statustostr(status
));
1417 status
= pcap_set_timeout(pd
, 1000);
1419 error("%s: pcap_set_timeout failed: %s",
1420 device
, pcap_statustostr(status
));
1422 status
= pcap_set_buffer_size(pd
, Bflag
);
1424 error("%s: Can't set buffer size: %s",
1425 device
, pcap_statustostr(status
));
1427 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1429 status
= pcap_set_tstamp_type(pd
, jflag
);
1431 error("%s: Can't set time stamp type: %s",
1432 device
, pcap_statustostr(status
));
1435 status
= pcap_activate(pd
);
1438 * pcap_activate() failed.
1440 cp
= pcap_geterr(pd
);
1441 if (status
== PCAP_ERROR
)
1443 else if ((status
== PCAP_ERROR_NO_SUCH_DEVICE
||
1444 status
== PCAP_ERROR_PERM_DENIED
) &&
1446 error("%s: %s\n(%s)", device
,
1447 pcap_statustostr(status
), cp
);
1449 error("%s: %s", device
,
1450 pcap_statustostr(status
));
1451 } else if (status
> 0) {
1453 * pcap_activate() succeeded, but it's warning us
1454 * of a problem it had.
1456 cp
= pcap_geterr(pd
);
1457 if (status
== PCAP_WARNING
)
1459 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1461 warning("%s: %s\n(%s)", device
,
1462 pcap_statustostr(status
), cp
);
1464 warning("%s: %s", device
,
1465 pcap_statustostr(status
));
1467 #ifdef HAVE_PCAP_SETDIRECTION
1469 status
= pcap_setdirection(pd
, Qflag
);
1471 error("%s: pcap_setdirection() failed: %s",
1472 device
, pcap_geterr(pd
));
1474 #endif /* HAVE_PCAP_SETDIRECTION */
1477 pd
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000,
1482 warning("%s", ebuf
);
1483 #endif /* HAVE_PCAP_CREATE */
1485 * Let user own process after socket has been opened.
1488 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1489 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1491 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1493 if(pcap_setbuff(pd
, Bflag
)==-1){
1494 error("%s", pcap_geterr(pd
));
1496 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1498 show_dlts_and_exit(device
);
1499 if (yflag_dlt
>= 0) {
1500 #ifdef HAVE_PCAP_SET_DATALINK
1501 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1502 error("%s", pcap_geterr(pd
));
1505 * We don't actually support changing the
1506 * data link type, so we only let them
1507 * set it to what it already is.
1509 if (yflag_dlt
!= pcap_datalink(pd
)) {
1510 error("%s is not one of the DLTs supported by this device\n",
1514 (void)fprintf(stderr
, "%s: data link type %s\n",
1515 program_name
, yflag_dlt_name
);
1516 (void)fflush(stderr
);
1518 i
= pcap_snapshot(pd
);
1519 if (ndo
->ndo_snaplen
< i
) {
1520 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1521 ndo
->ndo_snaplen
= i
;
1523 if(ndo
->ndo_fflag
!= 0) {
1524 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1525 warning("foreign (-f) flag used but: %s", ebuf
);
1531 cmdbuf
= read_infile(infile
);
1533 cmdbuf
= copy_argv(&argv
[optind
]);
1535 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1536 pcap_set_optimizer_debug(dflag
);
1538 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1539 error("%s", pcap_geterr(pd
));
1541 bpf_dump(&fcode
, dflag
);
1544 pcap_freecode(&fcode
);
1547 init_print(ndo
, localnet
, netmask
, timezone_offset
);
1550 (void)setsignal(SIGPIPE
, cleanup
);
1551 (void)setsignal(SIGTERM
, cleanup
);
1552 (void)setsignal(SIGINT
, cleanup
);
1554 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1555 (void)setsignal(SIGCHLD
, child_cleanup
);
1557 /* Cooperate with nohup(1) */
1559 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
1560 (void)setsignal(SIGHUP
, oldhandler
);
1565 * If a user name was specified with "-Z", attempt to switch to
1566 * that user's UID. This would probably be used with sudo,
1567 * to allow tcpdump to be run in a special restricted
1568 * account (if you just want to allow users to open capture
1569 * devices, and can't just give users that permission,
1570 * you'd make tcpdump set-UID or set-GID).
1572 * Tcpdump doesn't necessarily write only to one savefile;
1573 * the general only way to allow a -Z instance to write to
1574 * savefiles as the user under whose UID it's run, rather
1575 * than as the user specified with -Z, would thus be to switch
1576 * to the original user ID before opening a capture file and
1577 * then switch back to the -Z user ID after opening the savefile.
1578 * Switching to the -Z user ID only after opening the first
1579 * savefile doesn't handle the general case.
1582 if (getuid() == 0 || geteuid() == 0) {
1583 #ifdef HAVE_LIBCAP_NG
1584 /* Initialize capng */
1585 capng_clear(CAPNG_SELECT_BOTH
);
1589 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1598 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1602 capng_apply(CAPNG_SELECT_BOTH
);
1603 #endif /* HAVE_LIBCAP_NG */
1604 if (username
|| chroot_dir
)
1605 droproot(username
, chroot_dir
);
1610 if (pcap_setfilter(pd
, &fcode
) < 0)
1611 error("%s", pcap_geterr(pd
));
1612 #ifdef HAVE_CAPSICUM
1613 if (RFileName
== NULL
&& VFileName
== NULL
) {
1614 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
1616 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
);
1617 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
1619 error("unable to limit pcap descriptor");
1621 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
1622 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
1623 error("unable to limit ioctls on pcap descriptor");
1629 /* Do not exceed the default PATH_MAX for files. */
1630 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1632 if (dumpinfo
.CurrentFileName
== NULL
)
1633 error("malloc of dumpinfo.CurrentFileName");
1635 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1637 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
1639 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
1641 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
1642 #ifdef HAVE_LIBCAP_NG
1643 /* Give up CAP_DAC_OVERRIDE capability.
1644 * Only allow it to be restored if the -C or -G flag have been
1645 * set since we may need to create more files later on.
1649 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
1653 capng_apply(CAPNG_SELECT_BOTH
);
1654 #endif /* HAVE_LIBCAP_NG */
1656 error("%s", pcap_geterr(pd
));
1657 #ifdef HAVE_CAPSICUM
1658 set_dumper_capsicum_rights(p
);
1660 if (Cflag
!= 0 || Gflag
!= 0) {
1661 #ifdef HAVE_CAPSICUM
1662 dumpinfo
.WFileName
= strdup(basename(WFileName
));
1663 if (dumpinfo
.WFileName
== NULL
) {
1664 error("Unable to allocate memory for file %s",
1667 dumpinfo
.dirfd
= open(dirname(WFileName
),
1668 O_DIRECTORY
| O_RDONLY
);
1669 if (dumpinfo
.dirfd
< 0) {
1670 error("unable to open directory %s",
1671 dirname(WFileName
));
1673 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
1674 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
1675 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
1677 error("unable to limit directory rights");
1679 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
1681 error("unable to limit dump descriptor fcntls");
1683 #else /* !HAVE_CAPSICUM */
1684 dumpinfo
.WFileName
= WFileName
;
1686 callback
= dump_packet_and_trunc
;
1689 pcap_userdata
= (u_char
*)&dumpinfo
;
1691 callback
= dump_packet
;
1692 pcap_userdata
= (u_char
*)p
;
1694 #ifdef HAVE_PCAP_DUMP_FLUSH
1699 dlt
= pcap_datalink(pd
);
1700 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1701 callback
= print_packet
;
1702 pcap_userdata
= (u_char
*)ndo
;
1705 #ifdef SIGNAL_REQ_INFO
1707 * We can't get statistics when reading from a file rather
1708 * than capturing from a device.
1710 if (RFileName
== NULL
)
1711 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
1714 if (ndo
->ndo_vflag
> 0 && WFileName
) {
1716 * When capturing to a file, "-v" means tcpdump should,
1717 * every 10 seconds, "v"erbosely report the number of
1720 #ifdef USE_WIN32_MM_TIMER
1721 /* call verbose_stats_dump() each 1000 +/-100msec */
1722 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
1723 setvbuf(stderr
, NULL
, _IONBF
, 0);
1724 #elif defined(HAVE_ALARM)
1725 (void)setsignal(SIGALRM
, verbose_stats_dump
);
1731 if (RFileName
== NULL
) {
1733 * Live capture (if -V was specified, we set RFileName
1734 * to a file from the -V file). Print a message to
1735 * the standard error on UN*X.
1737 if (!ndo
->ndo_vflag
&& !WFileName
) {
1738 (void)fprintf(stderr
,
1739 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1742 (void)fprintf(stderr
, "%s: ", program_name
);
1743 dlt
= pcap_datalink(pd
);
1744 dlt_name
= pcap_datalink_val_to_name(dlt
);
1745 if (dlt_name
== NULL
) {
1746 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
1747 device
, dlt
, ndo
->ndo_snaplen
);
1749 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1751 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
1753 (void)fflush(stderr
);
1757 #ifdef HAVE_CAPSICUM
1758 cansandbox
= (ndo
->ndo_nflag
&& VFileName
== NULL
&& zflag
== NULL
);
1759 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
1760 error("unable to enter the capability mode");
1761 #endif /* HAVE_CAPSICUM */
1764 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
1765 if (WFileName
== NULL
) {
1767 * We're printing packets. Flush the printed output,
1768 * so it doesn't get intermingled with error output.
1772 * We got interrupted, so perhaps we didn't
1773 * manage to finish a line we were printing.
1774 * Print an extra newline, just in case.
1778 (void)fflush(stdout
);
1782 * We got interrupted. If we are reading multiple
1783 * files (via -V) set these so that we stop.
1792 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
1793 program_name
, pcap_geterr(pd
));
1795 if (RFileName
== NULL
) {
1797 * We're doing a live capture. Report the capture
1803 if (VFileName
!= NULL
) {
1804 ret
= get_next_file(VFile
, VFileLine
);
1808 RFileName
= VFileLine
;
1809 pd
= pcap_open_offline(RFileName
, ebuf
);
1812 #ifdef HAVE_CAPSICUM
1813 cap_rights_init(&rights
, CAP_READ
);
1814 if (cap_rights_limit(fileno(pcap_file(pd
)),
1815 &rights
) < 0 && errno
!= ENOSYS
) {
1816 error("unable to limit pcap descriptor");
1819 new_dlt
= pcap_datalink(pd
);
1820 if (new_dlt
!= dlt
) {
1822 * The new file has a different
1823 * link-layer header type from the
1826 if (WFileName
!= NULL
) {
1828 * We're writing raw packets
1829 * that match the filter to
1830 * a pcap file. pcap files
1831 * don't support multiple
1832 * different link-layer
1833 * header types, so we fail
1836 error("%s: new dlt does not match original", RFileName
);
1840 * We're printing the decoded packets;
1841 * switch to the new DLT.
1843 * To do that, we need to change
1844 * the printer, change the DLT name,
1845 * and recompile the filter with
1849 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1850 dlt_name
= pcap_datalink_val_to_name(dlt
);
1851 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1852 error("%s", pcap_geterr(pd
));
1856 * Set the filter on the new file.
1858 if (pcap_setfilter(pd
, &fcode
) < 0)
1859 error("%s", pcap_geterr(pd
));
1862 * Report the new file.
1864 if (dlt_name
== NULL
) {
1865 fprintf(stderr
, "reading from file %s, link-type %u\n",
1869 "reading from file %s, link-type %s (%s)\n",
1870 RFileName
, dlt_name
,
1871 pcap_datalink_val_to_description(dlt
));
1876 while (ret
!= NULL
);
1879 pcap_freecode(&fcode
);
1880 exit(status
== -1 ? 1 : 0);
1883 /* make a clean exit on interrupts */
1885 cleanup(int signo _U_
)
1887 #ifdef USE_WIN32_MM_TIMER
1889 timeKillEvent(timer_id
);
1891 #elif defined(HAVE_ALARM)
1895 #ifdef HAVE_PCAP_BREAKLOOP
1897 * We have "pcap_breakloop()"; use it, so that we do as little
1898 * as possible in the signal handler (it's probably not safe
1899 * to do anything with standard I/O streams in a signal handler -
1900 * the ANSI C standard doesn't say it is).
1905 * We don't have "pcap_breakloop()"; this isn't safe, but
1906 * it's the best we can do. Print the summary if we're
1907 * not reading from a savefile - i.e., if we're doing a
1908 * live capture - and exit.
1910 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
1912 * We got interrupted, so perhaps we didn't
1913 * manage to finish a line we were printing.
1914 * Print an extra newline, just in case.
1917 (void)fflush(stdout
);
1925 On windows, we do not use a fork, so we do not care less about
1926 waiting a child processes to die
1928 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1930 child_cleanup(int signo _U_
)
1934 #endif /* HAVE_FORK && HAVE_VFORK */
1937 info(register int verbose
)
1939 struct pcap_stat stats
;
1942 * Older versions of libpcap didn't set ps_ifdrop on some
1943 * platforms; initialize it to 0 to handle that.
1945 stats
.ps_ifdrop
= 0;
1946 if (pcap_stats(pd
, &stats
) < 0) {
1947 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
1953 fprintf(stderr
, "%s: ", program_name
);
1955 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
1956 PLURAL_SUFFIX(packets_captured
));
1958 fputs(", ", stderr
);
1961 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
1962 PLURAL_SUFFIX(stats
.ps_recv
));
1964 fputs(", ", stderr
);
1967 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
1968 PLURAL_SUFFIX(stats
.ps_drop
));
1969 if (stats
.ps_ifdrop
!= 0) {
1971 fputs(", ", stderr
);
1974 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
1975 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
1981 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1983 #define fork_subprocess() fork()
1985 #define fork_subprocess() vfork()
1988 compress_savefile(const char *filename
)
1992 child
= fork_subprocess();
1995 "compress_savefile: fork failed: %s\n",
1996 pcap_strerror(errno
));
2000 /* Parent process. */
2006 * Set to lowest priority so that this doesn't disturb the capture.
2009 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2011 setpriority(PRIO_PROCESS
, 0, 19);
2013 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2015 "compress_savefile: execlp(%s, %s) failed: %s\n",
2018 pcap_strerror(errno
));
2025 #else /* HAVE_FORK && HAVE_VFORK */
2027 compress_savefile(const char *filename
)
2030 "compress_savefile failed. Functionality not implemented under your system\n");
2032 #endif /* HAVE_FORK && HAVE_VFORK */
2035 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2037 struct dump_info
*dump_info
;
2043 dump_info
= (struct dump_info
*)user
;
2046 * XXX - this won't force the file to rotate on the specified time
2047 * boundary, but it will rotate on the first packet received after the
2048 * specified Gflag number of seconds. Note: if a Gflag time boundary
2049 * and a Cflag size boundary coincide, the time rotation will occur
2050 * first thereby cancelling the Cflag boundary (since the file should
2054 /* Check if it is time to rotate */
2057 /* Get the current time */
2058 if ((t
= time(NULL
)) == (time_t)-1) {
2059 error("dump_and_trunc_packet: can't get current_time: %s",
2060 pcap_strerror(errno
));
2064 /* If the time is greater than the specified window, rotate */
2065 if (t
- Gflag_time
>= Gflag
) {
2066 #ifdef HAVE_CAPSICUM
2071 /* Update the Gflag_time */
2073 /* Update Gflag_count */
2076 * Close the current file and open a new one.
2078 pcap_dump_close(dump_info
->p
);
2081 * Compress the file we just closed, if the user asked for it
2084 compress_savefile(dump_info
->CurrentFileName
);
2087 * Check to see if we've exceeded the Wflag (when
2090 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2091 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2096 if (dump_info
->CurrentFileName
!= NULL
)
2097 free(dump_info
->CurrentFileName
);
2098 /* Allocate space for max filename + \0. */
2099 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2100 if (dump_info
->CurrentFileName
== NULL
)
2101 error("dump_packet_and_trunc: malloc");
2103 * Gflag was set otherwise we wouldn't be here. Reset the count
2104 * so multiple files would end with 1,2,3 in the filename.
2105 * The counting is handled with the -C flow after this.
2110 * This is always the first file in the Cflag
2112 * We also don't need numbering if Cflag is not set.
2115 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2118 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2120 #ifdef HAVE_LIBCAP_NG
2121 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2122 capng_apply(CAPNG_SELECT_BOTH
);
2123 #endif /* HAVE_LIBCAP_NG */
2124 #ifdef HAVE_CAPSICUM
2125 fd
= openat(dump_info
->dirfd
,
2126 dump_info
->CurrentFileName
,
2127 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2129 error("unable to open file %s",
2130 dump_info
->CurrentFileName
);
2132 fp
= fdopen(fd
, "w");
2134 error("unable to fdopen file %s",
2135 dump_info
->CurrentFileName
);
2137 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2138 #else /* !HAVE_CAPSICUM */
2139 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2141 #ifdef HAVE_LIBCAP_NG
2142 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2143 capng_apply(CAPNG_SELECT_BOTH
);
2144 #endif /* HAVE_LIBCAP_NG */
2145 if (dump_info
->p
== NULL
)
2146 error("%s", pcap_geterr(pd
));
2147 #ifdef HAVE_CAPSICUM
2148 set_dumper_capsicum_rights(dump_info
->p
);
2154 * XXX - this won't prevent capture files from getting
2155 * larger than Cflag - the last packet written to the
2156 * file could put it over Cflag.
2159 long size
= pcap_dump_ftell(dump_info
->p
);
2162 error("ftell fails on output file");
2164 #ifdef HAVE_CAPSICUM
2170 * Close the current file and open a new one.
2172 pcap_dump_close(dump_info
->p
);
2175 * Compress the file we just closed, if the user
2179 compress_savefile(dump_info
->CurrentFileName
);
2183 if (Cflag_count
>= Wflag
)
2186 if (dump_info
->CurrentFileName
!= NULL
)
2187 free(dump_info
->CurrentFileName
);
2188 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2189 if (dump_info
->CurrentFileName
== NULL
)
2190 error("dump_packet_and_trunc: malloc");
2191 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2192 #ifdef HAVE_LIBCAP_NG
2193 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2194 capng_apply(CAPNG_SELECT_BOTH
);
2195 #endif /* HAVE_LIBCAP_NG */
2196 #ifdef HAVE_CAPSICUM
2197 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2198 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2200 error("unable to open file %s",
2201 dump_info
->CurrentFileName
);
2203 fp
= fdopen(fd
, "w");
2205 error("unable to fdopen file %s",
2206 dump_info
->CurrentFileName
);
2208 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2209 #else /* !HAVE_CAPSICUM */
2210 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2212 #ifdef HAVE_LIBCAP_NG
2213 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2214 capng_apply(CAPNG_SELECT_BOTH
);
2215 #endif /* HAVE_LIBCAP_NG */
2216 if (dump_info
->p
== NULL
)
2217 error("%s", pcap_geterr(pd
));
2218 #ifdef HAVE_CAPSICUM
2219 set_dumper_capsicum_rights(dump_info
->p
);
2224 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2225 #ifdef HAVE_PCAP_DUMP_FLUSH
2227 pcap_dump_flush(dump_info
->p
);
2236 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2242 pcap_dump(user
, h
, sp
);
2243 #ifdef HAVE_PCAP_DUMP_FLUSH
2245 pcap_dump_flush((pcap_dumper_t
*)user
);
2254 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2260 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2269 * XXX - there should really be libpcap calls to get the version
2270 * number as a string (the string would be generated from #defines
2271 * at run time, so that it's not generated from string constants
2272 * in the library, as, on many UNIX systems, those constants would
2273 * be statically linked into the application executable image, and
2274 * would thus reflect the version of libpcap on the system on
2275 * which the application was *linked*, not the system on which it's
2278 * That routine should be documented, unlike the "version[]"
2279 * string, so that UNIX vendors providing their own libpcaps
2280 * don't omit it (as a couple of vendors have...).
2282 * Packet.dll should perhaps also export a routine to return the
2283 * version number of the Packet.dll code, to supply the
2284 * "Wpcap_version" information on Windows.
2286 char WDversion
[]="current-git.tcpdump.org";
2287 #if !defined(HAVE_GENERATED_VERSION)
2288 char version
[]="current-git.tcpdump.org";
2290 char pcap_version
[]="current-git.tcpdump.org";
2291 char Wpcap_version
[]="3.1";
2294 #ifdef SIGNAL_REQ_INFO
2295 RETSIGTYPE
requestinfo(int signo _U_
)
2305 * Called once each second in verbose mode while dumping to file
2307 #ifdef USE_WIN32_MM_TIMER
2308 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2309 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2312 fprintf(stderr
, "Got %u\r", packets_captured
);
2314 #elif defined(HAVE_ALARM)
2315 static void verbose_stats_dump(int sig _U_
)
2318 fprintf(stderr
, "Got %u\r", packets_captured
);
2323 USES_APPLE_DEPRECATED_API
2327 extern char version
[];
2328 #ifndef HAVE_PCAP_LIB_VERSION
2329 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2330 extern char pcap_version
[];
2331 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2332 static char pcap_version
[] = "unknown";
2333 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2334 #endif /* HAVE_PCAP_LIB_VERSION */
2336 #ifdef HAVE_PCAP_LIB_VERSION
2338 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2340 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2342 (void)fprintf(stderr
, "%s\n",pcap_lib_version());
2343 #else /* HAVE_PCAP_LIB_VERSION */
2345 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2346 (void)fprintf(stderr
, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version
, pcap_version
);
2348 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2349 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2351 #endif /* HAVE_PCAP_LIB_VERSION */
2353 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2354 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2358 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2367 (void)fprintf(stderr
,
2368 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2369 (void)fprintf(stderr
,
2370 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2371 (void)fprintf(stderr
,
2372 "\t\t[ -i interface ]" j_FLAG_USAGE
" [ -M secret ] [ --number ]\n");
2373 #ifdef HAVE_PCAP_SETDIRECTION
2374 (void)fprintf(stderr
,
2375 "\t\t[ -Q in|out|inout ]\n");
2377 (void)fprintf(stderr
,
2378 "\t\t[ -r file ] [ -s snaplen ] ");
2379 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2380 (void)fprintf(stderr
, "[ --time-stamp-precision precision ]\n");
2381 (void)fprintf(stderr
,
2384 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2385 (void)fprintf(stderr
, "[ --immediate-mode ] ");
2387 (void)fprintf(stderr
, "[ -T type ] [ --version ] [ -V file ]\n");
2388 (void)fprintf(stderr
,
2389 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2390 (void)fprintf(stderr
,
2391 "\t\t[ -Z user ] [ expression ]\n");
2395 * c-style: whitesmith