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 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
207 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
209 static int timeout
= 1000; /* default timeout = 1000 ms = 1 s */
210 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
211 static int immediate_mode
;
213 static int count_mode
;
214 static u_int packets_to_skip
;
216 static int infodelay
;
217 static int infoprint
;
222 static int parse_int(const char *argname
, const char *string
, char **endp
,
223 int minval
, int maxval
, int base
);
224 static u_int
parse_u_int(const char *argname
, const char *string
, char **endp
,
225 u_int minval
, u_int maxval
, int base
);
226 static int64_t parse_int64(const char *argname
, const char *string
,
227 char **endp
, int64_t minval
, int64_t maxval
, int base
);
228 static void (*setsignal (int sig
, void (*func
)(int)))(int);
229 static void cleanup(int);
230 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
231 static void child_cleanup(int);
233 static void print_version(FILE *);
234 static void print_usage(FILE *);
236 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
237 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
238 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
240 #ifdef SIGNAL_REQ_INFO
241 static void requestinfo(int);
244 #ifdef SIGNAL_FLUSH_PCAP
245 static void flushpcap(int);
249 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
250 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
252 static void verbose_stats_dump(int sig
);
255 static void info(int);
256 static u_int packets_captured
;
258 static const struct tok status_flags
[] = {
260 { PCAP_IF_UP
, "Up" },
262 #ifdef PCAP_IF_RUNNING
263 { PCAP_IF_RUNNING
, "Running" },
265 { PCAP_IF_LOOPBACK
, "Loopback" },
266 #ifdef PCAP_IF_WIRELESS
267 { PCAP_IF_WIRELESS
, "Wireless" },
273 static pcap_dumper_t
*pdd
= NULL
;
275 static int supports_monitor_mode
;
283 char *CurrentFileName
;
286 netdissect_options
*ndo
;
292 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
294 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
295 * by any libpcap header, because it's a special hack, only available if
296 * libpcap was configured to include it, and only intended for use by
297 * libpcap developers trying to debug the parser for filter expressions).
300 __declspec(dllimport
)
304 void pcap_set_parser_debug(int);
305 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
307 * We don't have pcap_set_parser_debug() in libpcap, but we do have
308 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
309 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
312 pcap_set_parser_debug(int value
)
314 #ifdef HAVE_PCAP_DEBUG
315 extern int pcap_debug
;
318 #else /* HAVE_PCAP_DEBUG */
322 #endif /* HAVE_PCAP_DEBUG */
325 #define HAVE_PCAP_SET_PARSER_DEBUG
326 #endif // HAVE_PCAP_SET_PARSER_DEBUG, HAVE_PCAP_DEBUG, HAVE_YYDEBUG
328 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
330 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
331 * by any libpcap header, because it's a special hack, only available if
332 * libpcap was configured to include it, and only intended for use by
333 * libpcap developers trying to debug the optimizer for filter expressions).
336 __declspec(dllimport
)
340 void pcap_set_optimizer_debug(int);
341 #endif // HAVE_PCAP_SET_OPTIMIZER_DEBUG
344 exit_tcpdump(const int status
)
351 static void NORETURN
PRINTFLIKE(1, 2)
352 error(FORMAT_STRING(const char *fmt
), ...)
356 (void)fprintf(stderr
, "%s: ", program_name
);
358 (void)vfprintf(stderr
, fmt
, ap
);
363 (void)fputc('\n', stderr
);
365 exit_tcpdump(S_ERR_HOST_PROGRAM
);
370 static void PRINTFLIKE(1, 2)
371 warning(FORMAT_STRING(const char *fmt
), ...)
375 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
377 (void)vfprintf(stderr
, fmt
, ap
);
382 (void)fputc('\n', stderr
);
386 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
388 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
391 int *tstamp_types
= 0;
392 const char *tstamp_type_name
;
395 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
396 if (n_tstamp_types
< 0)
397 error("%s", pcap_geterr(pc
));
399 if (n_tstamp_types
== 0) {
400 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
402 exit_tcpdump(S_SUCCESS
);
404 fprintf(stdout
, "Time stamp types for %s (use option -j to set):\n",
406 for (i
= 0; i
< n_tstamp_types
; i
++) {
407 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
408 if (tstamp_type_name
!= NULL
) {
409 (void) fprintf(stdout
, " %s (%s)\n", tstamp_type_name
,
410 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
412 (void) fprintf(stdout
, " %d\n", tstamp_types
[i
]);
415 pcap_free_tstamp_types(tstamp_types
);
416 exit_tcpdump(S_SUCCESS
);
418 #endif // HAVE_PCAP_SET_TSTAMP_TYPE
421 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
425 const char *dlt_name
;
427 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
429 error("%s", pcap_geterr(pc
));
430 else if (n_dlts
== 0 || !dlts
)
431 error("No data link types.");
434 * If the interface is known to support monitor mode, indicate
435 * whether these are the data link types available when not in
436 * monitor mode, if -I wasn't specified, or when in monitor mode,
437 * when -I was specified (the link-layer types available in
438 * monitor mode might be different from the ones available when
439 * not in monitor mode).
441 (void) fprintf(stdout
, "Data link types for ");
442 if (supports_monitor_mode
)
443 (void) fprintf(stdout
, "%s %s",
445 Iflag
? "when in monitor mode" : "when not in monitor mode");
447 (void) fprintf(stdout
, "%s",
449 (void) fprintf(stdout
, " (use option -y to set):\n");
451 for (i
= 0; i
< n_dlts
; i
++) {
452 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
453 if (dlt_name
!= NULL
) {
454 (void) fprintf(stdout
, " %s (%s)", dlt_name
,
455 pcap_datalink_val_to_description(dlts
[i
]));
458 * OK, does tcpdump handle that type?
460 if (!has_printer(dlts
[i
]))
461 (void) fprintf(stdout
, " (printing not supported)");
462 fprintf(stdout
, "\n");
464 (void) fprintf(stdout
, " DLT %d (printing not supported)\n",
468 pcap_free_datalinks(dlts
);
469 exit_tcpdump(S_SUCCESS
);
473 show_devices_and_exit(void)
475 pcap_if_t
*dev
, *devlist
;
476 char ebuf
[PCAP_ERRBUF_SIZE
];
479 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
481 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
482 printf("%d.%s", i
+1, dev
->name
);
483 if (dev
->description
!= NULL
)
484 printf(" (%s)", dev
->description
);
485 if (dev
->flags
!= 0) {
487 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
488 #ifdef PCAP_IF_WIRELESS
489 if (dev
->flags
& PCAP_IF_WIRELESS
) {
490 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
492 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
493 printf(", Association status unknown");
496 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
497 printf(", Associated");
500 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
501 printf(", Not associated");
504 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
508 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
510 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
511 printf(", Connection status unknown");
514 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
515 printf(", Connected");
518 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
519 printf(", Disconnected");
522 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
526 #endif // PCAP_IF_WIRELESS
531 pcap_freealldevs(devlist
);
532 exit_tcpdump(S_SUCCESS
);
535 #ifdef HAVE_PCAP_FINDALLDEVS_EX
537 show_remote_devices_and_exit(void)
539 pcap_if_t
*dev
, *devlist
;
540 char ebuf
[PCAP_ERRBUF_SIZE
];
543 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
545 if (strcmp(ebuf
, "not supported") == 0) {
547 * macOS 14's pcap_findalldevs_ex(), which is a
548 * stub that always returns -1 with an error
549 * message of "not supported".
551 * In this case, as we passed it an rpcap://
552 * URL, treat that as meaning "remote capture
555 error("Remote capture not supported");
559 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
560 printf("%d.%s", i
+1, dev
->name
);
561 if (dev
->description
!= NULL
)
562 printf(" (%s)", dev
->description
);
564 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
567 pcap_freealldevs(devlist
);
568 exit_tcpdump(S_SUCCESS
);
570 #endif /* HAVE_PCAP_FINDALLDEVS_EX */
575 * Note that there we use all letters for short options except for g, k,
576 * o, and P, and those are used by other versions of tcpdump, and we should
577 * only use them for the same purposes that the other versions of tcpdump
580 * macOS tcpdump uses -g to force non--v output for IP to be on one
581 * line, making it more "g"repable;
583 * macOS tcpdump uses -k to specify that packet comments in pcapng files
586 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
587 * for hosts sending TCP SYN packets;
589 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
592 * macOS tcpdump also uses -Q to specify expressions that match packet
593 * metadata, including but not limited to the packet direction.
594 * The expression syntax is different from a simple "in|out|inout",
595 * and those expressions aren't accepted by macOS tcpdump, but the
596 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
597 * "inout" = "dir=in or dir=out", and the parser could conceivably
598 * special-case "in", "out", and "inout" as expressions for backwards
599 * compatibility, so all is not (yet) lost.
603 * Set up flags that might or might not be supported depending on the
604 * version of libpcap we're using.
606 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
608 #define j_FLAG_USAGE " [ -j tstamptype ]"
610 #else /* HAVE_PCAP_SET_TSTAMP_TYPE */
614 #endif /* HAVE_PCAP_SET_TSTAMP_TYPE */
617 #define m_FLAG_USAGE "[ -m module ] ..."
620 #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:#"
625 * We do not currently have long options corresponding to all short
626 * options; we should probably pick appropriate option names for them.
628 * However, the short options where the number of times the option is
629 * specified matters, such as -v and -d and -t, should probably not
630 * just map to a long option, as saying
632 * tcpdump --verbose --verbose
634 * doesn't make sense; it should be --verbosity={N} or something such
637 * For long options with no corresponding short options, we define values
638 * outside the range of ASCII graphic characters, make that the last
639 * component of the entry for the long option, and have a case for that
640 * option in the switch statement.
642 #define OPTION_VERSION 128
643 #define OPTION_TSTAMP_PRECISION 129
644 #define OPTION_IMMEDIATE_MODE 130
645 #define OPTION_PRINT 131
646 #define OPTION_LIST_REMOTE_INTERFACES 132
647 #define OPTION_TSTAMP_MICRO 133
648 #define OPTION_TSTAMP_NANO 134
649 #define OPTION_FP_TYPE 135
650 #define OPTION_COUNT 136
651 #define OPTION_PRINT_SAMPLING 137
652 #define OPTION_LENGTHS 138
653 #define OPTION_TIME_T_SIZE 139
654 #define OPTION_SKIP 140
656 static const struct option longopts
[] = {
657 { "buffer-size", required_argument
, NULL
, 'B' },
658 { "list-interfaces", no_argument
, NULL
, 'D' },
659 #ifdef HAVE_PCAP_FINDALLDEVS_EX
660 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
662 { "help", no_argument
, NULL
, 'h' },
663 { "interface", required_argument
, NULL
, 'i' },
664 { "monitor-mode", no_argument
, NULL
, 'I' },
665 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
666 { "time-stamp-type", required_argument
, NULL
, 'j' },
667 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
669 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
670 { "micro", no_argument
, NULL
, OPTION_TSTAMP_MICRO
},
671 { "nano", no_argument
, NULL
, OPTION_TSTAMP_NANO
},
672 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
674 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
675 { "list-data-link-types", no_argument
, NULL
, 'L' },
676 { "no-optimize", no_argument
, NULL
, 'O' },
677 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
678 { "direction", required_argument
, NULL
, 'Q' },
679 { "snapshot-length", required_argument
, NULL
, 's' },
680 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
681 { "packet-buffered", no_argument
, NULL
, 'U' },
682 { "linktype", required_argument
, NULL
, 'y' },
683 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
684 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
686 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
687 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
689 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
690 { "count", no_argument
, NULL
, OPTION_COUNT
},
691 { "fp-type", no_argument
, NULL
, OPTION_FP_TYPE
},
692 { "number", no_argument
, NULL
, '#' },
693 { "print", no_argument
, NULL
, OPTION_PRINT
},
694 { "print-sampling", required_argument
, NULL
, OPTION_PRINT_SAMPLING
},
695 { "lengths", no_argument
, NULL
, OPTION_LENGTHS
},
696 { "time-t-size", no_argument
, NULL
, OPTION_TIME_T_SIZE
},
697 { "skip", required_argument
, NULL
, OPTION_SKIP
},
698 { "version", no_argument
, NULL
, OPTION_VERSION
},
702 #ifdef HAVE_PCAP_FINDALLDEVS_EX
703 #define LIST_REMOTE_INTERFACES_USAGE " [ --list-remote-interfaces remote-source ]"
705 #define LIST_REMOTE_INTERFACES_USAGE
708 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
709 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
711 #define IMMEDIATE_MODE_USAGE ""
715 /* Drop root privileges and chroot if necessary */
717 droproot(const char *username
, const char *chroot_dir
)
719 struct passwd
*pw
= NULL
;
721 if (chroot_dir
&& !username
)
722 error("Chroot without dropping root is insecure");
724 pw
= getpwnam(username
);
727 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
728 error("Couldn't chroot/chdir to '%.64s': %s",
729 chroot_dir
, pcap_strerror(errno
));
731 #ifdef HAVE_LIBCAP_NG
733 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
735 error("capng_change_id(): return %d", ret
);
737 fprintf(stderr
, "dropped privs to %s\n", username
);
740 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
741 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
742 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
744 (unsigned long)pw
->pw_uid
,
745 (unsigned long)pw
->pw_gid
,
746 pcap_strerror(errno
));
748 fprintf(stderr
, "dropped privs to %s\n", username
);
750 #endif /* HAVE_LIBCAP_NG */
752 error("Couldn't find user '%.32s'", username
);
753 #ifdef HAVE_LIBCAP_NG
754 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT anymore. */
758 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
764 capng_apply(CAPNG_SELECT_BOTH
);
765 #endif /* HAVE_LIBCAP_NG */
786 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
788 char *filename
= malloc(PATH_MAX
+ 1);
789 if (filename
== NULL
)
790 error("%s: malloc", __func__
);
791 if (strlen(orig_name
) == 0)
792 error("an empty string is not a valid file name");
794 /* Process with strftime if Gflag is set. */
798 /* Convert Gflag_time to a usable format */
799 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
800 error("%s: localtime", __func__
);
803 /* There's no good way to detect an error in strftime since a return
804 * value of 0 isn't necessarily failure; if orig_name is an empty
805 * string, the formatted string will be empty.
807 * However, the C90 standard says that, if there *is* a
808 * buffer overflow, the content of the buffer is undefined,
809 * so we must check for a buffer overflow.
811 * So we check above for an empty orig_name, and only call
812 * strftime() if it's non-empty, in which case the return
813 * value will only be 0 if the formatted date doesn't fit
816 * (We check above because, even if we don't use -G, we
817 * want a better error message than "tcpdump: : No such
818 * file or directory" for this case.)
820 if (strftime(filename
, PATH_MAX
, orig_name
, local_tm
) == 0) {
821 error("%s: strftime", __func__
);
824 strncpy(filename
, orig_name
, PATH_MAX
);
827 if (cnt
== 0 && max_chars
== 0)
828 strncpy(buffer
, filename
, PATH_MAX
+ 1);
830 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
831 /* Report an error if the filename is too large */
832 error("too many output files or filename is too long (> %d)", PATH_MAX
);
837 get_next_file(FILE *VFile
, char *ptr
)
842 ret
= fgets(ptr
, PATH_MAX
, VFile
);
847 if (len
> 0 && ptr
[len
- 1] == '\n')
854 static cap_channel_t
*
857 cap_channel_t
*capcas
, *capdnsloc
;
858 const char *types
[1];
863 error("unable to create casper process");
864 capdnsloc
= cap_service_open(capcas
, "system.dns");
865 /* Casper capability no longer needed. */
867 if (capdnsloc
== NULL
)
868 error("unable to open system.dns service");
869 /* Limit system.dns to reverse DNS lookups. */
871 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
872 error("unable to limit access to system.dns service");
873 families
[0] = AF_INET
;
874 /* Casper is a feature of FreeBSD, which defines AF_INET6. */
875 families
[1] = AF_INET6
;
876 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
877 error("unable to limit access to system.dns service");
881 #endif /* HAVE_CASPER */
883 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
885 tstamp_precision_from_string(const char *precision
)
887 if (strncmp(precision
, "nano", strlen("nano")) == 0)
888 return PCAP_TSTAMP_PRECISION_NANO
;
890 if (strncmp(precision
, "micro", strlen("micro")) == 0)
891 return PCAP_TSTAMP_PRECISION_MICRO
;
897 tstamp_precision_to_string(int precision
)
901 case PCAP_TSTAMP_PRECISION_MICRO
:
904 case PCAP_TSTAMP_PRECISION_NANO
:
911 #endif // HAVE_PCAP_SET_TSTAMP_PRECISION
915 * Ensure that, on a dump file's descriptor, we have all the rights
916 * necessary to make the standard I/O library work with an fdopen()ed
917 * FILE * from that descriptor.
919 * A long time ago in a galaxy far, far away, AT&T decided that, instead
920 * of providing separate APIs for getting and setting the FD_ flags on a
921 * descriptor, getting and setting the O_ flags on a descriptor, and
922 * locking files, they'd throw them all into a kitchen-sink fcntl() call
923 * along the lines of ioctl(), the fact that ioctl() operations are
924 * largely specific to particular character devices but fcntl() operations
925 * are either generic to all descriptors or generic to all descriptors for
926 * regular files notwithstanding.
928 * The Capsicum people decided that fine-grained control of descriptor
929 * operations was required, so that you need to grant permission for
930 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
931 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
932 * collection of things, so there are *individual* fcntls for which
933 * permission needs to be granted.
935 * The FreeBSD standard I/O people implemented some optimizations that
936 * requires that the standard I/O routines be able to determine whether
937 * the descriptor for the FILE * is open append-only or not; as that
938 * descriptor could have come from an open() rather than an fopen(),
939 * that requires that it be able to do an F_GETFL fcntl() to read
942 * tcpdump uses ftell() to determine how much data has been written
943 * to a file in order to, when used with -C, determine when it's time
944 * to rotate capture files. ftell() therefore needs to do an lseek()
945 * to find out the file offset and must, thanks to the aforementioned
946 * optimization, also know whether the descriptor is open append-only
949 * The net result of all the above is that we need to grant CAP_SEEK,
950 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
952 * Perhaps this is the universe's way of saying that either
954 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
955 * using it, so that Capsicum-capable tcpdump wouldn't need to do
960 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
961 * I/O library that knows what rights are needed by the standard
962 * I/O library, based on the open mode, and assigns them, perhaps
963 * with an additional argument indicating, for example, whether
964 * seeking should be allowed, so that tcpdump doesn't need to know
965 * what the standard I/O library happens to require this week.
968 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
970 int fd
= fileno(pcap_dump_file(p
));
973 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
974 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
975 error("unable to limit dump descriptor");
977 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
978 error("unable to limit dump descriptor fcntls");
981 #endif // HAVE_CAPSICUM
984 * Copy arg vector into a new buffer, concatenating arguments with spaces.
987 copy_argv(char **argv
)
999 len
+= strlen(*p
++) + 1;
1001 buf
= (char *)malloc(len
);
1003 error("%s: malloc", __func__
);
1007 while ((src
= *p
++) != NULL
) {
1008 while ((*dst
++ = *src
++) != '\0')
1018 * On Windows, we need to open the file in binary mode, so that
1019 * we get all the bytes specified by the size we get from "fstat()".
1020 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1021 * we define it as 0 if it's not defined, so it does nothing.
1028 read_infile(char *fname
)
1035 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1037 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1039 if (our_fstat(fd
, &buf
) < 0)
1040 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1043 * Reject files whose size doesn't fit into an int; a filter
1044 * *that* large will probably be too big.
1046 if (buf
.st_size
> INT_MAX
)
1047 error("%s is too large", fname
);
1049 cp
= malloc((u_int
)buf
.st_size
+ 1);
1051 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1052 fname
, pcap_strerror(errno
));
1053 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1055 error("read %s: %s", fname
, pcap_strerror(errno
));
1056 if (cc
!= buf
.st_size
)
1057 error("short read %s (%d != %d)", fname
, (int) cc
,
1061 /* replace "# comment" with spaces */
1062 for (i
= 0; i
< cc
; i
++) {
1064 while (i
< cc
&& cp
[i
] != '\n')
1072 parse_interface_number(const char *device
)
1079 * Search for a colon, terminating any scheme at the beginning
1082 p
= strchr(device
, ':');
1085 * We found it. Is it followed by "//"?
1087 p
++; /* skip the : */
1088 if (strncmp(p
, "//", 2) == 0) {
1090 * Yes. Search for the next /, at the end of the
1091 * authority part of the URL.
1093 p
+= 2; /* skip the // */
1097 * OK, past the / is the path.
1103 devnum
= strtol(device
, &end
, 10);
1104 if (device
!= end
&& *end
== '\0') {
1106 * It's all-numeric, but is it a valid number?
1110 * No, it's not an ordinal.
1112 error("Invalid adapter index %s", device
);
1117 * It's not all-numeric; return -1, so our caller
1125 find_interface_by_number(const char *url
1126 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1131 pcap_if_t
*dev
, *devlist
;
1133 char ebuf
[PCAP_ERRBUF_SIZE
];
1135 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1141 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1143 * Search for a colon, terminating any scheme at the beginning
1146 endp
= strchr(url
, ':');
1149 * We found it. Is it followed by "//"?
1151 endp
++; /* skip the : */
1152 if (strncmp(endp
, "//", 2) == 0) {
1154 * Yes. Search for the next /, at the end of the
1155 * authority part of the URL.
1157 endp
+= 2; /* skip the // */
1158 endp
= strchr(endp
, '/');
1164 * OK, everything from device to endp is a URL to hand
1165 * to pcap_findalldevs_ex().
1167 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1168 host_url
= malloc(endp
- url
+ 1);
1169 if (host_url
== NULL
&& (endp
- url
+ 1) > 0)
1170 error("Invalid allocation for host");
1172 memcpy(host_url
, url
, endp
- url
);
1173 host_url
[endp
- url
] = '\0';
1174 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1177 #endif // HAVE_PCAP_FINDALLDEVS_EX
1178 status
= pcap_findalldevs(&devlist
, ebuf
);
1182 * Look for the devnum-th entry in the list of devices (1-based).
1184 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1185 i
++, dev
= dev
->next
)
1188 pcap_freealldevs(devlist
);
1189 error("Invalid adapter index %ld: only %ld interfaces found",
1192 device
= strdup(dev
->name
);
1193 pcap_freealldevs(devlist
);
1197 #ifdef HAVE_PCAP_OPEN
1199 * Prefixes for rpcap URLs.
1201 static char rpcap_prefix
[] = "rpcap://";
1202 static char rpcap_ssl_prefix
[] = "rpcaps://";
1206 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1212 #ifdef HAVE_PCAP_OPEN
1214 * Is this an rpcap URL?
1216 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0 ||
1217 strncmp(device
, rpcap_ssl_prefix
, sizeof(rpcap_ssl_prefix
) - 1) == 0) {
1219 * Yes. Open it with pcap_open().
1222 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1223 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, timeout
, NULL
,
1227 * macOS 14's pcap_pcap_open(), which is a
1228 * stub that always returns NULL with an error
1229 * message of "not supported".
1231 * In this case, as we passed it an rpcap://
1232 * URL, treat that as meaning "remote capture
1235 if (strcmp(ebuf
, "not supported") == 0)
1236 error("Remote capture not supported");
1239 * If this failed with "No such device" or "The system
1240 * cannot find the device specified", that means
1241 * the interface doesn't exist; return NULL, so that
1242 * the caller can see whether the device name is
1243 * actually an interface index.
1245 if (strstr(ebuf
, "No such device") != NULL
||
1246 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1251 warning("%s", ebuf
);
1254 #endif /* HAVE_PCAP_OPEN */
1256 pc
= pcap_create(device
, ebuf
);
1259 * If this failed with "No such device", that means
1260 * the interface doesn't exist; return NULL, so that
1261 * the caller can see whether the device name is
1262 * actually an interface index.
1264 if (strstr(ebuf
, "No such device") != NULL
)
1268 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1270 show_tstamp_types_and_exit(pc
, device
);
1272 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1273 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1275 error("%s: Can't set %ssecond time stamp precision: %s",
1277 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1278 pcap_statustostr(status
));
1281 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1282 if (immediate_mode
) {
1283 status
= pcap_set_immediate_mode(pc
, 1);
1285 error("%s: Can't set immediate mode: %s",
1286 device
, pcap_statustostr(status
));
1290 * Is this an interface that supports monitor mode?
1292 if (pcap_can_set_rfmon(pc
) == 1)
1293 supports_monitor_mode
= 1;
1295 supports_monitor_mode
= 0;
1296 if (ndo
->ndo_snaplen
!= 0) {
1298 * A snapshot length was explicitly specified;
1301 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1303 error("%s: Can't set snapshot length: %s",
1304 device
, pcap_statustostr(status
));
1306 status
= pcap_set_promisc(pc
, !pflag
);
1308 error("%s: Can't set promiscuous mode: %s",
1309 device
, pcap_statustostr(status
));
1311 status
= pcap_set_rfmon(pc
, 1);
1313 error("%s: Can't set monitor mode: %s",
1314 device
, pcap_statustostr(status
));
1316 status
= pcap_set_timeout(pc
, timeout
);
1318 error("%s: pcap_set_timeout failed: %s",
1319 device
, pcap_statustostr(status
));
1321 status
= pcap_set_buffer_size(pc
, Bflag
);
1323 error("%s: Can't set buffer size: %s",
1324 device
, pcap_statustostr(status
));
1326 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1328 status
= pcap_set_tstamp_type(pc
, jflag
);
1330 error("%s: Can't set time stamp type: %s",
1331 device
, pcap_statustostr(status
));
1332 else if (status
> 0)
1333 warning("When trying to set timestamp type '%s' on %s: %s",
1334 pcap_tstamp_type_val_to_name(jflag
), device
,
1335 pcap_statustostr(status
));
1338 status
= pcap_activate(pc
);
1341 * pcap_activate() failed.
1343 cp
= pcap_geterr(pc
);
1344 if (status
== PCAP_ERROR
)
1346 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1348 * Return an error for our caller to handle.
1350 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1351 device
, pcap_statustostr(status
), cp
);
1352 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1353 error("%s: %s\n(%s)", device
,
1354 pcap_statustostr(status
), cp
);
1355 #ifdef PCAP_ERROR_CAPTURE_NOTSUP
1356 else if (status
== PCAP_ERROR_CAPTURE_NOTSUP
&& *cp
!= '\0')
1357 error("%s: %s\n(%s)", device
,
1358 pcap_statustostr(status
), cp
);
1361 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1362 strncmp(device
, "wlan", 4) == 0) {
1363 char parent
[8], newdev
[8];
1365 size_t s
= sizeof(parent
);
1367 snprintf(sysctl
, sizeof(sysctl
),
1368 "net.wlan.%d.%%parent", atoi(device
+ 4));
1369 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1370 strlcpy(newdev
, device
, sizeof(newdev
));
1371 /* Suggest a new wlan device. */
1372 /* FIXME: incrementing the index this way is not going to work well
1373 * when the index is 9 or greater but the only consequence in this
1374 * specific case would be an error message that looks a bit odd.
1376 newdev
[strlen(newdev
)-1]++;
1377 error("%s is not a monitor mode VAP"
1378 "To create a new monitor mode VAP use:\n"
1379 " ifconfig %s create wlandev %s wlanmode monitor\n"
1380 "and use %s as the tcpdump interface",
1381 device
, newdev
, parent
, newdev
);
1383 #endif // __FreeBSD__
1385 error("%s: %s", device
,
1386 pcap_statustostr(status
));
1389 } else if (status
> 0) {
1391 * pcap_activate() succeeded, but it's warning us
1392 * of a problem it had.
1394 cp
= pcap_geterr(pc
);
1395 if (status
== PCAP_WARNING
)
1397 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1399 warning("%s: %s\n(%s)", device
,
1400 pcap_statustostr(status
), cp
);
1402 warning("%s: %s", device
,
1403 pcap_statustostr(status
));
1406 status
= pcap_setdirection(pc
, Qflag
);
1408 error("%s: pcap_setdirection() failed: %s",
1409 device
, pcap_geterr(pc
));
1416 main(int argc
, char **argv
)
1419 bpf_u_int32 localnet
= 0, netmask
= 0;
1420 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1422 pcap_handler callback
;
1424 const char *dlt_name
;
1425 struct bpf_program fcode
;
1427 void (*oldhandler
)(int);
1429 struct dump_info dumpinfo
;
1430 u_char
*pcap_userdata
;
1431 char ebuf
[PCAP_ERRBUF_SIZE
];
1432 char VFileLine
[PATH_MAX
+ 1];
1433 const char *username
= NULL
;
1435 const char *chroot_dir
= NULL
;
1442 #ifdef HAVE_CAPSICUM
1443 cap_rights_t rights
;
1445 #endif /* HAVE_CAPSICUM */
1446 int Oflag
= 1; /* run filter code optimizer */
1448 const char *yflag_dlt_name
= NULL
;
1452 netdissect_options Ndo
;
1453 netdissect_options
*ndo
= &Ndo
;
1457 * We need to look for wpcap.dll in \Windows\System32\Npcap first,
1460 * 1) WinPcap isn't installed and Npcap isn't installed in "WinPcap
1461 * API-compatible Mode", so there's no wpcap.dll in
1462 * \Windows\System32, only in \Windows\System32\Npcap;
1464 * 2) WinPcap is installed and Npcap isn't installed in "WinPcap
1465 * API-compatible Mode", so the wpcap.dll in \Windows\System32
1466 * is a WinPcap DLL, but we'd prefer an Npcap DLL (we should
1467 * work with either one if we're configured against WinPcap,
1468 * and we'll probably require Npcap if we're configured against
1469 * it), and that's in \Windows\System32\Npcap;
1471 * 3) Npcap is installed in "WinPcap API-compatible Mode", so both
1472 * \Windows\System32 and \Windows\System32\Npcap have an Npcap
1475 * Unfortunately, Windows has no notion of an rpath, so we can't
1476 * set the rpath to include \Windows\System32\Npcap at link time;
1477 * what we need to do is to link wpcap as a delay-load DLL and
1478 * add \Windows\System32\Npcap to the DLL search path early in
1479 * main() with a call to SetDllDirectory().
1481 * The same applies to packet.dll.
1483 * We add \Windows\System32\Npcap here.
1485 * See https://npcap.com/guide/npcap-devguide.html#npcap-feature-native-dll-implicitly
1487 WCHAR
*dll_directory
= NULL
;
1488 size_t dll_directory_buf_len
= 0; /* units of bytes */
1489 UINT system_directory_buf_len
= 0; /* units of WCHARs */
1490 UINT system_directory_len
; /* units of WCHARs */
1491 static const WCHAR npcap
[] = L
"\\Npcap";
1494 * Get the system directory path, in UTF-16, into a buffer that's
1495 * large enough for that directory path plus "\Npcap".
1497 * String manipulation in C, plus fetching a variable-length
1498 * string into a buffer whose size is fixed at the time of
1499 * the call, with an oddball return value (see below), is just
1500 * a huge bag of fun.
1502 * And it's even more fun when dealing with UTF-16, so that the
1503 * buffer sizes used in GetSystemDirectoryW() are in different
1504 * units from the buffer sizes used in realloc()! We maintain
1505 * all sizes/length in units of bytes, not WCHARs, so that our
1506 * heads don't explode.
1510 * Try to fetch the system directory.
1512 * GetSystemDirectoryW() expects a buffer size in units
1513 * of WCHARs, not bytes, and returns a directory path
1514 * length in units of WCHARs, not bytes.
1516 * For extra fun, if GetSystemDirectoryW() succeeds,
1517 * the return value is the length of the directory
1518 * path in units of WCHARs, *not* including the
1519 * terminating '\0', but if it fails because the
1520 * path string wouldn't fit, the return value is
1521 * the length of the directory path in units of WCHARs,
1522 * *including* the terminating '\0'.
1524 system_directory_len
= GetSystemDirectoryW(dll_directory
,
1525 system_directory_buf_len
);
1526 if (system_directory_len
== 0)
1527 error("GetSystemDirectoryW() failed");
1530 * Did the directory path fit in the buffer?
1532 * As per the above, this means that the return value
1533 * *plus 1*, so that the terminating '\0' is counted,
1534 * is <= the buffer size.
1536 * (If the directory path, complete with the terminating
1537 * '\0', fits *exactly*, the return value would be the
1538 * size of the buffer minus 1, as it doesn't count the
1539 * terminating '\0', so the test below would succeed.
1541 * If everything *but* the terminating '\0' fits,
1542 * the return value would be the size of the buffer + 1,
1543 * i.e., the size that the string in question would
1546 * The astute reader will note that returning the
1547 * size of the buffer is not one of the two cases
1548 * above, and should never happen.)
1550 if ((system_directory_len
+ 1) <= system_directory_buf_len
) {
1552 * No. We have a buffer that's large enough
1559 * Yes. Grow the buffer.
1561 * The space we'll need in the buffer for the system
1562 * directory, in units of WCHARs, is system_directory_len,
1563 * as that's the length of the system directory path
1564 * including the terminating '\0'.
1566 system_directory_buf_len
= system_directory_len
;
1569 * The size of the DLL directory buffer, in *bytes*, must
1570 * be the number of WCHARs taken by the system directory,
1571 * *minus* the terminating '\0' (as we'll overwrite that
1572 * with the "\" of the "\Npcap" string), multiplied by
1573 * sizeof(WCHAR) to convert it to the number of bytes,
1574 * plus the size of the "\Npcap" string, in bytes (which
1575 * will include the terminating '\0', as that will become
1576 * the DLL path's terminating '\0').
1578 dll_directory_buf_len
=
1579 ((system_directory_len
- 1)*sizeof(WCHAR
)) + sizeof npcap
;
1580 dll_directory
= realloc(dll_directory
, dll_directory_buf_len
);
1581 if (dll_directory
== NULL
)
1582 error("Can't allocate string for Npcap directory");
1588 * Now append \Npcap. We add the length of the system directory path,
1589 * in WCHARs, *not* including the terminating '\0' (which, since
1590 * GetSystemDirectoryW() succeeded, is the return value of
1591 * GetSystemDirectoryW(), as per the above), to the pointer to the
1592 * beginning of the path, to go past the end of the system directory
1593 * to point to the terminating '\0'.
1595 memcpy(dll_directory
+ system_directory_len
, npcap
, sizeof npcap
);
1598 * Now add that as a system DLL directory.
1600 if (!SetDllDirectoryW(dll_directory
))
1601 error("SetDllDirectory failed");
1603 free(dll_directory
);
1607 * Initialize the netdissect code.
1609 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1612 memset(ndo
, 0, sizeof(*ndo
));
1613 ndo_set_function_pointers(ndo
);
1623 if ((cp
= strrchr(argv
[0], PATH_SEPARATOR
)) != NULL
)
1624 ndo
->program_name
= program_name
= cp
+ 1;
1626 ndo
->program_name
= program_name
= argv
[0];
1628 #if defined(HAVE_PCAP_WSOCKINIT)
1629 if (pcap_wsockinit() != 0)
1630 error("Attempting to initialize Winsock failed");
1631 #elif defined(HAVE_WSOCKINIT)
1632 if (wsockinit() != 0)
1633 error("Attempting to initialize Winsock failed");
1637 * An explicit tzset() call is usually not needed as it happens
1638 * implicitly the first time we call localtime() or mktime(),
1639 * but in some cases (sandboxing, chroot) this may be too late.
1644 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1648 /* compatibility for old -a */
1660 Bflag
= parse_int("packet buffer size", optarg
, NULL
, 1,
1663 * Will multiplying it by 1024 overflow?
1665 if (Bflag
> INT_MAX
/ 1024)
1666 error("packet buffer size %s is too large", optarg
);
1671 cnt
= parse_int("packet count", optarg
, NULL
, 1,
1676 Cflag
= parse_int64("file size", optarg
, &endp
, 1,
1679 if (*endp
== '\0') {
1681 * There's nothing after the file size,
1682 * so the size is in units of 1 MB
1683 * (1,000,000 bytes).
1685 Cflagmult
= 1000000;
1688 * There's something after the file
1691 * If it's a single letter, then:
1693 * if the letter is k or K, the size
1694 * is in units of 1 KiB (1024 bytes);
1696 * if the letter is m or M, the size
1697 * is in units of 1 MiB (1,048,576 bytes);
1699 * if the letter is g or G, the size
1700 * is in units of 1 GiB (1,073,741,824 bytes).
1702 * Otherwise, it's an error.
1713 Cflagmult
= 1024*1024;
1718 Cflagmult
= 1024*1024*1024;
1722 error("invalid file size %s (invalid units)", optarg
);
1726 * OK, there was a letter that we treat
1727 * as a units indication; was there
1728 * anything after it?
1731 if (*endp
!= '\0') {
1733 error("invalid file size %s (invalid units)", optarg
);
1738 * Will multiplying it by multiplier overflow?
1740 #ifdef HAVE_PCAP_DUMP_FTELL64
1741 if (Cflag
> INT64_MAX
/ Cflagmult
)
1743 if (Cflag
> LONG_MAX
/ Cflagmult
)
1745 error("file size %s is too large", optarg
);
1757 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1758 case OPTION_LIST_REMOTE_INTERFACES
:
1759 remote_interfaces_source
= optarg
;
1772 #ifndef HAVE_LIBCRYPTO
1773 warning("crypto code not compiled in");
1775 ndo
->ndo_espsecret
= optarg
;
1787 Gflag
= parse_int("number of seconds", optarg
, NULL
, 0,
1790 /* We will create one file initially. */
1793 /* Grab the current time for rotation use. */
1794 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1795 error("%s: can't get current time: %s",
1796 __func__
, pcap_strerror(errno
));
1801 print_usage(stdout
);
1802 exit_tcpdump(S_SUCCESS
);
1817 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1819 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1821 error("invalid time stamp type %s", optarg
);
1832 * _IOLBF is the same as _IOFBF in Microsoft's C
1833 * libraries; the only alternative they offer
1836 * XXX - this should really be checking for MSVC++,
1837 * not _WIN32, if, for example, MinGW has its own
1838 * C library that is more UNIX-compatible.
1840 setvbuf(stdout
, NULL
, _IONBF
, 0);
1842 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1852 if (nd_have_smi_support()) {
1853 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1856 (void)fprintf(stderr
, "%s: ignoring option '-m %s' ",
1857 program_name
, optarg
);
1858 (void)fprintf(stderr
, "(no libsmi support)\n");
1863 /* TCP-MD5 shared secret */
1864 #ifndef HAVE_LIBCRYPTO
1865 warning("crypto code not compiled in");
1867 ndo
->ndo_sigsecret
= optarg
;
1888 ++ndo
->ndo_suppress_default_print
;
1892 if (ascii_strcasecmp(optarg
, "in") == 0)
1894 else if (ascii_strcasecmp(optarg
, "out") == 0)
1896 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1897 Qflag
= PCAP_D_INOUT
;
1899 error("unknown capture direction '%s'", optarg
);
1907 ndo
->ndo_snaplen
= parse_int("snaplen", optarg
, NULL
,
1908 0, MAXIMUM_SNAPLEN
, 0);
1920 if (ascii_strcasecmp(optarg
, "vat") == 0)
1921 ndo
->ndo_packettype
= PT_VAT
;
1922 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1923 ndo
->ndo_packettype
= PT_WB
;
1924 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1925 ndo
->ndo_packettype
= PT_RPC
;
1926 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1927 ndo
->ndo_packettype
= PT_RTP
;
1928 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1929 ndo
->ndo_packettype
= PT_RTCP
;
1930 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1931 ndo
->ndo_packettype
= PT_SNMP
;
1932 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1933 ndo
->ndo_packettype
= PT_CNFP
;
1934 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1935 ndo
->ndo_packettype
= PT_TFTP
;
1936 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1937 ndo
->ndo_packettype
= PT_AODV
;
1938 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1939 ndo
->ndo_packettype
= PT_CARP
;
1940 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1941 ndo
->ndo_packettype
= PT_RADIUS
;
1942 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1943 ndo
->ndo_packettype
= PT_ZMTP1
;
1944 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1945 ndo
->ndo_packettype
= PT_VXLAN
;
1946 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1947 ndo
->ndo_packettype
= PT_PGM
;
1948 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1949 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1950 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1951 ndo
->ndo_packettype
= PT_LMP
;
1952 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1953 ndo
->ndo_packettype
= PT_RESP
;
1954 else if (ascii_strcasecmp(optarg
, "ptp") == 0)
1955 ndo
->ndo_packettype
= PT_PTP
;
1956 else if (ascii_strcasecmp(optarg
, "someip") == 0)
1957 ndo
->ndo_packettype
= PT_SOMEIP
;
1958 else if (ascii_strcasecmp(optarg
, "domain") == 0)
1959 ndo
->ndo_packettype
= PT_DOMAIN
;
1960 else if (ascii_strcasecmp(optarg
, "quic") == 0)
1961 ndo
->ndo_packettype
= PT_QUIC
;
1963 error("unknown packet type '%s'", optarg
);
1987 Wflag
= parse_int("number of output files", optarg
,
1988 NULL
, 1, INT_MAX
, 10);
1989 WflagChars
= getWflagChars(Wflag
);
1994 ++ndo
->ndo_suppress_default_print
;
1999 ++ndo
->ndo_suppress_default_print
;
2003 yflag_dlt_name
= optarg
;
2005 pcap_datalink_name_to_val(yflag_dlt_name
);
2007 error("invalid data link type %s", yflag_dlt_name
);
2010 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
2013 /* Undocumented flag */
2014 pcap_set_parser_debug(1);
2019 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2022 error("-z cannot be used. Fork subprocess not implemented.");
2031 ndo
->ndo_packet_number
= 1;
2034 case OPTION_LENGTHS
:
2035 ndo
->ndo_lengths
= 1;
2038 case OPTION_TIME_T_SIZE
:
2039 printf("%zu\n", sizeof(time_t) * 8);
2042 case OPTION_VERSION
:
2043 print_version(stdout
);
2044 exit_tcpdump(S_SUCCESS
);
2047 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2048 case OPTION_TSTAMP_PRECISION
:
2049 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
2050 if (ndo
->ndo_tstamp_precision
< 0)
2051 error("unsupported time stamp precision");
2055 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2056 case OPTION_IMMEDIATE_MODE
:
2065 case OPTION_PRINT_SAMPLING
:
2068 ndo
->ndo_print_sampling
= parse_int("print sampling",
2069 optarg
, NULL
, 1, INT_MAX
, 10);
2073 packets_to_skip
= parse_u_int("packet skip count",
2074 optarg
, NULL
, 0, INT_MAX
, 0);
2077 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2078 case OPTION_TSTAMP_MICRO
:
2079 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
2082 case OPTION_TSTAMP_NANO
:
2083 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_NANO
;
2087 case OPTION_FP_TYPE
:
2089 * Print out the type of floating-point arithmetic
2090 * we're doing; it's probably IEEE, unless somebody
2091 * tries to run this on a VAX, but the precision
2092 * may differ (e.g., it might be 32-bit, 64-bit,
2095 float_type_check(0x4e93312d);
2103 print_usage(stderr
);
2104 exit_tcpdump(S_ERR_HOST_PROGRAM
);
2108 if (ndo
->ndo_Aflag
&& ndo
->ndo_xflag
)
2109 error("-A and -x[x] are mutually exclusive.");
2110 if (ndo
->ndo_Aflag
&& ndo
->ndo_Xflag
)
2111 error("-A and -X[X] are mutually exclusive.");
2112 if (ndo
->ndo_xflag
&& ndo
->ndo_Xflag
)
2113 error("-x[x] and -X[X] are mutually exclusive.");
2114 if (Cflag
!= 0 && WFileName
== NULL
)
2115 error("-C cannot be used without -w.");
2116 if (Gflag
!= 0 && WFileName
== NULL
)
2117 error("-G cannot be used without -w.");
2118 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2119 if (zflag
!= NULL
&& (WFileName
== NULL
|| (Cflag
== 0 && Gflag
== 0)))
2120 error("-z cannot be used without -w and (-C or -G).");
2124 if ((int)packets_to_skip
> (INT_MAX
- cnt
))
2125 // cnt + (int)packets_to_skip used in pcap_loop() call
2126 error("Overflow (-c count) %d + (--skip count) %d", cnt
,
2127 (int)packets_to_skip
);
2130 show_devices_and_exit();
2131 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2132 if (remote_interfaces_source
!= NULL
)
2133 show_remote_devices_and_exit();
2136 switch (ndo
->ndo_tflag
) {
2138 case 0: /* Default */
2139 case 1: /* No time stamp */
2140 case 2: /* Unix timeval style */
2141 case 3: /* Microseconds/nanoseconds since previous packet */
2142 case 4: /* Date + Default */
2143 case 5: /* Microseconds/nanoseconds since first packet */
2146 default: /* Not supported */
2147 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
2151 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
2152 error("-f cannot be used with -V or -r.");
2154 if (VFileName
!= NULL
&& RFileName
!= NULL
)
2155 error("-V and -r are mutually exclusive.");
2158 * If we're printing dissected packets to the standard output,
2159 * and either the standard output is a terminal or we're doing
2160 * "line" buffering, set the capture timeout to .1 second rather
2161 * than 1 second, as the user's probably expecting to see packets
2162 * pop up immediately shortly after they arrive.
2164 * XXX - would there be some value appropriate for all cases,
2165 * based on, say, the buffer size and packet input rate?
2167 if ((WFileName
== NULL
|| print
) && (isatty(1) || lflag
))
2171 /* if run as root, prepare for chrooting */
2172 if (getuid() == 0 || geteuid() == 0) {
2173 /* future extensibility for cmd-line arguments */
2175 chroot_dir
= WITH_CHROOT
;
2180 /* if run as root, prepare for dropping root privileges */
2181 if (getuid() == 0 || geteuid() == 0) {
2182 /* Run with '-Z root' to restore old behaviour */
2184 username
= WITH_USER
;
2185 else if (strcmp(username
, "root") == 0)
2190 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
2192 * If RFileName is non-null, it's the pathname of a
2193 * savefile to read. If VFileName is non-null, it's
2194 * the pathname of a file containing a list of pathnames
2195 * (one per line) of savefiles to read.
2197 * In either case, we're reading a savefile, not doing
2202 * We don't need network access, so relinquish any set-UID
2203 * or set-GID privileges we have (if any).
2205 * We do *not* want set-UID privileges when opening a
2206 * trace file, as that might let the user read other
2207 * people's trace files (especially if we're set-UID
2210 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2211 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2213 if (VFileName
!= NULL
) {
2214 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
2217 VFile
= fopen(VFileName
, "r");
2220 error("Unable to open file: %s", pcap_strerror(errno
));
2222 ret
= get_next_file(VFile
, VFileLine
);
2224 error("Nothing in %s", VFileName
);
2225 RFileName
= VFileLine
;
2228 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2229 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
2230 ndo
->ndo_tstamp_precision
, ebuf
);
2232 pd
= pcap_open_offline(RFileName
, ebuf
);
2237 #ifdef HAVE_CAPSICUM
2238 cap_rights_init(&rights
, CAP_READ
);
2239 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
2241 error("unable to limit pcap descriptor");
2244 dlt
= pcap_datalink(pd
);
2245 dlt_name
= pcap_datalink_val_to_name(dlt
);
2246 fprintf(stderr
, "reading from file %s", RFileName
);
2247 if (dlt_name
== NULL
) {
2248 fprintf(stderr
, ", link-type %u", dlt
);
2250 fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2251 pcap_datalink_val_to_description(dlt
));
2253 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2254 #if defined(DLT_LINUX_SLL2) && defined(__linux__)
2255 if (dlt
== DLT_LINUX_SLL2
)
2256 fprintf(stderr
, "Warning: interface names might be incorrect\n");
2258 } else if (dflag
&& !device
) {
2259 int dump_dlt
= DLT_EN10MB
;
2261 * We're dumping the compiled code without an explicit
2262 * device specification. (If a device is specified, we
2263 * definitely want to open it to use the DLT of that device.)
2264 * Either default to DLT_EN10MB with a warning, or use
2265 * the user-specified value if supplied.
2268 * If no snapshot length was specified, or a length of 0 was
2269 * specified, default to 256KB.
2271 if (ndo
->ndo_snaplen
== 0)
2272 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
2274 * If a DLT was specified with the -y flag, use that instead.
2276 if (yflag_dlt
!= -1)
2277 dump_dlt
= yflag_dlt
;
2279 fprintf(stderr
, "Warning: assuming Ethernet\n");
2280 pd
= pcap_open_dead(dump_dlt
, ndo
->ndo_snaplen
);
2283 * We're doing a live capture.
2285 if (device
== NULL
) {
2287 * No interface was specified. Pick one.
2290 * Find the list of interfaces, and pick
2291 * the first interface.
2293 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2295 if (devlist
== NULL
)
2296 error("no interfaces available for capture");
2297 device
= strdup(devlist
->name
);
2298 pcap_freealldevs(devlist
);
2302 * Try to open the interface with the specified name.
2304 pd
= open_interface(device
, ndo
, ebuf
);
2307 * That failed. If we can get a list of
2308 * interfaces, and the interface name
2309 * is purely numeric, try to use it as
2310 * a 1-based index in the list of
2313 devnum
= parse_interface_number(device
);
2316 * It's not a number; just report
2317 * the open error and fail.
2323 * OK, it's a number; try to find the
2324 * interface with that index, and try
2327 * find_interface_by_number() exits if it
2328 * couldn't be found.
2330 device
= find_interface_by_number(device
, devnum
);
2331 pd
= open_interface(device
, ndo
, ebuf
);
2337 * Let user own process after capture device has
2341 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2342 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2345 show_dlts_and_exit(pd
, device
);
2346 if (yflag_dlt
>= 0) {
2347 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2348 error("%s", pcap_geterr(pd
));
2349 (void)fprintf(stderr
, "%s: data link type %s\n",
2351 pcap_datalink_val_to_name(yflag_dlt
));
2352 (void)fflush(stderr
);
2354 #if defined(DLT_LINUX_SLL2)
2357 * Attempt to set default linktype to
2358 * DLT_LINUX_SLL2 when capturing on the
2361 * If the attempt fails, just quietly drive
2362 * on; this may be a non-Linux "any" device
2363 * that doesn't support DLT_LINUX_SLL2.
2365 if (strcmp(device
, "any") == 0) {
2366 DIAG_OFF_WARN_UNUSED_RESULT
2367 (void) pcap_set_datalink(pd
, DLT_LINUX_SLL2
);
2368 DIAG_ON_WARN_UNUSED_RESULT
2372 i
= pcap_snapshot(pd
);
2373 if (ndo
->ndo_snaplen
< i
) {
2374 if (ndo
->ndo_snaplen
!= 0)
2375 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2376 ndo
->ndo_snaplen
= i
;
2377 } else if (ndo
->ndo_snaplen
> i
) {
2378 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2379 ndo
->ndo_snaplen
= i
;
2381 if(ndo
->ndo_fflag
!= 0) {
2382 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2383 warning("foreign (-f) flag used but: %s", ebuf
);
2389 cmdbuf
= read_infile(infile
);
2391 cmdbuf
= copy_argv(&argv
[optind
]);
2393 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2394 pcap_set_optimizer_debug(dflag
);
2397 * netmask is in network byte order, pcap_compile() takes it
2398 * in host byte order.
2400 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, ntohl(netmask
)) < 0)
2401 error("%s", pcap_geterr(pd
));
2403 bpf_dump(&fcode
, dflag
);
2406 pcap_freecode(&fcode
);
2407 exit_tcpdump(S_SUCCESS
);
2411 if (!ndo
->ndo_nflag
)
2412 capdns
= capdns_setup();
2413 #endif /* HAVE_CASPER */
2415 // Both localnet and netmask are in network byte order.
2416 init_print(ndo
, localnet
, netmask
);
2419 (void)setsignal(SIGPIPE
, cleanup
);
2420 (void)setsignal(SIGTERM
, cleanup
);
2422 (void)setsignal(SIGINT
, cleanup
);
2423 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2424 (void)setsignal(SIGCHLD
, child_cleanup
);
2426 /* Cooperate with nohup(1) */
2429 * In illumos /usr/include/sys/iso/signal_iso.h causes Clang to
2430 * generate a -Wstrict-prototypes warning here, see [1]. The
2431 * __illumos__ macro is available since at least GCC 11 and Clang 13,
2433 * 1: https://www.illumos.org/issues/16344
2434 * 2: https://www.illumos.org/issues/13726
2437 DIAG_OFF_STRICT_PROTOTYPES
2438 #endif /* __illumos__ */
2439 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2441 DIAG_ON_STRICT_PROTOTYPES
2442 #endif /* __illumos__ */
2443 (void)setsignal(SIGHUP
, oldhandler
);
2448 * If a user name was specified with "-Z", attempt to switch to
2449 * that user's UID. This would probably be used with sudo,
2450 * to allow tcpdump to be run in a special restricted
2451 * account (if you just want to allow users to open capture
2452 * devices, and can't just give users that permission,
2453 * you'd make tcpdump set-UID or set-GID).
2455 * tcpdump doesn't necessarily write only to one savefile;
2456 * the general only way to allow a -Z instance to write to
2457 * savefiles as the user under whose UID it's run, rather
2458 * than as the user specified with -Z, would thus be to switch
2459 * to the original user ID before opening a capture file and
2460 * then switch back to the -Z user ID after opening the savefile.
2461 * Switching to the -Z user ID only after opening the first
2462 * savefile doesn't handle the general case.
2465 if (getuid() == 0 || geteuid() == 0) {
2466 #ifdef HAVE_LIBCAP_NG
2467 /* Initialize capng */
2468 capng_clear(CAPNG_SELECT_BOTH
);
2470 DIAG_OFF_ASSIGN_ENUM
2473 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2480 DIAG_OFF_ASSIGN_ENUM
2483 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2490 DIAG_OFF_ASSIGN_ENUM
2493 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2498 capng_apply(CAPNG_SELECT_BOTH
);
2499 #endif /* HAVE_LIBCAP_NG */
2500 if (username
|| chroot_dir
)
2501 droproot(username
, chroot_dir
);
2506 if (pcap_setfilter(pd
, &fcode
) < 0)
2507 error("%s", pcap_geterr(pd
));
2508 #ifdef HAVE_CAPSICUM
2509 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2510 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2513 * The various libpcap devices use a combination of
2514 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2515 * so we add the relevant access rights.
2517 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2518 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2520 error("unable to limit pcap descriptor");
2522 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2523 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2524 error("unable to limit ioctls on pcap descriptor");
2529 /* Do not exceed the default PATH_MAX for files. */
2530 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2532 if (dumpinfo
.CurrentFileName
== NULL
)
2533 error("malloc of dumpinfo.CurrentFileName");
2535 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2537 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2539 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2541 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2542 #ifdef HAVE_LIBCAP_NG
2543 /* Give up CAP_DAC_OVERRIDE capability.
2544 * Only allow it to be restored if the -C or -G flag have been
2545 * set since we may need to create more files later on.
2549 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2553 capng_apply(CAPNG_SELECT_BOTH
);
2554 #endif /* HAVE_LIBCAP_NG */
2556 error("%s", pcap_geterr(pd
));
2557 #ifdef HAVE_CAPSICUM
2558 set_dumper_capsicum_rights(pdd
);
2560 if (Cflag
!= 0 || Gflag
!= 0) {
2561 #ifdef HAVE_CAPSICUM
2563 * basename() and dirname() may modify their input buffer
2564 * and they do since FreeBSD 12.0, but they didn't before.
2565 * Hence use the return value only, but always assume the
2566 * input buffer has been modified and would need to be
2567 * reset before the next use.
2569 char *WFileName_copy
;
2571 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2572 error("Unable to allocate memory for file %s",
2575 DIAG_OFF_C11_EXTENSIONS
2576 dumpinfo
.WFileName
= strdup(basename(WFileName_copy
));
2577 DIAG_ON_C11_EXTENSIONS
2578 if (dumpinfo
.WFileName
== NULL
) {
2579 error("Unable to allocate memory for file %s",
2582 free(WFileName_copy
);
2584 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2585 error("Unable to allocate memory for file %s",
2588 DIAG_OFF_C11_EXTENSIONS
2589 char *WFileName_dirname
= dirname(WFileName_copy
);
2590 DIAG_ON_C11_EXTENSIONS
2591 dumpinfo
.dirfd
= open(WFileName_dirname
,
2592 O_DIRECTORY
| O_RDONLY
);
2593 if (dumpinfo
.dirfd
< 0) {
2594 error("unable to open directory %s",
2597 free(WFileName_dirname
);
2598 free(WFileName_copy
);
2600 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2601 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2602 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2604 error("unable to limit directory rights");
2606 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2608 error("unable to limit dump descriptor fcntls");
2610 #else /* !HAVE_CAPSICUM */
2611 dumpinfo
.WFileName
= WFileName
;
2613 callback
= dump_packet_and_trunc
;
2616 pcap_userdata
= (u_char
*)&dumpinfo
;
2618 callback
= dump_packet
;
2619 dumpinfo
.WFileName
= WFileName
;
2622 pcap_userdata
= (u_char
*)&dumpinfo
;
2625 dlt
= pcap_datalink(pd
);
2626 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2629 dumpinfo
.ndo
= NULL
;
2632 pcap_dump_flush(pdd
);
2634 dlt
= pcap_datalink(pd
);
2635 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2636 callback
= print_packet
;
2637 pcap_userdata
= (u_char
*)ndo
;
2640 #ifdef SIGNAL_REQ_INFO
2642 * We can't get statistics when reading from a file rather
2643 * than capturing from a device.
2645 if (RFileName
== NULL
)
2646 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2648 #ifdef SIGNAL_FLUSH_PCAP
2649 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2652 if (ndo
->ndo_vflag
> 0 && WFileName
&& RFileName
== NULL
&& !print
) {
2654 * When capturing to a file, if "--print" wasn't specified,
2655 *"-v" means tcpdump should, once per second,
2656 * "v"erbosely report the number of packets captured.
2657 * Except when reading from a file, because -r, -w and -v
2658 * together used to make a corner case, in which pcap_loop()
2659 * errored due to EINTR (see GH #155 for details).
2663 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2665 * suggests that this dates back to W2K.
2667 * I don't know what a "long wait" is, but we'll assume
2668 * that printing the stats could be a "long wait".
2670 CreateTimerQueueTimer(&timer_handle
, NULL
,
2671 verbose_stats_dump
, NULL
, 1000, 1000,
2672 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2673 setvbuf(stderr
, NULL
, _IONBF
, 0);
2676 * Assume this is UN*X, and that it has setitimer(); that
2677 * dates back to UNIX 95.
2679 struct itimerval timer
;
2680 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2681 timer
.it_interval
.tv_sec
= 1;
2682 timer
.it_interval
.tv_usec
= 0;
2683 timer
.it_value
.tv_sec
= 1;
2684 timer
.it_value
.tv_usec
= 1;
2685 setitimer(ITIMER_REAL
, &timer
, NULL
);
2689 if (RFileName
== NULL
) {
2691 * Live capture (if -V was specified, we set RFileName
2692 * to a file from the -V file). Print a message to
2693 * the standard error on UN*X.
2695 if (!ndo
->ndo_vflag
&& !WFileName
) {
2696 (void)fprintf(stderr
,
2697 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2700 (void)fprintf(stderr
, "%s: ", program_name
);
2701 dlt
= pcap_datalink(pd
);
2702 dlt_name
= pcap_datalink_val_to_name(dlt
);
2703 (void)fprintf(stderr
, "listening on %s", device
);
2704 if (dlt_name
== NULL
) {
2705 (void)fprintf(stderr
, ", link-type %u", dlt
);
2707 (void)fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2708 pcap_datalink_val_to_description(dlt
));
2710 (void)fprintf(stderr
, ", snapshot length %d bytes\n", ndo
->ndo_snaplen
);
2711 (void)fflush(stderr
);
2714 #ifdef HAVE_CAPSICUM
2715 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2717 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2719 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2720 #endif /* HAVE_CASPER */
2721 cansandbox
= (cansandbox
&& (pcap_fileno(pd
) != -1 ||
2722 RFileName
!= NULL
));
2724 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2725 error("unable to enter the capability mode");
2726 #endif /* HAVE_CAPSICUM */
2729 status
= pcap_loop(pd
,
2730 (cnt
== -1 ? -1 : cnt
+ (int)packets_to_skip
),
2731 callback
, pcap_userdata
);
2732 if (WFileName
== NULL
) {
2734 * We're printing packets. Flush the printed output,
2735 * so it doesn't get intermingled with error output.
2739 * We got interrupted, so perhaps we didn't
2740 * manage to finish a line we were printing.
2741 * Print an extra newline, just in case.
2745 (void)fflush(stdout
);
2749 * We got interrupted. If we are reading multiple
2750 * files (via -V) set these so that we stop.
2759 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2760 program_name
, pcap_geterr(pd
));
2762 if (RFileName
== NULL
) {
2764 * We're doing a live capture. Report the capture
2770 if (VFileName
!= NULL
) {
2771 ret
= get_next_file(VFile
, VFileLine
);
2775 RFileName
= VFileLine
;
2776 pd
= pcap_open_offline(RFileName
, ebuf
);
2779 #ifdef HAVE_CAPSICUM
2780 cap_rights_init(&rights
, CAP_READ
);
2781 if (cap_rights_limit(fileno(pcap_file(pd
)),
2782 &rights
) < 0 && errno
!= ENOSYS
) {
2783 error("unable to limit pcap descriptor");
2786 new_dlt
= pcap_datalink(pd
);
2787 if (new_dlt
!= dlt
) {
2789 * The new file has a different
2790 * link-layer header type from the
2793 if (WFileName
!= NULL
) {
2795 * We're writing raw packets
2796 * that match the filter to
2797 * a pcap file. pcap files
2798 * don't support multiple
2799 * different link-layer
2800 * header types, so we fail
2803 error("%s: new dlt does not match original", RFileName
);
2807 * We're printing the decoded packets;
2808 * switch to the new DLT.
2810 * To do that, we need to change
2811 * the printer, change the DLT name,
2812 * and recompile the filter with
2816 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2817 /* Free the old filter */
2818 pcap_freecode(&fcode
);
2820 * netmask is in network byte order, pcap_compile() takes it
2821 * in host byte order.
2823 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, ntohl(netmask
)) < 0)
2824 error("%s", pcap_geterr(pd
));
2828 * Set the filter on the new file.
2830 if (pcap_setfilter(pd
, &fcode
) < 0)
2831 error("%s", pcap_geterr(pd
));
2834 * Report the new file.
2836 dlt_name
= pcap_datalink_val_to_name(dlt
);
2837 fprintf(stderr
, "reading from file %s", RFileName
);
2838 if (dlt_name
== NULL
) {
2839 fprintf(stderr
, ", link-type %u", dlt
);
2841 fprintf(stderr
, ", link-type %s (%s)",
2843 pcap_datalink_val_to_description(dlt
));
2845 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2849 while (ret
!= NULL
);
2851 if (count_mode
&& RFileName
!= NULL
)
2852 fprintf(stdout
, "%u packet%s\n", packets_captured
,
2853 PLURAL_SUFFIX(packets_captured
));
2856 pcap_freecode(&fcode
);
2857 exit_tcpdump(status
== -1 ? S_ERR_HOST_PROGRAM
: S_SUCCESS
);
2861 * Routines to parse numerical command-line arguments and check for
2862 * errors, including "too large for that type".
2865 parse_int(const char *argname
, const char *string
, char **endpp
,
2866 int minval
, int maxval
, int base
)
2872 val
= strtol(string
, &endp
, base
);
2875 * Did it either not parse any of the string, find extra stuff
2876 * at the end that the caller isn't interested in, or get
2877 * another parsing error?
2879 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2880 (val
== 0 && errno
== EINVAL
)) {
2881 error("invalid %s \"%s\" (not a valid number)", argname
,
2886 * Did it get a value that's out of range?
2888 if (((val
== LONG_MAX
|| val
== LONG_MIN
) && errno
== ERANGE
) ||
2889 val
< minval
|| val
> maxval
) {
2890 error("invalid %s %s (must be >= %d and <= %d)",
2891 argname
, string
, minval
, maxval
);
2895 * OK, it passes all the tests.
2903 parse_u_int(const char *argname
, const char *string
, char **endpp
,
2904 u_int minval
, u_int maxval
, int base
)
2912 * strtoul() does *NOT* report an error if the string
2913 * begins with a minus sign. We do.
2915 if (*string
== '-') {
2916 error("invalid %s \"%s\" (not a valid unsigned number)",
2920 val
= strtoul(string
, &endp
, base
);
2923 * Did it either not parse any of the string, find extra stuff
2924 * at the end that the caller isn't interested in, or get
2925 * another parsing error?
2927 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2928 (val
== 0 && errno
== EINVAL
)) {
2929 error("invalid %s \"%s\" (not a valid unsigned number)",
2934 * Did it get a value that's out of range?
2936 if ((val
== ULONG_MAX
&& errno
== ERANGE
) ||
2937 val
< minval
|| val
> maxval
) {
2938 error("invalid %s %s (must be >= %u and <= %u)",
2939 argname
, string
, minval
, maxval
);
2943 * OK, it passes all the tests.
2947 return ((u_int
)val
);
2951 parse_int64(const char *argname
, const char *string
, char **endpp
,
2952 int64_t minval
, int64_t maxval
, int base
)
2958 val
= strtoimax(string
, &endp
, base
);
2961 * Did it either not parse any of the string, find extra stuff
2962 * at the end that the caller isn't interested in, or get
2963 * another parsing error?
2965 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2966 (val
== 0 && errno
== EINVAL
)) {
2967 error("invalid %s \"%s\" (not a valid number)", argname
,
2972 * Did it get a value that's out of range?
2974 if (((val
== INTMAX_MAX
|| val
== INTMAX_MIN
) && errno
== ERANGE
) ||
2975 val
< minval
|| val
> maxval
) {
2976 error("invalid %s %s (must be >= %" PRId64
" and <= %" PRId64
")",
2977 argname
, string
, minval
, maxval
);
2981 * OK, it passes all the tests.
2985 return ((int64_t)val
);
2992 (*setsignal (int sig
, void (*func
)(int)))(int)
2995 return (signal(sig
, func
));
2997 struct sigaction old
, new;
2999 memset(&new, 0, sizeof(new));
3000 new.sa_handler
= func
;
3001 if ((sig
== SIGCHLD
)
3002 # ifdef SIGNAL_REQ_INFO
3003 || (sig
== SIGNAL_REQ_INFO
)
3005 # ifdef SIGNAL_FLUSH_PCAP
3006 || (sig
== SIGNAL_FLUSH_PCAP
)
3009 new.sa_flags
= SA_RESTART
;
3010 if (sigaction(sig
, &new, &old
) < 0)
3011 /* The same workaround as for SIG_DFL above. */
3013 DIAG_OFF_STRICT_PROTOTYPES
3014 #endif /* __illumos__ */
3017 DIAG_ON_STRICT_PROTOTYPES
3018 #endif /* __illumos__ */
3019 return (old
.sa_handler
);
3023 /* make a clean exit on interrupts */
3025 cleanup(int signo _U_
)
3028 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
3029 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
3030 CloseHandle(timer_handle
);
3031 timer_handle
= INVALID_HANDLE_VALUE
;
3034 struct itimerval timer
;
3036 timer
.it_interval
.tv_sec
= 0;
3037 timer
.it_interval
.tv_usec
= 0;
3038 timer
.it_value
.tv_sec
= 0;
3039 timer
.it_value
.tv_usec
= 0;
3040 setitimer(ITIMER_REAL
, &timer
, NULL
);
3044 * We have "pcap_breakloop()"; use it, so that we do as little
3045 * as possible in the signal handler (it's probably not safe
3046 * to do anything with standard I/O streams in a signal handler -
3047 * the ANSI C standard doesn't say it is).
3053 On windows, we do not use a fork, so we do not care less about
3054 waiting a child processes to die
3056 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3058 child_cleanup(int signo _U_
)
3060 while (waitpid(-1, NULL
, WNOHANG
) >= 0);
3062 #endif /* HAVE_FORK && HAVE_VFORK */
3067 struct pcap_stat stats
;
3070 * Older versions of libpcap didn't set ps_ifdrop on some
3071 * platforms; initialize it to 0 to handle that.
3073 stats
.ps_ifdrop
= 0;
3074 if (pcap_stats(pd
, &stats
) < 0) {
3075 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
3081 fprintf(stderr
, "%s: ", program_name
);
3083 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
3084 PLURAL_SUFFIX(packets_captured
));
3086 fputs(", ", stderr
);
3089 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
3090 PLURAL_SUFFIX(stats
.ps_recv
));
3092 fputs(", ", stderr
);
3095 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
3096 PLURAL_SUFFIX(stats
.ps_drop
));
3097 if (stats
.ps_ifdrop
!= 0) {
3099 fputs(", ", stderr
);
3102 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
3103 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
3109 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3111 #define fork_subprocess() fork()
3113 #define fork_subprocess() vfork()
3116 compress_savefile(const char *filename
)
3120 child
= fork_subprocess();
3123 "%s: fork failed: %s\n",
3124 __func__
, pcap_strerror(errno
));
3128 /* Parent process. */
3134 * Set to lowest priority so that this doesn't disturb the capture.
3137 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
3139 setpriority(PRIO_PROCESS
, 0, 19);
3141 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
3143 "%s: execlp(%s, %s) failed: %s\n",
3144 __func__
, zflag
, filename
, pcap_strerror(errno
));
3146 exit(S_ERR_HOST_PROGRAM
);
3148 _exit(S_ERR_HOST_PROGRAM
);
3151 #endif /* HAVE_FORK || HAVE_VFORK */
3154 close_old_dump_file(struct dump_info
*dump_info
)
3157 * Close the current file and open a new one.
3159 pcap_dump_close(dump_info
->pdd
);
3161 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3163 * Compress the file we just closed, if the user asked for it.
3166 compress_savefile(dump_info
->CurrentFileName
);
3171 open_new_dump_file(struct dump_info
*dump_info
)
3173 #ifdef HAVE_CAPSICUM
3178 #ifdef HAVE_LIBCAP_NG
3179 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3180 capng_apply(CAPNG_SELECT_BOTH
);
3181 #endif /* HAVE_LIBCAP_NG */
3182 #ifdef HAVE_CAPSICUM
3183 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
3184 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
3186 error("unable to open file %s", dump_info
->CurrentFileName
);
3188 fp
= fdopen(fd
, "w");
3190 error("unable to fdopen file %s", dump_info
->CurrentFileName
);
3192 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
3193 #else /* !HAVE_CAPSICUM */
3194 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
3196 #ifdef HAVE_LIBCAP_NG
3197 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3198 capng_apply(CAPNG_SELECT_BOTH
);
3199 #endif /* HAVE_LIBCAP_NG */
3200 if (dump_info
->pdd
== NULL
)
3201 error("%s", pcap_geterr(pd
));
3202 #ifdef HAVE_CAPSICUM
3203 set_dumper_capsicum_rights(dump_info
->pdd
);
3208 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3210 struct dump_info
*dump_info
;
3216 dump_info
= (struct dump_info
*)user
;
3218 if (packets_captured
<= packets_to_skip
)
3222 * XXX - this won't force the file to rotate on the specified time
3223 * boundary, but it will rotate on the first packet received after the
3224 * specified Gflag number of seconds. Note: if a Gflag time boundary
3225 * and a Cflag size boundary coincide, the time rotation will occur
3226 * first thereby cancelling the Cflag boundary (since the file should
3230 /* Check if it is time to rotate */
3233 /* Get the current time */
3234 if ((t
= time(NULL
)) == (time_t)-1) {
3235 error("%s: can't get current_time: %s",
3236 __func__
, pcap_strerror(errno
));
3240 /* If the time is greater than the specified window, rotate */
3241 if (t
- Gflag_time
>= Gflag
) {
3242 /* Update the Gflag_time */
3244 /* Update Gflag_count */
3247 close_old_dump_file(dump_info
);
3250 * Check to see if we've exceeded the Wflag (when
3253 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
3254 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
3257 exit_tcpdump(S_SUCCESS
);
3260 if (dump_info
->CurrentFileName
!= NULL
)
3261 free(dump_info
->CurrentFileName
);
3262 /* Allocate space for max filename + \0. */
3263 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
3264 if (dump_info
->CurrentFileName
== NULL
)
3265 error("dump_packet_and_trunc: malloc");
3267 * Gflag was set otherwise we wouldn't be here. Reset the count
3268 * so multiple files would end with 1,2,3 in the filename.
3269 * The counting is handled with the -C flow after this.
3274 * This is always the first file in the Cflag
3276 * We also don't need numbering if Cflag is not set.
3279 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
3282 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
3284 open_new_dump_file(dump_info
);
3289 * XXX - this won't prevent capture files from getting
3290 * larger than Cflag - the last packet written to the
3291 * file could put it over Cflag.
3294 #ifdef HAVE_PCAP_DUMP_FTELL64
3295 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
3298 * XXX - this only handles a Cflag value > 2^31-1 on
3299 * LP64 platforms; to handle ILP32 (32-bit UN*X and
3300 * Windows) or LLP64 (64-bit Windows) would require
3301 * a version of libpcap with pcap_dump_ftell64().
3303 long size
= pcap_dump_ftell(dump_info
->pdd
);
3307 error("ftell fails on output file");
3309 close_old_dump_file(dump_info
);
3313 if (Cflag_count
>= Wflag
)
3316 if (dump_info
->CurrentFileName
!= NULL
)
3317 free(dump_info
->CurrentFileName
);
3318 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
3319 if (dump_info
->CurrentFileName
== NULL
)
3320 error("%s: malloc", __func__
);
3321 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
3323 open_new_dump_file(dump_info
);
3327 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3329 pcap_dump_flush(dump_info
->pdd
);
3331 if (dump_info
->ndo
!= NULL
)
3332 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3340 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3342 struct dump_info
*dump_info
;
3348 dump_info
= (struct dump_info
*)user
;
3350 if (packets_captured
<= packets_to_skip
)
3353 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3355 pcap_dump_flush(dump_info
->pdd
);
3357 if (dump_info
->ndo
!= NULL
)
3358 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3366 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3372 if (!count_mode
&& packets_captured
> packets_to_skip
)
3373 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
3380 #ifdef SIGNAL_REQ_INFO
3382 requestinfo(int signo _U_
)
3391 #ifdef SIGNAL_FLUSH_PCAP
3393 flushpcap(int signo _U_
)
3396 pcap_dump_flush(pdd
);
3401 print_packets_captured (void)
3403 static u_int prev_packets_captured
, first
= 1;
3405 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
3406 fprintf(stderr
, "Got %u\r", packets_captured
);
3408 prev_packets_captured
= packets_captured
;
3413 * Called once each second in verbose mode while dumping to file
3416 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
3417 BOOLEAN timer_fired _U_
)
3419 print_packets_captured();
3422 static void verbose_stats_dump(int sig _U_
)
3424 print_packets_captured();
3428 DIAG_OFF_DEPRECATION
3430 print_version(FILE *f
)
3432 const char *smi_version_string
;
3434 (void)fprintf(f
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3435 (void)fprintf(f
, "%s\n", pcap_lib_version());
3437 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3438 (void)fprintf (f
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3441 smi_version_string
= nd_smi_version_string();
3442 if (smi_version_string
!= NULL
)
3443 (void)fprintf (f
, "SMI-library: %s\n", smi_version_string
);
3445 #if defined(__SANITIZE_ADDRESS__)
3446 (void)fprintf (f
, "Compiled with AddressSanitizer/GCC.\n");
3447 #elif defined(__has_feature)
3448 # if __has_feature(address_sanitizer)
3449 (void)fprintf (f
, "Compiled with AddressSanitizer/Clang.\n");
3450 # elif __has_feature(memory_sanitizer)
3451 (void)fprintf (f
, "Compiled with MemorySanitizer/Clang.\n");
3453 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3454 (void)fprintf (f
, "%zu-bit build, %zu-bit time_t\n",
3455 sizeof(void *) * 8, sizeof(time_t) * 8);
3460 print_usage(FILE *f
)
3464 "Usage: %s [-AbdDefhHI" J_FLAG
"KlLnNOpqStuUvxX#] [ -B size ] [ -c count ] [--count]\n", program_name
);
3466 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3468 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3470 "\t\t[ --lengths ]" LIST_REMOTE_INTERFACES_USAGE
"\n");
3473 "\t\t" m_FLAG_USAGE
"\n");
3476 "\t\t[ -M secret ] [ --number ] [ --print ]\n");
3478 "\t\t[ --print-sampling nth ] [ -Q in|out|inout ] [ -r file ]\n");
3480 "\t\t[ -s snaplen ] [ --skip count ] [ -T type ] [ --version ]\n");
3482 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3483 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3485 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3488 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");