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.
37 #ifndef TCPDUMP_CONFIG_H_
38 #error "The included config.h header is not from the tcpdump build."
41 #include "netdissect-stdinc.h"
44 * This must appear after including netdissect-stdinc.h, so that _U_ is
48 static const char copyright
[] _U_
=
49 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
50 The Regents of the University of California. All rights reserved.\n";
58 #include <openssl/crypto.h>
61 #ifdef HAVE_GETOPT_LONG
64 #include "missing/getopt_long.h"
66 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
67 * to compile if <pcap.h> has already been included; including the headers
68 * in the opposite order works fine. For the most part anyway, because in
69 * FreeBSD <pcap/pcap.h> declares bpf_dump() instead of <net/bpf.h>. Thus
70 * interface.h takes care of it later to avoid a compiler warning.
73 #include <sys/capsicum.h>
74 #include <sys/ioccom.h>
78 #include <libcasper.h>
79 #include <casper/cap_dns.h>
81 #endif /* HAVE_CASPER */
82 #endif /* HAVE_CAPSICUM */
85 * We found pcap_open() in the capture library, so we'll be using
86 * the remote capture APIs; define PCAP_REMOTE before we include pcap.h,
87 * so we get those APIs declared, and the types and #defines that they
90 * WinPcap's headers require that PCAP_REMOTE be defined in order to get
91 * remote-capture APIs declared and types and #defines that they use
94 * (Versions of libpcap with those APIs, and thus Npcap, which is based on
95 * those versions of libpcap, don't require it.)
109 #include <sys/time.h>
110 #include <sys/wait.h>
111 #include <sys/resource.h>
117 * Pathname separator.
118 * Use this in pathnames, but do *not* use it in URLs.
121 #define PATH_SEPARATOR '\\'
123 #define PATH_SEPARATOR '/'
126 /* capabilities convenience library */
127 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
128 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
129 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
131 #ifdef HAVE_LIBCAP_NG
135 #undef HAVE_LIBCAP_NG
136 #endif /* HAVE_CAP_NG_H */
137 #endif /* HAVE_LIBCAP_NG */
140 #include <sys/sysctl.h>
141 #endif /* __FreeBSD__ */
143 #include "netdissect-stdinc.h"
144 #include "netdissect.h"
145 #include "interface.h"
146 #include "addrtoname.h"
147 #include "ascii_strcasecmp.h"
151 #include "diag-control.h"
156 #define PATH_MAX 1024
160 #define SIGNAL_REQ_INFO SIGINFO
161 #elif defined(SIGUSR1)
162 #define SIGNAL_REQ_INFO SIGUSR1
166 #define SIGNAL_FLUSH_PCAP SIGUSR2
169 static int Bflag
; /* buffer size */
170 static int64_t Cflag
; /* rotate dump files after this many bytes */
171 static int Cflag_count
; /* Keep track of which file number we're writing */
172 static int Dflag
; /* list available devices and exit */
173 #ifdef HAVE_PCAP_FINDALLDEVS_EX
174 static char *remote_interfaces_source
; /* list available devices from this source and exit */
178 * This is exported because, in some versions of libpcap, if libpcap
179 * is built with optimizer debugging code (which is *NOT* the default
180 * configuration!), the library *imports*(!) a variable named dflag,
181 * under the expectation that tcpdump is exporting it, to govern
182 * how much debugging information to print when optimizing
183 * the generated BPF code.
185 * This is a horrible hack; newer versions of libpcap don't import
186 * dflag but, instead, *if* built with optimizer debugging code,
187 * *export* a routine to set that flag.
190 int dflag
; /* print filter code */
191 static int Gflag
; /* rotate dump files after this many seconds */
192 static int Gflag_count
; /* number of files created with Gflag rotation */
193 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
194 static int Lflag
; /* list available data link types and exit */
195 static int Iflag
; /* rfmon (monitor) mode */
196 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
197 static int Jflag
; /* list available time stamp types */
198 static int jflag
= -1; /* packet time stamp source */
200 static int lflag
; /* line-buffered output */
201 static int pflag
; /* don't go promiscuous */
202 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
203 static int Uflag
; /* "unbuffered" output of dump files */
204 static int Wflag
; /* recycle output files after this number of files */
205 static int WflagChars
;
206 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
207 static int timeout
= 1000; /* default timeout = 1000 ms = 1 s */
208 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
209 static int immediate_mode
;
211 static int count_mode
;
212 static u_int packets_to_skip
;
214 static int infodelay
;
215 static int infoprint
;
220 static int parse_int(const char *argname
, const char *string
, char **endp
,
221 int minval
, int maxval
, int base
);
222 static u_int
parse_u_int(const char *argname
, const char *string
, char **endp
,
223 u_int minval
, u_int maxval
, int base
);
224 static int64_t parse_int64(const char *argname
, const char *string
,
225 char **endp
, int64_t minval
, int64_t maxval
, int base
);
226 static void (*setsignal (int sig
, void (*func
)(int)))(int);
227 static void cleanup(int);
228 static void child_cleanup(int);
229 static void print_version(FILE *);
230 static void print_usage(FILE *);
232 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
233 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
234 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
236 #ifdef SIGNAL_REQ_INFO
237 static void requestinfo(int);
240 #ifdef SIGNAL_FLUSH_PCAP
241 static void flushpcap(int);
245 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
246 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
248 static void verbose_stats_dump(int sig
);
251 static void info(int);
252 static u_int packets_captured
;
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" },
262 #ifdef PCAP_IF_WIRELESS
263 { PCAP_IF_WIRELESS
, "Wireless" },
269 static pcap_dumper_t
*pdd
= NULL
;
271 static int supports_monitor_mode
;
279 char *CurrentFileName
;
282 netdissect_options
*ndo
;
288 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
290 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
291 * by any libpcap header, because it's a special hack, only available if
292 * libpcap was configured to include it, and only intended for use by
293 * libpcap developers trying to debug the parser for filter expressions).
296 __declspec(dllimport
)
300 void pcap_set_parser_debug(int);
301 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
303 * We don't have pcap_set_parser_debug() in libpcap, but we do have
304 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
305 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
308 pcap_set_parser_debug(int value
)
310 #ifdef HAVE_PCAP_DEBUG
311 extern int pcap_debug
;
314 #else /* HAVE_PCAP_DEBUG */
318 #endif /* HAVE_PCAP_DEBUG */
321 #define HAVE_PCAP_SET_PARSER_DEBUG
322 #endif // HAVE_PCAP_SET_PARSER_DEBUG, HAVE_PCAP_DEBUG, HAVE_YYDEBUG
324 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
326 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
327 * by any libpcap header, because it's a special hack, only available if
328 * libpcap was configured to include it, and only intended for use by
329 * libpcap developers trying to debug the optimizer for filter expressions).
332 __declspec(dllimport
)
336 void pcap_set_optimizer_debug(int);
337 #endif // HAVE_PCAP_SET_OPTIMIZER_DEBUG
340 exit_tcpdump(const int status
)
347 static void NORETURN
PRINTFLIKE(1, 2)
348 error(FORMAT_STRING(const char *fmt
), ...)
352 (void)fprintf(stderr
, "%s: ", program_name
);
354 (void)vfprintf(stderr
, fmt
, ap
);
359 (void)fputc('\n', stderr
);
361 exit_tcpdump(S_ERR_HOST_PROGRAM
);
366 static void PRINTFLIKE(1, 2)
367 warning(FORMAT_STRING(const char *fmt
), ...)
371 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
373 (void)vfprintf(stderr
, fmt
, ap
);
378 (void)fputc('\n', stderr
);
382 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
384 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
387 int *tstamp_types
= 0;
388 const char *tstamp_type_name
;
391 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
392 if (n_tstamp_types
< 0)
393 error("%s", pcap_geterr(pc
));
395 if (n_tstamp_types
== 0) {
396 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
398 exit_tcpdump(S_SUCCESS
);
400 fprintf(stdout
, "Time stamp types for %s (use option -j to set):\n",
402 for (i
= 0; i
< n_tstamp_types
; i
++) {
403 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
404 if (tstamp_type_name
!= NULL
) {
405 (void) fprintf(stdout
, " %s (%s)\n", tstamp_type_name
,
406 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
408 (void) fprintf(stdout
, " %d\n", tstamp_types
[i
]);
411 pcap_free_tstamp_types(tstamp_types
);
412 exit_tcpdump(S_SUCCESS
);
414 #endif // HAVE_PCAP_SET_TSTAMP_TYPE
417 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
421 const char *dlt_name
;
423 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
425 error("%s", pcap_geterr(pc
));
426 else if (n_dlts
== 0 || !dlts
)
427 error("No data link types.");
430 * If the interface is known to support monitor mode, indicate
431 * whether these are the data link types available when not in
432 * monitor mode, if -I wasn't specified, or when in monitor mode,
433 * when -I was specified (the link-layer types available in
434 * monitor mode might be different from the ones available when
435 * not in monitor mode).
437 (void) fprintf(stdout
, "Data link types for ");
438 if (supports_monitor_mode
)
439 (void) fprintf(stdout
, "%s %s",
441 Iflag
? "when in monitor mode" : "when not in monitor mode");
443 (void) fprintf(stdout
, "%s",
445 (void) fprintf(stdout
, " (use option -y to set):\n");
447 for (i
= 0; i
< n_dlts
; i
++) {
448 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
449 if (dlt_name
!= NULL
) {
450 (void) fprintf(stdout
, " %s (%s)", dlt_name
,
451 pcap_datalink_val_to_description(dlts
[i
]));
454 * OK, does tcpdump handle that type?
456 if (!has_printer(dlts
[i
]))
457 (void) fprintf(stdout
, " (printing not supported)");
458 fprintf(stdout
, "\n");
460 (void) fprintf(stdout
, " DLT %d (printing not supported)\n",
464 pcap_free_datalinks(dlts
);
465 exit_tcpdump(S_SUCCESS
);
469 show_devices_and_exit(void)
471 pcap_if_t
*dev
, *devlist
;
472 char ebuf
[PCAP_ERRBUF_SIZE
];
475 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
477 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
478 printf("%d.%s", i
+1, dev
->name
);
479 if (dev
->description
!= NULL
)
480 printf(" (%s)", dev
->description
);
481 if (dev
->flags
!= 0) {
483 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
484 #ifdef PCAP_IF_WIRELESS
485 if (dev
->flags
& PCAP_IF_WIRELESS
) {
486 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
488 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
489 printf(", Association status unknown");
492 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
493 printf(", Associated");
496 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
497 printf(", Not associated");
500 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
504 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
506 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
507 printf(", Connection status unknown");
510 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
511 printf(", Connected");
514 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
515 printf(", Disconnected");
518 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
522 #endif // PCAP_IF_WIRELESS
527 pcap_freealldevs(devlist
);
528 exit_tcpdump(S_SUCCESS
);
531 #ifdef HAVE_PCAP_FINDALLDEVS_EX
533 show_remote_devices_and_exit(void)
535 pcap_if_t
*dev
, *devlist
;
536 char ebuf
[PCAP_ERRBUF_SIZE
];
539 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
541 if (strcmp(ebuf
, "not supported") == 0) {
543 * macOS 14's pcap_findalldevs_ex(), which is a
544 * stub that always returns -1 with an error
545 * message of "not supported".
547 * In this case, as we passed it an rpcap://
548 * URL, treat that as meaning "remote capture
551 error("Remote capture not supported");
555 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
556 printf("%d.%s", i
+1, dev
->name
);
557 if (dev
->description
!= NULL
)
558 printf(" (%s)", dev
->description
);
560 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
563 pcap_freealldevs(devlist
);
564 exit_tcpdump(S_SUCCESS
);
566 #endif /* HAVE_PCAP_FINDALLDEVS_EX */
571 * Note that there we use all letters for short options except for g, k,
572 * o, and P, and those are used by other versions of tcpdump, and we should
573 * only use them for the same purposes that the other versions of tcpdump
576 * macOS tcpdump uses -g to force non--v output for IP to be on one
577 * line, making it more "g"repable;
579 * macOS tcpdump uses -k to specify that packet comments in pcapng files
582 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
583 * for hosts sending TCP SYN packets;
585 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
588 * macOS tcpdump also uses -Q to specify expressions that match packet
589 * metadata, including but not limited to the packet direction.
590 * The expression syntax is different from a simple "in|out|inout",
591 * and those expressions aren't accepted by macOS tcpdump, but the
592 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
593 * "inout" = "dir=in or dir=out", and the parser could conceivably
594 * special-case "in", "out", and "inout" as expressions for backwards
595 * compatibility, so all is not (yet) lost.
599 * Set up flags that might or might not be supported depending on the
600 * version of libpcap we're using.
602 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
604 #define j_FLAG_USAGE " [ -j tstamptype ]"
606 #else /* HAVE_PCAP_SET_TSTAMP_TYPE */
610 #endif /* HAVE_PCAP_SET_TSTAMP_TYPE */
613 #define m_FLAG_USAGE "[ -m module ] ..."
616 #define SHORTOPTS "aAbB:c:C:dDeE:fF:G:hHi:I" j_FLAG J_FLAG "KlLm:M:nNOpqQ:r:s:StT:uUvV:w:W:xXy:Yz:Z:#"
621 * We do not currently have long options corresponding to all short
622 * options; we should probably pick appropriate option names for them.
624 * However, the short options where the number of times the option is
625 * specified matters, such as -v and -d and -t, should probably not
626 * just map to a long option, as saying
628 * tcpdump --verbose --verbose
630 * doesn't make sense; it should be --verbosity={N} or something such
633 * For long options with no corresponding short options, we define values
634 * outside the range of ASCII graphic characters, make that the last
635 * component of the entry for the long option, and have a case for that
636 * option in the switch statement.
638 #define OPTION_VERSION 128
639 #define OPTION_TSTAMP_PRECISION 129
640 #define OPTION_IMMEDIATE_MODE 130
641 #define OPTION_PRINT 131
642 #define OPTION_LIST_REMOTE_INTERFACES 132
643 #define OPTION_TSTAMP_MICRO 133
644 #define OPTION_TSTAMP_NANO 134
645 #define OPTION_FP_TYPE 135
646 #define OPTION_COUNT 136
647 #define OPTION_PRINT_SAMPLING 137
648 #define OPTION_LENGTHS 138
649 #define OPTION_TIME_T_SIZE 139
650 #define OPTION_SKIP 140
652 static const struct option longopts
[] = {
653 { "buffer-size", required_argument
, NULL
, 'B' },
654 { "list-interfaces", no_argument
, NULL
, 'D' },
655 #ifdef HAVE_PCAP_FINDALLDEVS_EX
656 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
658 { "help", no_argument
, NULL
, 'h' },
659 { "interface", required_argument
, NULL
, 'i' },
660 { "monitor-mode", no_argument
, NULL
, 'I' },
661 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
662 { "time-stamp-type", required_argument
, NULL
, 'j' },
663 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
665 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
666 { "micro", no_argument
, NULL
, OPTION_TSTAMP_MICRO
},
667 { "nano", no_argument
, NULL
, OPTION_TSTAMP_NANO
},
668 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
670 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
671 { "list-data-link-types", no_argument
, NULL
, 'L' },
672 { "no-optimize", no_argument
, NULL
, 'O' },
673 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
674 { "direction", required_argument
, NULL
, 'Q' },
675 { "snapshot-length", required_argument
, NULL
, 's' },
676 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
677 { "packet-buffered", no_argument
, NULL
, 'U' },
678 { "linktype", required_argument
, NULL
, 'y' },
679 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
680 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
682 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
683 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
685 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
686 { "count", no_argument
, NULL
, OPTION_COUNT
},
687 { "fp-type", no_argument
, NULL
, OPTION_FP_TYPE
},
688 { "number", no_argument
, NULL
, '#' },
689 { "print", no_argument
, NULL
, OPTION_PRINT
},
690 { "print-sampling", required_argument
, NULL
, OPTION_PRINT_SAMPLING
},
691 { "lengths", no_argument
, NULL
, OPTION_LENGTHS
},
692 { "time-t-size", no_argument
, NULL
, OPTION_TIME_T_SIZE
},
693 { "skip", required_argument
, NULL
, OPTION_SKIP
},
694 { "version", no_argument
, NULL
, OPTION_VERSION
},
698 #ifdef HAVE_PCAP_FINDALLDEVS_EX
699 #define LIST_REMOTE_INTERFACES_USAGE " [ --list-remote-interfaces remote-source ]"
701 #define LIST_REMOTE_INTERFACES_USAGE
704 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
705 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
707 #define IMMEDIATE_MODE_USAGE ""
711 /* Drop root privileges and chroot if necessary */
713 droproot(const char *username
, const char *chroot_dir
)
715 struct passwd
*pw
= NULL
;
717 if (chroot_dir
&& !username
)
718 error("Chroot without dropping root is insecure");
720 pw
= getpwnam(username
);
723 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
724 error("Couldn't chroot/chdir to '%.64s': %s",
725 chroot_dir
, pcap_strerror(errno
));
727 #ifdef HAVE_LIBCAP_NG
729 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
731 error("capng_change_id(): return %d\n", ret
);
733 fprintf(stderr
, "dropped privs to %s\n", username
);
736 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
737 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
738 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
740 (unsigned long)pw
->pw_uid
,
741 (unsigned long)pw
->pw_gid
,
742 pcap_strerror(errno
));
744 fprintf(stderr
, "dropped privs to %s\n", username
);
746 #endif /* HAVE_LIBCAP_NG */
748 error("Couldn't find user '%.32s'", username
);
749 #ifdef HAVE_LIBCAP_NG
750 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT anymore. */
754 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
760 capng_apply(CAPNG_SELECT_BOTH
);
761 #endif /* HAVE_LIBCAP_NG */
782 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
784 char *filename
= malloc(PATH_MAX
+ 1);
785 if (filename
== NULL
)
786 error("%s: malloc", __func__
);
787 if (strlen(orig_name
) == 0)
788 error("an empty string is not a valid file name");
790 /* Process with strftime if Gflag is set. */
794 /* Convert Gflag_time to a usable format */
795 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
796 error("%s: localtime", __func__
);
799 /* There's no good way to detect an error in strftime since a return
800 * value of 0 isn't necessarily failure; if orig_name is an empty
801 * string, the formatted string will be empty.
803 * However, the C90 standard says that, if there *is* a
804 * buffer overflow, the content of the buffer is undefined,
805 * so we must check for a buffer overflow.
807 * So we check above for an empty orig_name, and only call
808 * strftime() if it's non-empty, in which case the return
809 * value will only be 0 if the formatted date doesn't fit
812 * (We check above because, even if we don't use -G, we
813 * want a better error message than "tcpdump: : No such
814 * file or directory" for this case.)
816 if (strftime(filename
, PATH_MAX
, orig_name
, local_tm
) == 0) {
817 error("%s: strftime", __func__
);
820 strncpy(filename
, orig_name
, PATH_MAX
);
823 if (cnt
== 0 && max_chars
== 0)
824 strncpy(buffer
, filename
, PATH_MAX
+ 1);
826 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
827 /* Report an error if the filename is too large */
828 error("too many output files or filename is too long (> %d)", PATH_MAX
);
833 get_next_file(FILE *VFile
, char *ptr
)
838 ret
= fgets(ptr
, PATH_MAX
, VFile
);
843 if (len
> 0 && ptr
[len
- 1] == '\n')
850 static cap_channel_t
*
853 cap_channel_t
*capcas
, *capdnsloc
;
854 const char *types
[1];
859 error("unable to create casper process");
860 capdnsloc
= cap_service_open(capcas
, "system.dns");
861 /* Casper capability no longer needed. */
863 if (capdnsloc
== NULL
)
864 error("unable to open system.dns service");
865 /* Limit system.dns to reverse DNS lookups. */
867 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
868 error("unable to limit access to system.dns service");
869 families
[0] = AF_INET
;
870 /* Casper is a feature of FreeBSD, which defines AF_INET6. */
871 families
[1] = AF_INET6
;
872 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
873 error("unable to limit access to system.dns service");
877 #endif /* HAVE_CASPER */
879 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
881 tstamp_precision_from_string(const char *precision
)
883 if (strncmp(precision
, "nano", strlen("nano")) == 0)
884 return PCAP_TSTAMP_PRECISION_NANO
;
886 if (strncmp(precision
, "micro", strlen("micro")) == 0)
887 return PCAP_TSTAMP_PRECISION_MICRO
;
893 tstamp_precision_to_string(int precision
)
897 case PCAP_TSTAMP_PRECISION_MICRO
:
900 case PCAP_TSTAMP_PRECISION_NANO
:
907 #endif // HAVE_PCAP_SET_TSTAMP_PRECISION
911 * Ensure that, on a dump file's descriptor, we have all the rights
912 * necessary to make the standard I/O library work with an fdopen()ed
913 * FILE * from that descriptor.
915 * A long time ago in a galaxy far, far away, AT&T decided that, instead
916 * of providing separate APIs for getting and setting the FD_ flags on a
917 * descriptor, getting and setting the O_ flags on a descriptor, and
918 * locking files, they'd throw them all into a kitchen-sink fcntl() call
919 * along the lines of ioctl(), the fact that ioctl() operations are
920 * largely specific to particular character devices but fcntl() operations
921 * are either generic to all descriptors or generic to all descriptors for
922 * regular files notwithstanding.
924 * The Capsicum people decided that fine-grained control of descriptor
925 * operations was required, so that you need to grant permission for
926 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
927 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
928 * collection of things, so there are *individual* fcntls for which
929 * permission needs to be granted.
931 * The FreeBSD standard I/O people implemented some optimizations that
932 * requires that the standard I/O routines be able to determine whether
933 * the descriptor for the FILE * is open append-only or not; as that
934 * descriptor could have come from an open() rather than an fopen(),
935 * that requires that it be able to do an F_GETFL fcntl() to read
938 * tcpdump uses ftell() to determine how much data has been written
939 * to a file in order to, when used with -C, determine when it's time
940 * to rotate capture files. ftell() therefore needs to do an lseek()
941 * to find out the file offset and must, thanks to the aforementioned
942 * optimization, also know whether the descriptor is open append-only
945 * The net result of all the above is that we need to grant CAP_SEEK,
946 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
948 * Perhaps this is the universe's way of saying that either
950 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
951 * using it, so that Capsicum-capable tcpdump wouldn't need to do
956 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
957 * I/O library that knows what rights are needed by the standard
958 * I/O library, based on the open mode, and assigns them, perhaps
959 * with an additional argument indicating, for example, whether
960 * seeking should be allowed, so that tcpdump doesn't need to know
961 * what the standard I/O library happens to require this week.
964 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
966 int fd
= fileno(pcap_dump_file(p
));
969 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
970 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
971 error("unable to limit dump descriptor");
973 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
974 error("unable to limit dump descriptor fcntls");
977 #endif // HAVE_CAPSICUM
980 * Copy arg vector into a new buffer, concatenating arguments with spaces.
983 copy_argv(char **argv
)
995 len
+= strlen(*p
++) + 1;
997 buf
= (char *)malloc(len
);
999 error("%s: malloc", __func__
);
1003 while ((src
= *p
++) != NULL
) {
1004 while ((*dst
++ = *src
++) != '\0')
1014 * On Windows, we need to open the file in binary mode, so that
1015 * we get all the bytes specified by the size we get from "fstat()".
1016 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1017 * we define it as 0 if it's not defined, so it does nothing.
1024 read_infile(char *fname
)
1031 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1033 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1035 if (our_fstat(fd
, &buf
) < 0)
1036 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1039 * Reject files whose size doesn't fit into an int; a filter
1040 * *that* large will probably be too big.
1042 if (buf
.st_size
> INT_MAX
)
1043 error("%s is too large", fname
);
1045 cp
= malloc((u_int
)buf
.st_size
+ 1);
1047 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1048 fname
, pcap_strerror(errno
));
1049 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1051 error("read %s: %s", fname
, pcap_strerror(errno
));
1052 if (cc
!= buf
.st_size
)
1053 error("short read %s (%d != %d)", fname
, (int) cc
,
1057 /* replace "# comment" with spaces */
1058 for (i
= 0; i
< cc
; i
++) {
1060 while (i
< cc
&& cp
[i
] != '\n')
1068 parse_interface_number(const char *device
)
1075 * Search for a colon, terminating any scheme at the beginning
1078 p
= strchr(device
, ':');
1081 * We found it. Is it followed by "//"?
1083 p
++; /* skip the : */
1084 if (strncmp(p
, "//", 2) == 0) {
1086 * Yes. Search for the next /, at the end of the
1087 * authority part of the URL.
1089 p
+= 2; /* skip the // */
1093 * OK, past the / is the path.
1099 devnum
= strtol(device
, &end
, 10);
1100 if (device
!= end
&& *end
== '\0') {
1102 * It's all-numeric, but is it a valid number?
1106 * No, it's not an ordinal.
1108 error("Invalid adapter index %s", device
);
1113 * It's not all-numeric; return -1, so our caller
1121 find_interface_by_number(const char *url
1122 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1127 pcap_if_t
*dev
, *devlist
;
1129 char ebuf
[PCAP_ERRBUF_SIZE
];
1131 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1137 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1139 * Search for a colon, terminating any scheme at the beginning
1142 endp
= strchr(url
, ':');
1145 * We found it. Is it followed by "//"?
1147 endp
++; /* skip the : */
1148 if (strncmp(endp
, "//", 2) == 0) {
1150 * Yes. Search for the next /, at the end of the
1151 * authority part of the URL.
1153 endp
+= 2; /* skip the // */
1154 endp
= strchr(endp
, '/');
1160 * OK, everything from device to endp is a URL to hand
1161 * to pcap_findalldevs_ex().
1163 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1164 host_url
= malloc(endp
- url
+ 1);
1165 if (host_url
== NULL
&& (endp
- url
+ 1) > 0)
1166 error("Invalid allocation for host");
1168 memcpy(host_url
, url
, endp
- url
);
1169 host_url
[endp
- url
] = '\0';
1170 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1173 #endif // HAVE_PCAP_FINDALLDEVS_EX
1174 status
= pcap_findalldevs(&devlist
, ebuf
);
1178 * Look for the devnum-th entry in the list of devices (1-based).
1180 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1181 i
++, dev
= dev
->next
)
1184 pcap_freealldevs(devlist
);
1185 error("Invalid adapter index %ld: only %ld interfaces found",
1188 device
= strdup(dev
->name
);
1189 pcap_freealldevs(devlist
);
1193 #ifdef HAVE_PCAP_OPEN
1195 * Prefixes for rpcap URLs.
1197 static char rpcap_prefix
[] = "rpcap://";
1198 static char rpcap_ssl_prefix
[] = "rpcaps://";
1202 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1208 #ifdef HAVE_PCAP_OPEN
1210 * Is this an rpcap URL?
1212 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0 ||
1213 strncmp(device
, rpcap_ssl_prefix
, sizeof(rpcap_ssl_prefix
) - 1) == 0) {
1215 * Yes. Open it with pcap_open().
1218 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1219 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, timeout
, NULL
,
1223 * macOS 14's pcap_pcap_open(), which is a
1224 * stub that always returns NULL with an error
1225 * message of "not supported".
1227 * In this case, as we passed it an rpcap://
1228 * URL, treat that as meaning "remote capture
1231 if (strcmp(ebuf
, "not supported") == 0)
1232 error("Remote capture not supported");
1235 * If this failed with "No such device" or "The system
1236 * cannot find the device specified", that means
1237 * the interface doesn't exist; return NULL, so that
1238 * the caller can see whether the device name is
1239 * actually an interface index.
1241 if (strstr(ebuf
, "No such device") != NULL
||
1242 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1247 warning("%s", ebuf
);
1250 #endif /* HAVE_PCAP_OPEN */
1252 pc
= pcap_create(device
, ebuf
);
1255 * If this failed with "No such device", that means
1256 * the interface doesn't exist; return NULL, so that
1257 * the caller can see whether the device name is
1258 * actually an interface index.
1260 if (strstr(ebuf
, "No such device") != NULL
)
1264 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1266 show_tstamp_types_and_exit(pc
, device
);
1268 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1269 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1271 error("%s: Can't set %ssecond time stamp precision: %s",
1273 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1274 pcap_statustostr(status
));
1277 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1278 if (immediate_mode
) {
1279 status
= pcap_set_immediate_mode(pc
, 1);
1281 error("%s: Can't set immediate mode: %s",
1282 device
, pcap_statustostr(status
));
1286 * Is this an interface that supports monitor mode?
1288 if (pcap_can_set_rfmon(pc
) == 1)
1289 supports_monitor_mode
= 1;
1291 supports_monitor_mode
= 0;
1292 if (ndo
->ndo_snaplen
!= 0) {
1294 * A snapshot length was explicitly specified;
1297 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1299 error("%s: Can't set snapshot length: %s",
1300 device
, pcap_statustostr(status
));
1302 status
= pcap_set_promisc(pc
, !pflag
);
1304 error("%s: Can't set promiscuous mode: %s",
1305 device
, pcap_statustostr(status
));
1307 status
= pcap_set_rfmon(pc
, 1);
1309 error("%s: Can't set monitor mode: %s",
1310 device
, pcap_statustostr(status
));
1312 status
= pcap_set_timeout(pc
, timeout
);
1314 error("%s: pcap_set_timeout failed: %s",
1315 device
, pcap_statustostr(status
));
1317 status
= pcap_set_buffer_size(pc
, Bflag
);
1319 error("%s: Can't set buffer size: %s",
1320 device
, pcap_statustostr(status
));
1322 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1324 status
= pcap_set_tstamp_type(pc
, jflag
);
1326 error("%s: Can't set time stamp type: %s",
1327 device
, pcap_statustostr(status
));
1328 else if (status
> 0)
1329 warning("When trying to set timestamp type '%s' on %s: %s",
1330 pcap_tstamp_type_val_to_name(jflag
), device
,
1331 pcap_statustostr(status
));
1334 status
= pcap_activate(pc
);
1337 * pcap_activate() failed.
1339 cp
= pcap_geterr(pc
);
1340 if (status
== PCAP_ERROR
)
1342 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1344 * Return an error for our caller to handle.
1346 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1347 device
, pcap_statustostr(status
), cp
);
1348 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1349 error("%s: %s\n(%s)", device
,
1350 pcap_statustostr(status
), cp
);
1351 #ifdef PCAP_ERROR_CAPTURE_NOTSUP
1352 else if (status
== PCAP_ERROR_CAPTURE_NOTSUP
&& *cp
!= '\0')
1353 error("%s: %s\n(%s)", device
,
1354 pcap_statustostr(status
), cp
);
1357 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1358 strncmp(device
, "wlan", 4) == 0) {
1359 char parent
[8], newdev
[8];
1361 size_t s
= sizeof(parent
);
1363 snprintf(sysctl
, sizeof(sysctl
),
1364 "net.wlan.%d.%%parent", atoi(device
+ 4));
1365 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1366 strlcpy(newdev
, device
, sizeof(newdev
));
1367 /* Suggest a new wlan device. */
1368 /* FIXME: incrementing the index this way is not going to work well
1369 * when the index is 9 or greater but the only consequence in this
1370 * specific case would be an error message that looks a bit odd.
1372 newdev
[strlen(newdev
)-1]++;
1373 error("%s is not a monitor mode VAP\n"
1374 "To create a new monitor mode VAP use:\n"
1375 " ifconfig %s create wlandev %s wlanmode monitor\n"
1376 "and use %s as the tcpdump interface",
1377 device
, newdev
, parent
, newdev
);
1379 #endif // __FreeBSD__
1381 error("%s: %s", device
,
1382 pcap_statustostr(status
));
1385 } else if (status
> 0) {
1387 * pcap_activate() succeeded, but it's warning us
1388 * of a problem it had.
1390 cp
= pcap_geterr(pc
);
1391 if (status
== PCAP_WARNING
)
1393 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1395 warning("%s: %s\n(%s)", device
,
1396 pcap_statustostr(status
), cp
);
1398 warning("%s: %s", device
,
1399 pcap_statustostr(status
));
1402 status
= pcap_setdirection(pc
, Qflag
);
1404 error("%s: pcap_setdirection() failed: %s",
1405 device
, pcap_geterr(pc
));
1412 main(int argc
, char **argv
)
1415 bpf_u_int32 localnet
= 0, netmask
= 0;
1416 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1418 pcap_handler callback
;
1420 const char *dlt_name
;
1421 struct bpf_program fcode
;
1423 void (*oldhandler
)(int);
1425 struct dump_info dumpinfo
;
1426 u_char
*pcap_userdata
;
1427 char ebuf
[PCAP_ERRBUF_SIZE
];
1428 char VFileLine
[PATH_MAX
+ 1];
1429 const char *username
= NULL
;
1431 const char *chroot_dir
= NULL
;
1438 #ifdef HAVE_CAPSICUM
1439 cap_rights_t rights
;
1441 #endif /* HAVE_CAPSICUM */
1442 int Oflag
= 1; /* run filter code optimizer */
1444 const char *yflag_dlt_name
= NULL
;
1448 netdissect_options Ndo
;
1449 netdissect_options
*ndo
= &Ndo
;
1453 * We need to look for wpcap.dll in \Windows\System32\Npcap first,
1456 * 1) WinPcap isn't installed and Npcap isn't installed in "WinPcap
1457 * API-compatible Mode", so there's no wpcap.dll in
1458 * \Windows\System32, only in \Windows\System32\Npcap;
1460 * 2) WinPcap is installed and Npcap isn't installed in "WinPcap
1461 * API-compatible Mode", so the wpcap.dll in \Windows\System32
1462 * is a WinPcap DLL, but we'd prefer an Npcap DLL (we should
1463 * work with either one if we're configured against WinPcap,
1464 * and we'll probably require Npcap if we're configured against
1465 * it), and that's in \Windows\System32\Npcap;
1467 * 3) Npcap is installed in "WinPcap API-compatible Mode", so both
1468 * \Windows\System32 and \Windows\System32\Npcap have an Npcap
1471 * Unfortunately, Windows has no notion of an rpath, so we can't
1472 * set the rpath to include \Windows\System32\Npcap at link time;
1473 * what we need to do is to link wpcap as a delay-load DLL and
1474 * add \Windows\System32\Npcap to the DLL search path early in
1475 * main() with a call to SetDllDirectory().
1477 * The same applies to packet.dll.
1479 * We add \Windows\System32\Npcap here.
1481 * See https://npcap.com/guide/npcap-devguide.html#npcap-feature-native-dll-implicitly
1483 WCHAR
*dll_directory
= NULL
;
1484 size_t dll_directory_buf_len
= 0; /* units of bytes */
1485 UINT system_directory_buf_len
= 0; /* units of WCHARs */
1486 UINT system_directory_len
; /* units of WCHARs */
1487 static const WCHAR npcap
[] = L
"\\Npcap";
1490 * Get the system directory path, in UTF-16, into a buffer that's
1491 * large enough for that directory path plus "\Npcap".
1493 * String manipulation in C, plus fetching a variable-length
1494 * string into a buffer whose size is fixed at the time of
1495 * the call, with an oddball return value (see below), is just
1496 * a huge bag of fun.
1498 * And it's even more fun when dealing with UTF-16, so that the
1499 * buffer sizes used in GetSystemDirectoryW() are in different
1500 * units from the buffer sizes used in realloc()! We maintain
1501 * all sizes/length in units of bytes, not WCHARs, so that our
1502 * heads don't explode.
1506 * Try to fetch the system directory.
1508 * GetSystemDirectoryW() expects a buffer size in units
1509 * of WCHARs, not bytes, and returns a directory path
1510 * length in units of WCHARs, not bytes.
1512 * For extra fun, if GetSystemDirectoryW() succeeds,
1513 * the return value is the length of the directory
1514 * path in units of WCHARs, *not* including the
1515 * terminating '\0', but if it fails because the
1516 * path string wouldn't fit, the return value is
1517 * the length of the directory path in units of WCHARs,
1518 * *including* the terminating '\0'.
1520 system_directory_len
= GetSystemDirectoryW(dll_directory
,
1521 system_directory_buf_len
);
1522 if (system_directory_len
== 0)
1523 error("GetSystemDirectoryW() failed");
1526 * Did the directory path fit in the buffer?
1528 * As per the above, this means that the return value
1529 * *plus 1*, so that the terminating '\0' is counted,
1530 * is <= the buffer size.
1532 * (If the directory path, complete with the terminating
1533 * '\0', fits *exactly*, the return value would be the
1534 * size of the buffer minus 1, as it doesn't count the
1535 * terminating '\0', so the test below would succeed.
1537 * If everything *but* the terminating '\0' fits,
1538 * the return value would be the size of the buffer + 1,
1539 * i.e., the size that the string in question would
1542 * The astute reader will note that returning the
1543 * size of the buffer is not one of the two cases
1544 * above, and should never happen.)
1546 if ((system_directory_len
+ 1) <= system_directory_buf_len
) {
1548 * No. We have a buffer that's large enough
1555 * Yes. Grow the buffer.
1557 * The space we'll need in the buffer for the system
1558 * directory, in units of WCHARs, is system_directory_len,
1559 * as that's the length of the system directory path
1560 * including the terminating '\0'.
1562 system_directory_buf_len
= system_directory_len
;
1565 * The size of the DLL directory buffer, in *bytes*, must
1566 * be the number of WCHARs taken by the system directory,
1567 * *minus* the terminating '\0' (as we'll overwrite that
1568 * with the "\" of the "\Npcap" string), multiplied by
1569 * sizeof(WCHAR) to convert it to the number of bytes,
1570 * plus the size of the "\Npcap" string, in bytes (which
1571 * will include the terminating '\0', as that will become
1572 * the DLL path's terminating '\0').
1574 dll_directory_buf_len
=
1575 ((system_directory_len
- 1)*sizeof(WCHAR
)) + sizeof npcap
;
1576 dll_directory
= realloc(dll_directory
, dll_directory_buf_len
);
1577 if (dll_directory
== NULL
)
1578 error("Can't allocate string for Npcap directory");
1584 * Now append \Npcap. We add the length of the system directory path,
1585 * in WCHARs, *not* including the terminating '\0' (which, since
1586 * GetSystemDirectoryW() succeeded, is the return value of
1587 * GetSystemDirectoryW(), as per the above), to the pointer to the
1588 * beginning of the path, to go past the end of the system directory
1589 * to point to the terminating '\0'.
1591 memcpy(dll_directory
+ system_directory_len
, npcap
, sizeof npcap
);
1594 * Now add that as a system DLL directory.
1596 if (!SetDllDirectoryW(dll_directory
))
1597 error("SetDllDirectory failed");
1599 free(dll_directory
);
1603 * Initialize the netdissect code.
1605 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1608 memset(ndo
, 0, sizeof(*ndo
));
1609 ndo_set_function_pointers(ndo
);
1619 if ((cp
= strrchr(argv
[0], PATH_SEPARATOR
)) != NULL
)
1620 ndo
->program_name
= program_name
= cp
+ 1;
1622 ndo
->program_name
= program_name
= argv
[0];
1624 #if defined(HAVE_PCAP_WSOCKINIT)
1625 if (pcap_wsockinit() != 0)
1626 error("Attempting to initialize Winsock failed");
1627 #elif defined(HAVE_WSOCKINIT)
1628 if (wsockinit() != 0)
1629 error("Attempting to initialize Winsock failed");
1633 * An explicit tzset() call is usually not needed as it happens
1634 * implicitly the first time we call localtime() or mktime(),
1635 * but in some cases (sandboxing, chroot) this may be too late.
1640 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1644 /* compatibility for old -a */
1656 Bflag
= parse_int("packet buffer size", optarg
, NULL
, 1,
1659 * Will multiplying it by 1024 overflow?
1661 if (Bflag
> INT_MAX
/ 1024)
1662 error("packet buffer size %s is too large", optarg
);
1667 cnt
= parse_int("packet count", optarg
, NULL
, 1,
1672 Cflag
= parse_int64("file size", optarg
, &endp
, 1,
1675 if (*endp
== '\0') {
1677 * There's nothing after the file size,
1678 * so the size is in units of 1 MB
1679 * (1,000,000 bytes).
1681 Cflagmult
= 1000000;
1684 * There's something after the file
1687 * If it's a single letter, then:
1689 * if the letter is k or K, the size
1690 * is in units of 1 KiB (1024 bytes);
1692 * if the letter is m or M, the size
1693 * is in units of 1 MiB (1,048,576 bytes);
1695 * if the letter is g or G, the size
1696 * is in units of 1 GiB (1,073,741,824 bytes).
1698 * Otherwise, it's an error.
1709 Cflagmult
= 1024*1024;
1714 Cflagmult
= 1024*1024*1024;
1718 error("invalid file size %s (invalid units)", optarg
);
1722 * OK, there was a letter that we treat
1723 * as a units indication; was there
1724 * anything after it?
1727 if (*endp
!= '\0') {
1729 error("invalid file size %s (invalid units)", optarg
);
1734 * Will multiplying it by multiplier overflow?
1736 #ifdef HAVE_PCAP_DUMP_FTELL64
1737 if (Cflag
> INT64_MAX
/ Cflagmult
)
1739 if (Cflag
> LONG_MAX
/ Cflagmult
)
1741 error("file size %s is too large", optarg
);
1753 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1754 case OPTION_LIST_REMOTE_INTERFACES
:
1755 remote_interfaces_source
= optarg
;
1768 #ifndef HAVE_LIBCRYPTO
1769 warning("crypto code not compiled in");
1771 ndo
->ndo_espsecret
= optarg
;
1783 Gflag
= parse_int("number of seconds", optarg
, NULL
, 0,
1786 /* We will create one file initially. */
1789 /* Grab the current time for rotation use. */
1790 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1791 error("%s: can't get current time: %s",
1792 __func__
, pcap_strerror(errno
));
1797 print_usage(stdout
);
1798 exit_tcpdump(S_SUCCESS
);
1813 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1815 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1817 error("invalid time stamp type %s", optarg
);
1828 * _IOLBF is the same as _IOFBF in Microsoft's C
1829 * libraries; the only alternative they offer
1832 * XXX - this should really be checking for MSVC++,
1833 * not _WIN32, if, for example, MinGW has its own
1834 * C library that is more UNIX-compatible.
1836 setvbuf(stdout
, NULL
, _IONBF
, 0);
1838 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1848 if (nd_have_smi_support()) {
1849 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1852 (void)fprintf(stderr
, "%s: ignoring option '-m %s' ",
1853 program_name
, optarg
);
1854 (void)fprintf(stderr
, "(no libsmi support)\n");
1859 /* TCP-MD5 shared secret */
1860 #ifndef HAVE_LIBCRYPTO
1861 warning("crypto code not compiled in");
1863 ndo
->ndo_sigsecret
= optarg
;
1884 ++ndo
->ndo_suppress_default_print
;
1888 if (ascii_strcasecmp(optarg
, "in") == 0)
1890 else if (ascii_strcasecmp(optarg
, "out") == 0)
1892 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1893 Qflag
= PCAP_D_INOUT
;
1895 error("unknown capture direction '%s'", optarg
);
1903 ndo
->ndo_snaplen
= parse_int("snaplen", optarg
, NULL
,
1904 0, MAXIMUM_SNAPLEN
, 0);
1916 if (ascii_strcasecmp(optarg
, "vat") == 0)
1917 ndo
->ndo_packettype
= PT_VAT
;
1918 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1919 ndo
->ndo_packettype
= PT_WB
;
1920 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1921 ndo
->ndo_packettype
= PT_RPC
;
1922 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1923 ndo
->ndo_packettype
= PT_RTP
;
1924 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1925 ndo
->ndo_packettype
= PT_RTCP
;
1926 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1927 ndo
->ndo_packettype
= PT_SNMP
;
1928 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1929 ndo
->ndo_packettype
= PT_CNFP
;
1930 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1931 ndo
->ndo_packettype
= PT_TFTP
;
1932 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1933 ndo
->ndo_packettype
= PT_AODV
;
1934 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1935 ndo
->ndo_packettype
= PT_CARP
;
1936 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1937 ndo
->ndo_packettype
= PT_RADIUS
;
1938 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1939 ndo
->ndo_packettype
= PT_ZMTP1
;
1940 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1941 ndo
->ndo_packettype
= PT_VXLAN
;
1942 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1943 ndo
->ndo_packettype
= PT_PGM
;
1944 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1945 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1946 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1947 ndo
->ndo_packettype
= PT_LMP
;
1948 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1949 ndo
->ndo_packettype
= PT_RESP
;
1950 else if (ascii_strcasecmp(optarg
, "ptp") == 0)
1951 ndo
->ndo_packettype
= PT_PTP
;
1952 else if (ascii_strcasecmp(optarg
, "someip") == 0)
1953 ndo
->ndo_packettype
= PT_SOMEIP
;
1954 else if (ascii_strcasecmp(optarg
, "domain") == 0)
1955 ndo
->ndo_packettype
= PT_DOMAIN
;
1956 else if (ascii_strcasecmp(optarg
, "quic") == 0)
1957 ndo
->ndo_packettype
= PT_QUIC
;
1959 error("unknown packet type '%s'", optarg
);
1983 Wflag
= parse_int("number of output files", optarg
,
1984 NULL
, 1, INT_MAX
, 10);
1985 WflagChars
= getWflagChars(Wflag
);
1990 ++ndo
->ndo_suppress_default_print
;
1995 ++ndo
->ndo_suppress_default_print
;
1999 yflag_dlt_name
= optarg
;
2001 pcap_datalink_name_to_val(yflag_dlt_name
);
2003 error("invalid data link type %s", yflag_dlt_name
);
2006 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
2009 /* Undocumented flag */
2010 pcap_set_parser_debug(1);
2023 ndo
->ndo_packet_number
= 1;
2026 case OPTION_LENGTHS
:
2027 ndo
->ndo_lengths
= 1;
2030 case OPTION_TIME_T_SIZE
:
2031 printf("%zu\n", sizeof(time_t) * 8);
2034 case OPTION_VERSION
:
2035 print_version(stdout
);
2036 exit_tcpdump(S_SUCCESS
);
2039 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2040 case OPTION_TSTAMP_PRECISION
:
2041 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
2042 if (ndo
->ndo_tstamp_precision
< 0)
2043 error("unsupported time stamp precision");
2047 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2048 case OPTION_IMMEDIATE_MODE
:
2057 case OPTION_PRINT_SAMPLING
:
2060 ndo
->ndo_print_sampling
= parse_int("print sampling",
2061 optarg
, NULL
, 1, INT_MAX
, 10);
2065 packets_to_skip
= parse_u_int("packet skip count",
2066 optarg
, NULL
, 0, INT_MAX
, 0);
2069 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2070 case OPTION_TSTAMP_MICRO
:
2071 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
2074 case OPTION_TSTAMP_NANO
:
2075 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_NANO
;
2079 case OPTION_FP_TYPE
:
2081 * Print out the type of floating-point arithmetic
2082 * we're doing; it's probably IEEE, unless somebody
2083 * tries to run this on a VAX, but the precision
2084 * may differ (e.g., it might be 32-bit, 64-bit,
2087 float_type_check(0x4e93312d);
2095 print_usage(stderr
);
2096 exit_tcpdump(S_ERR_HOST_PROGRAM
);
2100 if (ndo
->ndo_Aflag
&& ndo
->ndo_xflag
)
2101 warning("-A and -x[x] are mutually exclusive. -A ignored.");
2102 if (ndo
->ndo_Aflag
&& ndo
->ndo_Xflag
)
2103 warning("-A and -X[X] are mutually exclusive. -A ignored.");
2104 if (ndo
->ndo_xflag
&& ndo
->ndo_Xflag
)
2105 warning("-x[x] and -X[X] are mutually exclusive. -x[x] ignored.");
2108 if ((int)packets_to_skip
> (INT_MAX
- cnt
))
2109 // cnt + (int)packets_to_skip used in pcap_loop() call
2110 error("Overflow (-c count) %d + (--skip count) %d", cnt
,
2111 (int)packets_to_skip
);
2114 show_devices_and_exit();
2115 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2116 if (remote_interfaces_source
!= NULL
)
2117 show_remote_devices_and_exit();
2120 switch (ndo
->ndo_tflag
) {
2122 case 0: /* Default */
2123 case 1: /* No time stamp */
2124 case 2: /* Unix timeval style */
2125 case 3: /* Microseconds/nanoseconds since previous packet */
2126 case 4: /* Date + Default */
2127 case 5: /* Microseconds/nanoseconds since first packet */
2130 default: /* Not supported */
2131 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
2135 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
2136 error("-f can not be used with -V or -r");
2138 if (VFileName
!= NULL
&& RFileName
!= NULL
)
2139 error("-V and -r are mutually exclusive.");
2142 * If we're printing dissected packets to the standard output,
2143 * and either the standard output is a terminal or we're doing
2144 * "line" buffering, set the capture timeout to .1 second rather
2145 * than 1 second, as the user's probably expecting to see packets
2146 * pop up immediately shortly after they arrive.
2148 * XXX - would there be some value appropriate for all cases,
2149 * based on, say, the buffer size and packet input rate?
2151 if ((WFileName
== NULL
|| print
) && (isatty(1) || lflag
))
2155 /* if run as root, prepare for chrooting */
2156 if (getuid() == 0 || geteuid() == 0) {
2157 /* future extensibility for cmd-line arguments */
2159 chroot_dir
= WITH_CHROOT
;
2164 /* if run as root, prepare for dropping root privileges */
2165 if (getuid() == 0 || geteuid() == 0) {
2166 /* Run with '-Z root' to restore old behaviour */
2168 username
= WITH_USER
;
2169 else if (strcmp(username
, "root") == 0)
2174 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
2176 * If RFileName is non-null, it's the pathname of a
2177 * savefile to read. If VFileName is non-null, it's
2178 * the pathname of a file containing a list of pathnames
2179 * (one per line) of savefiles to read.
2181 * In either case, we're reading a savefile, not doing
2186 * We don't need network access, so relinquish any set-UID
2187 * or set-GID privileges we have (if any).
2189 * We do *not* want set-UID privileges when opening a
2190 * trace file, as that might let the user read other
2191 * people's trace files (especially if we're set-UID
2194 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2195 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2197 if (VFileName
!= NULL
) {
2198 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
2201 VFile
= fopen(VFileName
, "r");
2204 error("Unable to open file: %s\n", pcap_strerror(errno
));
2206 ret
= get_next_file(VFile
, VFileLine
);
2208 error("Nothing in %s\n", VFileName
);
2209 RFileName
= VFileLine
;
2212 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2213 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
2214 ndo
->ndo_tstamp_precision
, ebuf
);
2216 pd
= pcap_open_offline(RFileName
, ebuf
);
2221 #ifdef HAVE_CAPSICUM
2222 cap_rights_init(&rights
, CAP_READ
);
2223 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
2225 error("unable to limit pcap descriptor");
2228 dlt
= pcap_datalink(pd
);
2229 dlt_name
= pcap_datalink_val_to_name(dlt
);
2230 fprintf(stderr
, "reading from file %s", RFileName
);
2231 if (dlt_name
== NULL
) {
2232 fprintf(stderr
, ", link-type %u", dlt
);
2234 fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2235 pcap_datalink_val_to_description(dlt
));
2237 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2238 #if defined(DLT_LINUX_SLL2) && defined(__linux__)
2239 if (dlt
== DLT_LINUX_SLL2
)
2240 fprintf(stderr
, "Warning: interface names might be incorrect\n");
2242 } else if (dflag
&& !device
) {
2243 int dump_dlt
= DLT_EN10MB
;
2245 * We're dumping the compiled code without an explicit
2246 * device specification. (If a device is specified, we
2247 * definitely want to open it to use the DLT of that device.)
2248 * Either default to DLT_EN10MB with a warning, or use
2249 * the user-specified value if supplied.
2252 * If no snapshot length was specified, or a length of 0 was
2253 * specified, default to 256KB.
2255 if (ndo
->ndo_snaplen
== 0)
2256 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
2258 * If a DLT was specified with the -y flag, use that instead.
2260 if (yflag_dlt
!= -1)
2261 dump_dlt
= yflag_dlt
;
2263 fprintf(stderr
, "Warning: assuming Ethernet\n");
2264 pd
= pcap_open_dead(dump_dlt
, ndo
->ndo_snaplen
);
2267 * We're doing a live capture.
2269 if (device
== NULL
) {
2271 * No interface was specified. Pick one.
2274 * Find the list of interfaces, and pick
2275 * the first interface.
2277 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2279 if (devlist
== NULL
)
2280 error("no interfaces available for capture");
2281 device
= strdup(devlist
->name
);
2282 pcap_freealldevs(devlist
);
2286 * Try to open the interface with the specified name.
2288 pd
= open_interface(device
, ndo
, ebuf
);
2291 * That failed. If we can get a list of
2292 * interfaces, and the interface name
2293 * is purely numeric, try to use it as
2294 * a 1-based index in the list of
2297 devnum
= parse_interface_number(device
);
2300 * It's not a number; just report
2301 * the open error and fail.
2307 * OK, it's a number; try to find the
2308 * interface with that index, and try
2311 * find_interface_by_number() exits if it
2312 * couldn't be found.
2314 device
= find_interface_by_number(device
, devnum
);
2315 pd
= open_interface(device
, ndo
, ebuf
);
2321 * Let user own process after capture device has
2325 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2326 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2329 show_dlts_and_exit(pd
, device
);
2330 if (yflag_dlt
>= 0) {
2331 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2332 error("%s", pcap_geterr(pd
));
2333 (void)fprintf(stderr
, "%s: data link type %s\n",
2335 pcap_datalink_val_to_name(yflag_dlt
));
2336 (void)fflush(stderr
);
2338 #if defined(DLT_LINUX_SLL2)
2341 * Attempt to set default linktype to
2342 * DLT_LINUX_SLL2 when capturing on the
2345 * If the attempt fails, just quietly drive
2346 * on; this may be a non-Linux "any" device
2347 * that doesn't support DLT_LINUX_SLL2.
2349 if (strcmp(device
, "any") == 0) {
2350 DIAG_OFF_WARN_UNUSED_RESULT
2351 (void) pcap_set_datalink(pd
, DLT_LINUX_SLL2
);
2352 DIAG_ON_WARN_UNUSED_RESULT
2356 i
= pcap_snapshot(pd
);
2357 if (ndo
->ndo_snaplen
< i
) {
2358 if (ndo
->ndo_snaplen
!= 0)
2359 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2360 ndo
->ndo_snaplen
= i
;
2361 } else if (ndo
->ndo_snaplen
> i
) {
2362 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2363 ndo
->ndo_snaplen
= i
;
2365 if(ndo
->ndo_fflag
!= 0) {
2366 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2367 warning("foreign (-f) flag used but: %s", ebuf
);
2373 cmdbuf
= read_infile(infile
);
2375 cmdbuf
= copy_argv(&argv
[optind
]);
2377 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2378 pcap_set_optimizer_debug(dflag
);
2381 * netmask is in network byte order, pcap_compile() takes it
2382 * in host byte order.
2384 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, ntohl(netmask
)) < 0)
2385 error("%s", pcap_geterr(pd
));
2387 bpf_dump(&fcode
, dflag
);
2390 pcap_freecode(&fcode
);
2391 exit_tcpdump(S_SUCCESS
);
2395 if (!ndo
->ndo_nflag
)
2396 capdns
= capdns_setup();
2397 #endif /* HAVE_CASPER */
2399 // Both localnet and netmask are in network byte order.
2400 init_print(ndo
, localnet
, netmask
);
2403 (void)setsignal(SIGPIPE
, cleanup
);
2404 (void)setsignal(SIGTERM
, cleanup
);
2406 (void)setsignal(SIGINT
, cleanup
);
2407 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2408 (void)setsignal(SIGCHLD
, child_cleanup
);
2410 /* Cooperate with nohup(1) */
2413 * In illumos /usr/include/sys/iso/signal_iso.h causes Clang to
2414 * generate a -Wstrict-prototypes warning here, see [1]. The
2415 * __illumos__ macro is available since at least GCC 11 and Clang 13,
2417 * 1: https://www.illumos.org/issues/16344
2418 * 2: https://www.illumos.org/issues/13726
2421 DIAG_OFF_STRICT_PROTOTYPES
2422 #endif /* __illumos__ */
2423 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2425 DIAG_ON_STRICT_PROTOTYPES
2426 #endif /* __illumos__ */
2427 (void)setsignal(SIGHUP
, oldhandler
);
2432 * If a user name was specified with "-Z", attempt to switch to
2433 * that user's UID. This would probably be used with sudo,
2434 * to allow tcpdump to be run in a special restricted
2435 * account (if you just want to allow users to open capture
2436 * devices, and can't just give users that permission,
2437 * you'd make tcpdump set-UID or set-GID).
2439 * tcpdump doesn't necessarily write only to one savefile;
2440 * the general only way to allow a -Z instance to write to
2441 * savefiles as the user under whose UID it's run, rather
2442 * than as the user specified with -Z, would thus be to switch
2443 * to the original user ID before opening a capture file and
2444 * then switch back to the -Z user ID after opening the savefile.
2445 * Switching to the -Z user ID only after opening the first
2446 * savefile doesn't handle the general case.
2449 if (getuid() == 0 || geteuid() == 0) {
2450 #ifdef HAVE_LIBCAP_NG
2451 /* Initialize capng */
2452 capng_clear(CAPNG_SELECT_BOTH
);
2454 DIAG_OFF_ASSIGN_ENUM
2457 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2464 DIAG_OFF_ASSIGN_ENUM
2467 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2474 DIAG_OFF_ASSIGN_ENUM
2477 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2482 capng_apply(CAPNG_SELECT_BOTH
);
2483 #endif /* HAVE_LIBCAP_NG */
2484 if (username
|| chroot_dir
)
2485 droproot(username
, chroot_dir
);
2490 if (pcap_setfilter(pd
, &fcode
) < 0)
2491 error("%s", pcap_geterr(pd
));
2492 #ifdef HAVE_CAPSICUM
2493 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2494 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2497 * The various libpcap devices use a combination of
2498 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2499 * so we add the relevant access rights.
2501 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2502 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2504 error("unable to limit pcap descriptor");
2506 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2507 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2508 error("unable to limit ioctls on pcap descriptor");
2513 /* Do not exceed the default PATH_MAX for files. */
2514 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2516 if (dumpinfo
.CurrentFileName
== NULL
)
2517 error("malloc of dumpinfo.CurrentFileName");
2519 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2521 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2523 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2525 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2526 #ifdef HAVE_LIBCAP_NG
2527 /* Give up CAP_DAC_OVERRIDE capability.
2528 * Only allow it to be restored if the -C or -G flag have been
2529 * set since we may need to create more files later on.
2533 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2537 capng_apply(CAPNG_SELECT_BOTH
);
2538 #endif /* HAVE_LIBCAP_NG */
2540 error("%s", pcap_geterr(pd
));
2541 #ifdef HAVE_CAPSICUM
2542 set_dumper_capsicum_rights(pdd
);
2544 if (Cflag
!= 0 || Gflag
!= 0) {
2545 #ifdef HAVE_CAPSICUM
2547 * basename() and dirname() may modify their input buffer
2548 * and they do since FreeBSD 12.0, but they didn't before.
2549 * Hence use the return value only, but always assume the
2550 * input buffer has been modified and would need to be
2551 * reset before the next use.
2553 char *WFileName_copy
;
2555 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2556 error("Unable to allocate memory for file %s",
2559 DIAG_OFF_C11_EXTENSIONS
2560 dumpinfo
.WFileName
= strdup(basename(WFileName_copy
));
2561 DIAG_ON_C11_EXTENSIONS
2562 if (dumpinfo
.WFileName
== NULL
) {
2563 error("Unable to allocate memory for file %s",
2566 free(WFileName_copy
);
2568 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2569 error("Unable to allocate memory for file %s",
2572 DIAG_OFF_C11_EXTENSIONS
2573 char *WFileName_dirname
= dirname(WFileName_copy
);
2574 DIAG_ON_C11_EXTENSIONS
2575 dumpinfo
.dirfd
= open(WFileName_dirname
,
2576 O_DIRECTORY
| O_RDONLY
);
2577 if (dumpinfo
.dirfd
< 0) {
2578 error("unable to open directory %s",
2581 free(WFileName_dirname
);
2582 free(WFileName_copy
);
2584 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2585 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2586 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2588 error("unable to limit directory rights");
2590 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2592 error("unable to limit dump descriptor fcntls");
2594 #else /* !HAVE_CAPSICUM */
2595 dumpinfo
.WFileName
= WFileName
;
2597 callback
= dump_packet_and_trunc
;
2600 pcap_userdata
= (u_char
*)&dumpinfo
;
2602 callback
= dump_packet
;
2603 dumpinfo
.WFileName
= WFileName
;
2606 pcap_userdata
= (u_char
*)&dumpinfo
;
2609 dlt
= pcap_datalink(pd
);
2610 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2613 dumpinfo
.ndo
= NULL
;
2616 pcap_dump_flush(pdd
);
2618 dlt
= pcap_datalink(pd
);
2619 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2620 callback
= print_packet
;
2621 pcap_userdata
= (u_char
*)ndo
;
2624 #ifdef SIGNAL_REQ_INFO
2626 * We can't get statistics when reading from a file rather
2627 * than capturing from a device.
2629 if (RFileName
== NULL
)
2630 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2632 #ifdef SIGNAL_FLUSH_PCAP
2633 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2636 if (ndo
->ndo_vflag
> 0 && WFileName
&& RFileName
== NULL
&& !print
) {
2638 * When capturing to a file, if "--print" wasn't specified,
2639 *"-v" means tcpdump should, once per second,
2640 * "v"erbosely report the number of packets captured.
2641 * Except when reading from a file, because -r, -w and -v
2642 * together used to make a corner case, in which pcap_loop()
2643 * errored due to EINTR (see GH #155 for details).
2647 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2649 * suggests that this dates back to W2K.
2651 * I don't know what a "long wait" is, but we'll assume
2652 * that printing the stats could be a "long wait".
2654 CreateTimerQueueTimer(&timer_handle
, NULL
,
2655 verbose_stats_dump
, NULL
, 1000, 1000,
2656 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2657 setvbuf(stderr
, NULL
, _IONBF
, 0);
2660 * Assume this is UN*X, and that it has setitimer(); that
2661 * dates back to UNIX 95.
2663 struct itimerval timer
;
2664 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2665 timer
.it_interval
.tv_sec
= 1;
2666 timer
.it_interval
.tv_usec
= 0;
2667 timer
.it_value
.tv_sec
= 1;
2668 timer
.it_value
.tv_usec
= 1;
2669 setitimer(ITIMER_REAL
, &timer
, NULL
);
2673 if (RFileName
== NULL
) {
2675 * Live capture (if -V was specified, we set RFileName
2676 * to a file from the -V file). Print a message to
2677 * the standard error on UN*X.
2679 if (!ndo
->ndo_vflag
&& !WFileName
) {
2680 (void)fprintf(stderr
,
2681 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2684 (void)fprintf(stderr
, "%s: ", program_name
);
2685 dlt
= pcap_datalink(pd
);
2686 dlt_name
= pcap_datalink_val_to_name(dlt
);
2687 (void)fprintf(stderr
, "listening on %s", device
);
2688 if (dlt_name
== NULL
) {
2689 (void)fprintf(stderr
, ", link-type %u", dlt
);
2691 (void)fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2692 pcap_datalink_val_to_description(dlt
));
2694 (void)fprintf(stderr
, ", snapshot length %d bytes\n", ndo
->ndo_snaplen
);
2695 (void)fflush(stderr
);
2698 #ifdef HAVE_CAPSICUM
2699 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2701 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2703 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2704 #endif /* HAVE_CASPER */
2705 cansandbox
= (cansandbox
&& (pcap_fileno(pd
) != -1 ||
2706 RFileName
!= NULL
));
2708 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2709 error("unable to enter the capability mode");
2710 #endif /* HAVE_CAPSICUM */
2713 status
= pcap_loop(pd
,
2714 (cnt
== -1 ? -1 : cnt
+ (int)packets_to_skip
),
2715 callback
, pcap_userdata
);
2716 if (WFileName
== NULL
) {
2718 * We're printing packets. Flush the printed output,
2719 * so it doesn't get intermingled with error output.
2723 * We got interrupted, so perhaps we didn't
2724 * manage to finish a line we were printing.
2725 * Print an extra newline, just in case.
2729 (void)fflush(stdout
);
2733 * We got interrupted. If we are reading multiple
2734 * files (via -V) set these so that we stop.
2743 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2744 program_name
, pcap_geterr(pd
));
2746 if (RFileName
== NULL
) {
2748 * We're doing a live capture. Report the capture
2754 if (VFileName
!= NULL
) {
2755 ret
= get_next_file(VFile
, VFileLine
);
2759 RFileName
= VFileLine
;
2760 pd
= pcap_open_offline(RFileName
, ebuf
);
2763 #ifdef HAVE_CAPSICUM
2764 cap_rights_init(&rights
, CAP_READ
);
2765 if (cap_rights_limit(fileno(pcap_file(pd
)),
2766 &rights
) < 0 && errno
!= ENOSYS
) {
2767 error("unable to limit pcap descriptor");
2770 new_dlt
= pcap_datalink(pd
);
2771 if (new_dlt
!= dlt
) {
2773 * The new file has a different
2774 * link-layer header type from the
2777 if (WFileName
!= NULL
) {
2779 * We're writing raw packets
2780 * that match the filter to
2781 * a pcap file. pcap files
2782 * don't support multiple
2783 * different link-layer
2784 * header types, so we fail
2787 error("%s: new dlt does not match original", RFileName
);
2791 * We're printing the decoded packets;
2792 * switch to the new DLT.
2794 * To do that, we need to change
2795 * the printer, change the DLT name,
2796 * and recompile the filter with
2800 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2801 /* Free the old filter */
2802 pcap_freecode(&fcode
);
2804 * netmask is in network byte order, pcap_compile() takes it
2805 * in host byte order.
2807 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, ntohl(netmask
)) < 0)
2808 error("%s", pcap_geterr(pd
));
2812 * Set the filter on the new file.
2814 if (pcap_setfilter(pd
, &fcode
) < 0)
2815 error("%s", pcap_geterr(pd
));
2818 * Report the new file.
2820 dlt_name
= pcap_datalink_val_to_name(dlt
);
2821 fprintf(stderr
, "reading from file %s", RFileName
);
2822 if (dlt_name
== NULL
) {
2823 fprintf(stderr
, ", link-type %u", dlt
);
2825 fprintf(stderr
, ", link-type %s (%s)",
2827 pcap_datalink_val_to_description(dlt
));
2829 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2833 while (ret
!= NULL
);
2835 if (count_mode
&& RFileName
!= NULL
)
2836 fprintf(stdout
, "%u packet%s\n", packets_captured
,
2837 PLURAL_SUFFIX(packets_captured
));
2840 pcap_freecode(&fcode
);
2841 exit_tcpdump(status
== -1 ? S_ERR_HOST_PROGRAM
: S_SUCCESS
);
2845 * Routines to parse numerical command-line arguments and check for
2846 * errors, including "too large for that type".
2849 parse_int(const char *argname
, const char *string
, char **endpp
,
2850 int minval
, int maxval
, int base
)
2856 val
= strtol(string
, &endp
, base
);
2859 * Did it either not parse any of the string, find extra stuff
2860 * at the end that the caller isn't interested in, or get
2861 * another parsing error?
2863 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2864 (val
== 0 && errno
== EINVAL
)) {
2865 error("invalid %s \"%s\" (not a valid number)", argname
,
2870 * Did it get a value that's out of range?
2872 if (((val
== LONG_MAX
|| val
== LONG_MIN
) && errno
== ERANGE
) ||
2873 val
< minval
|| val
> maxval
) {
2874 error("invalid %s %s (must be >= %d and <= %d)",
2875 argname
, string
, minval
, maxval
);
2879 * OK, it passes all the tests.
2887 parse_u_int(const char *argname
, const char *string
, char **endpp
,
2888 u_int minval
, u_int maxval
, int base
)
2896 * strtoul() does *NOT* report an error if the string
2897 * begins with a minus sign. We do.
2899 if (*string
== '-') {
2900 error("invalid %s \"%s\" (not a valid unsigned number)",
2904 val
= strtoul(string
, &endp
, base
);
2907 * Did it either not parse any of the string, find extra stuff
2908 * at the end that the caller isn't interested in, or get
2909 * another parsing error?
2911 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2912 (val
== 0 && errno
== EINVAL
)) {
2913 error("invalid %s \"%s\" (not a valid unsigned number)",
2918 * Did it get a value that's out of range?
2920 if ((val
== ULONG_MAX
&& errno
== ERANGE
) ||
2921 val
< minval
|| val
> maxval
) {
2922 error("invalid %s %s (must be >= %u and <= %u)",
2923 argname
, string
, minval
, maxval
);
2927 * OK, it passes all the tests.
2931 return ((u_int
)val
);
2935 parse_int64(const char *argname
, const char *string
, char **endpp
,
2936 int64_t minval
, int64_t maxval
, int base
)
2942 val
= strtoimax(string
, &endp
, base
);
2945 * Did it either not parse any of the string, find extra stuff
2946 * at the end that the caller isn't interested in, or get
2947 * another parsing error?
2949 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2950 (val
== 0 && errno
== EINVAL
)) {
2951 error("invalid %s \"%s\" (not a valid number)", argname
,
2956 * Did it get a value that's out of range?
2958 if (((val
== INTMAX_MAX
|| val
== INTMAX_MIN
) && errno
== ERANGE
) ||
2959 val
< minval
|| val
> maxval
) {
2960 error("invalid %s %s (must be >= %" PRId64
" and <= %" PRId64
")",
2961 argname
, string
, minval
, maxval
);
2965 * OK, it passes all the tests.
2969 return ((int64_t)val
);
2976 (*setsignal (int sig
, void (*func
)(int)))(int)
2979 return (signal(sig
, func
));
2981 struct sigaction old
, new;
2983 memset(&new, 0, sizeof(new));
2984 new.sa_handler
= func
;
2985 if ((sig
== SIGCHLD
)
2986 # ifdef SIGNAL_REQ_INFO
2987 || (sig
== SIGNAL_REQ_INFO
)
2989 # ifdef SIGNAL_FLUSH_PCAP
2990 || (sig
== SIGNAL_FLUSH_PCAP
)
2993 new.sa_flags
= SA_RESTART
;
2994 if (sigaction(sig
, &new, &old
) < 0)
2995 /* The same workaround as for SIG_DFL above. */
2997 DIAG_OFF_STRICT_PROTOTYPES
2998 #endif /* __illumos__ */
3001 DIAG_ON_STRICT_PROTOTYPES
3002 #endif /* __illumos__ */
3003 return (old
.sa_handler
);
3007 /* make a clean exit on interrupts */
3009 cleanup(int signo _U_
)
3012 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
3013 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
3014 CloseHandle(timer_handle
);
3015 timer_handle
= INVALID_HANDLE_VALUE
;
3018 struct itimerval timer
;
3020 timer
.it_interval
.tv_sec
= 0;
3021 timer
.it_interval
.tv_usec
= 0;
3022 timer
.it_value
.tv_sec
= 0;
3023 timer
.it_value
.tv_usec
= 0;
3024 setitimer(ITIMER_REAL
, &timer
, NULL
);
3028 * We have "pcap_breakloop()"; use it, so that we do as little
3029 * as possible in the signal handler (it's probably not safe
3030 * to do anything with standard I/O streams in a signal handler -
3031 * the ANSI C standard doesn't say it is).
3037 On windows, we do not use a fork, so we do not care less about
3038 waiting a child processes to die
3040 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3042 child_cleanup(int signo _U_
)
3044 while (waitpid(-1, NULL
, WNOHANG
) >= 0);
3046 #endif /* HAVE_FORK && HAVE_VFORK */
3051 struct pcap_stat stats
;
3054 * Older versions of libpcap didn't set ps_ifdrop on some
3055 * platforms; initialize it to 0 to handle that.
3057 stats
.ps_ifdrop
= 0;
3058 if (pcap_stats(pd
, &stats
) < 0) {
3059 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
3065 fprintf(stderr
, "%s: ", program_name
);
3067 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
3068 PLURAL_SUFFIX(packets_captured
));
3070 fputs(", ", stderr
);
3073 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
3074 PLURAL_SUFFIX(stats
.ps_recv
));
3076 fputs(", ", stderr
);
3079 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
3080 PLURAL_SUFFIX(stats
.ps_drop
));
3081 if (stats
.ps_ifdrop
!= 0) {
3083 fputs(", ", stderr
);
3086 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
3087 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
3093 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3095 #define fork_subprocess() fork()
3097 #define fork_subprocess() vfork()
3100 compress_savefile(const char *filename
)
3104 child
= fork_subprocess();
3107 "compress_savefile: fork failed: %s\n",
3108 pcap_strerror(errno
));
3112 /* Parent process. */
3118 * Set to lowest priority so that this doesn't disturb the capture.
3121 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
3123 setpriority(PRIO_PROCESS
, 0, 19);
3125 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
3127 "compress_savefile: execlp(%s, %s) failed: %s\n",
3130 pcap_strerror(errno
));
3132 exit(S_ERR_HOST_PROGRAM
);
3134 _exit(S_ERR_HOST_PROGRAM
);
3137 #else /* HAVE_FORK && HAVE_VFORK */
3139 compress_savefile(const char *filename
)
3142 "compress_savefile failed. Functionality not implemented under your system\n");
3144 #endif /* HAVE_FORK && HAVE_VFORK */
3147 close_old_dump_file(struct dump_info
*dump_info
)
3150 * Close the current file and open a new one.
3152 pcap_dump_close(dump_info
->pdd
);
3155 * Compress the file we just closed, if the user asked for it.
3158 compress_savefile(dump_info
->CurrentFileName
);
3162 open_new_dump_file(struct dump_info
*dump_info
)
3164 #ifdef HAVE_CAPSICUM
3169 #ifdef HAVE_LIBCAP_NG
3170 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3171 capng_apply(CAPNG_SELECT_BOTH
);
3172 #endif /* HAVE_LIBCAP_NG */
3173 #ifdef HAVE_CAPSICUM
3174 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
3175 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
3177 error("unable to open file %s", dump_info
->CurrentFileName
);
3179 fp
= fdopen(fd
, "w");
3181 error("unable to fdopen file %s", dump_info
->CurrentFileName
);
3183 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
3184 #else /* !HAVE_CAPSICUM */
3185 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
3187 #ifdef HAVE_LIBCAP_NG
3188 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3189 capng_apply(CAPNG_SELECT_BOTH
);
3190 #endif /* HAVE_LIBCAP_NG */
3191 if (dump_info
->pdd
== NULL
)
3192 error("%s", pcap_geterr(pd
));
3193 #ifdef HAVE_CAPSICUM
3194 set_dumper_capsicum_rights(dump_info
->pdd
);
3199 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3201 struct dump_info
*dump_info
;
3207 dump_info
= (struct dump_info
*)user
;
3209 if (packets_captured
<= packets_to_skip
)
3213 * XXX - this won't force the file to rotate on the specified time
3214 * boundary, but it will rotate on the first packet received after the
3215 * specified Gflag number of seconds. Note: if a Gflag time boundary
3216 * and a Cflag size boundary coincide, the time rotation will occur
3217 * first thereby cancelling the Cflag boundary (since the file should
3221 /* Check if it is time to rotate */
3224 /* Get the current time */
3225 if ((t
= time(NULL
)) == (time_t)-1) {
3226 error("%s: can't get current_time: %s",
3227 __func__
, pcap_strerror(errno
));
3231 /* If the time is greater than the specified window, rotate */
3232 if (t
- Gflag_time
>= Gflag
) {
3233 /* Update the Gflag_time */
3235 /* Update Gflag_count */
3238 close_old_dump_file(dump_info
);
3241 * Check to see if we've exceeded the Wflag (when
3244 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
3245 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
3248 exit_tcpdump(S_SUCCESS
);
3251 if (dump_info
->CurrentFileName
!= NULL
)
3252 free(dump_info
->CurrentFileName
);
3253 /* Allocate space for max filename + \0. */
3254 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
3255 if (dump_info
->CurrentFileName
== NULL
)
3256 error("dump_packet_and_trunc: malloc");
3258 * Gflag was set otherwise we wouldn't be here. Reset the count
3259 * so multiple files would end with 1,2,3 in the filename.
3260 * The counting is handled with the -C flow after this.
3265 * This is always the first file in the Cflag
3267 * We also don't need numbering if Cflag is not set.
3270 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
3273 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
3275 open_new_dump_file(dump_info
);
3280 * XXX - this won't prevent capture files from getting
3281 * larger than Cflag - the last packet written to the
3282 * file could put it over Cflag.
3285 #ifdef HAVE_PCAP_DUMP_FTELL64
3286 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
3289 * XXX - this only handles a Cflag value > 2^31-1 on
3290 * LP64 platforms; to handle ILP32 (32-bit UN*X and
3291 * Windows) or LLP64 (64-bit Windows) would require
3292 * a version of libpcap with pcap_dump_ftell64().
3294 long size
= pcap_dump_ftell(dump_info
->pdd
);
3298 error("ftell fails on output file");
3300 close_old_dump_file(dump_info
);
3304 if (Cflag_count
>= Wflag
)
3307 if (dump_info
->CurrentFileName
!= NULL
)
3308 free(dump_info
->CurrentFileName
);
3309 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
3310 if (dump_info
->CurrentFileName
== NULL
)
3311 error("%s: malloc", __func__
);
3312 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
3314 open_new_dump_file(dump_info
);
3318 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3320 pcap_dump_flush(dump_info
->pdd
);
3322 if (dump_info
->ndo
!= NULL
)
3323 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3331 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3333 struct dump_info
*dump_info
;
3339 dump_info
= (struct dump_info
*)user
;
3341 if (packets_captured
<= packets_to_skip
)
3344 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3346 pcap_dump_flush(dump_info
->pdd
);
3348 if (dump_info
->ndo
!= NULL
)
3349 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3357 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3363 if (!count_mode
&& packets_captured
> packets_to_skip
)
3364 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
3371 #ifdef SIGNAL_REQ_INFO
3373 requestinfo(int signo _U_
)
3382 #ifdef SIGNAL_FLUSH_PCAP
3384 flushpcap(int signo _U_
)
3387 pcap_dump_flush(pdd
);
3392 print_packets_captured (void)
3394 static u_int prev_packets_captured
, first
= 1;
3396 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
3397 fprintf(stderr
, "Got %u\r", packets_captured
);
3399 prev_packets_captured
= packets_captured
;
3404 * Called once each second in verbose mode while dumping to file
3407 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
3408 BOOLEAN timer_fired _U_
)
3410 print_packets_captured();
3413 static void verbose_stats_dump(int sig _U_
)
3415 print_packets_captured();
3419 DIAG_OFF_DEPRECATION
3421 print_version(FILE *f
)
3423 const char *smi_version_string
;
3425 (void)fprintf(f
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3426 (void)fprintf(f
, "%s\n", pcap_lib_version());
3428 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3429 (void)fprintf (f
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3432 smi_version_string
= nd_smi_version_string();
3433 if (smi_version_string
!= NULL
)
3434 (void)fprintf (f
, "SMI-library: %s\n", smi_version_string
);
3436 #if defined(__SANITIZE_ADDRESS__)
3437 (void)fprintf (f
, "Compiled with AddressSanitizer/GCC.\n");
3438 #elif defined(__has_feature)
3439 # if __has_feature(address_sanitizer)
3440 (void)fprintf (f
, "Compiled with AddressSanitizer/Clang.\n");
3441 # elif __has_feature(memory_sanitizer)
3442 (void)fprintf (f
, "Compiled with MemorySanitizer/Clang.\n");
3444 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3445 (void)fprintf (f
, "%zu-bit build, %zu-bit time_t\n",
3446 sizeof(void *) * 8, sizeof(time_t) * 8);
3451 print_usage(FILE *f
)
3455 "Usage: %s [-AbdDefhHI" J_FLAG
"KlLnNOpqStuUvxX#] [ -B size ] [ -c count ] [--count]\n", program_name
);
3457 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3459 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3461 "\t\t[ --lengths ]" LIST_REMOTE_INTERFACES_USAGE
"\n");
3464 "\t\t" m_FLAG_USAGE
"\n");
3467 "\t\t[ -M secret ] [ --number ] [ --print ]\n");
3469 "\t\t[ --print-sampling nth ] [ -Q in|out|inout ] [ -r file ]\n");
3471 "\t\t[ -s snaplen ] [ --skip count ] [ -T type ] [ --version ]\n");
3473 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3474 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3476 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3479 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");