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 * tcpdump - dump traffic on a network
31 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
32 * Mercilessly hacked and occasionally improved since then via the
33 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
41 * Some older versions of Mac OS X may ship pcap.h from libpcap 0.6 with a
42 * libpcap based on 0.8. That means it has pcap_findalldevs() but the
43 * header doesn't define pcap_if_t, meaning that we can't actually *use*
46 #ifdef HAVE_PCAP_FINDALLDEVS
47 #ifndef HAVE_PCAP_IF_T
48 #undef HAVE_PCAP_FINDALLDEVS
52 #include "netdissect-stdinc.h"
55 * This must appear after including netdissect-stdinc.h, so that _U_ is
59 static const char copyright
[] _U_
=
60 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
61 The Regents of the University of California. All rights reserved.\n";
71 #include <openssl/crypto.h>
74 #ifdef HAVE_GETOPT_LONG
77 #include "getopt_long.h"
79 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
80 * to compile if <pcap.h> has already been included; including the headers
81 * in the opposite order works fine.
84 #include <sys/capability.h>
85 #include <sys/ioccom.h>
89 #include <libcasper.h>
90 #include <casper/cap_dns.h>
92 #endif /* HAVE_CASPER */
93 #endif /* HAVE_CAPSICUM */
107 #include <sys/time.h>
108 #include <sys/wait.h>
109 #include <sys/resource.h>
114 /* capabilities convenience library */
115 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
116 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
117 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
119 #ifdef HAVE_LIBCAP_NG
123 #undef HAVE_LIBCAP_NG
124 #endif /* HAVE_CAP_NG_H */
125 #endif /* HAVE_LIBCAP_NG */
128 #include <sys/sysctl.h>
129 #endif /* __FreeBSD__ */
131 #include "netdissect.h"
132 #include "interface.h"
133 #include "addrtoname.h"
135 #include "gmt2local.h"
136 #include "pcap-missing.h"
137 #include "ascii_strcasecmp.h"
142 #define PATH_MAX 1024
146 #define SIGNAL_REQ_INFO SIGINFO
148 #define SIGNAL_REQ_INFO SIGUSR1
151 #if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
152 #define SIGNAL_FLUSH_PCAP SIGUSR2
155 static int Bflag
; /* buffer size */
156 #ifdef HAVE_PCAP_DUMP_FTELL64
157 static int64_t Cflag
; /* rotate dump files after this many bytes */
159 static long Cflag
; /* rotate dump files after this many bytes */
161 static int Cflag_count
; /* Keep track of which file number we're writing */
162 #ifdef HAVE_PCAP_FINDALLDEVS
163 static int Dflag
; /* list available devices and exit */
165 #ifdef HAVE_PCAP_FINDALLDEVS_EX
166 static char *remote_interfaces_source
; /* list available devices from this source and exit */
170 * This is exported because, in some versions of libpcap, if libpcap
171 * is built with optimizer debugging code (which is *NOT* the default
172 * configuration!), the library *imports*(!) a variable named dflag,
173 * under the expectation that tcpdump is exporting it, to govern
174 * how much debugging information to print when optimizing
175 * the generated BPF code.
177 * This is a horrible hack; newer versions of libpcap don't import
178 * dflag but, instead, *if* built with optimizer debugging code,
179 * *export* a routine to set that flag.
181 int dflag
; /* print filter code */
182 static int Gflag
; /* rotate dump files after this many seconds */
183 static int Gflag_count
; /* number of files created with Gflag rotation */
184 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
185 static int Lflag
; /* list available data link types and exit */
186 static int Iflag
; /* rfmon (monitor) mode */
187 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
188 static int Jflag
; /* list available time stamp types */
190 static int jflag
= -1; /* packet time stamp source */
191 static int pflag
; /* don't go promiscuous */
192 #ifdef HAVE_PCAP_SETDIRECTION
193 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
195 static int Uflag
; /* "unbuffered" output of dump files */
196 static int Wflag
; /* recycle output files after this number of files */
197 static int WflagChars
;
198 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
199 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
200 static int immediate_mode
;
203 static int infodelay
;
204 static int infoprint
;
209 cap_channel_t
*capdns
;
213 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
214 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
215 static NORETURN
void exit_tcpdump(int);
216 static void (*setsignal (int sig
, void (*func
)(int)))(int);
217 static void cleanup(int);
218 static void child_cleanup(int);
219 static void print_version(void);
220 static void print_usage(void);
221 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
222 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
223 #ifdef HAVE_PCAP_FINDALLDEVS
224 static NORETURN
void show_devices_and_exit(void);
226 #ifdef HAVE_PCAP_FINDALLDEVS_EX
227 static NORETURN
void show_remote_devices_and_exit(void);
230 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
231 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
232 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
233 static void droproot(const char *, const char *);
235 #ifdef SIGNAL_REQ_INFO
236 void requestinfo(int);
239 #ifdef SIGNAL_FLUSH_PCAP
244 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
245 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
247 static void verbose_stats_dump(int sig
);
250 static void info(int);
251 static u_int packets_captured
;
253 #ifdef HAVE_PCAP_FINDALLDEVS
254 static const struct tok status_flags
[] = {
256 { PCAP_IF_UP
, "Up" },
258 #ifdef PCAP_IF_RUNNING
259 { PCAP_IF_RUNNING
, "Running" },
261 { PCAP_IF_LOOPBACK
, "Loopback" },
266 static pcap_dumper_t
*p
= NULL
;
269 static int supports_monitor_mode
;
277 char *CurrentFileName
;
280 netdissect_options
*ndo
;
286 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
288 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
289 * by any libpcap header, because it's a special hack, only available if
290 * libpcap was configured to include it, and only intended for use by
291 * libpcap developers trying to debug the parser for filter expressions).
294 __declspec(dllimport
)
298 void pcap_set_parser_debug(int);
299 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
301 * We don't have pcap_set_parser_debug() in libpcap, but we do have
302 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
303 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
306 pcap_set_parser_debug(int value
)
308 #ifdef HAVE_PCAP_DEBUG
309 extern int pcap_debug
;
312 #else /* HAVE_PCAP_DEBUG */
316 #endif /* HAVE_PCAP_DEBUG */
319 #define HAVE_PCAP_SET_PARSER_DEBUG
322 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
324 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
325 * by any libpcap header, because it's a special hack, only available if
326 * libpcap was configured to include it, and only intended for use by
327 * libpcap developers trying to debug the optimizer for filter expressions).
330 __declspec(dllimport
)
334 void pcap_set_optimizer_debug(int);
339 error(const char *fmt
, ...)
343 (void)fprintf(stderr
, "%s: ", program_name
);
345 (void)vfprintf(stderr
, fmt
, ap
);
350 (void)fputc('\n', stderr
);
352 exit_tcpdump(S_ERR_HOST_PROGRAM
);
358 warning(const char *fmt
, ...)
362 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
364 (void)vfprintf(stderr
, fmt
, ap
);
369 (void)fputc('\n', stderr
);
374 exit_tcpdump(int status
)
380 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
382 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
385 int *tstamp_types
= 0;
386 const char *tstamp_type_name
;
389 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
390 if (n_tstamp_types
< 0)
391 error("%s", pcap_geterr(pc
));
393 if (n_tstamp_types
== 0) {
394 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
396 exit_tcpdump(S_SUCCESS
);
398 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
400 for (i
= 0; i
< n_tstamp_types
; i
++) {
401 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
402 if (tstamp_type_name
!= NULL
) {
403 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
404 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
406 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
409 pcap_free_tstamp_types(tstamp_types
);
410 exit_tcpdump(S_SUCCESS
);
415 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
419 const char *dlt_name
;
421 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
423 error("%s", pcap_geterr(pc
));
424 else if (n_dlts
== 0 || !dlts
)
425 error("No data link types.");
428 * If the interface is known to support monitor mode, indicate
429 * whether these are the data link types available when not in
430 * monitor mode, if -I wasn't specified, or when in monitor mode,
431 * when -I was specified (the link-layer types available in
432 * monitor mode might be different from the ones available when
433 * not in monitor mode).
435 if (supports_monitor_mode
)
436 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
438 Iflag
? "when in monitor mode" : "when not in monitor mode");
440 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
443 for (i
= 0; i
< n_dlts
; i
++) {
444 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
445 if (dlt_name
!= NULL
) {
446 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
447 pcap_datalink_val_to_description(dlts
[i
]));
450 * OK, does tcpdump handle that type?
452 if (!has_printer(dlts
[i
]))
453 (void) fprintf(stderr
, " (printing not supported)");
454 fprintf(stderr
, "\n");
456 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
460 #ifdef HAVE_PCAP_FREE_DATALINKS
461 pcap_free_datalinks(dlts
);
463 exit_tcpdump(S_SUCCESS
);
466 #ifdef HAVE_PCAP_FINDALLDEVS
468 show_devices_and_exit(void)
470 pcap_if_t
*dev
, *devlist
;
471 char ebuf
[PCAP_ERRBUF_SIZE
];
474 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
476 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
477 printf("%d.%s", i
+1, dev
->name
);
478 if (dev
->description
!= NULL
)
479 printf(" (%s)", dev
->description
);
481 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
484 pcap_freealldevs(devlist
);
485 exit_tcpdump(S_SUCCESS
);
487 #endif /* HAVE_PCAP_FINDALLDEVS */
489 #ifdef HAVE_PCAP_FINDALLDEVS_EX
491 show_remote_devices_and_exit(void)
493 pcap_if_t
*dev
, *devlist
;
494 char ebuf
[PCAP_ERRBUF_SIZE
];
497 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
500 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
501 printf("%d.%s", i
+1, dev
->name
);
502 if (dev
->description
!= NULL
)
503 printf(" (%s)", dev
->description
);
505 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
508 pcap_freealldevs(devlist
);
509 exit_tcpdump(S_SUCCESS
);
511 #endif /* HAVE_PCAP_FINDALLDEVS */
516 * Note that there we use all letters for short options except for g, k,
517 * o, and P, and those are used by other versions of tcpdump, and we should
518 * only use them for the same purposes that the other versions of tcpdump
521 * macOS tcpdump uses -g to force non--v output for IP to be on one
522 * line, making it more "g"repable;
524 * macOS tcpdump uses -k to specify that packet comments in pcapng files
527 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
528 * for hosts sending TCP SYN packets;
530 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
533 * macOS tcpdump also uses -Q to specify expressions that match packet
534 * metadata, including but not limited to the packet direction.
535 * The expression syntax is different from a simple "in|out|inout",
536 * and those expressions aren't accepted by macOS tcpdump, but the
537 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
538 * "inout" = "dir=in or dir=out", and the parser could conceivably
539 * special-case "in", "out", and "inout" as expressions for backwards
540 * compatibility, so all is not (yet) lost.
544 * Set up flags that might or might not be supported depending on the
545 * version of libpcap we're using.
547 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
549 #define B_FLAG_USAGE " [ -B size ]"
550 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
553 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
555 #ifdef HAVE_PCAP_FINDALLDEVS
561 #ifdef HAVE_PCAP_CREATE
563 #else /* HAVE_PCAP_CREATE */
565 #endif /* HAVE_PCAP_CREATE */
567 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
569 #define j_FLAG_USAGE " [ -j tstamptype ]"
571 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
575 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
577 #ifdef HAVE_PCAP_SETDIRECTION
579 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
585 #ifdef HAVE_PCAP_DUMP_FLUSH
591 #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:#"
596 * We do not currently have long options corresponding to all short
597 * options; we should probably pick appropriate option names for them.
599 * However, the short options where the number of times the option is
600 * specified matters, such as -v and -d and -t, should probably not
601 * just map to a long option, as saying
603 * tcpdump --verbose --verbose
605 * doesn't make sense; it should be --verbosity={N} or something such
608 * For long options with no corresponding short options, we define values
609 * outside the range of ASCII graphic characters, make that the last
610 * component of the entry for the long option, and have a case for that
611 * option in the switch statement.
613 #define OPTION_VERSION 128
614 #define OPTION_TSTAMP_PRECISION 129
615 #define OPTION_IMMEDIATE_MODE 130
616 #define OPTION_PRINT 131
617 #define OPTION_LIST_REMOTE_INTERFACES 132
619 static const struct option longopts
[] = {
620 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
621 { "buffer-size", required_argument
, NULL
, 'B' },
623 { "list-interfaces", no_argument
, NULL
, 'D' },
624 #ifdef HAVE_PCAP_FINDALLDEVS_EX
625 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
627 { "help", no_argument
, NULL
, 'h' },
628 { "interface", required_argument
, NULL
, 'i' },
629 #ifdef HAVE_PCAP_CREATE
630 { "monitor-mode", no_argument
, NULL
, 'I' },
632 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
633 { "time-stamp-type", required_argument
, NULL
, 'j' },
634 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
636 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
637 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
639 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
640 { "list-data-link-types", no_argument
, NULL
, 'L' },
641 { "no-optimize", no_argument
, NULL
, 'O' },
642 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
643 #ifdef HAVE_PCAP_SETDIRECTION
644 { "direction", required_argument
, NULL
, 'Q' },
646 { "snapshot-length", required_argument
, NULL
, 's' },
647 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
648 #ifdef HAVE_PCAP_DUMP_FLUSH
649 { "packet-buffered", no_argument
, NULL
, 'U' },
651 { "linktype", required_argument
, NULL
, 'y' },
652 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
653 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
655 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
656 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
658 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
659 { "number", no_argument
, NULL
, '#' },
660 { "print", no_argument
, NULL
, OPTION_PRINT
},
661 { "version", no_argument
, NULL
, OPTION_VERSION
},
665 #ifdef HAVE_PCAP_FINDALLDEVS_EX
666 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
668 #define LIST_REMOTE_INTERFACES_USAGE
671 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
672 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
674 #define IMMEDIATE_MODE_USAGE ""
677 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
678 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
680 #define TIME_STAMP_PRECISION_USAGE
684 /* Drop root privileges and chroot if necessary */
686 droproot(const char *username
, const char *chroot_dir
)
688 struct passwd
*pw
= NULL
;
690 if (chroot_dir
&& !username
) {
691 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
693 exit_tcpdump(S_ERR_HOST_PROGRAM
);
696 pw
= getpwnam(username
);
699 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
700 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
701 program_name
, chroot_dir
, pcap_strerror(errno
));
702 exit_tcpdump(S_ERR_HOST_PROGRAM
);
705 #ifdef HAVE_LIBCAP_NG
707 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
709 fprintf(stderr
, "error : ret %d\n", ret
);
711 fprintf(stderr
, "dropped privs to %s\n", username
);
715 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
716 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
717 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
718 program_name
, username
,
719 (unsigned long)pw
->pw_uid
,
720 (unsigned long)pw
->pw_gid
,
721 pcap_strerror(errno
));
722 exit_tcpdump(S_ERR_HOST_PROGRAM
);
725 fprintf(stderr
, "dropped privs to %s\n", username
);
727 #endif /* HAVE_LIBCAP_NG */
730 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
731 program_name
, username
);
732 exit_tcpdump(S_ERR_HOST_PROGRAM
);
734 #ifdef HAVE_LIBCAP_NG
735 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
736 DIAG_OFF_CLANG(assign
-enum)
739 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
744 DIAG_ON_CLANG(assign
-enum)
745 capng_apply(CAPNG_SELECT_BOTH
);
746 #endif /* HAVE_LIBCAP_NG */
767 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
769 char *filename
= malloc(PATH_MAX
+ 1);
770 if (filename
== NULL
)
771 error("Makefilename: malloc");
773 /* Process with strftime if Gflag is set. */
777 /* Convert Gflag_time to a usable format */
778 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
779 error("MakeTimedFilename: localtime");
782 /* There's no good way to detect an error in strftime since a return
783 * value of 0 isn't necessarily failure.
785 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
787 strncpy(filename
, orig_name
, PATH_MAX
);
790 if (cnt
== 0 && max_chars
== 0)
791 strncpy(buffer
, filename
, PATH_MAX
+ 1);
793 if (nd_snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
794 /* Report an error if the filename is too large */
795 error("too many output files or filename is too long (> %d)", PATH_MAX
);
800 get_next_file(FILE *VFile
, char *ptr
)
804 ret
= fgets(ptr
, PATH_MAX
, VFile
);
808 if (ptr
[strlen(ptr
) - 1] == '\n')
809 ptr
[strlen(ptr
) - 1] = '\0';
815 static cap_channel_t
*
818 cap_channel_t
*capcas
, *capdnsloc
;
819 const char *types
[1];
824 error("unable to create casper process");
825 capdnsloc
= cap_service_open(capcas
, "system.dns");
826 /* Casper capability no longer needed. */
828 if (capdnsloc
== NULL
)
829 error("unable to open system.dns service");
830 /* Limit system.dns to reverse DNS lookups. */
832 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
833 error("unable to limit access to system.dns service");
834 families
[0] = AF_INET
;
835 families
[1] = AF_INET6
;
836 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
837 error("unable to limit access to system.dns service");
841 #endif /* HAVE_CASPER */
843 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
845 tstamp_precision_from_string(const char *precision
)
847 if (strncmp(precision
, "nano", strlen("nano")) == 0)
848 return PCAP_TSTAMP_PRECISION_NANO
;
850 if (strncmp(precision
, "micro", strlen("micro")) == 0)
851 return PCAP_TSTAMP_PRECISION_MICRO
;
857 tstamp_precision_to_string(int precision
)
861 case PCAP_TSTAMP_PRECISION_MICRO
:
864 case PCAP_TSTAMP_PRECISION_NANO
:
875 * Ensure that, on a dump file's descriptor, we have all the rights
876 * necessary to make the standard I/O library work with an fdopen()ed
877 * FILE * from that descriptor.
879 * A long time ago, in a galaxy far far away, AT&T decided that, instead
880 * of providing separate APIs for getting and setting the FD_ flags on a
881 * descriptor, getting and setting the O_ flags on a descriptor, and
882 * locking files, they'd throw them all into a kitchen-sink fcntl() call
883 * along the lines of ioctl(), the fact that ioctl() operations are
884 * largely specific to particular character devices but fcntl() operations
885 * are either generic to all descriptors or generic to all descriptors for
886 * regular files nonwithstanding.
888 * The Capsicum people decided that fine-grained control of descriptor
889 * operations was required, so that you need to grant permission for
890 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
891 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
892 * collection of things, so there are *individual* fcntls for which
893 * permission needs to be granted.
895 * The FreeBSD standard I/O people implemented some optimizations that
896 * requires that the standard I/O routines be able to determine whether
897 * the descriptor for the FILE * is open append-only or not; as that
898 * descriptor could have come from an open() rather than an fopen(),
899 * that requires that it be able to do an F_GETFL fcntl() to read
902 * Tcpdump uses ftell() to determine how much data has been written
903 * to a file in order to, when used with -C, determine when it's time
904 * to rotate capture files. ftell() therefore needs to do an lseek()
905 * to find out the file offset and must, thanks to the aforementioned
906 * optimization, also know whether the descriptor is open append-only
909 * The net result of all the above is that we need to grant CAP_SEEK,
910 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
912 * Perhaps this is the universe's way of saying that either
914 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
915 * using it, so that Capsicum-capable tcpdump wouldn't need to do
920 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
921 * I/O library that knows what rights are needed by the standard
922 * I/O library, based on the open mode, and assigns them, perhaps
923 * with an additional argument indicating, for example, whether
924 * seeking should be allowed, so that tcpdump doesn't need to know
925 * what the standard I/O library happens to require this week.
928 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
930 int fd
= fileno(pcap_dump_file(p
));
933 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
934 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
935 error("unable to limit dump descriptor");
937 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
938 error("unable to limit dump descriptor fcntls");
944 * Copy arg vector into a new buffer, concatenating arguments with spaces.
947 copy_argv(char **argv
)
959 len
+= strlen(*p
++) + 1;
961 buf
= (char *)malloc(len
);
963 error("copy_argv: malloc");
967 while ((src
= *p
++) != NULL
) {
968 while ((*dst
++ = *src
++) != '\0')
978 * On Windows, we need to open the file in binary mode, so that
979 * we get all the bytes specified by the size we get from "fstat()".
980 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
981 * we define it as 0 if it's not defined, so it does nothing.
988 read_infile(char *fname
)
994 fd
= open(fname
, O_RDONLY
|O_BINARY
);
996 error("can't open %s: %s", fname
, pcap_strerror(errno
));
998 if (fstat(fd
, &buf
) < 0)
999 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1001 cp
= malloc((u_int
)buf
.st_size
+ 1);
1003 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1004 fname
, pcap_strerror(errno
));
1005 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1007 error("read %s: %s", fname
, pcap_strerror(errno
));
1008 if (cc
!= buf
.st_size
)
1009 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
1012 /* replace "# comment" with spaces */
1013 for (i
= 0; i
< cc
; i
++) {
1015 while (i
< cc
&& cp
[i
] != '\n')
1022 #ifdef HAVE_PCAP_FINDALLDEVS
1024 parse_interface_number(const char *device
)
1031 * Search for a colon, terminating any scheme at the beginning
1034 p
= strchr(device
, ':');
1037 * We found it. Is it followed by "//"?
1039 p
++; /* skip the : */
1040 if (strncmp(p
, "//", 2) == 0) {
1042 * Yes. Search for the next /, at the end of the
1043 * authority part of the URL.
1045 p
+= 2; /* skip the // */
1049 * OK, past the / is the path.
1055 devnum
= strtol(device
, &end
, 10);
1056 if (device
!= end
&& *end
== '\0') {
1058 * It's all-numeric, but is it a valid number?
1062 * No, it's not an ordinal.
1064 error("Invalid adapter index");
1069 * It's not all-numeric; return -1, so our caller
1077 find_interface_by_number(const char *url
, long devnum
)
1079 pcap_if_t
*dev
, *devlist
;
1081 char ebuf
[PCAP_ERRBUF_SIZE
];
1083 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1089 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1091 * Search for a colon, terminating any scheme at the beginning
1094 endp
= strchr(url
, ':');
1097 * We found it. Is it followed by "//"?
1099 endp
++; /* skip the : */
1100 if (strncmp(endp
, "//", 2) == 0) {
1102 * Yes. Search for the next /, at the end of the
1103 * authority part of the URL.
1105 endp
+= 2; /* skip the // */
1106 endp
= strchr(endp
, '/');
1112 * OK, everything from device to endp is a URL to hand
1113 * to pcap_findalldevs_ex().
1115 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1116 host_url
= malloc(endp
- url
+ 1);
1117 memcpy(host_url
, url
, endp
- url
);
1118 host_url
[endp
- url
] = '\0';
1119 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1123 status
= pcap_findalldevs(&devlist
, ebuf
);
1127 * Look for the devnum-th entry in the list of devices (1-based).
1129 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1130 i
++, dev
= dev
->next
)
1133 error("Invalid adapter index");
1134 device
= strdup(dev
->name
);
1135 pcap_freealldevs(devlist
);
1140 #ifdef HAVE_PCAP_OPEN
1142 * Prefix for rpcap URLs.
1144 static char rpcap_prefix
[] = "rpcap://";
1148 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1151 #ifdef HAVE_PCAP_CREATE
1156 #ifdef HAVE_PCAP_OPEN
1158 * Is this an rpcap URL?
1160 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1162 * Yes. Open it with pcap_open().
1165 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1166 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1170 * If this failed with "No such device" or "The system
1171 * cannot find the device specified", that means
1172 * the interface doesn't exist; return NULL, so that
1173 * the caller can see whether the device name is
1174 * actually an interface index.
1176 if (strstr(ebuf
, "No such device") != NULL
||
1177 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1182 warning("%s", ebuf
);
1185 #endif /* HAVE_PCAP_OPEN */
1187 #ifdef HAVE_PCAP_CREATE
1188 pc
= pcap_create(device
, ebuf
);
1191 * If this failed with "No such device", that means
1192 * the interface doesn't exist; return NULL, so that
1193 * the caller can see whether the device name is
1194 * actually an interface index.
1196 if (strstr(ebuf
, "No such device") != NULL
)
1200 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1202 show_tstamp_types_and_exit(pc
, device
);
1204 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1205 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1207 error("%s: Can't set %ssecond time stamp precision: %s",
1209 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1210 pcap_statustostr(status
));
1213 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1214 if (immediate_mode
) {
1215 status
= pcap_set_immediate_mode(pc
, 1);
1217 error("%s: Can't set immediate mode: %s",
1219 pcap_statustostr(status
));
1223 * Is this an interface that supports monitor mode?
1225 if (pcap_can_set_rfmon(pc
) == 1)
1226 supports_monitor_mode
= 1;
1228 supports_monitor_mode
= 0;
1229 if (ndo
->ndo_snaplen
!= 0) {
1231 * A snapshot length was explicitly specified;
1234 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1236 error("%s: Can't set snapshot length: %s",
1237 device
, pcap_statustostr(status
));
1239 status
= pcap_set_promisc(pc
, !pflag
);
1241 error("%s: Can't set promiscuous mode: %s",
1242 device
, pcap_statustostr(status
));
1244 status
= pcap_set_rfmon(pc
, 1);
1246 error("%s: Can't set monitor mode: %s",
1247 device
, pcap_statustostr(status
));
1249 status
= pcap_set_timeout(pc
, 1000);
1251 error("%s: pcap_set_timeout failed: %s",
1252 device
, pcap_statustostr(status
));
1254 status
= pcap_set_buffer_size(pc
, Bflag
);
1256 error("%s: Can't set buffer size: %s",
1257 device
, pcap_statustostr(status
));
1259 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1261 status
= pcap_set_tstamp_type(pc
, jflag
);
1263 error("%s: Can't set time stamp type: %s",
1264 device
, pcap_statustostr(status
));
1267 status
= pcap_activate(pc
);
1270 * pcap_activate() failed.
1272 cp
= pcap_geterr(pc
);
1273 if (status
== PCAP_ERROR
)
1275 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1277 * Return an error for our caller to handle.
1279 nd_snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1280 device
, pcap_statustostr(status
), cp
);
1283 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1284 error("%s: %s\n(%s)", device
,
1285 pcap_statustostr(status
), cp
);
1287 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1288 strncmp(device
, "wlan", 4) == 0) {
1289 char parent
[8], newdev
[8];
1291 size_t s
= sizeof(parent
);
1293 nd_snprintf(sysctl
, sizeof(sysctl
),
1294 "net.wlan.%d.%%parent", atoi(device
+ 4));
1295 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1296 strlcpy(newdev
, device
, sizeof(newdev
));
1297 /* Suggest a new wlan device. */
1298 /* FIXME: incrementing the index this way is not going to work well
1299 * when the index is 9 or greater but the only consequence in this
1300 * specific case would be an error message that looks a bit odd.
1302 newdev
[strlen(newdev
)-1]++;
1303 error("%s is not a monitor mode VAP\n"
1304 "To create a new monitor mode VAP use:\n"
1305 " ifconfig %s create wlandev %s wlanmode monitor\n"
1306 "and use %s as the tcpdump interface",
1307 device
, newdev
, parent
, newdev
);
1311 error("%s: %s", device
,
1312 pcap_statustostr(status
));
1313 } else if (status
> 0) {
1315 * pcap_activate() succeeded, but it's warning us
1316 * of a problem it had.
1318 cp
= pcap_geterr(pc
);
1319 if (status
== PCAP_WARNING
)
1321 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1323 warning("%s: %s\n(%s)", device
,
1324 pcap_statustostr(status
), cp
);
1326 warning("%s: %s", device
,
1327 pcap_statustostr(status
));
1329 #ifdef HAVE_PCAP_SETDIRECTION
1331 status
= pcap_setdirection(pc
, Qflag
);
1333 error("%s: pcap_setdirection() failed: %s",
1334 device
, pcap_geterr(pc
));
1336 #endif /* HAVE_PCAP_SETDIRECTION */
1337 #else /* HAVE_PCAP_CREATE */
1340 * If no snapshot length was specified, or a length of 0 was
1341 * specified, default to 256KB.
1343 if (ndo
->ndo_snaplen
== 0)
1344 ndo
->ndo_snaplen
= 262144;
1345 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1348 * If this failed with "No such device", that means
1349 * the interface doesn't exist; return NULL, so that
1350 * the caller can see whether the device name is
1351 * actually an interface index.
1353 if (strstr(ebuf
, "No such device") != NULL
)
1358 warning("%s", ebuf
);
1359 #endif /* HAVE_PCAP_CREATE */
1365 main(int argc
, char **argv
)
1368 bpf_u_int32 localnet
= 0, netmask
= 0;
1369 int timezone_offset
= 0;
1370 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1372 pcap_handler callback
;
1374 const char *dlt_name
;
1375 struct bpf_program fcode
;
1377 void (*oldhandler
)(int);
1379 struct dump_info dumpinfo
;
1380 u_char
*pcap_userdata
;
1381 char ebuf
[PCAP_ERRBUF_SIZE
];
1382 char VFileLine
[PATH_MAX
+ 1];
1383 char *username
= NULL
;
1384 char *chroot_dir
= NULL
;
1387 #ifdef HAVE_PCAP_FINDALLDEVS
1393 #ifdef HAVE_CAPSICUM
1394 cap_rights_t rights
;
1396 #endif /* HAVE_CAPSICUM */
1397 int Oflag
= 1; /* run filter code optimizer */
1399 const char *yflag_dlt_name
= NULL
;
1402 netdissect_options Ndo
;
1403 netdissect_options
*ndo
= &Ndo
;
1406 * Initialize the netdissect code.
1408 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1411 memset(ndo
, 0, sizeof(*ndo
));
1412 ndo_set_function_pointers(ndo
);
1422 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1423 ndo
->program_name
= program_name
= cp
+ 1;
1425 ndo
->program_name
= program_name
= argv
[0];
1427 #if defined(HAVE_PCAP_WSOCKINIT)
1428 if (pcap_wsockinit() != 0)
1429 error("Attempting to initialize Winsock failed");
1430 #elif defined(HAVE_WSOCKINIT)
1431 if (wsockinit() != 0)
1432 error("Attempting to initialize Winsock failed");
1436 * On platforms where the CPU doesn't support unaligned loads,
1437 * force unaligned accesses to abort with SIGBUS, rather than
1438 * being fixed up (slowly) by the OS kernel; on those platforms,
1439 * misaligned accesses are bugs, and we want tcpdump to crash so
1440 * that the bugs are reported.
1442 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1446 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1450 /* compatibility for old -a */
1461 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1463 Bflag
= atoi(optarg
)*1024;
1465 error("invalid packet buffer size %s", optarg
);
1467 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1472 error("invalid packet count %s", optarg
);
1477 #ifdef HAVE_PCAP_DUMP_FTELL64
1478 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1480 Cflag
= strtol(optarg
, &endp
, 10);
1482 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1484 error("invalid file size %s", optarg
);
1486 * Will multiplying it by 1000000 overflow?
1488 #ifdef HAVE_PCAP_DUMP_FTELL64
1489 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1491 if (Cflag
> LONG_MAX
/ 1000000)
1493 error("file size %s is too large", optarg
);
1501 #ifdef HAVE_PCAP_FINDALLDEVS
1507 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1508 case OPTION_LIST_REMOTE_INTERFACES
:
1509 remote_interfaces_source
= optarg
;
1522 #ifndef HAVE_LIBCRYPTO
1523 warning("crypto code not compiled in");
1525 ndo
->ndo_espsecret
= optarg
;
1537 Gflag
= atoi(optarg
);
1539 error("invalid number of seconds %s", optarg
);
1541 /* We will create one file initially. */
1544 /* Grab the current time for rotation use. */
1545 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1546 error("main: can't get current time: %s",
1547 pcap_strerror(errno
));
1553 exit_tcpdump(S_SUCCESS
);
1564 #ifdef HAVE_PCAP_CREATE
1568 #endif /* HAVE_PCAP_CREATE */
1570 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1572 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1574 error("invalid time stamp type %s", optarg
);
1585 * _IOLBF is the same as _IOFBF in Microsoft's C
1586 * libraries; the only alternative they offer
1589 * XXX - this should really be checking for MSVC++,
1590 * not _WIN32, if, for example, MinGW has its own
1591 * C library that is more UNIX-compatible.
1593 setvbuf(stdout
, NULL
, _IONBF
, 0);
1595 #ifdef HAVE_SETLINEBUF
1598 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1608 if (nd_have_smi_support()) {
1609 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1612 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1613 program_name
, optarg
);
1614 (void)fprintf(stderr
, "(no libsmi support)\n");
1619 /* TCP-MD5 shared secret */
1620 #ifndef HAVE_LIBCRYPTO
1621 warning("crypto code not compiled in");
1623 ndo
->ndo_sigsecret
= optarg
;
1644 ++ndo
->ndo_suppress_default_print
;
1647 #ifdef HAVE_PCAP_SETDIRECTION
1649 if (ascii_strcasecmp(optarg
, "in") == 0)
1651 else if (ascii_strcasecmp(optarg
, "out") == 0)
1653 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1654 Qflag
= PCAP_D_INOUT
;
1656 error("unknown capture direction `%s'", optarg
);
1658 #endif /* HAVE_PCAP_SETDIRECTION */
1665 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1666 if (optarg
== end
|| *end
!= '\0'
1667 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1668 error("invalid snaplen %s", optarg
);
1680 if (ascii_strcasecmp(optarg
, "vat") == 0)
1681 ndo
->ndo_packettype
= PT_VAT
;
1682 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1683 ndo
->ndo_packettype
= PT_WB
;
1684 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1685 ndo
->ndo_packettype
= PT_RPC
;
1686 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1687 ndo
->ndo_packettype
= PT_RTP
;
1688 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1689 ndo
->ndo_packettype
= PT_RTCP
;
1690 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1691 ndo
->ndo_packettype
= PT_SNMP
;
1692 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1693 ndo
->ndo_packettype
= PT_CNFP
;
1694 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1695 ndo
->ndo_packettype
= PT_TFTP
;
1696 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1697 ndo
->ndo_packettype
= PT_AODV
;
1698 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1699 ndo
->ndo_packettype
= PT_CARP
;
1700 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1701 ndo
->ndo_packettype
= PT_RADIUS
;
1702 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1703 ndo
->ndo_packettype
= PT_ZMTP1
;
1704 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1705 ndo
->ndo_packettype
= PT_VXLAN
;
1706 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1707 ndo
->ndo_packettype
= PT_PGM
;
1708 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1709 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1710 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1711 ndo
->ndo_packettype
= PT_LMP
;
1712 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1713 ndo
->ndo_packettype
= PT_RESP
;
1715 error("unknown packet type `%s'", optarg
);
1722 #ifdef HAVE_PCAP_DUMP_FLUSH
1741 Wflag
= atoi(optarg
);
1743 error("invalid number of output files %s", optarg
);
1744 WflagChars
= getWflagChars(Wflag
);
1749 ++ndo
->ndo_suppress_default_print
;
1754 ++ndo
->ndo_suppress_default_print
;
1758 yflag_dlt_name
= optarg
;
1760 pcap_datalink_name_to_val(yflag_dlt_name
);
1762 error("invalid data link type %s", yflag_dlt_name
);
1765 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1768 /* Undocumented flag */
1769 pcap_set_parser_debug(1);
1782 ndo
->ndo_packet_number
= 1;
1785 case OPTION_VERSION
:
1787 exit_tcpdump(S_SUCCESS
);
1790 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1791 case OPTION_TSTAMP_PRECISION
:
1792 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1793 if (ndo
->ndo_tstamp_precision
< 0)
1794 error("unsupported time stamp precision");
1798 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1799 case OPTION_IMMEDIATE_MODE
:
1810 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1814 #ifdef HAVE_PCAP_FINDALLDEVS
1816 show_devices_and_exit();
1818 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1819 if (remote_interfaces_source
!= NULL
)
1820 show_remote_devices_and_exit();
1823 switch (ndo
->ndo_tflag
) {
1825 case 0: /* Default */
1826 case 4: /* Default + Date*/
1827 timezone_offset
= gmt2local(0);
1830 case 1: /* No time stamp */
1831 case 2: /* Unix timeval style */
1832 case 3: /* Microseconds since previous packet */
1833 case 5: /* Microseconds since first packet */
1836 default: /* Not supported */
1837 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1841 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1842 error("-f can not be used with -V or -r");
1844 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1845 error("-V and -r are mutually exclusive.");
1847 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1849 * If we're printing dissected packets to the standard output
1850 * and the standard output is a terminal, use immediate mode,
1851 * as the user's probably expecting to see packets pop up
1854 * XXX - set the timeout to a lower value, instead? If so,
1855 * what value would be appropriate?
1857 if ((WFileName
== NULL
|| print
) && isatty(1))
1862 /* if run as root, prepare for chrooting */
1863 if (getuid() == 0 || geteuid() == 0) {
1864 /* future extensibility for cmd-line arguments */
1866 chroot_dir
= WITH_CHROOT
;
1871 /* if run as root, prepare for dropping root privileges */
1872 if (getuid() == 0 || geteuid() == 0) {
1873 /* Run with '-Z root' to restore old behaviour */
1875 username
= WITH_USER
;
1879 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1881 * If RFileName is non-null, it's the pathname of a
1882 * savefile to read. If VFileName is non-null, it's
1883 * the pathname of a file containing a list of pathnames
1884 * (one per line) of savefiles to read.
1886 * In either case, we're reading a savefile, not doing
1891 * We don't need network access, so relinquish any set-UID
1892 * or set-GID privileges we have (if any).
1894 * We do *not* want set-UID privileges when opening a
1895 * trace file, as that might let the user read other
1896 * people's trace files (especially if we're set-UID
1899 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1900 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1902 if (VFileName
!= NULL
) {
1903 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1906 VFile
= fopen(VFileName
, "r");
1909 error("Unable to open file: %s\n", pcap_strerror(errno
));
1911 ret
= get_next_file(VFile
, VFileLine
);
1913 error("Nothing in %s\n", VFileName
);
1914 RFileName
= VFileLine
;
1917 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1918 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1919 ndo
->ndo_tstamp_precision
, ebuf
);
1921 pd
= pcap_open_offline(RFileName
, ebuf
);
1926 #ifdef HAVE_CAPSICUM
1927 cap_rights_init(&rights
, CAP_READ
);
1928 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1930 error("unable to limit pcap descriptor");
1933 dlt
= pcap_datalink(pd
);
1934 dlt_name
= pcap_datalink_val_to_name(dlt
);
1935 if (dlt_name
== NULL
) {
1936 fprintf(stderr
, "reading from file %s, link-type %u\n",
1940 "reading from file %s, link-type %s (%s)\n",
1941 RFileName
, dlt_name
,
1942 pcap_datalink_val_to_description(dlt
));
1946 * We're doing a live capture.
1948 if (device
== NULL
) {
1950 * No interface was specified. Pick one.
1952 #ifdef HAVE_PCAP_FINDALLDEVS
1954 * Find the list of interfaces, and pick
1955 * the first interface.
1957 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
1959 if (devlist
== NULL
)
1960 error("no interfaces available for capture");
1961 device
= strdup(devlist
->name
);
1962 pcap_freealldevs(devlist
);
1963 #else /* HAVE_PCAP_FINDALLDEVS */
1965 * Use whatever interface pcap_lookupdev()
1968 device
= pcap_lookupdev(ebuf
);
1975 * Try to open the interface with the specified name.
1977 pd
= open_interface(device
, ndo
, ebuf
);
1980 * That failed. If we can get a list of
1981 * interfaces, and the interface name
1982 * is purely numeric, try to use it as
1983 * a 1-based index in the list of
1986 #ifdef HAVE_PCAP_FINDALLDEVS
1987 devnum
= parse_interface_number(device
);
1990 * It's not a number; just report
1991 * the open error and fail.
1997 * OK, it's a number; try to find the
1998 * interface with that index, and try
2001 * find_interface_by_number() exits if it
2002 * couldn't be found.
2004 device
= find_interface_by_number(device
, devnum
);
2005 pd
= open_interface(device
, ndo
, ebuf
);
2008 #else /* HAVE_PCAP_FINDALLDEVS */
2010 * We can't get a list of interfaces; just
2014 #endif /* HAVE_PCAP_FINDALLDEVS */
2018 * Let user own process after capture device has
2022 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2023 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2025 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2027 if(pcap_setbuff(pd
, Bflag
)==-1){
2028 error("%s", pcap_geterr(pd
));
2030 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2032 show_dlts_and_exit(pd
, device
);
2033 if (yflag_dlt
>= 0) {
2034 #ifdef HAVE_PCAP_SET_DATALINK
2035 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2036 error("%s", pcap_geterr(pd
));
2039 * We don't actually support changing the
2040 * data link type, so we only let them
2041 * set it to what it already is.
2043 if (yflag_dlt
!= pcap_datalink(pd
)) {
2044 error("%s is not one of the DLTs supported by this device\n",
2048 (void)fprintf(stderr
, "%s: data link type %s\n",
2049 program_name
, yflag_dlt_name
);
2050 (void)fflush(stderr
);
2052 i
= pcap_snapshot(pd
);
2053 if (ndo
->ndo_snaplen
< i
) {
2054 if (ndo
->ndo_snaplen
!= 0)
2055 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2056 ndo
->ndo_snaplen
= i
;
2057 } else if (ndo
->ndo_snaplen
> i
) {
2058 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2059 ndo
->ndo_snaplen
= i
;
2061 if(ndo
->ndo_fflag
!= 0) {
2062 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2063 warning("foreign (-f) flag used but: %s", ebuf
);
2069 cmdbuf
= read_infile(infile
);
2071 cmdbuf
= copy_argv(&argv
[optind
]);
2073 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2074 pcap_set_optimizer_debug(dflag
);
2076 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2077 error("%s", pcap_geterr(pd
));
2079 bpf_dump(&fcode
, dflag
);
2082 pcap_freecode(&fcode
);
2083 exit_tcpdump(S_SUCCESS
);
2087 if (!ndo
->ndo_nflag
)
2088 capdns
= capdns_setup();
2089 #endif /* HAVE_CASPER */
2091 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2094 (void)setsignal(SIGPIPE
, cleanup
);
2095 (void)setsignal(SIGTERM
, cleanup
);
2097 (void)setsignal(SIGINT
, cleanup
);
2098 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2099 (void)setsignal(SIGCHLD
, child_cleanup
);
2101 /* Cooperate with nohup(1) */
2103 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2104 (void)setsignal(SIGHUP
, oldhandler
);
2109 * If a user name was specified with "-Z", attempt to switch to
2110 * that user's UID. This would probably be used with sudo,
2111 * to allow tcpdump to be run in a special restricted
2112 * account (if you just want to allow users to open capture
2113 * devices, and can't just give users that permission,
2114 * you'd make tcpdump set-UID or set-GID).
2116 * Tcpdump doesn't necessarily write only to one savefile;
2117 * the general only way to allow a -Z instance to write to
2118 * savefiles as the user under whose UID it's run, rather
2119 * than as the user specified with -Z, would thus be to switch
2120 * to the original user ID before opening a capture file and
2121 * then switch back to the -Z user ID after opening the savefile.
2122 * Switching to the -Z user ID only after opening the first
2123 * savefile doesn't handle the general case.
2126 if (getuid() == 0 || geteuid() == 0) {
2127 #ifdef HAVE_LIBCAP_NG
2128 /* Initialize capng */
2129 capng_clear(CAPNG_SELECT_BOTH
);
2131 DIAG_OFF_CLANG(assign
-enum)
2134 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2138 DIAG_ON_CLANG(assign
-enum)
2141 DIAG_OFF_CLANG(assign
-enum)
2144 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2147 DIAG_ON_CLANG(assign
-enum)
2151 DIAG_OFF_CLANG(assign
-enum)
2154 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2157 DIAG_ON_CLANG(assign
-enum)
2159 capng_apply(CAPNG_SELECT_BOTH
);
2160 #endif /* HAVE_LIBCAP_NG */
2161 if (username
|| chroot_dir
)
2162 droproot(username
, chroot_dir
);
2167 if (pcap_setfilter(pd
, &fcode
) < 0)
2168 error("%s", pcap_geterr(pd
));
2169 #ifdef HAVE_CAPSICUM
2170 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2171 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2174 * The various libpcap devices use a combination of
2175 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2176 * so we add the relevant access rights.
2178 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2179 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2181 error("unable to limit pcap descriptor");
2183 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2184 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2185 error("unable to limit ioctls on pcap descriptor");
2190 /* Do not exceed the default PATH_MAX for files. */
2191 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2193 if (dumpinfo
.CurrentFileName
== NULL
)
2194 error("malloc of dumpinfo.CurrentFileName");
2196 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2198 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2200 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2202 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2203 #ifdef HAVE_LIBCAP_NG
2204 /* Give up CAP_DAC_OVERRIDE capability.
2205 * Only allow it to be restored if the -C or -G flag have been
2206 * set since we may need to create more files later on.
2210 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2214 capng_apply(CAPNG_SELECT_BOTH
);
2215 #endif /* HAVE_LIBCAP_NG */
2217 error("%s", pcap_geterr(pd
));
2218 #ifdef HAVE_CAPSICUM
2219 set_dumper_capsicum_rights(p
);
2221 if (Cflag
!= 0 || Gflag
!= 0) {
2222 #ifdef HAVE_CAPSICUM
2223 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2224 if (dumpinfo
.WFileName
== NULL
) {
2225 error("Unable to allocate memory for file %s",
2228 dumpinfo
.dirfd
= open(dirname(WFileName
),
2229 O_DIRECTORY
| O_RDONLY
);
2230 if (dumpinfo
.dirfd
< 0) {
2231 error("unable to open directory %s",
2232 dirname(WFileName
));
2234 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2235 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2236 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2238 error("unable to limit directory rights");
2240 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2242 error("unable to limit dump descriptor fcntls");
2244 #else /* !HAVE_CAPSICUM */
2245 dumpinfo
.WFileName
= WFileName
;
2247 callback
= dump_packet_and_trunc
;
2250 pcap_userdata
= (u_char
*)&dumpinfo
;
2252 callback
= dump_packet
;
2253 dumpinfo
.WFileName
= WFileName
;
2256 pcap_userdata
= (u_char
*)&dumpinfo
;
2259 dlt
= pcap_datalink(pd
);
2260 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2263 dumpinfo
.ndo
= NULL
;
2265 #ifdef HAVE_PCAP_DUMP_FLUSH
2270 dlt
= pcap_datalink(pd
);
2271 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2272 callback
= print_packet
;
2273 pcap_userdata
= (u_char
*)ndo
;
2276 #ifdef SIGNAL_REQ_INFO
2278 * We can't get statistics when reading from a file rather
2279 * than capturing from a device.
2281 if (RFileName
== NULL
)
2282 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2284 #ifdef SIGNAL_FLUSH_PCAP
2285 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2288 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2290 * When capturing to a file, if "--print" wasn't specified,
2291 *"-v" means tcpdump should, once per second,
2292 * "v"erbosely report the number of packets captured.
2296 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2298 * suggests that this dates back to W2K.
2300 * I don't know what a "long wait" is, but we'll assume
2301 * that printing the stats could be a "long wait".
2303 CreateTimerQueueTimer(&timer_handle
, NULL
,
2304 verbose_stats_dump
, NULL
, 1000, 1000,
2305 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2306 setvbuf(stderr
, NULL
, _IONBF
, 0);
2309 * Assume this is UN*X, and that it has setitimer(); that
2310 * dates back to UNIX 95.
2312 struct itimerval timer
;
2313 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2314 timer
.it_interval
.tv_sec
= 1;
2315 timer
.it_interval
.tv_usec
= 0;
2316 timer
.it_value
.tv_sec
= 1;
2317 timer
.it_value
.tv_usec
= 1;
2318 setitimer(ITIMER_REAL
, &timer
, NULL
);
2322 if (RFileName
== NULL
) {
2324 * Live capture (if -V was specified, we set RFileName
2325 * to a file from the -V file). Print a message to
2326 * the standard error on UN*X.
2328 if (!ndo
->ndo_vflag
&& !WFileName
) {
2329 (void)fprintf(stderr
,
2330 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2333 (void)fprintf(stderr
, "%s: ", program_name
);
2334 dlt
= pcap_datalink(pd
);
2335 dlt_name
= pcap_datalink_val_to_name(dlt
);
2336 if (dlt_name
== NULL
) {
2337 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2338 device
, dlt
, ndo
->ndo_snaplen
);
2340 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2342 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2344 (void)fflush(stderr
);
2347 #ifdef HAVE_CAPSICUM
2348 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2350 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2352 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2353 #endif /* HAVE_CASPER */
2354 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2355 error("unable to enter the capability mode");
2356 #endif /* HAVE_CAPSICUM */
2359 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2360 if (WFileName
== NULL
) {
2362 * We're printing packets. Flush the printed output,
2363 * so it doesn't get intermingled with error output.
2367 * We got interrupted, so perhaps we didn't
2368 * manage to finish a line we were printing.
2369 * Print an extra newline, just in case.
2373 (void)fflush(stdout
);
2377 * We got interrupted. If we are reading multiple
2378 * files (via -V) set these so that we stop.
2387 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2388 program_name
, pcap_geterr(pd
));
2390 if (RFileName
== NULL
) {
2392 * We're doing a live capture. Report the capture
2398 if (VFileName
!= NULL
) {
2399 ret
= get_next_file(VFile
, VFileLine
);
2403 RFileName
= VFileLine
;
2404 pd
= pcap_open_offline(RFileName
, ebuf
);
2407 #ifdef HAVE_CAPSICUM
2408 cap_rights_init(&rights
, CAP_READ
);
2409 if (cap_rights_limit(fileno(pcap_file(pd
)),
2410 &rights
) < 0 && errno
!= ENOSYS
) {
2411 error("unable to limit pcap descriptor");
2414 new_dlt
= pcap_datalink(pd
);
2415 if (new_dlt
!= dlt
) {
2417 * The new file has a different
2418 * link-layer header type from the
2421 if (WFileName
!= NULL
) {
2423 * We're writing raw packets
2424 * that match the filter to
2425 * a pcap file. pcap files
2426 * don't support multiple
2427 * different link-layer
2428 * header types, so we fail
2431 error("%s: new dlt does not match original", RFileName
);
2435 * We're printing the decoded packets;
2436 * switch to the new DLT.
2438 * To do that, we need to change
2439 * the printer, change the DLT name,
2440 * and recompile the filter with
2444 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2445 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2446 error("%s", pcap_geterr(pd
));
2450 * Set the filter on the new file.
2452 if (pcap_setfilter(pd
, &fcode
) < 0)
2453 error("%s", pcap_geterr(pd
));
2456 * Report the new file.
2458 dlt_name
= pcap_datalink_val_to_name(dlt
);
2459 if (dlt_name
== NULL
) {
2460 fprintf(stderr
, "reading from file %s, link-type %u\n",
2464 "reading from file %s, link-type %s (%s)\n",
2465 RFileName
, dlt_name
,
2466 pcap_datalink_val_to_description(dlt
));
2471 while (ret
!= NULL
);
2474 pcap_freecode(&fcode
);
2475 exit_tcpdump(status
== -1 ? 1 : 0);
2482 (*setsignal (int sig
, void (*func
)(int)))(int)
2485 return (signal(sig
, func
));
2487 struct sigaction old
, new;
2489 memset(&new, 0, sizeof(new));
2490 new.sa_handler
= func
;
2492 new.sa_flags
= SA_RESTART
;
2493 if (sigaction(sig
, &new, &old
) < 0)
2495 return (old
.sa_handler
);
2499 /* make a clean exit on interrupts */
2501 cleanup(int signo _U_
)
2504 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2505 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2506 CloseHandle(timer_handle
);
2507 timer_handle
= INVALID_HANDLE_VALUE
;
2510 struct itimerval timer
;
2512 timer
.it_interval
.tv_sec
= 0;
2513 timer
.it_interval
.tv_usec
= 0;
2514 timer
.it_value
.tv_sec
= 0;
2515 timer
.it_value
.tv_usec
= 0;
2516 setitimer(ITIMER_REAL
, &timer
, NULL
);
2519 #ifdef HAVE_PCAP_BREAKLOOP
2521 * We have "pcap_breakloop()"; use it, so that we do as little
2522 * as possible in the signal handler (it's probably not safe
2523 * to do anything with standard I/O streams in a signal handler -
2524 * the ANSI C standard doesn't say it is).
2529 * We don't have "pcap_breakloop()"; this isn't safe, but
2530 * it's the best we can do. Print the summary if we're
2531 * not reading from a savefile - i.e., if we're doing a
2532 * live capture - and exit.
2534 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2536 * We got interrupted, so perhaps we didn't
2537 * manage to finish a line we were printing.
2538 * Print an extra newline, just in case.
2541 (void)fflush(stdout
);
2544 exit_tcpdump(S_SUCCESS
);
2549 On windows, we do not use a fork, so we do not care less about
2550 waiting a child processes to die
2552 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2554 child_cleanup(int signo _U_
)
2558 #endif /* HAVE_FORK && HAVE_VFORK */
2563 struct pcap_stat stats
;
2566 * Older versions of libpcap didn't set ps_ifdrop on some
2567 * platforms; initialize it to 0 to handle that.
2569 stats
.ps_ifdrop
= 0;
2570 if (pcap_stats(pd
, &stats
) < 0) {
2571 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2577 fprintf(stderr
, "%s: ", program_name
);
2579 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2580 PLURAL_SUFFIX(packets_captured
));
2582 fputs(", ", stderr
);
2585 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2586 PLURAL_SUFFIX(stats
.ps_recv
));
2588 fputs(", ", stderr
);
2591 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2592 PLURAL_SUFFIX(stats
.ps_drop
));
2593 if (stats
.ps_ifdrop
!= 0) {
2595 fputs(", ", stderr
);
2598 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2599 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2605 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2607 #define fork_subprocess() fork()
2609 #define fork_subprocess() vfork()
2612 compress_savefile(const char *filename
)
2616 child
= fork_subprocess();
2619 "compress_savefile: fork failed: %s\n",
2620 pcap_strerror(errno
));
2624 /* Parent process. */
2630 * Set to lowest priority so that this doesn't disturb the capture.
2633 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2635 setpriority(PRIO_PROCESS
, 0, 19);
2637 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2639 "compress_savefile: execlp(%s, %s) failed: %s\n",
2642 pcap_strerror(errno
));
2644 exit(S_ERR_HOST_PROGRAM
);
2646 _exit(S_ERR_HOST_PROGRAM
);
2649 #else /* HAVE_FORK && HAVE_VFORK */
2651 compress_savefile(const char *filename
)
2654 "compress_savefile failed. Functionality not implemented under your system\n");
2656 #endif /* HAVE_FORK && HAVE_VFORK */
2659 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2661 struct dump_info
*dump_info
;
2667 dump_info
= (struct dump_info
*)user
;
2670 * XXX - this won't force the file to rotate on the specified time
2671 * boundary, but it will rotate on the first packet received after the
2672 * specified Gflag number of seconds. Note: if a Gflag time boundary
2673 * and a Cflag size boundary coincide, the time rotation will occur
2674 * first thereby cancelling the Cflag boundary (since the file should
2678 /* Check if it is time to rotate */
2681 /* Get the current time */
2682 if ((t
= time(NULL
)) == (time_t)-1) {
2683 error("dump_and_trunc_packet: can't get current_time: %s",
2684 pcap_strerror(errno
));
2688 /* If the time is greater than the specified window, rotate */
2689 if (t
- Gflag_time
>= Gflag
) {
2690 #ifdef HAVE_CAPSICUM
2695 /* Update the Gflag_time */
2697 /* Update Gflag_count */
2700 * Close the current file and open a new one.
2702 pcap_dump_close(dump_info
->p
);
2705 * Compress the file we just closed, if the user asked for it
2708 compress_savefile(dump_info
->CurrentFileName
);
2711 * Check to see if we've exceeded the Wflag (when
2714 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2715 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2718 exit_tcpdump(S_SUCCESS
);
2721 if (dump_info
->CurrentFileName
!= NULL
)
2722 free(dump_info
->CurrentFileName
);
2723 /* Allocate space for max filename + \0. */
2724 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2725 if (dump_info
->CurrentFileName
== NULL
)
2726 error("dump_packet_and_trunc: malloc");
2728 * Gflag was set otherwise we wouldn't be here. Reset the count
2729 * so multiple files would end with 1,2,3 in the filename.
2730 * The counting is handled with the -C flow after this.
2735 * This is always the first file in the Cflag
2737 * We also don't need numbering if Cflag is not set.
2740 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2743 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2745 #ifdef HAVE_LIBCAP_NG
2746 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2747 capng_apply(CAPNG_SELECT_BOTH
);
2748 #endif /* HAVE_LIBCAP_NG */
2749 #ifdef HAVE_CAPSICUM
2750 fd
= openat(dump_info
->dirfd
,
2751 dump_info
->CurrentFileName
,
2752 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2754 error("unable to open file %s",
2755 dump_info
->CurrentFileName
);
2757 fp
= fdopen(fd
, "w");
2759 error("unable to fdopen file %s",
2760 dump_info
->CurrentFileName
);
2762 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2763 #else /* !HAVE_CAPSICUM */
2764 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2766 #ifdef HAVE_LIBCAP_NG
2767 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2768 capng_apply(CAPNG_SELECT_BOTH
);
2769 #endif /* HAVE_LIBCAP_NG */
2770 if (dump_info
->p
== NULL
)
2771 error("%s", pcap_geterr(pd
));
2772 #ifdef HAVE_CAPSICUM
2773 set_dumper_capsicum_rights(dump_info
->p
);
2779 * XXX - this won't prevent capture files from getting
2780 * larger than Cflag - the last packet written to the
2781 * file could put it over Cflag.
2784 #ifdef HAVE_PCAP_DUMP_FTELL64
2785 int64_t size
= pcap_dump_ftell64(dump_info
->p
);
2788 * XXX - this only handles a Cflag value > 2^31-1 on
2789 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2790 * Windows) or LLP64 (64-bit Windows) would require
2791 * a version of libpcap with pcap_dump_ftell64().
2793 long size
= pcap_dump_ftell(dump_info
->p
);
2797 error("ftell fails on output file");
2799 #ifdef HAVE_CAPSICUM
2805 * Close the current file and open a new one.
2807 pcap_dump_close(dump_info
->p
);
2810 * Compress the file we just closed, if the user
2814 compress_savefile(dump_info
->CurrentFileName
);
2818 if (Cflag_count
>= Wflag
)
2821 if (dump_info
->CurrentFileName
!= NULL
)
2822 free(dump_info
->CurrentFileName
);
2823 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2824 if (dump_info
->CurrentFileName
== NULL
)
2825 error("dump_packet_and_trunc: malloc");
2826 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2827 #ifdef HAVE_LIBCAP_NG
2828 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2829 capng_apply(CAPNG_SELECT_BOTH
);
2830 #endif /* HAVE_LIBCAP_NG */
2831 #ifdef HAVE_CAPSICUM
2832 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2833 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2835 error("unable to open file %s",
2836 dump_info
->CurrentFileName
);
2838 fp
= fdopen(fd
, "w");
2840 error("unable to fdopen file %s",
2841 dump_info
->CurrentFileName
);
2843 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2844 #else /* !HAVE_CAPSICUM */
2845 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2847 #ifdef HAVE_LIBCAP_NG
2848 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2849 capng_apply(CAPNG_SELECT_BOTH
);
2850 #endif /* HAVE_LIBCAP_NG */
2851 if (dump_info
->p
== NULL
)
2852 error("%s", pcap_geterr(pd
));
2853 #ifdef HAVE_CAPSICUM
2854 set_dumper_capsicum_rights(dump_info
->p
);
2859 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2860 #ifdef HAVE_PCAP_DUMP_FLUSH
2862 pcap_dump_flush(dump_info
->p
);
2865 if (dump_info
->ndo
!= NULL
)
2866 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2874 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2876 struct dump_info
*dump_info
;
2882 dump_info
= (struct dump_info
*)user
;
2884 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2885 #ifdef HAVE_PCAP_DUMP_FLUSH
2887 pcap_dump_flush(dump_info
->p
);
2890 if (dump_info
->ndo
!= NULL
)
2891 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2899 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2905 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2912 #ifdef SIGNAL_REQ_INFO
2913 void requestinfo(int signo _U_
)
2922 #ifdef SIGNAL_FLUSH_PCAP
2923 void flushpcap(int signo _U_
)
2931 print_packets_captured (void)
2933 static u_int prev_packets_captured
, first
= 1;
2935 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2936 fprintf(stderr
, "Got %u\r", packets_captured
);
2938 prev_packets_captured
= packets_captured
;
2943 * Called once each second in verbose mode while dumping to file
2946 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
2947 BOOLEAN timer_fired _U_
)
2949 print_packets_captured();
2952 static void verbose_stats_dump(int sig _U_
)
2954 print_packets_captured();
2958 USES_APPLE_DEPRECATED_API
2962 #ifndef HAVE_PCAP_LIB_VERSION
2963 #ifdef HAVE_PCAP_VERSION
2964 extern char pcap_version
[];
2965 #else /* HAVE_PCAP_VERSION */
2966 static char pcap_version
[] = "unknown";
2967 #endif /* HAVE_PCAP_VERSION */
2968 #endif /* HAVE_PCAP_LIB_VERSION */
2969 const char *smi_version_string
;
2971 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
2972 #ifdef HAVE_PCAP_LIB_VERSION
2973 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
2974 #else /* HAVE_PCAP_LIB_VERSION */
2975 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2976 #endif /* HAVE_PCAP_LIB_VERSION */
2978 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2979 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2982 smi_version_string
= nd_smi_version_string();
2983 if (smi_version_string
!= NULL
)
2984 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2985 #ifdef HAVE_DNET_HTOA
2986 (void)fprintf(stderr
, "libdnet unknown version\n");
2989 #if defined(__SANITIZE_ADDRESS__)
2990 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
2991 #elif defined(__has_feature)
2992 # if __has_feature(address_sanitizer)
2993 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
2995 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3003 (void)fprintf(stderr
,
3004 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
3005 (void)fprintf(stderr
,
3006 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3007 (void)fprintf(stderr
,
3008 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3009 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3010 (void)fprintf(stderr
,
3011 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
3013 (void)fprintf(stderr
,
3014 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
3015 (void)fprintf(stderr
,
3016 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
3017 (void)fprintf(stderr
,
3018 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
3019 (void)fprintf(stderr
,
3020 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
3021 (void)fprintf(stderr
,
3022 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");