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.h"
144 #include "interface.h"
145 #include "addrtoname.h"
146 #include "ascii_strcasecmp.h"
150 #include "diag-control.h"
155 #define PATH_MAX 1024
159 #define SIGNAL_REQ_INFO SIGINFO
160 #elif defined(SIGUSR1)
161 #define SIGNAL_REQ_INFO SIGUSR1
165 #define SIGNAL_FLUSH_PCAP SIGUSR2
168 static int Bflag
; /* buffer size */
169 static int64_t Cflag
; /* rotate dump files after this many bytes */
170 static int Cflag_count
; /* Keep track of which file number we're writing */
171 static int Dflag
; /* list available devices and exit */
172 #ifdef HAVE_PCAP_FINDALLDEVS_EX
173 static char *remote_interfaces_source
; /* list available devices from this source and exit */
177 * This is exported because, in some versions of libpcap, if libpcap
178 * is built with optimizer debugging code (which is *NOT* the default
179 * configuration!), the library *imports*(!) a variable named dflag,
180 * under the expectation that tcpdump is exporting it, to govern
181 * how much debugging information to print when optimizing
182 * the generated BPF code.
184 * This is a horrible hack; newer versions of libpcap don't import
185 * dflag but, instead, *if* built with optimizer debugging code,
186 * *export* a routine to set that flag.
189 int dflag
; /* print filter code */
190 static int Gflag
; /* rotate dump files after this many seconds */
191 static int Gflag_count
; /* number of files created with Gflag rotation */
192 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
193 static int Lflag
; /* list available data link types and exit */
194 static int Iflag
; /* rfmon (monitor) mode */
195 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
196 static int Jflag
; /* list available time stamp types */
197 static int jflag
= -1; /* packet time stamp source */
199 static int lflag
; /* line-buffered output */
200 static int pflag
; /* don't go promiscuous */
201 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
202 static int Uflag
; /* "unbuffered" output of dump files */
203 static int Wflag
; /* recycle output files after this number of files */
204 static int WflagChars
;
205 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
206 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
208 static int timeout
= 1000; /* default timeout = 1000 ms = 1 s */
209 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
210 static int immediate_mode
;
212 static int count_mode
;
213 static u_int packets_to_skip
;
215 static int infodelay
;
216 static int infoprint
;
221 static int parse_int(const char *argname
, const char *string
, char **endp
,
222 int minval
, int maxval
, int base
);
223 static u_int
parse_u_int(const char *argname
, const char *string
, char **endp
,
224 u_int minval
, u_int maxval
, int base
);
225 static int64_t parse_int64(const char *argname
, const char *string
,
226 char **endp
, int64_t minval
, int64_t maxval
, int base
);
227 static void (*setsignal (int sig
, void (*func
)(int)))(int);
228 static void cleanup(int);
229 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
230 static void child_cleanup(int);
232 static void print_version(FILE *);
233 static void print_usage(FILE *);
235 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
236 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
237 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
239 #ifdef SIGNAL_REQ_INFO
240 static void requestinfo(int);
243 #ifdef SIGNAL_FLUSH_PCAP
244 static void flushpcap(int);
248 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
249 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
251 static void verbose_stats_dump(int sig
);
254 static void info(int);
255 static u_int packets_captured
;
257 static const struct tok status_flags
[] = {
259 { PCAP_IF_UP
, "Up" },
261 #ifdef PCAP_IF_RUNNING
262 { PCAP_IF_RUNNING
, "Running" },
264 { PCAP_IF_LOOPBACK
, "Loopback" },
265 #ifdef PCAP_IF_WIRELESS
266 { PCAP_IF_WIRELESS
, "Wireless" },
272 static pcap_dumper_t
*pdd
= NULL
;
274 static int supports_monitor_mode
;
282 char *CurrentFileName
;
285 netdissect_options
*ndo
;
291 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
293 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
294 * by any libpcap header, because it's a special hack, only available if
295 * libpcap was configured to include it, and only intended for use by
296 * libpcap developers trying to debug the parser for filter expressions).
299 __declspec(dllimport
)
303 void pcap_set_parser_debug(int);
304 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
306 * We don't have pcap_set_parser_debug() in libpcap, but we do have
307 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
308 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
311 pcap_set_parser_debug(int value
)
313 #ifdef HAVE_PCAP_DEBUG
314 extern int pcap_debug
;
317 #else /* HAVE_PCAP_DEBUG */
321 #endif /* HAVE_PCAP_DEBUG */
324 #define HAVE_PCAP_SET_PARSER_DEBUG
325 #endif // HAVE_PCAP_SET_PARSER_DEBUG, HAVE_PCAP_DEBUG, HAVE_YYDEBUG
327 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
329 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
330 * by any libpcap header, because it's a special hack, only available if
331 * libpcap was configured to include it, and only intended for use by
332 * libpcap developers trying to debug the optimizer for filter expressions).
335 __declspec(dllimport
)
339 void pcap_set_optimizer_debug(int);
340 #endif // HAVE_PCAP_SET_OPTIMIZER_DEBUG
343 exit_tcpdump(const int status
)
350 static void NORETURN
PRINTFLIKE(1, 2)
351 error(FORMAT_STRING(const char *fmt
), ...)
355 (void)fprintf(stderr
, "%s: ", program_name
);
357 (void)vfprintf(stderr
, fmt
, ap
);
362 (void)fputc('\n', stderr
);
364 exit_tcpdump(S_ERR_HOST_PROGRAM
);
369 static void PRINTFLIKE(1, 2)
370 warning(FORMAT_STRING(const char *fmt
), ...)
374 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
376 (void)vfprintf(stderr
, fmt
, ap
);
381 (void)fputc('\n', stderr
);
385 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
387 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
390 int *tstamp_types
= 0;
391 const char *tstamp_type_name
;
394 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
395 if (n_tstamp_types
< 0)
396 error("%s", pcap_geterr(pc
));
398 if (n_tstamp_types
== 0) {
399 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
401 exit_tcpdump(S_SUCCESS
);
403 fprintf(stdout
, "Time stamp types for %s (use option -j to set):\n",
405 for (i
= 0; i
< n_tstamp_types
; i
++) {
406 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
407 if (tstamp_type_name
!= NULL
) {
408 (void) fprintf(stdout
, " %s (%s)\n", tstamp_type_name
,
409 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
411 (void) fprintf(stdout
, " %d\n", tstamp_types
[i
]);
414 pcap_free_tstamp_types(tstamp_types
);
415 exit_tcpdump(S_SUCCESS
);
417 #endif // HAVE_PCAP_SET_TSTAMP_TYPE
420 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
424 const char *dlt_name
;
426 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
428 error("%s", pcap_geterr(pc
));
429 else if (n_dlts
== 0 || !dlts
)
430 error("No data link types.");
433 * If the interface is known to support monitor mode, indicate
434 * whether these are the data link types available when not in
435 * monitor mode, if -I wasn't specified, or when in monitor mode,
436 * when -I was specified (the link-layer types available in
437 * monitor mode might be different from the ones available when
438 * not in monitor mode).
440 (void) fprintf(stdout
, "Data link types for ");
441 if (supports_monitor_mode
)
442 (void) fprintf(stdout
, "%s %s",
444 Iflag
? "when in monitor mode" : "when not in monitor mode");
446 (void) fprintf(stdout
, "%s",
448 (void) fprintf(stdout
, " (use option -y to set):\n");
450 for (i
= 0; i
< n_dlts
; i
++) {
451 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
452 if (dlt_name
!= NULL
) {
453 (void) fprintf(stdout
, " %s (%s)", dlt_name
,
454 pcap_datalink_val_to_description(dlts
[i
]));
457 * OK, does tcpdump handle that type?
459 if (!has_printer(dlts
[i
]))
460 (void) fprintf(stdout
, " (printing not supported)");
461 fprintf(stdout
, "\n");
463 (void) fprintf(stdout
, " DLT %d (printing not supported)\n",
467 pcap_free_datalinks(dlts
);
468 exit_tcpdump(S_SUCCESS
);
472 show_devices_and_exit(void)
474 pcap_if_t
*dev
, *devlist
;
475 char ebuf
[PCAP_ERRBUF_SIZE
];
478 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
480 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
481 printf("%d.%s", i
+1, dev
->name
);
482 if (dev
->description
!= NULL
)
483 printf(" (%s)", dev
->description
);
484 if (dev
->flags
!= 0) {
486 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
487 #ifdef PCAP_IF_WIRELESS
488 if (dev
->flags
& PCAP_IF_WIRELESS
) {
489 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
491 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
492 printf(", Association status unknown");
495 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
496 printf(", Associated");
499 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
500 printf(", Not associated");
503 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
507 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
509 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
510 printf(", Connection status unknown");
513 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
514 printf(", Connected");
517 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
518 printf(", Disconnected");
521 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
525 #endif // PCAP_IF_WIRELESS
530 pcap_freealldevs(devlist
);
531 exit_tcpdump(S_SUCCESS
);
534 #ifdef HAVE_PCAP_FINDALLDEVS_EX
536 show_remote_devices_and_exit(void)
538 pcap_if_t
*dev
, *devlist
;
539 char ebuf
[PCAP_ERRBUF_SIZE
];
542 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
544 if (strcmp(ebuf
, "not supported") == 0) {
546 * macOS 14's pcap_findalldevs_ex(), which is a
547 * stub that always returns -1 with an error
548 * message of "not supported".
550 * In this case, as we passed it an rpcap://
551 * URL, treat that as meaning "remote capture
554 error("Remote capture not supported");
558 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
559 printf("%d.%s", i
+1, dev
->name
);
560 if (dev
->description
!= NULL
)
561 printf(" (%s)", dev
->description
);
563 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
566 pcap_freealldevs(devlist
);
567 exit_tcpdump(S_SUCCESS
);
569 #endif /* HAVE_PCAP_FINDALLDEVS_EX */
574 * Note that there we use all letters for short options except for g, k,
575 * o, and P, and those are used by other versions of tcpdump, and we should
576 * only use them for the same purposes that the other versions of tcpdump
579 * macOS tcpdump uses -g to force non--v output for IP to be on one
580 * line, making it more "g"repable;
582 * macOS tcpdump uses -k to specify that packet comments in pcapng files
585 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
586 * for hosts sending TCP SYN packets;
588 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
591 * macOS tcpdump also uses -Q to specify expressions that match packet
592 * metadata, including but not limited to the packet direction.
593 * The expression syntax is different from a simple "in|out|inout",
594 * and those expressions aren't accepted by macOS tcpdump, but the
595 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
596 * "inout" = "dir=in or dir=out", and the parser could conceivably
597 * special-case "in", "out", and "inout" as expressions for backwards
598 * compatibility, so all is not (yet) lost.
602 * Set up flags that might or might not be supported depending on the
603 * version of libpcap we're using.
605 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
607 #define j_FLAG_USAGE " [ -j tstamptype ]"
609 #else /* HAVE_PCAP_SET_TSTAMP_TYPE */
613 #endif /* HAVE_PCAP_SET_TSTAMP_TYPE */
616 #define m_FLAG_USAGE "[ -m module ] ..."
619 #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:#"
624 * We do not currently have long options corresponding to all short
625 * options; we should probably pick appropriate option names for them.
627 * However, the short options where the number of times the option is
628 * specified matters, such as -v and -d and -t, should probably not
629 * just map to a long option, as saying
631 * tcpdump --verbose --verbose
633 * doesn't make sense; it should be --verbosity={N} or something such
636 * For long options with no corresponding short options, we define values
637 * outside the range of ASCII graphic characters, make that the last
638 * component of the entry for the long option, and have a case for that
639 * option in the switch statement.
641 #define OPTION_VERSION 128
642 #define OPTION_TSTAMP_PRECISION 129
643 #define OPTION_IMMEDIATE_MODE 130
644 #define OPTION_PRINT 131
645 #define OPTION_LIST_REMOTE_INTERFACES 132
646 #define OPTION_TSTAMP_MICRO 133
647 #define OPTION_TSTAMP_NANO 134
648 #define OPTION_FP_TYPE 135
649 #define OPTION_COUNT 136
650 #define OPTION_PRINT_SAMPLING 137
651 #define OPTION_LENGTHS 138
652 #define OPTION_TIME_T_SIZE 139
653 #define OPTION_SKIP 140
655 static const struct option longopts
[] = {
656 { "buffer-size", required_argument
, NULL
, 'B' },
657 { "list-interfaces", no_argument
, NULL
, 'D' },
658 #ifdef HAVE_PCAP_FINDALLDEVS_EX
659 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
661 { "help", no_argument
, NULL
, 'h' },
662 { "interface", required_argument
, NULL
, 'i' },
663 { "monitor-mode", no_argument
, NULL
, 'I' },
664 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
665 { "time-stamp-type", required_argument
, NULL
, 'j' },
666 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
668 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
669 { "micro", no_argument
, NULL
, OPTION_TSTAMP_MICRO
},
670 { "nano", no_argument
, NULL
, OPTION_TSTAMP_NANO
},
671 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
673 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
674 { "list-data-link-types", no_argument
, NULL
, 'L' },
675 { "no-optimize", no_argument
, NULL
, 'O' },
676 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
677 { "direction", required_argument
, NULL
, 'Q' },
678 { "snapshot-length", required_argument
, NULL
, 's' },
679 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
680 { "packet-buffered", no_argument
, NULL
, 'U' },
681 { "linktype", required_argument
, NULL
, 'y' },
682 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
683 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
685 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
686 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
688 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
689 { "count", no_argument
, NULL
, OPTION_COUNT
},
690 { "fp-type", no_argument
, NULL
, OPTION_FP_TYPE
},
691 { "number", no_argument
, NULL
, '#' },
692 { "print", no_argument
, NULL
, OPTION_PRINT
},
693 { "print-sampling", required_argument
, NULL
, OPTION_PRINT_SAMPLING
},
694 { "lengths", no_argument
, NULL
, OPTION_LENGTHS
},
695 { "time-t-size", no_argument
, NULL
, OPTION_TIME_T_SIZE
},
696 { "skip", required_argument
, NULL
, OPTION_SKIP
},
697 { "version", no_argument
, NULL
, OPTION_VERSION
},
701 #ifdef HAVE_PCAP_FINDALLDEVS_EX
702 #define LIST_REMOTE_INTERFACES_USAGE " [ --list-remote-interfaces remote-source ]"
704 #define LIST_REMOTE_INTERFACES_USAGE
707 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
708 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
710 #define IMMEDIATE_MODE_USAGE ""
714 /* Drop root privileges and chroot if necessary */
716 droproot(const char *username
, const char *chroot_dir
)
718 struct passwd
*pw
= NULL
;
720 if (chroot_dir
&& !username
)
721 error("Chroot without dropping root is insecure");
723 pw
= getpwnam(username
);
726 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
727 error("Couldn't chroot/chdir to '%.64s': %s",
728 chroot_dir
, pcap_strerror(errno
));
730 #ifdef HAVE_LIBCAP_NG
732 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
734 error("capng_change_id(): return %d", ret
);
736 fprintf(stderr
, "dropped privs to %s\n", username
);
739 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
740 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
741 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
743 (unsigned long)pw
->pw_uid
,
744 (unsigned long)pw
->pw_gid
,
745 pcap_strerror(errno
));
747 fprintf(stderr
, "dropped privs to %s\n", username
);
749 #endif /* HAVE_LIBCAP_NG */
751 error("Couldn't find user '%.32s'", username
);
752 #ifdef HAVE_LIBCAP_NG
753 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT anymore. */
757 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
763 capng_apply(CAPNG_SELECT_BOTH
);
764 #endif /* HAVE_LIBCAP_NG */
785 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
787 char *filename
= malloc(PATH_MAX
+ 1);
788 if (filename
== NULL
)
789 error("%s: malloc", __func__
);
790 if (strlen(orig_name
) == 0)
791 error("an empty string is not a valid file name");
793 /* Process with strftime if Gflag is set. */
797 /* Convert Gflag_time to a usable format */
798 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
799 error("%s: localtime", __func__
);
802 /* There's no good way to detect an error in strftime since a return
803 * value of 0 isn't necessarily failure; if orig_name is an empty
804 * string, the formatted string will be empty.
806 * However, the C90 standard says that, if there *is* a
807 * buffer overflow, the content of the buffer is undefined,
808 * so we must check for a buffer overflow.
810 * So we check above for an empty orig_name, and only call
811 * strftime() if it's non-empty, in which case the return
812 * value will only be 0 if the formatted date doesn't fit
815 * (We check above because, even if we don't use -G, we
816 * want a better error message than "tcpdump: : No such
817 * file or directory" for this case.)
819 if (strftime(filename
, PATH_MAX
, orig_name
, local_tm
) == 0) {
820 error("%s: strftime", __func__
);
823 strncpy(filename
, orig_name
, PATH_MAX
);
826 if (cnt
== 0 && max_chars
== 0)
827 strncpy(buffer
, filename
, PATH_MAX
+ 1);
829 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
830 /* Report an error if the filename is too large */
831 error("too many output files or filename is too long (> %d)", PATH_MAX
);
836 get_next_file(FILE *VFile
, char *ptr
)
841 ret
= fgets(ptr
, PATH_MAX
, VFile
);
846 if (len
> 0 && ptr
[len
- 1] == '\n')
853 static cap_channel_t
*
856 cap_channel_t
*capcas
, *capdnsloc
;
857 const char *types
[1];
862 error("unable to create casper process");
863 capdnsloc
= cap_service_open(capcas
, "system.dns");
864 /* Casper capability no longer needed. */
866 if (capdnsloc
== NULL
)
867 error("unable to open system.dns service");
868 /* Limit system.dns to reverse DNS lookups. */
870 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
871 error("unable to limit access to system.dns service");
872 families
[0] = AF_INET
;
873 /* Casper is a feature of FreeBSD, which defines AF_INET6. */
874 families
[1] = AF_INET6
;
875 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
876 error("unable to limit access to system.dns service");
880 #endif /* HAVE_CASPER */
882 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
884 tstamp_precision_from_string(const char *precision
)
886 if (strncmp(precision
, "nano", strlen("nano")) == 0)
887 return PCAP_TSTAMP_PRECISION_NANO
;
889 if (strncmp(precision
, "micro", strlen("micro")) == 0)
890 return PCAP_TSTAMP_PRECISION_MICRO
;
896 tstamp_precision_to_string(int precision
)
900 case PCAP_TSTAMP_PRECISION_MICRO
:
903 case PCAP_TSTAMP_PRECISION_NANO
:
910 #endif // HAVE_PCAP_SET_TSTAMP_PRECISION
914 * Ensure that, on a dump file's descriptor, we have all the rights
915 * necessary to make the standard I/O library work with an fdopen()ed
916 * FILE * from that descriptor.
918 * A long time ago in a galaxy far, far away, AT&T decided that, instead
919 * of providing separate APIs for getting and setting the FD_ flags on a
920 * descriptor, getting and setting the O_ flags on a descriptor, and
921 * locking files, they'd throw them all into a kitchen-sink fcntl() call
922 * along the lines of ioctl(), the fact that ioctl() operations are
923 * largely specific to particular character devices but fcntl() operations
924 * are either generic to all descriptors or generic to all descriptors for
925 * regular files notwithstanding.
927 * The Capsicum people decided that fine-grained control of descriptor
928 * operations was required, so that you need to grant permission for
929 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
930 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
931 * collection of things, so there are *individual* fcntls for which
932 * permission needs to be granted.
934 * The FreeBSD standard I/O people implemented some optimizations that
935 * requires that the standard I/O routines be able to determine whether
936 * the descriptor for the FILE * is open append-only or not; as that
937 * descriptor could have come from an open() rather than an fopen(),
938 * that requires that it be able to do an F_GETFL fcntl() to read
941 * tcpdump uses ftell() to determine how much data has been written
942 * to a file in order to, when used with -C, determine when it's time
943 * to rotate capture files. ftell() therefore needs to do an lseek()
944 * to find out the file offset and must, thanks to the aforementioned
945 * optimization, also know whether the descriptor is open append-only
948 * The net result of all the above is that we need to grant CAP_SEEK,
949 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
951 * Perhaps this is the universe's way of saying that either
953 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
954 * using it, so that Capsicum-capable tcpdump wouldn't need to do
959 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
960 * I/O library that knows what rights are needed by the standard
961 * I/O library, based on the open mode, and assigns them, perhaps
962 * with an additional argument indicating, for example, whether
963 * seeking should be allowed, so that tcpdump doesn't need to know
964 * what the standard I/O library happens to require this week.
967 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
969 int fd
= fileno(pcap_dump_file(p
));
972 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
973 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
974 error("unable to limit dump descriptor");
976 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
977 error("unable to limit dump descriptor fcntls");
980 #endif // HAVE_CAPSICUM
983 * Copy arg vector into a new buffer, concatenating arguments with spaces.
986 copy_argv(char **argv
)
998 len
+= strlen(*p
++) + 1;
1000 buf
= (char *)malloc(len
);
1002 error("%s: malloc", __func__
);
1006 while ((src
= *p
++) != NULL
) {
1007 while ((*dst
++ = *src
++) != '\0')
1017 * On Windows, we need to open the file in binary mode, so that
1018 * we get all the bytes specified by the size we get from "fstat()".
1019 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1020 * we define it as 0 if it's not defined, so it does nothing.
1027 read_infile(char *fname
)
1034 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1036 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1038 if (our_fstat(fd
, &buf
) < 0)
1039 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1042 * Reject files whose size doesn't fit into an int; a filter
1043 * *that* large will probably be too big.
1045 if (buf
.st_size
> INT_MAX
)
1046 error("%s is too large", fname
);
1048 cp
= malloc((u_int
)buf
.st_size
+ 1);
1050 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1051 fname
, pcap_strerror(errno
));
1052 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1054 error("read %s: %s", fname
, pcap_strerror(errno
));
1055 if (cc
!= buf
.st_size
)
1056 error("short read %s (%d != %d)", fname
, (int) cc
,
1060 /* replace "# comment" with spaces */
1061 for (i
= 0; i
< cc
; i
++) {
1063 while (i
< cc
&& cp
[i
] != '\n')
1071 parse_interface_number(const char *device
)
1078 * Search for a colon, terminating any scheme at the beginning
1081 p
= strchr(device
, ':');
1084 * We found it. Is it followed by "//"?
1086 p
++; /* skip the : */
1087 if (strncmp(p
, "//", 2) == 0) {
1089 * Yes. Search for the next /, at the end of the
1090 * authority part of the URL.
1092 p
+= 2; /* skip the // */
1096 * OK, past the / is the path.
1102 devnum
= strtol(device
, &end
, 10);
1103 if (device
!= end
&& *end
== '\0') {
1105 * It's all-numeric, but is it a valid number?
1109 * No, it's not an ordinal.
1111 error("Invalid adapter index %s", device
);
1116 * It's not all-numeric; return -1, so our caller
1124 find_interface_by_number(const char *url
1125 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1130 pcap_if_t
*dev
, *devlist
;
1132 char ebuf
[PCAP_ERRBUF_SIZE
];
1134 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1140 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1142 * Search for a colon, terminating any scheme at the beginning
1145 endp
= strchr(url
, ':');
1148 * We found it. Is it followed by "//"?
1150 endp
++; /* skip the : */
1151 if (strncmp(endp
, "//", 2) == 0) {
1153 * Yes. Search for the next /, at the end of the
1154 * authority part of the URL.
1156 endp
+= 2; /* skip the // */
1157 endp
= strchr(endp
, '/');
1163 * OK, everything from device to endp is a URL to hand
1164 * to pcap_findalldevs_ex().
1166 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1167 host_url
= malloc(endp
- url
+ 1);
1168 if (host_url
== NULL
&& (endp
- url
+ 1) > 0)
1169 error("Invalid allocation for host");
1171 memcpy(host_url
, url
, endp
- url
);
1172 host_url
[endp
- url
] = '\0';
1173 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1176 #endif // HAVE_PCAP_FINDALLDEVS_EX
1177 status
= pcap_findalldevs(&devlist
, ebuf
);
1181 * Look for the devnum-th entry in the list of devices (1-based).
1183 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1184 i
++, dev
= dev
->next
)
1187 pcap_freealldevs(devlist
);
1188 error("Invalid adapter index %ld: only %ld interfaces found",
1191 device
= strdup(dev
->name
);
1192 pcap_freealldevs(devlist
);
1196 #ifdef HAVE_PCAP_OPEN
1198 * Prefixes for rpcap URLs.
1200 static char rpcap_prefix
[] = "rpcap://";
1201 static char rpcap_ssl_prefix
[] = "rpcaps://";
1205 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1211 #ifdef HAVE_PCAP_OPEN
1213 * Is this an rpcap URL?
1215 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0 ||
1216 strncmp(device
, rpcap_ssl_prefix
, sizeof(rpcap_ssl_prefix
) - 1) == 0) {
1218 * Yes. Open it with pcap_open().
1221 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1222 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, timeout
, NULL
,
1226 * macOS 14's pcap_pcap_open(), which is a
1227 * stub that always returns NULL with an error
1228 * message of "not supported".
1230 * In this case, as we passed it an rpcap://
1231 * URL, treat that as meaning "remote capture
1234 if (strcmp(ebuf
, "not supported") == 0)
1235 error("Remote capture not supported");
1238 * If this failed with "No such device" or "The system
1239 * cannot find the device specified", that means
1240 * the interface doesn't exist; return NULL, so that
1241 * the caller can see whether the device name is
1242 * actually an interface index.
1244 if (strstr(ebuf
, "No such device") != NULL
||
1245 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1250 warning("%s", ebuf
);
1253 #endif /* HAVE_PCAP_OPEN */
1255 pc
= pcap_create(device
, ebuf
);
1258 * If this failed with "No such device", that means
1259 * the interface doesn't exist; return NULL, so that
1260 * the caller can see whether the device name is
1261 * actually an interface index.
1263 if (strstr(ebuf
, "No such device") != NULL
)
1267 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1269 show_tstamp_types_and_exit(pc
, device
);
1271 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1272 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1274 error("%s: Can't set %ssecond time stamp precision: %s",
1276 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1277 pcap_statustostr(status
));
1280 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1281 if (immediate_mode
) {
1282 status
= pcap_set_immediate_mode(pc
, 1);
1284 error("%s: Can't set immediate mode: %s",
1285 device
, pcap_statustostr(status
));
1289 * Is this an interface that supports monitor mode?
1291 if (pcap_can_set_rfmon(pc
) == 1)
1292 supports_monitor_mode
= 1;
1294 supports_monitor_mode
= 0;
1295 if (ndo
->ndo_snaplen
!= 0) {
1297 * A snapshot length was explicitly specified;
1300 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1302 error("%s: Can't set snapshot length: %s",
1303 device
, pcap_statustostr(status
));
1305 status
= pcap_set_promisc(pc
, !pflag
);
1307 error("%s: Can't set promiscuous mode: %s",
1308 device
, pcap_statustostr(status
));
1310 status
= pcap_set_rfmon(pc
, 1);
1312 error("%s: Can't set monitor mode: %s",
1313 device
, pcap_statustostr(status
));
1315 status
= pcap_set_timeout(pc
, timeout
);
1317 error("%s: pcap_set_timeout failed: %s",
1318 device
, pcap_statustostr(status
));
1320 status
= pcap_set_buffer_size(pc
, Bflag
);
1322 error("%s: Can't set buffer size: %s",
1323 device
, pcap_statustostr(status
));
1325 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1327 status
= pcap_set_tstamp_type(pc
, jflag
);
1329 error("%s: Can't set time stamp type: %s",
1330 device
, pcap_statustostr(status
));
1331 else if (status
> 0)
1332 warning("When trying to set timestamp type '%s' on %s: %s",
1333 pcap_tstamp_type_val_to_name(jflag
), device
,
1334 pcap_statustostr(status
));
1337 status
= pcap_activate(pc
);
1340 * pcap_activate() failed.
1342 cp
= pcap_geterr(pc
);
1343 if (status
== PCAP_ERROR
)
1345 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1347 * Return an error for our caller to handle.
1349 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1350 device
, pcap_statustostr(status
), cp
);
1351 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1352 error("%s: %s\n(%s)", device
,
1353 pcap_statustostr(status
), cp
);
1354 #ifdef PCAP_ERROR_CAPTURE_NOTSUP
1355 else if (status
== PCAP_ERROR_CAPTURE_NOTSUP
&& *cp
!= '\0')
1356 error("%s: %s\n(%s)", device
,
1357 pcap_statustostr(status
), cp
);
1360 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1361 strncmp(device
, "wlan", 4) == 0) {
1362 char parent
[8], newdev
[8];
1364 size_t s
= sizeof(parent
);
1366 snprintf(sysctl
, sizeof(sysctl
),
1367 "net.wlan.%d.%%parent", atoi(device
+ 4));
1368 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1369 strlcpy(newdev
, device
, sizeof(newdev
));
1370 /* Suggest a new wlan device. */
1371 /* FIXME: incrementing the index this way is not going to work well
1372 * when the index is 9 or greater but the only consequence in this
1373 * specific case would be an error message that looks a bit odd.
1375 newdev
[strlen(newdev
)-1]++;
1376 error("%s is not a monitor mode VAP"
1377 "To create a new monitor mode VAP use:\n"
1378 " ifconfig %s create wlandev %s wlanmode monitor\n"
1379 "and use %s as the tcpdump interface",
1380 device
, newdev
, parent
, newdev
);
1382 #endif // __FreeBSD__
1384 error("%s: %s", device
,
1385 pcap_statustostr(status
));
1388 } else if (status
> 0) {
1390 * pcap_activate() succeeded, but it's warning us
1391 * of a problem it had.
1393 cp
= pcap_geterr(pc
);
1394 if (status
== PCAP_WARNING
)
1396 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1398 warning("%s: %s\n(%s)", device
,
1399 pcap_statustostr(status
), cp
);
1401 warning("%s: %s", device
,
1402 pcap_statustostr(status
));
1405 status
= pcap_setdirection(pc
, Qflag
);
1407 error("%s: pcap_setdirection() failed: %s",
1408 device
, pcap_geterr(pc
));
1415 main(int argc
, char **argv
)
1418 bpf_u_int32 localnet
= 0, netmask
= 0;
1419 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1421 pcap_handler callback
;
1423 const char *dlt_name
;
1424 struct bpf_program fcode
;
1426 void (*oldhandler
)(int);
1428 struct dump_info dumpinfo
;
1429 u_char
*pcap_userdata
;
1430 char ebuf
[PCAP_ERRBUF_SIZE
];
1431 char VFileLine
[PATH_MAX
+ 1];
1432 const char *username
= NULL
;
1434 const char *chroot_dir
= NULL
;
1441 #ifdef HAVE_CAPSICUM
1442 cap_rights_t rights
;
1444 #endif /* HAVE_CAPSICUM */
1445 int Oflag
= 1; /* run filter code optimizer */
1447 const char *yflag_dlt_name
= NULL
;
1451 netdissect_options Ndo
;
1452 netdissect_options
*ndo
= &Ndo
;
1456 * We need to look for wpcap.dll in \Windows\System32\Npcap first,
1459 * 1) WinPcap isn't installed and Npcap isn't installed in "WinPcap
1460 * API-compatible Mode", so there's no wpcap.dll in
1461 * \Windows\System32, only in \Windows\System32\Npcap;
1463 * 2) WinPcap is installed and Npcap isn't installed in "WinPcap
1464 * API-compatible Mode", so the wpcap.dll in \Windows\System32
1465 * is a WinPcap DLL, but we'd prefer an Npcap DLL (we should
1466 * work with either one if we're configured against WinPcap,
1467 * and we'll probably require Npcap if we're configured against
1468 * it), and that's in \Windows\System32\Npcap;
1470 * 3) Npcap is installed in "WinPcap API-compatible Mode", so both
1471 * \Windows\System32 and \Windows\System32\Npcap have an Npcap
1474 * Unfortunately, Windows has no notion of an rpath, so we can't
1475 * set the rpath to include \Windows\System32\Npcap at link time;
1476 * what we need to do is to link wpcap as a delay-load DLL and
1477 * add \Windows\System32\Npcap to the DLL search path early in
1478 * main() with a call to SetDllDirectory().
1480 * The same applies to packet.dll.
1482 * We add \Windows\System32\Npcap here.
1484 * See https://npcap.com/guide/npcap-devguide.html#npcap-feature-native-dll-implicitly
1486 WCHAR
*dll_directory
= NULL
;
1487 size_t dll_directory_buf_len
= 0; /* units of bytes */
1488 UINT system_directory_buf_len
= 0; /* units of WCHARs */
1489 UINT system_directory_len
; /* units of WCHARs */
1490 static const WCHAR npcap
[] = L
"\\Npcap";
1493 * Get the system directory path, in UTF-16, into a buffer that's
1494 * large enough for that directory path plus "\Npcap".
1496 * String manipulation in C, plus fetching a variable-length
1497 * string into a buffer whose size is fixed at the time of
1498 * the call, with an oddball return value (see below), is just
1499 * a huge bag of fun.
1501 * And it's even more fun when dealing with UTF-16, so that the
1502 * buffer sizes used in GetSystemDirectoryW() are in different
1503 * units from the buffer sizes used in realloc()! We maintain
1504 * all sizes/length in units of bytes, not WCHARs, so that our
1505 * heads don't explode.
1509 * Try to fetch the system directory.
1511 * GetSystemDirectoryW() expects a buffer size in units
1512 * of WCHARs, not bytes, and returns a directory path
1513 * length in units of WCHARs, not bytes.
1515 * For extra fun, if GetSystemDirectoryW() succeeds,
1516 * the return value is the length of the directory
1517 * path in units of WCHARs, *not* including the
1518 * terminating '\0', but if it fails because the
1519 * path string wouldn't fit, the return value is
1520 * the length of the directory path in units of WCHARs,
1521 * *including* the terminating '\0'.
1523 system_directory_len
= GetSystemDirectoryW(dll_directory
,
1524 system_directory_buf_len
);
1525 if (system_directory_len
== 0)
1526 error("GetSystemDirectoryW() failed");
1529 * Did the directory path fit in the buffer?
1531 * As per the above, this means that the return value
1532 * *plus 1*, so that the terminating '\0' is counted,
1533 * is <= the buffer size.
1535 * (If the directory path, complete with the terminating
1536 * '\0', fits *exactly*, the return value would be the
1537 * size of the buffer minus 1, as it doesn't count the
1538 * terminating '\0', so the test below would succeed.
1540 * If everything *but* the terminating '\0' fits,
1541 * the return value would be the size of the buffer + 1,
1542 * i.e., the size that the string in question would
1545 * The astute reader will note that returning the
1546 * size of the buffer is not one of the two cases
1547 * above, and should never happen.)
1549 if ((system_directory_len
+ 1) <= system_directory_buf_len
) {
1551 * No. We have a buffer that's large enough
1558 * Yes. Grow the buffer.
1560 * The space we'll need in the buffer for the system
1561 * directory, in units of WCHARs, is system_directory_len,
1562 * as that's the length of the system directory path
1563 * including the terminating '\0'.
1565 system_directory_buf_len
= system_directory_len
;
1568 * The size of the DLL directory buffer, in *bytes*, must
1569 * be the number of WCHARs taken by the system directory,
1570 * *minus* the terminating '\0' (as we'll overwrite that
1571 * with the "\" of the "\Npcap" string), multiplied by
1572 * sizeof(WCHAR) to convert it to the number of bytes,
1573 * plus the size of the "\Npcap" string, in bytes (which
1574 * will include the terminating '\0', as that will become
1575 * the DLL path's terminating '\0').
1577 dll_directory_buf_len
=
1578 ((system_directory_len
- 1)*sizeof(WCHAR
)) + sizeof npcap
;
1579 dll_directory
= realloc(dll_directory
, dll_directory_buf_len
);
1580 if (dll_directory
== NULL
)
1581 error("Can't allocate string for Npcap directory");
1587 * Now append \Npcap. We add the length of the system directory path,
1588 * in WCHARs, *not* including the terminating '\0' (which, since
1589 * GetSystemDirectoryW() succeeded, is the return value of
1590 * GetSystemDirectoryW(), as per the above), to the pointer to the
1591 * beginning of the path, to go past the end of the system directory
1592 * to point to the terminating '\0'.
1594 memcpy(dll_directory
+ system_directory_len
, npcap
, sizeof npcap
);
1597 * Now add that as a system DLL directory.
1599 if (!SetDllDirectoryW(dll_directory
))
1600 error("SetDllDirectory failed");
1602 free(dll_directory
);
1606 * Initialize the netdissect code.
1608 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1611 memset(ndo
, 0, sizeof(*ndo
));
1612 ndo_set_function_pointers(ndo
);
1622 if ((cp
= strrchr(argv
[0], PATH_SEPARATOR
)) != NULL
)
1623 ndo
->program_name
= program_name
= cp
+ 1;
1625 ndo
->program_name
= program_name
= argv
[0];
1627 #if defined(HAVE_PCAP_WSOCKINIT)
1628 if (pcap_wsockinit() != 0)
1629 error("Attempting to initialize Winsock failed");
1630 #elif defined(HAVE_WSOCKINIT)
1631 if (wsockinit() != 0)
1632 error("Attempting to initialize Winsock failed");
1636 * An explicit tzset() call is usually not needed as it happens
1637 * implicitly the first time we call localtime() or mktime(),
1638 * but in some cases (sandboxing, chroot) this may be too late.
1643 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1647 /* compatibility for old -a */
1659 Bflag
= parse_int("packet buffer size", optarg
, NULL
, 1,
1662 * Will multiplying it by 1024 overflow?
1664 if (Bflag
> INT_MAX
/ 1024)
1665 error("packet buffer size %s is too large", optarg
);
1670 cnt
= parse_int("packet count", optarg
, NULL
, 1,
1675 Cflag
= parse_int64("file size", optarg
, &endp
, 1,
1678 if (*endp
== '\0') {
1680 * There's nothing after the file size,
1681 * so the size is in units of 1 MB
1682 * (1,000,000 bytes).
1684 Cflagmult
= 1000000;
1687 * There's something after the file
1690 * If it's a single letter, then:
1692 * if the letter is k or K, the size
1693 * is in units of 1 KiB (1024 bytes);
1695 * if the letter is m or M, the size
1696 * is in units of 1 MiB (1,048,576 bytes);
1698 * if the letter is g or G, the size
1699 * is in units of 1 GiB (1,073,741,824 bytes).
1701 * Otherwise, it's an error.
1712 Cflagmult
= 1024*1024;
1717 Cflagmult
= 1024*1024*1024;
1721 error("invalid file size %s (invalid units)", optarg
);
1725 * OK, there was a letter that we treat
1726 * as a units indication; was there
1727 * anything after it?
1730 if (*endp
!= '\0') {
1732 error("invalid file size %s (invalid units)", optarg
);
1737 * Will multiplying it by multiplier overflow?
1739 #ifdef HAVE_PCAP_DUMP_FTELL64
1740 if (Cflag
> INT64_MAX
/ Cflagmult
)
1742 if (Cflag
> LONG_MAX
/ Cflagmult
)
1744 error("file size %s is too large", optarg
);
1756 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1757 case OPTION_LIST_REMOTE_INTERFACES
:
1758 remote_interfaces_source
= optarg
;
1771 #ifndef HAVE_LIBCRYPTO
1772 warning("crypto code not compiled in");
1774 ndo
->ndo_espsecret
= optarg
;
1786 Gflag
= parse_int("number of seconds", optarg
, NULL
, 0,
1789 /* We will create one file initially. */
1792 /* Grab the current time for rotation use. */
1793 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1794 error("%s: can't get current time: %s",
1795 __func__
, pcap_strerror(errno
));
1800 print_usage(stdout
);
1801 exit_tcpdump(S_SUCCESS
);
1816 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1818 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1820 error("invalid time stamp type %s", optarg
);
1831 * _IOLBF is the same as _IOFBF in Microsoft's C
1832 * libraries; the only alternative they offer
1835 * XXX - this should really be checking for MSVC++,
1836 * not _WIN32, if, for example, MinGW has its own
1837 * C library that is more UNIX-compatible.
1839 setvbuf(stdout
, NULL
, _IONBF
, 0);
1841 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1851 if (nd_have_smi_support()) {
1852 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1855 (void)fprintf(stderr
, "%s: ignoring option '-m %s' ",
1856 program_name
, optarg
);
1857 (void)fprintf(stderr
, "(no libsmi support)\n");
1862 /* TCP-MD5 shared secret */
1863 #ifndef HAVE_LIBCRYPTO
1864 warning("crypto code not compiled in");
1866 ndo
->ndo_sigsecret
= optarg
;
1887 ++ndo
->ndo_suppress_default_print
;
1891 if (ascii_strcasecmp(optarg
, "in") == 0)
1893 else if (ascii_strcasecmp(optarg
, "out") == 0)
1895 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1896 Qflag
= PCAP_D_INOUT
;
1898 error("unknown capture direction '%s'", optarg
);
1906 ndo
->ndo_snaplen
= parse_int("snaplen", optarg
, NULL
,
1907 0, MAXIMUM_SNAPLEN
, 0);
1919 if (ascii_strcasecmp(optarg
, "vat") == 0)
1920 ndo
->ndo_packettype
= PT_VAT
;
1921 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1922 ndo
->ndo_packettype
= PT_WB
;
1923 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1924 ndo
->ndo_packettype
= PT_RPC
;
1925 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1926 ndo
->ndo_packettype
= PT_RTP
;
1927 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1928 ndo
->ndo_packettype
= PT_RTCP
;
1929 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1930 ndo
->ndo_packettype
= PT_SNMP
;
1931 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1932 ndo
->ndo_packettype
= PT_CNFP
;
1933 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1934 ndo
->ndo_packettype
= PT_TFTP
;
1935 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1936 ndo
->ndo_packettype
= PT_AODV
;
1937 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1938 ndo
->ndo_packettype
= PT_CARP
;
1939 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1940 ndo
->ndo_packettype
= PT_RADIUS
;
1941 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1942 ndo
->ndo_packettype
= PT_ZMTP1
;
1943 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1944 ndo
->ndo_packettype
= PT_VXLAN
;
1945 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1946 ndo
->ndo_packettype
= PT_PGM
;
1947 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1948 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1949 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1950 ndo
->ndo_packettype
= PT_LMP
;
1951 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1952 ndo
->ndo_packettype
= PT_RESP
;
1953 else if (ascii_strcasecmp(optarg
, "ptp") == 0)
1954 ndo
->ndo_packettype
= PT_PTP
;
1955 else if (ascii_strcasecmp(optarg
, "someip") == 0)
1956 ndo
->ndo_packettype
= PT_SOMEIP
;
1957 else if (ascii_strcasecmp(optarg
, "domain") == 0)
1958 ndo
->ndo_packettype
= PT_DOMAIN
;
1959 else if (ascii_strcasecmp(optarg
, "quic") == 0)
1960 ndo
->ndo_packettype
= PT_QUIC
;
1962 error("unknown packet type '%s'", optarg
);
1986 Wflag
= parse_int("number of output files", optarg
,
1987 NULL
, 1, INT_MAX
, 10);
1988 WflagChars
= getWflagChars(Wflag
);
1993 ++ndo
->ndo_suppress_default_print
;
1998 ++ndo
->ndo_suppress_default_print
;
2002 yflag_dlt_name
= optarg
;
2004 pcap_datalink_name_to_val(yflag_dlt_name
);
2006 error("invalid data link type %s", yflag_dlt_name
);
2009 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
2012 /* Undocumented flag */
2013 pcap_set_parser_debug(1);
2018 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2021 error("-z cannot be used. Fork subprocess not implemented.");
2030 ndo
->ndo_packet_number
= 1;
2033 case OPTION_LENGTHS
:
2034 ndo
->ndo_lengths
= 1;
2037 case OPTION_TIME_T_SIZE
:
2038 printf("%zu\n", sizeof(time_t) * 8);
2041 case OPTION_VERSION
:
2042 print_version(stdout
);
2043 exit_tcpdump(S_SUCCESS
);
2046 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2047 case OPTION_TSTAMP_PRECISION
:
2048 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
2049 if (ndo
->ndo_tstamp_precision
< 0)
2050 error("unsupported time stamp precision");
2054 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2055 case OPTION_IMMEDIATE_MODE
:
2064 case OPTION_PRINT_SAMPLING
:
2067 ndo
->ndo_print_sampling
= parse_int("print sampling",
2068 optarg
, NULL
, 1, INT_MAX
, 10);
2072 packets_to_skip
= parse_u_int("packet skip count",
2073 optarg
, NULL
, 0, INT_MAX
, 0);
2076 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2077 case OPTION_TSTAMP_MICRO
:
2078 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
2081 case OPTION_TSTAMP_NANO
:
2082 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_NANO
;
2086 case OPTION_FP_TYPE
:
2088 * Print out the type of floating-point arithmetic
2089 * we're doing; it's probably IEEE, unless somebody
2090 * tries to run this on a VAX, but the precision
2091 * may differ (e.g., it might be 32-bit, 64-bit,
2094 float_type_check(0x4e93312d);
2102 print_usage(stderr
);
2103 exit_tcpdump(S_ERR_HOST_PROGRAM
);
2107 if (ndo
->ndo_Aflag
&& ndo
->ndo_xflag
)
2108 error("-A and -x[x] are mutually exclusive.");
2109 if (ndo
->ndo_Aflag
&& ndo
->ndo_Xflag
)
2110 error("-A and -X[X] are mutually exclusive.");
2111 if (ndo
->ndo_xflag
&& ndo
->ndo_Xflag
)
2112 error("-x[x] and -X[X] are mutually exclusive.");
2113 if (Cflag
!= 0 && WFileName
== NULL
)
2114 error("-C cannot be used without -w.");
2115 if (Gflag
!= 0 && WFileName
== NULL
)
2116 error("-G cannot be used without -w.");
2117 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2118 if (zflag
!= NULL
&& (WFileName
== NULL
|| (Cflag
== 0 && Gflag
== 0)))
2119 error("-z cannot be used without -w and (-C or -G).");
2123 if ((int)packets_to_skip
> (INT_MAX
- cnt
))
2124 // cnt + (int)packets_to_skip used in pcap_loop() call
2125 error("Overflow (-c count) %d + (--skip count) %d", cnt
,
2126 (int)packets_to_skip
);
2129 show_devices_and_exit();
2130 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2131 if (remote_interfaces_source
!= NULL
)
2132 show_remote_devices_and_exit();
2135 switch (ndo
->ndo_tflag
) {
2137 case 0: /* Default */
2138 case 1: /* No time stamp */
2139 case 2: /* Unix timeval style */
2140 case 3: /* Microseconds/nanoseconds since previous packet */
2141 case 4: /* Date + Default */
2142 case 5: /* Microseconds/nanoseconds since first packet */
2145 default: /* Not supported */
2146 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
2150 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
2151 error("-f cannot be used with -V or -r.");
2153 if (VFileName
!= NULL
&& RFileName
!= NULL
)
2154 error("-V and -r are mutually exclusive.");
2157 * If we're printing dissected packets to the standard output,
2158 * and either the standard output is a terminal or we're doing
2159 * "line" buffering, set the capture timeout to .1 second rather
2160 * than 1 second, as the user's probably expecting to see packets
2161 * pop up immediately shortly after they arrive.
2163 * XXX - would there be some value appropriate for all cases,
2164 * based on, say, the buffer size and packet input rate?
2166 if ((WFileName
== NULL
|| print
) && (isatty(1) || lflag
))
2170 /* if run as root, prepare for chrooting */
2171 if (getuid() == 0 || geteuid() == 0) {
2172 /* future extensibility for cmd-line arguments */
2174 chroot_dir
= WITH_CHROOT
;
2179 /* if run as root, prepare for dropping root privileges */
2180 if (getuid() == 0 || geteuid() == 0) {
2181 /* Run with '-Z root' to restore old behaviour */
2183 username
= WITH_USER
;
2184 else if (strcmp(username
, "root") == 0)
2189 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
2191 * If RFileName is non-null, it's the pathname of a
2192 * savefile to read. If VFileName is non-null, it's
2193 * the pathname of a file containing a list of pathnames
2194 * (one per line) of savefiles to read.
2196 * In either case, we're reading a savefile, not doing
2201 * We don't need network access, so relinquish any set-UID
2202 * or set-GID privileges we have (if any).
2204 * We do *not* want set-UID privileges when opening a
2205 * trace file, as that might let the user read other
2206 * people's trace files (especially if we're set-UID
2209 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2210 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2212 if (VFileName
!= NULL
) {
2213 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
2216 VFile
= fopen(VFileName
, "r");
2219 error("Unable to open file: %s", pcap_strerror(errno
));
2221 ret
= get_next_file(VFile
, VFileLine
);
2223 error("Nothing in %s", VFileName
);
2224 RFileName
= VFileLine
;
2227 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2228 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
2229 ndo
->ndo_tstamp_precision
, ebuf
);
2231 pd
= pcap_open_offline(RFileName
, ebuf
);
2236 #ifdef HAVE_CAPSICUM
2237 cap_rights_init(&rights
, CAP_READ
);
2238 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
2240 error("unable to limit pcap descriptor");
2243 dlt
= pcap_datalink(pd
);
2244 dlt_name
= pcap_datalink_val_to_name(dlt
);
2245 fprintf(stderr
, "reading from file %s", RFileName
);
2246 if (dlt_name
== NULL
) {
2247 fprintf(stderr
, ", link-type %u", dlt
);
2249 fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2250 pcap_datalink_val_to_description(dlt
));
2252 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2253 #if defined(DLT_LINUX_SLL2) && defined(__linux__)
2254 if (dlt
== DLT_LINUX_SLL2
)
2255 fprintf(stderr
, "Warning: interface names might be incorrect\n");
2257 } else if (dflag
&& !device
) {
2258 int dump_dlt
= DLT_EN10MB
;
2260 * We're dumping the compiled code without an explicit
2261 * device specification. (If a device is specified, we
2262 * definitely want to open it to use the DLT of that device.)
2263 * Either default to DLT_EN10MB with a warning, or use
2264 * the user-specified value if supplied.
2267 * If no snapshot length was specified, or a length of 0 was
2268 * specified, default to 256KB.
2270 if (ndo
->ndo_snaplen
== 0)
2271 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
2273 * If a DLT was specified with the -y flag, use that instead.
2275 if (yflag_dlt
!= -1)
2276 dump_dlt
= yflag_dlt
;
2278 fprintf(stderr
, "Warning: assuming Ethernet\n");
2279 pd
= pcap_open_dead(dump_dlt
, ndo
->ndo_snaplen
);
2282 * We're doing a live capture.
2284 if (device
== NULL
) {
2286 * No interface was specified. Pick one.
2289 * Find the list of interfaces, and pick
2290 * the first interface.
2292 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2294 if (devlist
== NULL
)
2295 error("no interfaces available for capture");
2296 device
= strdup(devlist
->name
);
2297 pcap_freealldevs(devlist
);
2301 * Try to open the interface with the specified name.
2303 pd
= open_interface(device
, ndo
, ebuf
);
2306 * That failed. If we can get a list of
2307 * interfaces, and the interface name
2308 * is purely numeric, try to use it as
2309 * a 1-based index in the list of
2312 devnum
= parse_interface_number(device
);
2315 * It's not a number; just report
2316 * the open error and fail.
2322 * OK, it's a number; try to find the
2323 * interface with that index, and try
2326 * find_interface_by_number() exits if it
2327 * couldn't be found.
2329 device
= find_interface_by_number(device
, devnum
);
2330 pd
= open_interface(device
, ndo
, ebuf
);
2336 * Let user own process after capture device has
2340 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2341 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2344 show_dlts_and_exit(pd
, device
);
2345 if (yflag_dlt
>= 0) {
2346 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2347 error("%s", pcap_geterr(pd
));
2348 (void)fprintf(stderr
, "%s: data link type %s\n",
2350 pcap_datalink_val_to_name(yflag_dlt
));
2351 (void)fflush(stderr
);
2353 #if defined(DLT_LINUX_SLL2)
2356 * Attempt to set default linktype to
2357 * DLT_LINUX_SLL2 when capturing on the
2360 * If the attempt fails, just quietly drive
2361 * on; this may be a non-Linux "any" device
2362 * that doesn't support DLT_LINUX_SLL2.
2364 if (strcmp(device
, "any") == 0) {
2365 DIAG_OFF_WARN_UNUSED_RESULT
2366 (void) pcap_set_datalink(pd
, DLT_LINUX_SLL2
);
2367 DIAG_ON_WARN_UNUSED_RESULT
2371 i
= pcap_snapshot(pd
);
2372 if (ndo
->ndo_snaplen
< i
) {
2373 if (ndo
->ndo_snaplen
!= 0)
2374 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2375 ndo
->ndo_snaplen
= i
;
2376 } else if (ndo
->ndo_snaplen
> i
) {
2377 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2378 ndo
->ndo_snaplen
= i
;
2380 if(ndo
->ndo_fflag
!= 0) {
2381 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2382 warning("foreign (-f) flag used but: %s", ebuf
);
2388 cmdbuf
= read_infile(infile
);
2390 cmdbuf
= copy_argv(&argv
[optind
]);
2392 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2393 pcap_set_optimizer_debug(dflag
);
2396 * netmask is in network byte order, pcap_compile() takes it
2397 * in host byte order.
2399 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, ntohl(netmask
)) < 0)
2400 error("%s", pcap_geterr(pd
));
2402 bpf_dump(&fcode
, dflag
);
2405 pcap_freecode(&fcode
);
2406 exit_tcpdump(S_SUCCESS
);
2410 if (!ndo
->ndo_nflag
)
2411 capdns
= capdns_setup();
2412 #endif /* HAVE_CASPER */
2414 // Both localnet and netmask are in network byte order.
2415 init_print(ndo
, localnet
, netmask
);
2418 (void)setsignal(SIGPIPE
, cleanup
);
2419 (void)setsignal(SIGTERM
, cleanup
);
2421 (void)setsignal(SIGINT
, cleanup
);
2422 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2423 (void)setsignal(SIGCHLD
, child_cleanup
);
2425 /* Cooperate with nohup(1) */
2428 * In illumos /usr/include/sys/iso/signal_iso.h causes Clang to
2429 * generate a -Wstrict-prototypes warning here, see [1]. The
2430 * __illumos__ macro is available since at least GCC 11 and Clang 13,
2432 * 1: https://www.illumos.org/issues/16344
2433 * 2: https://www.illumos.org/issues/13726
2436 DIAG_OFF_STRICT_PROTOTYPES
2437 #endif /* __illumos__ */
2438 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2440 DIAG_ON_STRICT_PROTOTYPES
2441 #endif /* __illumos__ */
2442 (void)setsignal(SIGHUP
, oldhandler
);
2447 * If a user name was specified with "-Z", attempt to switch to
2448 * that user's UID. This would probably be used with sudo,
2449 * to allow tcpdump to be run in a special restricted
2450 * account (if you just want to allow users to open capture
2451 * devices, and can't just give users that permission,
2452 * you'd make tcpdump set-UID or set-GID).
2454 * tcpdump doesn't necessarily write only to one savefile;
2455 * the general only way to allow a -Z instance to write to
2456 * savefiles as the user under whose UID it's run, rather
2457 * than as the user specified with -Z, would thus be to switch
2458 * to the original user ID before opening a capture file and
2459 * then switch back to the -Z user ID after opening the savefile.
2460 * Switching to the -Z user ID only after opening the first
2461 * savefile doesn't handle the general case.
2464 if (getuid() == 0 || geteuid() == 0) {
2465 #ifdef HAVE_LIBCAP_NG
2466 /* Initialize capng */
2467 capng_clear(CAPNG_SELECT_BOTH
);
2469 DIAG_OFF_ASSIGN_ENUM
2472 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2479 DIAG_OFF_ASSIGN_ENUM
2482 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2489 DIAG_OFF_ASSIGN_ENUM
2492 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2497 capng_apply(CAPNG_SELECT_BOTH
);
2498 #endif /* HAVE_LIBCAP_NG */
2499 if (username
|| chroot_dir
)
2500 droproot(username
, chroot_dir
);
2505 if (pcap_setfilter(pd
, &fcode
) < 0)
2506 error("%s", pcap_geterr(pd
));
2507 #ifdef HAVE_CAPSICUM
2508 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2509 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2512 * The various libpcap devices use a combination of
2513 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2514 * so we add the relevant access rights.
2516 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2517 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2519 error("unable to limit pcap descriptor");
2521 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2522 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2523 error("unable to limit ioctls on pcap descriptor");
2528 /* Do not exceed the default PATH_MAX for files. */
2529 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2531 if (dumpinfo
.CurrentFileName
== NULL
)
2532 error("malloc of dumpinfo.CurrentFileName");
2534 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2536 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2538 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2540 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2541 #ifdef HAVE_LIBCAP_NG
2542 /* Give up CAP_DAC_OVERRIDE capability.
2543 * Only allow it to be restored if the -C or -G flag have been
2544 * set since we may need to create more files later on.
2548 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2552 capng_apply(CAPNG_SELECT_BOTH
);
2553 #endif /* HAVE_LIBCAP_NG */
2555 error("%s", pcap_geterr(pd
));
2556 #ifdef HAVE_CAPSICUM
2557 set_dumper_capsicum_rights(pdd
);
2559 if (Cflag
!= 0 || Gflag
!= 0) {
2560 #ifdef HAVE_CAPSICUM
2562 * basename() and dirname() may modify their input buffer
2563 * and they do since FreeBSD 12.0, but they didn't before.
2564 * Hence use the return value only, but always assume the
2565 * input buffer has been modified and would need to be
2566 * reset before the next use.
2568 char *WFileName_copy
;
2570 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2571 error("Unable to allocate memory for file %s",
2574 DIAG_OFF_C11_EXTENSIONS
2575 dumpinfo
.WFileName
= strdup(basename(WFileName_copy
));
2576 DIAG_ON_C11_EXTENSIONS
2577 if (dumpinfo
.WFileName
== NULL
) {
2578 error("Unable to allocate memory for file %s",
2581 free(WFileName_copy
);
2583 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2584 error("Unable to allocate memory for file %s",
2587 DIAG_OFF_C11_EXTENSIONS
2588 char *WFileName_dirname
= dirname(WFileName_copy
);
2589 DIAG_ON_C11_EXTENSIONS
2590 dumpinfo
.dirfd
= open(WFileName_dirname
,
2591 O_DIRECTORY
| O_RDONLY
);
2592 if (dumpinfo
.dirfd
< 0) {
2593 error("unable to open directory %s",
2596 free(WFileName_dirname
);
2597 free(WFileName_copy
);
2599 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2600 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2601 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2603 error("unable to limit directory rights");
2605 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2607 error("unable to limit dump descriptor fcntls");
2609 #else /* !HAVE_CAPSICUM */
2610 dumpinfo
.WFileName
= WFileName
;
2612 callback
= dump_packet_and_trunc
;
2615 pcap_userdata
= (u_char
*)&dumpinfo
;
2617 callback
= dump_packet
;
2618 dumpinfo
.WFileName
= WFileName
;
2621 pcap_userdata
= (u_char
*)&dumpinfo
;
2624 dlt
= pcap_datalink(pd
);
2625 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2628 dumpinfo
.ndo
= NULL
;
2631 pcap_dump_flush(pdd
);
2633 dlt
= pcap_datalink(pd
);
2634 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2635 callback
= print_packet
;
2636 pcap_userdata
= (u_char
*)ndo
;
2639 #ifdef SIGNAL_REQ_INFO
2641 * We can't get statistics when reading from a file rather
2642 * than capturing from a device.
2644 if (RFileName
== NULL
)
2645 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2647 #ifdef SIGNAL_FLUSH_PCAP
2648 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2651 if (ndo
->ndo_vflag
> 0 && WFileName
&& RFileName
== NULL
&& !print
) {
2653 * When capturing to a file, if "--print" wasn't specified,
2654 *"-v" means tcpdump should, once per second,
2655 * "v"erbosely report the number of packets captured.
2656 * Except when reading from a file, because -r, -w and -v
2657 * together used to make a corner case, in which pcap_loop()
2658 * errored due to EINTR (see GH #155 for details).
2662 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2664 * suggests that this dates back to W2K.
2666 * I don't know what a "long wait" is, but we'll assume
2667 * that printing the stats could be a "long wait".
2669 CreateTimerQueueTimer(&timer_handle
, NULL
,
2670 verbose_stats_dump
, NULL
, 1000, 1000,
2671 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2672 setvbuf(stderr
, NULL
, _IONBF
, 0);
2675 * Assume this is UN*X, and that it has setitimer(); that
2676 * dates back to UNIX 95.
2678 struct itimerval timer
;
2679 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2680 timer
.it_interval
.tv_sec
= 1;
2681 timer
.it_interval
.tv_usec
= 0;
2682 timer
.it_value
.tv_sec
= 1;
2683 timer
.it_value
.tv_usec
= 1;
2684 setitimer(ITIMER_REAL
, &timer
, NULL
);
2688 if (RFileName
== NULL
) {
2690 * Live capture (if -V was specified, we set RFileName
2691 * to a file from the -V file). Print a message to
2692 * the standard error on UN*X.
2694 if (!ndo
->ndo_vflag
&& !WFileName
) {
2695 (void)fprintf(stderr
,
2696 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2699 (void)fprintf(stderr
, "%s: ", program_name
);
2700 dlt
= pcap_datalink(pd
);
2701 dlt_name
= pcap_datalink_val_to_name(dlt
);
2702 (void)fprintf(stderr
, "listening on %s", device
);
2703 if (dlt_name
== NULL
) {
2704 (void)fprintf(stderr
, ", link-type %u", dlt
);
2706 (void)fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2707 pcap_datalink_val_to_description(dlt
));
2709 (void)fprintf(stderr
, ", snapshot length %d bytes\n", ndo
->ndo_snaplen
);
2710 (void)fflush(stderr
);
2713 #ifdef HAVE_CAPSICUM
2714 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2716 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2718 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2719 #endif /* HAVE_CASPER */
2720 cansandbox
= (cansandbox
&& (pcap_fileno(pd
) != -1 ||
2721 RFileName
!= NULL
));
2723 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2724 error("unable to enter the capability mode");
2725 #endif /* HAVE_CAPSICUM */
2728 status
= pcap_loop(pd
,
2729 (cnt
== -1 ? -1 : cnt
+ (int)packets_to_skip
),
2730 callback
, pcap_userdata
);
2731 if (WFileName
== NULL
) {
2733 * We're printing packets. Flush the printed output,
2734 * so it doesn't get intermingled with error output.
2738 * We got interrupted, so perhaps we didn't
2739 * manage to finish a line we were printing.
2740 * Print an extra newline, just in case.
2744 (void)fflush(stdout
);
2748 * We got interrupted. If we are reading multiple
2749 * files (via -V) set these so that we stop.
2758 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2759 program_name
, pcap_geterr(pd
));
2761 if (RFileName
== NULL
) {
2763 * We're doing a live capture. Report the capture
2769 if (VFileName
!= NULL
) {
2770 ret
= get_next_file(VFile
, VFileLine
);
2774 RFileName
= VFileLine
;
2775 pd
= pcap_open_offline(RFileName
, ebuf
);
2778 #ifdef HAVE_CAPSICUM
2779 cap_rights_init(&rights
, CAP_READ
);
2780 if (cap_rights_limit(fileno(pcap_file(pd
)),
2781 &rights
) < 0 && errno
!= ENOSYS
) {
2782 error("unable to limit pcap descriptor");
2785 new_dlt
= pcap_datalink(pd
);
2786 if (new_dlt
!= dlt
) {
2788 * The new file has a different
2789 * link-layer header type from the
2792 if (WFileName
!= NULL
) {
2794 * We're writing raw packets
2795 * that match the filter to
2796 * a pcap file. pcap files
2797 * don't support multiple
2798 * different link-layer
2799 * header types, so we fail
2802 error("%s: new dlt does not match original", RFileName
);
2806 * We're printing the decoded packets;
2807 * switch to the new DLT.
2809 * To do that, we need to change
2810 * the printer, change the DLT name,
2811 * and recompile the filter with
2815 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2816 /* Free the old filter */
2817 pcap_freecode(&fcode
);
2819 * netmask is in network byte order, pcap_compile() takes it
2820 * in host byte order.
2822 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, ntohl(netmask
)) < 0)
2823 error("%s", pcap_geterr(pd
));
2827 * Set the filter on the new file.
2829 if (pcap_setfilter(pd
, &fcode
) < 0)
2830 error("%s", pcap_geterr(pd
));
2833 * Report the new file.
2835 dlt_name
= pcap_datalink_val_to_name(dlt
);
2836 fprintf(stderr
, "reading from file %s", RFileName
);
2837 if (dlt_name
== NULL
) {
2838 fprintf(stderr
, ", link-type %u", dlt
);
2840 fprintf(stderr
, ", link-type %s (%s)",
2842 pcap_datalink_val_to_description(dlt
));
2844 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2848 while (ret
!= NULL
);
2850 if (count_mode
&& RFileName
!= NULL
)
2851 fprintf(stdout
, "%u packet%s\n", packets_captured
,
2852 PLURAL_SUFFIX(packets_captured
));
2855 pcap_freecode(&fcode
);
2856 exit_tcpdump(status
== -1 ? S_ERR_HOST_PROGRAM
: S_SUCCESS
);
2860 * Routines to parse numerical command-line arguments and check for
2861 * errors, including "too large for that type".
2864 parse_int(const char *argname
, const char *string
, char **endpp
,
2865 int minval
, int maxval
, int base
)
2871 val
= strtol(string
, &endp
, base
);
2874 * Did it either not parse any of the string, find extra stuff
2875 * at the end that the caller isn't interested in, or get
2876 * another parsing error?
2878 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2879 (val
== 0 && errno
== EINVAL
)) {
2880 error("invalid %s \"%s\" (not a valid number)", argname
,
2885 * Did it get a value that's out of range?
2887 if (((val
== LONG_MAX
|| val
== LONG_MIN
) && errno
== ERANGE
) ||
2888 val
< minval
|| val
> maxval
) {
2889 error("invalid %s %s (must be >= %d and <= %d)",
2890 argname
, string
, minval
, maxval
);
2894 * OK, it passes all the tests.
2902 parse_u_int(const char *argname
, const char *string
, char **endpp
,
2903 u_int minval
, u_int maxval
, int base
)
2911 * strtoul() does *NOT* report an error if the string
2912 * begins with a minus sign. We do.
2914 if (*string
== '-') {
2915 error("invalid %s \"%s\" (not a valid unsigned number)",
2919 val
= strtoul(string
, &endp
, base
);
2922 * Did it either not parse any of the string, find extra stuff
2923 * at the end that the caller isn't interested in, or get
2924 * another parsing error?
2926 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2927 (val
== 0 && errno
== EINVAL
)) {
2928 error("invalid %s \"%s\" (not a valid unsigned number)",
2933 * Did it get a value that's out of range?
2935 if ((val
== ULONG_MAX
&& errno
== ERANGE
) ||
2936 val
< minval
|| val
> maxval
) {
2937 error("invalid %s %s (must be >= %u and <= %u)",
2938 argname
, string
, minval
, maxval
);
2942 * OK, it passes all the tests.
2946 return ((u_int
)val
);
2950 parse_int64(const char *argname
, const char *string
, char **endpp
,
2951 int64_t minval
, int64_t maxval
, int base
)
2957 val
= strtoimax(string
, &endp
, base
);
2960 * Did it either not parse any of the string, find extra stuff
2961 * at the end that the caller isn't interested in, or get
2962 * another parsing error?
2964 if (string
== endp
|| (endpp
== NULL
&& *endp
!= '\0') ||
2965 (val
== 0 && errno
== EINVAL
)) {
2966 error("invalid %s \"%s\" (not a valid number)", argname
,
2971 * Did it get a value that's out of range?
2973 if (((val
== INTMAX_MAX
|| val
== INTMAX_MIN
) && errno
== ERANGE
) ||
2974 val
< minval
|| val
> maxval
) {
2975 error("invalid %s %s (must be >= %" PRId64
" and <= %" PRId64
")",
2976 argname
, string
, minval
, maxval
);
2980 * OK, it passes all the tests.
2984 return ((int64_t)val
);
2991 (*setsignal (int sig
, void (*func
)(int)))(int)
2994 return (signal(sig
, func
));
2996 struct sigaction old
, new;
2998 memset(&new, 0, sizeof(new));
2999 new.sa_handler
= func
;
3000 if ((sig
== SIGCHLD
)
3001 # ifdef SIGNAL_REQ_INFO
3002 || (sig
== SIGNAL_REQ_INFO
)
3004 # ifdef SIGNAL_FLUSH_PCAP
3005 || (sig
== SIGNAL_FLUSH_PCAP
)
3008 new.sa_flags
= SA_RESTART
;
3009 if (sigaction(sig
, &new, &old
) < 0)
3010 /* The same workaround as for SIG_DFL above. */
3012 DIAG_OFF_STRICT_PROTOTYPES
3013 #endif /* __illumos__ */
3016 DIAG_ON_STRICT_PROTOTYPES
3017 #endif /* __illumos__ */
3018 return (old
.sa_handler
);
3022 /* make a clean exit on interrupts */
3024 cleanup(int signo _U_
)
3027 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
3028 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
3029 CloseHandle(timer_handle
);
3030 timer_handle
= INVALID_HANDLE_VALUE
;
3033 struct itimerval timer
;
3035 timer
.it_interval
.tv_sec
= 0;
3036 timer
.it_interval
.tv_usec
= 0;
3037 timer
.it_value
.tv_sec
= 0;
3038 timer
.it_value
.tv_usec
= 0;
3039 setitimer(ITIMER_REAL
, &timer
, NULL
);
3043 * We have "pcap_breakloop()"; use it, so that we do as little
3044 * as possible in the signal handler (it's probably not safe
3045 * to do anything with standard I/O streams in a signal handler -
3046 * the ANSI C standard doesn't say it is).
3052 On windows, we do not use a fork, so we do not care less about
3053 waiting a child processes to die
3055 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3057 child_cleanup(int signo _U_
)
3059 while (waitpid(-1, NULL
, WNOHANG
) >= 0);
3061 #endif /* HAVE_FORK && HAVE_VFORK */
3066 struct pcap_stat stats
;
3069 * Older versions of libpcap didn't set ps_ifdrop on some
3070 * platforms; initialize it to 0 to handle that.
3072 stats
.ps_ifdrop
= 0;
3073 if (pcap_stats(pd
, &stats
) < 0) {
3074 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
3080 fprintf(stderr
, "%s: ", program_name
);
3082 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
3083 PLURAL_SUFFIX(packets_captured
));
3085 fputs(", ", stderr
);
3088 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
3089 PLURAL_SUFFIX(stats
.ps_recv
));
3091 fputs(", ", stderr
);
3094 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
3095 PLURAL_SUFFIX(stats
.ps_drop
));
3096 if (stats
.ps_ifdrop
!= 0) {
3098 fputs(", ", stderr
);
3101 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
3102 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
3108 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3110 #define fork_subprocess() fork()
3112 #define fork_subprocess() vfork()
3115 compress_savefile(const char *filename
)
3119 child
= fork_subprocess();
3122 "%s: fork failed: %s\n",
3123 __func__
, pcap_strerror(errno
));
3127 /* Parent process. */
3133 * Set to lowest priority so that this doesn't disturb the capture.
3136 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
3138 setpriority(PRIO_PROCESS
, 0, 19);
3140 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
3142 "%s: execlp(%s, %s) failed: %s\n",
3143 __func__
, zflag
, filename
, pcap_strerror(errno
));
3145 exit(S_ERR_HOST_PROGRAM
);
3147 _exit(S_ERR_HOST_PROGRAM
);
3150 #endif /* HAVE_FORK || HAVE_VFORK */
3153 close_old_dump_file(struct dump_info
*dump_info
)
3156 * Close the current file and open a new one.
3158 pcap_dump_close(dump_info
->pdd
);
3160 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
3162 * Compress the file we just closed, if the user asked for it.
3165 compress_savefile(dump_info
->CurrentFileName
);
3170 open_new_dump_file(struct dump_info
*dump_info
)
3172 #ifdef HAVE_CAPSICUM
3177 #ifdef HAVE_LIBCAP_NG
3178 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3179 capng_apply(CAPNG_SELECT_BOTH
);
3180 #endif /* HAVE_LIBCAP_NG */
3181 #ifdef HAVE_CAPSICUM
3182 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
3183 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
3185 error("unable to open file %s", dump_info
->CurrentFileName
);
3187 fp
= fdopen(fd
, "w");
3189 error("unable to fdopen file %s", dump_info
->CurrentFileName
);
3191 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
3192 #else /* !HAVE_CAPSICUM */
3193 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
3195 #ifdef HAVE_LIBCAP_NG
3196 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3197 capng_apply(CAPNG_SELECT_BOTH
);
3198 #endif /* HAVE_LIBCAP_NG */
3199 if (dump_info
->pdd
== NULL
)
3200 error("%s", pcap_geterr(pd
));
3201 #ifdef HAVE_CAPSICUM
3202 set_dumper_capsicum_rights(dump_info
->pdd
);
3207 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3209 struct dump_info
*dump_info
;
3215 dump_info
= (struct dump_info
*)user
;
3217 if (packets_captured
<= packets_to_skip
)
3221 * XXX - this won't force the file to rotate on the specified time
3222 * boundary, but it will rotate on the first packet received after the
3223 * specified Gflag number of seconds. Note: if a Gflag time boundary
3224 * and a Cflag size boundary coincide, the time rotation will occur
3225 * first thereby cancelling the Cflag boundary (since the file should
3229 /* Check if it is time to rotate */
3232 /* Get the current time */
3233 if ((t
= time(NULL
)) == (time_t)-1) {
3234 error("%s: can't get current_time: %s",
3235 __func__
, pcap_strerror(errno
));
3239 /* If the time is greater than the specified window, rotate */
3240 if (t
- Gflag_time
>= Gflag
) {
3241 /* Update the Gflag_time */
3243 /* Update Gflag_count */
3246 close_old_dump_file(dump_info
);
3249 * Check to see if we've exceeded the Wflag (when
3252 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
3253 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
3256 exit_tcpdump(S_SUCCESS
);
3259 if (dump_info
->CurrentFileName
!= NULL
)
3260 free(dump_info
->CurrentFileName
);
3261 /* Allocate space for max filename + \0. */
3262 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
3263 if (dump_info
->CurrentFileName
== NULL
)
3264 error("dump_packet_and_trunc: malloc");
3266 * Gflag was set otherwise we wouldn't be here. Reset the count
3267 * so multiple files would end with 1,2,3 in the filename.
3268 * The counting is handled with the -C flow after this.
3273 * This is always the first file in the Cflag
3275 * We also don't need numbering if Cflag is not set.
3278 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
3281 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
3283 open_new_dump_file(dump_info
);
3288 * XXX - this won't prevent capture files from getting
3289 * larger than Cflag - the last packet written to the
3290 * file could put it over Cflag.
3293 #ifdef HAVE_PCAP_DUMP_FTELL64
3294 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
3297 * XXX - this only handles a Cflag value > 2^31-1 on
3298 * LP64 platforms; to handle ILP32 (32-bit UN*X and
3299 * Windows) or LLP64 (64-bit Windows) would require
3300 * a version of libpcap with pcap_dump_ftell64().
3302 long size
= pcap_dump_ftell(dump_info
->pdd
);
3306 error("ftell fails on output file");
3308 close_old_dump_file(dump_info
);
3312 if (Cflag_count
>= Wflag
)
3315 if (dump_info
->CurrentFileName
!= NULL
)
3316 free(dump_info
->CurrentFileName
);
3317 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
3318 if (dump_info
->CurrentFileName
== NULL
)
3319 error("%s: malloc", __func__
);
3320 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
3322 open_new_dump_file(dump_info
);
3326 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3328 pcap_dump_flush(dump_info
->pdd
);
3330 if (dump_info
->ndo
!= NULL
)
3331 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3339 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3341 struct dump_info
*dump_info
;
3347 dump_info
= (struct dump_info
*)user
;
3349 if (packets_captured
<= packets_to_skip
)
3352 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3354 pcap_dump_flush(dump_info
->pdd
);
3356 if (dump_info
->ndo
!= NULL
)
3357 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3365 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3371 if (!count_mode
&& packets_captured
> packets_to_skip
)
3372 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
3379 #ifdef SIGNAL_REQ_INFO
3381 requestinfo(int signo _U_
)
3390 #ifdef SIGNAL_FLUSH_PCAP
3392 flushpcap(int signo _U_
)
3395 pcap_dump_flush(pdd
);
3400 print_packets_captured (void)
3402 static u_int prev_packets_captured
, first
= 1;
3404 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
3405 fprintf(stderr
, "Got %u\r", packets_captured
);
3407 prev_packets_captured
= packets_captured
;
3412 * Called once each second in verbose mode while dumping to file
3415 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
3416 BOOLEAN timer_fired _U_
)
3418 print_packets_captured();
3421 static void verbose_stats_dump(int sig _U_
)
3423 print_packets_captured();
3427 DIAG_OFF_DEPRECATION
3429 print_version(FILE *f
)
3431 const char *smi_version_string
;
3433 (void)fprintf(f
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3434 (void)fprintf(f
, "%s\n", pcap_lib_version());
3436 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3437 (void)fprintf (f
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3440 smi_version_string
= nd_smi_version_string();
3441 if (smi_version_string
!= NULL
)
3442 (void)fprintf (f
, "SMI-library: %s\n", smi_version_string
);
3444 #if defined(__SANITIZE_ADDRESS__)
3445 (void)fprintf (f
, "Compiled with AddressSanitizer/GCC.\n");
3446 #elif defined(__has_feature)
3447 # if __has_feature(address_sanitizer)
3448 (void)fprintf (f
, "Compiled with AddressSanitizer/Clang.\n");
3449 # elif __has_feature(memory_sanitizer)
3450 (void)fprintf (f
, "Compiled with MemorySanitizer/Clang.\n");
3452 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3453 (void)fprintf (f
, "%zu-bit build, %zu-bit time_t\n",
3454 sizeof(void *) * 8, sizeof(time_t) * 8);
3459 print_usage(FILE *f
)
3463 "Usage: %s [-AbdDefhHI" J_FLAG
"KlLnNOpqStuUvxX#] [ -B size ] [ -c count ] [--count]\n", program_name
);
3465 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3467 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3469 "\t\t[ --lengths ]" LIST_REMOTE_INTERFACES_USAGE
"\n");
3472 "\t\t" m_FLAG_USAGE
"\n");
3475 "\t\t[ -M secret ] [ --number ] [ --print ]\n");
3477 "\t\t[ --print-sampling nth ] [ -Q in|out|inout ] [ -r file ]\n");
3479 "\t\t[ -s snaplen ] [ --skip count ] [ -T type ] [ --version ]\n");
3481 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3482 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3484 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3487 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");