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.
38 #include "netdissect-stdinc.h"
41 * This must appear after including netdissect-stdinc.h, so that _U_ is
45 static const char copyright
[] _U_
=
46 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
47 The Regents of the University of California. All rights reserved.\n";
55 #include <openssl/crypto.h>
58 #ifdef HAVE_GETOPT_LONG
61 #include "missing/getopt_long.h"
63 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
64 * to compile if <pcap.h> has already been included; including the headers
65 * in the opposite order works fine. For the most part anyway, because in
66 * FreeBSD <pcap/pcap.h> declares bpf_dump() instead of <net/bpf.h>. Thus
67 * interface.h takes care of it later to avoid a compiler warning.
70 #include <sys/capsicum.h>
71 #include <sys/ioccom.h>
75 #include <libcasper.h>
76 #include <casper/cap_dns.h>
78 #endif /* HAVE_CASPER */
79 #endif /* HAVE_CAPSICUM */
82 * We found pcap_open() in the capture library, so we'll be using
83 * the remote capture APIs; define PCAP_REMOTE before we include pcap.h,
84 * so we get those APIs declared, and the types and #defines that they
87 * WinPcap's headers require that PCAP_REMOTE be defined in order to get
88 * remote-capture APIs declared and types and #defines that they use
91 * (Versions of libpcap with those APIs, and thus Npcap, which is based on
92 * those versions of libpcap, don't require it.)
106 #include <sys/time.h>
107 #include <sys/wait.h>
108 #include <sys/resource.h>
114 * Pathname separator.
115 * Use this in pathnames, but do *not* use it in URLs.
118 #define PATH_SEPARATOR '\\'
120 #define PATH_SEPARATOR '/'
123 /* capabilities convenience library */
124 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
125 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
126 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
128 #ifdef HAVE_LIBCAP_NG
132 #undef HAVE_LIBCAP_NG
133 #endif /* HAVE_CAP_NG_H */
134 #endif /* HAVE_LIBCAP_NG */
137 #include <sys/sysctl.h>
138 #endif /* __FreeBSD__ */
140 #include "netdissect-stdinc.h"
141 #include "netdissect.h"
142 #include "interface.h"
143 #include "addrtoname.h"
144 #include "pcap-missing.h"
145 #include "ascii_strcasecmp.h"
149 #include "diag-control.h"
154 #define PATH_MAX 1024
158 #define SIGNAL_REQ_INFO SIGINFO
159 #elif defined(SIGUSR1)
160 #define SIGNAL_REQ_INFO SIGUSR1
164 #define SIGNAL_FLUSH_PCAP SIGUSR2
167 static int Bflag
; /* buffer size */
168 #ifdef HAVE_PCAP_DUMP_FTELL64
169 static int64_t Cflag
; /* rotate dump files after this many bytes */
171 static long Cflag
; /* rotate dump files after this many bytes */
173 static int Cflag_count
; /* Keep track of which file number we're writing */
174 static int Dflag
; /* list available devices and exit */
175 #ifdef HAVE_PCAP_FINDALLDEVS_EX
176 static char *remote_interfaces_source
; /* list available devices from this source and exit */
180 * This is exported because, in some versions of libpcap, if libpcap
181 * is built with optimizer debugging code (which is *NOT* the default
182 * configuration!), the library *imports*(!) a variable named dflag,
183 * under the expectation that tcpdump is exporting it, to govern
184 * how much debugging information to print when optimizing
185 * the generated BPF code.
187 * This is a horrible hack; newer versions of libpcap don't import
188 * dflag but, instead, *if* built with optimizer debugging code,
189 * *export* a routine to set that flag.
192 int dflag
; /* print filter code */
193 static int Gflag
; /* rotate dump files after this many seconds */
194 static int Gflag_count
; /* number of files created with Gflag rotation */
195 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
196 static int Lflag
; /* list available data link types and exit */
197 static int Iflag
; /* rfmon (monitor) mode */
198 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
199 static int Jflag
; /* list available time stamp types */
200 static int jflag
= -1; /* packet time stamp source */
202 static int lflag
; /* line-buffered output */
203 static int pflag
; /* don't go promiscuous */
204 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
205 static int Uflag
; /* "unbuffered" output of dump files */
206 static int Wflag
; /* recycle output files after this number of files */
207 static int WflagChars
;
208 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
;
215 static int infodelay
;
216 static int infoprint
;
221 static void (*setsignal (int sig
, void (*func
)(int)))(int);
222 static void cleanup(int);
223 static void child_cleanup(int);
224 static void print_version(FILE *);
225 static void print_usage(FILE *);
227 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
228 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
229 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
231 #ifdef SIGNAL_REQ_INFO
232 static void requestinfo(int);
235 #ifdef SIGNAL_FLUSH_PCAP
236 static void flushpcap(int);
240 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
241 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
243 static void verbose_stats_dump(int sig
);
246 static void info(int);
247 static u_int packets_captured
;
249 static const struct tok status_flags
[] = {
251 { PCAP_IF_UP
, "Up" },
253 #ifdef PCAP_IF_RUNNING
254 { PCAP_IF_RUNNING
, "Running" },
256 { PCAP_IF_LOOPBACK
, "Loopback" },
257 #ifdef PCAP_IF_WIRELESS
258 { PCAP_IF_WIRELESS
, "Wireless" },
264 static pcap_dumper_t
*pdd
= NULL
;
266 static int supports_monitor_mode
;
274 char *CurrentFileName
;
277 netdissect_options
*ndo
;
283 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
285 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
286 * by any libpcap header, because it's a special hack, only available if
287 * libpcap was configured to include it, and only intended for use by
288 * libpcap developers trying to debug the parser for filter expressions).
291 __declspec(dllimport
)
295 void pcap_set_parser_debug(int);
296 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
298 * We don't have pcap_set_parser_debug() in libpcap, but we do have
299 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
300 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
303 pcap_set_parser_debug(int value
)
305 #ifdef HAVE_PCAP_DEBUG
306 extern int pcap_debug
;
309 #else /* HAVE_PCAP_DEBUG */
313 #endif /* HAVE_PCAP_DEBUG */
316 #define HAVE_PCAP_SET_PARSER_DEBUG
319 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
321 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
322 * by any libpcap header, because it's a special hack, only available if
323 * libpcap was configured to include it, and only intended for use by
324 * libpcap developers trying to debug the optimizer for filter expressions).
327 __declspec(dllimport
)
331 void pcap_set_optimizer_debug(int);
335 exit_tcpdump(const int status
)
342 static void NORETURN
PRINTFLIKE(1, 2)
343 error(FORMAT_STRING(const char *fmt
), ...)
347 (void)fprintf(stderr
, "%s: ", program_name
);
349 (void)vfprintf(stderr
, fmt
, ap
);
354 (void)fputc('\n', stderr
);
356 exit_tcpdump(S_ERR_HOST_PROGRAM
);
361 static void PRINTFLIKE(1, 2)
362 warning(FORMAT_STRING(const char *fmt
), ...)
366 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
368 (void)vfprintf(stderr
, fmt
, ap
);
373 (void)fputc('\n', stderr
);
377 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
379 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
382 int *tstamp_types
= 0;
383 const char *tstamp_type_name
;
386 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
387 if (n_tstamp_types
< 0)
388 error("%s", pcap_geterr(pc
));
390 if (n_tstamp_types
== 0) {
391 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
393 exit_tcpdump(S_SUCCESS
);
395 fprintf(stdout
, "Time stamp types for %s (use option -j to set):\n",
397 for (i
= 0; i
< n_tstamp_types
; i
++) {
398 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
399 if (tstamp_type_name
!= NULL
) {
400 (void) fprintf(stdout
, " %s (%s)\n", tstamp_type_name
,
401 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
403 (void) fprintf(stdout
, " %d\n", tstamp_types
[i
]);
406 pcap_free_tstamp_types(tstamp_types
);
407 exit_tcpdump(S_SUCCESS
);
412 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
416 const char *dlt_name
;
418 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
420 error("%s", pcap_geterr(pc
));
421 else if (n_dlts
== 0 || !dlts
)
422 error("No data link types.");
425 * If the interface is known to support monitor mode, indicate
426 * whether these are the data link types available when not in
427 * monitor mode, if -I wasn't specified, or when in monitor mode,
428 * when -I was specified (the link-layer types available in
429 * monitor mode might be different from the ones available when
430 * not in monitor mode).
432 (void) fprintf(stdout
, "Data link types for ");
433 if (supports_monitor_mode
)
434 (void) fprintf(stdout
, "%s %s",
436 Iflag
? "when in monitor mode" : "when not in monitor mode");
438 (void) fprintf(stdout
, "%s",
440 (void) fprintf(stdout
, " (use option -y to set):\n");
442 for (i
= 0; i
< n_dlts
; i
++) {
443 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
444 if (dlt_name
!= NULL
) {
445 (void) fprintf(stdout
, " %s (%s)", dlt_name
,
446 pcap_datalink_val_to_description(dlts
[i
]));
449 * OK, does tcpdump handle that type?
451 if (!has_printer(dlts
[i
]))
452 (void) fprintf(stdout
, " (printing not supported)");
453 fprintf(stdout
, "\n");
455 (void) fprintf(stdout
, " DLT %d (printing not supported)\n",
459 pcap_free_datalinks(dlts
);
460 exit_tcpdump(S_SUCCESS
);
464 show_devices_and_exit(void)
466 pcap_if_t
*dev
, *devlist
;
467 char ebuf
[PCAP_ERRBUF_SIZE
];
470 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
472 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
473 printf("%d.%s", i
+1, dev
->name
);
474 if (dev
->description
!= NULL
)
475 printf(" (%s)", dev
->description
);
476 if (dev
->flags
!= 0) {
478 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
479 #ifdef PCAP_IF_WIRELESS
480 if (dev
->flags
& PCAP_IF_WIRELESS
) {
481 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
483 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
484 printf(", Association status unknown");
487 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
488 printf(", Associated");
491 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
492 printf(", Not associated");
495 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
499 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
501 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
502 printf(", Connection status unknown");
505 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
506 printf(", Connected");
509 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
510 printf(", Disconnected");
513 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
522 pcap_freealldevs(devlist
);
523 exit_tcpdump(S_SUCCESS
);
526 #ifdef HAVE_PCAP_FINDALLDEVS_EX
528 show_remote_devices_and_exit(void)
530 pcap_if_t
*dev
, *devlist
;
531 char ebuf
[PCAP_ERRBUF_SIZE
];
534 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
536 if (strcmp(ebuf
, "not supported") == 0) {
538 * macOS 14's pcap_findalldevs_ex(), which is a
539 * stub that always returns -1 with an error
540 * message of "not supported".
542 * In this case, as we passed it an rpcap://
543 * URL, treat that as meaning "remote capture
546 error("Remote capture not supported");
550 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
551 printf("%d.%s", i
+1, dev
->name
);
552 if (dev
->description
!= NULL
)
553 printf(" (%s)", dev
->description
);
555 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
558 pcap_freealldevs(devlist
);
559 exit_tcpdump(S_SUCCESS
);
561 #endif /* HAVE_PCAP_FINDALLDEVS_EX */
566 * Note that there we use all letters for short options except for g, k,
567 * o, and P, and those are used by other versions of tcpdump, and we should
568 * only use them for the same purposes that the other versions of tcpdump
571 * macOS tcpdump uses -g to force non--v output for IP to be on one
572 * line, making it more "g"repable;
574 * macOS tcpdump uses -k to specify that packet comments in pcapng files
577 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
578 * for hosts sending TCP SYN packets;
580 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
583 * macOS tcpdump also uses -Q to specify expressions that match packet
584 * metadata, including but not limited to the packet direction.
585 * The expression syntax is different from a simple "in|out|inout",
586 * and those expressions aren't accepted by macOS tcpdump, but the
587 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
588 * "inout" = "dir=in or dir=out", and the parser could conceivably
589 * special-case "in", "out", and "inout" as expressions for backwards
590 * compatibility, so all is not (yet) lost.
594 * Set up flags that might or might not be supported depending on the
595 * version of libpcap we're using.
597 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
599 #define j_FLAG_USAGE " [ -j tstamptype ]"
601 #else /* HAVE_PCAP_SET_TSTAMP_TYPE */
605 #endif /* HAVE_PCAP_SET_TSTAMP_TYPE */
608 #define m_FLAG_USAGE "[ -m module ] ..."
611 #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:#"
616 * We do not currently have long options corresponding to all short
617 * options; we should probably pick appropriate option names for them.
619 * However, the short options where the number of times the option is
620 * specified matters, such as -v and -d and -t, should probably not
621 * just map to a long option, as saying
623 * tcpdump --verbose --verbose
625 * doesn't make sense; it should be --verbosity={N} or something such
628 * For long options with no corresponding short options, we define values
629 * outside the range of ASCII graphic characters, make that the last
630 * component of the entry for the long option, and have a case for that
631 * option in the switch statement.
633 #define OPTION_VERSION 128
634 #define OPTION_TSTAMP_PRECISION 129
635 #define OPTION_IMMEDIATE_MODE 130
636 #define OPTION_PRINT 131
637 #define OPTION_LIST_REMOTE_INTERFACES 132
638 #define OPTION_TSTAMP_MICRO 133
639 #define OPTION_TSTAMP_NANO 134
640 #define OPTION_FP_TYPE 135
641 #define OPTION_COUNT 136
642 #define OPTION_PRINT_SAMPLING 137
643 #define OPTION_LENGTHS 138
645 static const struct option longopts
[] = {
646 { "buffer-size", required_argument
, NULL
, 'B' },
647 { "list-interfaces", no_argument
, NULL
, 'D' },
648 #ifdef HAVE_PCAP_FINDALLDEVS_EX
649 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
651 { "help", no_argument
, NULL
, 'h' },
652 { "interface", required_argument
, NULL
, 'i' },
653 { "monitor-mode", no_argument
, NULL
, 'I' },
654 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
655 { "time-stamp-type", required_argument
, NULL
, 'j' },
656 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
658 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
659 { "micro", no_argument
, NULL
, OPTION_TSTAMP_MICRO
},
660 { "nano", no_argument
, NULL
, OPTION_TSTAMP_NANO
},
661 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
663 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
664 { "list-data-link-types", no_argument
, NULL
, 'L' },
665 { "no-optimize", no_argument
, NULL
, 'O' },
666 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
667 { "direction", required_argument
, NULL
, 'Q' },
668 { "snapshot-length", required_argument
, NULL
, 's' },
669 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
670 { "packet-buffered", no_argument
, NULL
, 'U' },
671 { "linktype", required_argument
, NULL
, 'y' },
672 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
673 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
675 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
676 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
678 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
679 { "count", no_argument
, NULL
, OPTION_COUNT
},
680 { "fp-type", no_argument
, NULL
, OPTION_FP_TYPE
},
681 { "number", no_argument
, NULL
, '#' },
682 { "print", no_argument
, NULL
, OPTION_PRINT
},
683 { "print-sampling", required_argument
, NULL
, OPTION_PRINT_SAMPLING
},
684 { "lengths", no_argument
, NULL
, OPTION_LENGTHS
},
685 { "version", no_argument
, NULL
, OPTION_VERSION
},
689 #ifdef HAVE_PCAP_FINDALLDEVS_EX
690 #define LIST_REMOTE_INTERFACES_USAGE " [ --list-remote-interfaces remote-source ]"
692 #define LIST_REMOTE_INTERFACES_USAGE
695 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
696 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
698 #define IMMEDIATE_MODE_USAGE ""
702 /* Drop root privileges and chroot if necessary */
704 droproot(const char *username
, const char *chroot_dir
)
706 struct passwd
*pw
= NULL
;
708 if (chroot_dir
&& !username
)
709 error("Chroot without dropping root is insecure");
711 pw
= getpwnam(username
);
714 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
715 error("Couldn't chroot/chdir to '%.64s': %s",
716 chroot_dir
, pcap_strerror(errno
));
718 #ifdef HAVE_LIBCAP_NG
720 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
722 error("capng_change_id(): return %d\n", ret
);
724 fprintf(stderr
, "dropped privs to %s\n", username
);
727 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
728 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
729 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
731 (unsigned long)pw
->pw_uid
,
732 (unsigned long)pw
->pw_gid
,
733 pcap_strerror(errno
));
735 fprintf(stderr
, "dropped privs to %s\n", username
);
737 #endif /* HAVE_LIBCAP_NG */
739 error("Couldn't find user '%.32s'", username
);
740 #ifdef HAVE_LIBCAP_NG
741 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT anymore. */
745 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
751 capng_apply(CAPNG_SELECT_BOTH
);
752 #endif /* HAVE_LIBCAP_NG */
773 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
775 char *filename
= malloc(PATH_MAX
+ 1);
776 if (filename
== NULL
)
777 error("%s: malloc", __func__
);
778 if (strlen(orig_name
) == 0)
779 error("an empty string is not a valid file name");
781 /* Process with strftime if Gflag is set. */
785 /* Convert Gflag_time to a usable format */
786 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
787 error("%s: localtime", __func__
);
790 /* There's no good way to detect an error in strftime since a return
791 * value of 0 isn't necessarily failure; if orig_name is an empty
792 * string, the formatted string will be empty.
794 * However, the C90 standard says that, if there *is* a
795 * buffer overflow, the content of the buffer is undefined,
796 * so we must check for a buffer overflow.
798 * So we check above for an empty orig_name, and only call
799 * strftime() if it's non-empty, in which case the return
800 * value will only be 0 if the formatted date doesn't fit
803 * (We check above because, even if we don't use -G, we
804 * want a better error message than "tcpdump: : No such
805 * file or directory" for this case.)
807 if (strftime(filename
, PATH_MAX
, orig_name
, local_tm
) == 0) {
808 error("%s: strftime", __func__
);
811 strncpy(filename
, orig_name
, PATH_MAX
);
814 if (cnt
== 0 && max_chars
== 0)
815 strncpy(buffer
, filename
, PATH_MAX
+ 1);
817 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
818 /* Report an error if the filename is too large */
819 error("too many output files or filename is too long (> %d)", PATH_MAX
);
824 get_next_file(FILE *VFile
, char *ptr
)
829 ret
= fgets(ptr
, PATH_MAX
, VFile
);
834 if (len
> 0 && ptr
[len
- 1] == '\n')
841 static cap_channel_t
*
844 cap_channel_t
*capcas
, *capdnsloc
;
845 const char *types
[1];
850 error("unable to create casper process");
851 capdnsloc
= cap_service_open(capcas
, "system.dns");
852 /* Casper capability no longer needed. */
854 if (capdnsloc
== NULL
)
855 error("unable to open system.dns service");
856 /* Limit system.dns to reverse DNS lookups. */
858 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
859 error("unable to limit access to system.dns service");
860 families
[0] = AF_INET
;
861 /* Casper is a feature of FreeBSD, which defines AF_INET6. */
862 families
[1] = AF_INET6
;
863 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
864 error("unable to limit access to system.dns service");
868 #endif /* HAVE_CASPER */
870 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
872 tstamp_precision_from_string(const char *precision
)
874 if (strncmp(precision
, "nano", strlen("nano")) == 0)
875 return PCAP_TSTAMP_PRECISION_NANO
;
877 if (strncmp(precision
, "micro", strlen("micro")) == 0)
878 return PCAP_TSTAMP_PRECISION_MICRO
;
884 tstamp_precision_to_string(int precision
)
888 case PCAP_TSTAMP_PRECISION_MICRO
:
891 case PCAP_TSTAMP_PRECISION_NANO
:
902 * Ensure that, on a dump file's descriptor, we have all the rights
903 * necessary to make the standard I/O library work with an fdopen()ed
904 * FILE * from that descriptor.
906 * A long time ago in a galaxy far, far away, AT&T decided that, instead
907 * of providing separate APIs for getting and setting the FD_ flags on a
908 * descriptor, getting and setting the O_ flags on a descriptor, and
909 * locking files, they'd throw them all into a kitchen-sink fcntl() call
910 * along the lines of ioctl(), the fact that ioctl() operations are
911 * largely specific to particular character devices but fcntl() operations
912 * are either generic to all descriptors or generic to all descriptors for
913 * regular files notwithstanding.
915 * The Capsicum people decided that fine-grained control of descriptor
916 * operations was required, so that you need to grant permission for
917 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
918 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
919 * collection of things, so there are *individual* fcntls for which
920 * permission needs to be granted.
922 * The FreeBSD standard I/O people implemented some optimizations that
923 * requires that the standard I/O routines be able to determine whether
924 * the descriptor for the FILE * is open append-only or not; as that
925 * descriptor could have come from an open() rather than an fopen(),
926 * that requires that it be able to do an F_GETFL fcntl() to read
929 * tcpdump uses ftell() to determine how much data has been written
930 * to a file in order to, when used with -C, determine when it's time
931 * to rotate capture files. ftell() therefore needs to do an lseek()
932 * to find out the file offset and must, thanks to the aforementioned
933 * optimization, also know whether the descriptor is open append-only
936 * The net result of all the above is that we need to grant CAP_SEEK,
937 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
939 * Perhaps this is the universe's way of saying that either
941 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
942 * using it, so that Capsicum-capable tcpdump wouldn't need to do
947 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
948 * I/O library that knows what rights are needed by the standard
949 * I/O library, based on the open mode, and assigns them, perhaps
950 * with an additional argument indicating, for example, whether
951 * seeking should be allowed, so that tcpdump doesn't need to know
952 * what the standard I/O library happens to require this week.
955 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
957 int fd
= fileno(pcap_dump_file(p
));
960 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
961 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
962 error("unable to limit dump descriptor");
964 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
965 error("unable to limit dump descriptor fcntls");
971 * Copy arg vector into a new buffer, concatenating arguments with spaces.
974 copy_argv(char **argv
)
986 len
+= strlen(*p
++) + 1;
988 buf
= (char *)malloc(len
);
990 error("%s: malloc", __func__
);
994 while ((src
= *p
++) != NULL
) {
995 while ((*dst
++ = *src
++) != '\0')
1005 * On Windows, we need to open the file in binary mode, so that
1006 * we get all the bytes specified by the size we get from "fstat()".
1007 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1008 * we define it as 0 if it's not defined, so it does nothing.
1015 read_infile(char *fname
)
1022 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1024 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1026 if (our_fstat(fd
, &buf
) < 0)
1027 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1030 * Reject files whose size doesn't fit into an int; a filter
1031 * *that* large will probably be too big.
1033 if (buf
.st_size
> INT_MAX
)
1034 error("%s is too large", fname
);
1036 cp
= malloc((u_int
)buf
.st_size
+ 1);
1038 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1039 fname
, pcap_strerror(errno
));
1040 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1042 error("read %s: %s", fname
, pcap_strerror(errno
));
1043 if (cc
!= buf
.st_size
)
1044 error("short read %s (%d != %d)", fname
, (int) cc
,
1048 /* replace "# comment" with spaces */
1049 for (i
= 0; i
< cc
; i
++) {
1051 while (i
< cc
&& cp
[i
] != '\n')
1059 parse_interface_number(const char *device
)
1066 * Search for a colon, terminating any scheme at the beginning
1069 p
= strchr(device
, ':');
1072 * We found it. Is it followed by "//"?
1074 p
++; /* skip the : */
1075 if (strncmp(p
, "//", 2) == 0) {
1077 * Yes. Search for the next /, at the end of the
1078 * authority part of the URL.
1080 p
+= 2; /* skip the // */
1084 * OK, past the / is the path.
1090 devnum
= strtol(device
, &end
, 10);
1091 if (device
!= end
&& *end
== '\0') {
1093 * It's all-numeric, but is it a valid number?
1097 * No, it's not an ordinal.
1099 error("Invalid adapter index");
1104 * It's not all-numeric; return -1, so our caller
1112 find_interface_by_number(const char *url
1113 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1118 pcap_if_t
*dev
, *devlist
;
1120 char ebuf
[PCAP_ERRBUF_SIZE
];
1122 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1128 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1130 * Search for a colon, terminating any scheme at the beginning
1133 endp
= strchr(url
, ':');
1136 * We found it. Is it followed by "//"?
1138 endp
++; /* skip the : */
1139 if (strncmp(endp
, "//", 2) == 0) {
1141 * Yes. Search for the next /, at the end of the
1142 * authority part of the URL.
1144 endp
+= 2; /* skip the // */
1145 endp
= strchr(endp
, '/');
1151 * OK, everything from device to endp is a URL to hand
1152 * to pcap_findalldevs_ex().
1154 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1155 host_url
= malloc(endp
- url
+ 1);
1156 if (host_url
== NULL
&& (endp
- url
+ 1) > 0)
1157 error("Invalid allocation for host");
1159 memcpy(host_url
, url
, endp
- url
);
1160 host_url
[endp
- url
] = '\0';
1161 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1165 status
= pcap_findalldevs(&devlist
, ebuf
);
1169 * Look for the devnum-th entry in the list of devices (1-based).
1171 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1172 i
++, dev
= dev
->next
)
1175 error("Invalid adapter index");
1176 device
= strdup(dev
->name
);
1177 pcap_freealldevs(devlist
);
1181 #ifdef HAVE_PCAP_OPEN
1183 * Prefixes for rpcap URLs.
1185 static char rpcap_prefix
[] = "rpcap://";
1186 static char rpcap_ssl_prefix
[] = "rpcaps://";
1190 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1196 #ifdef HAVE_PCAP_OPEN
1198 * Is this an rpcap URL?
1200 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0 ||
1201 strncmp(device
, rpcap_ssl_prefix
, sizeof(rpcap_ssl_prefix
) - 1) == 0) {
1203 * Yes. Open it with pcap_open().
1206 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1207 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, timeout
, NULL
,
1211 * macOS 14's pcap_pcap_open(), which is a
1212 * stub that always returns NULL with an error
1213 * message of "not supported".
1215 * In this case, as we passed it an rpcap://
1216 * URL, treat that as meaning "remote capture
1219 if (strcmp(ebuf
, "not supported") == 0)
1220 error("Remote capture not supported");
1223 * If this failed with "No such device" or "The system
1224 * cannot find the device specified", that means
1225 * the interface doesn't exist; return NULL, so that
1226 * the caller can see whether the device name is
1227 * actually an interface index.
1229 if (strstr(ebuf
, "No such device") != NULL
||
1230 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1235 warning("%s", ebuf
);
1238 #endif /* HAVE_PCAP_OPEN */
1240 pc
= pcap_create(device
, ebuf
);
1243 * If this failed with "No such device", that means
1244 * the interface doesn't exist; return NULL, so that
1245 * the caller can see whether the device name is
1246 * actually an interface index.
1248 if (strstr(ebuf
, "No such device") != NULL
)
1252 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1254 show_tstamp_types_and_exit(pc
, device
);
1256 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1257 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1259 error("%s: Can't set %ssecond time stamp precision: %s",
1261 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1262 pcap_statustostr(status
));
1265 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1266 if (immediate_mode
) {
1267 status
= pcap_set_immediate_mode(pc
, 1);
1269 error("%s: Can't set immediate mode: %s",
1270 device
, pcap_statustostr(status
));
1274 * Is this an interface that supports monitor mode?
1276 if (pcap_can_set_rfmon(pc
) == 1)
1277 supports_monitor_mode
= 1;
1279 supports_monitor_mode
= 0;
1280 if (ndo
->ndo_snaplen
!= 0) {
1282 * A snapshot length was explicitly specified;
1285 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1287 error("%s: Can't set snapshot length: %s",
1288 device
, pcap_statustostr(status
));
1290 status
= pcap_set_promisc(pc
, !pflag
);
1292 error("%s: Can't set promiscuous mode: %s",
1293 device
, pcap_statustostr(status
));
1295 status
= pcap_set_rfmon(pc
, 1);
1297 error("%s: Can't set monitor mode: %s",
1298 device
, pcap_statustostr(status
));
1300 status
= pcap_set_timeout(pc
, timeout
);
1302 error("%s: pcap_set_timeout failed: %s",
1303 device
, pcap_statustostr(status
));
1305 status
= pcap_set_buffer_size(pc
, Bflag
);
1307 error("%s: Can't set buffer size: %s",
1308 device
, pcap_statustostr(status
));
1310 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1312 status
= pcap_set_tstamp_type(pc
, jflag
);
1314 error("%s: Can't set time stamp type: %s",
1315 device
, pcap_statustostr(status
));
1316 else if (status
> 0)
1317 warning("When trying to set timestamp type '%s' on %s: %s",
1318 pcap_tstamp_type_val_to_name(jflag
), device
,
1319 pcap_statustostr(status
));
1322 status
= pcap_activate(pc
);
1325 * pcap_activate() failed.
1327 cp
= pcap_geterr(pc
);
1328 if (status
== PCAP_ERROR
)
1330 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1332 * Return an error for our caller to handle.
1334 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1335 device
, pcap_statustostr(status
), cp
);
1336 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1337 error("%s: %s\n(%s)", device
,
1338 pcap_statustostr(status
), cp
);
1340 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1341 strncmp(device
, "wlan", 4) == 0) {
1342 char parent
[8], newdev
[8];
1344 size_t s
= sizeof(parent
);
1346 snprintf(sysctl
, sizeof(sysctl
),
1347 "net.wlan.%d.%%parent", atoi(device
+ 4));
1348 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1349 strlcpy(newdev
, device
, sizeof(newdev
));
1350 /* Suggest a new wlan device. */
1351 /* FIXME: incrementing the index this way is not going to work well
1352 * when the index is 9 or greater but the only consequence in this
1353 * specific case would be an error message that looks a bit odd.
1355 newdev
[strlen(newdev
)-1]++;
1356 error("%s is not a monitor mode VAP\n"
1357 "To create a new monitor mode VAP use:\n"
1358 " ifconfig %s create wlandev %s wlanmode monitor\n"
1359 "and use %s as the tcpdump interface",
1360 device
, newdev
, parent
, newdev
);
1364 error("%s: %s", device
,
1365 pcap_statustostr(status
));
1368 } else if (status
> 0) {
1370 * pcap_activate() succeeded, but it's warning us
1371 * of a problem it had.
1373 cp
= pcap_geterr(pc
);
1374 if (status
== PCAP_WARNING
)
1376 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1378 warning("%s: %s\n(%s)", device
,
1379 pcap_statustostr(status
), cp
);
1381 warning("%s: %s", device
,
1382 pcap_statustostr(status
));
1385 status
= pcap_setdirection(pc
, Qflag
);
1387 error("%s: pcap_setdirection() failed: %s",
1388 device
, pcap_geterr(pc
));
1395 main(int argc
, char **argv
)
1398 bpf_u_int32 localnet
= 0, netmask
= 0;
1399 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1401 pcap_handler callback
;
1403 const char *dlt_name
;
1404 struct bpf_program fcode
;
1406 void (*oldhandler
)(int);
1408 struct dump_info dumpinfo
;
1409 u_char
*pcap_userdata
;
1410 char ebuf
[PCAP_ERRBUF_SIZE
];
1411 char VFileLine
[PATH_MAX
+ 1];
1412 const char *username
= NULL
;
1414 const char *chroot_dir
= NULL
;
1422 #ifdef HAVE_CAPSICUM
1423 cap_rights_t rights
;
1425 #endif /* HAVE_CAPSICUM */
1426 int Oflag
= 1; /* run filter code optimizer */
1428 const char *yflag_dlt_name
= NULL
;
1432 netdissect_options Ndo
;
1433 netdissect_options
*ndo
= &Ndo
;
1436 * Initialize the netdissect code.
1438 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1441 memset(ndo
, 0, sizeof(*ndo
));
1442 ndo_set_function_pointers(ndo
);
1452 if ((cp
= strrchr(argv
[0], PATH_SEPARATOR
)) != NULL
)
1453 ndo
->program_name
= program_name
= cp
+ 1;
1455 ndo
->program_name
= program_name
= argv
[0];
1457 #if defined(HAVE_PCAP_WSOCKINIT)
1458 if (pcap_wsockinit() != 0)
1459 error("Attempting to initialize Winsock failed");
1460 #elif defined(HAVE_WSOCKINIT)
1461 if (wsockinit() != 0)
1462 error("Attempting to initialize Winsock failed");
1466 * An explicit tzset() call is usually not needed as it happens
1467 * implicitly the first time we call localtime() or mktime(),
1468 * but in some cases (sandboxing, chroot) this may be too late.
1473 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1477 /* compatibility for old -a */
1489 Bflag
= atoi(optarg
)*1024;
1491 error("invalid packet buffer size %s", optarg
);
1497 error("invalid packet count %s", optarg
);
1502 #ifdef HAVE_PCAP_DUMP_FTELL64
1503 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1505 Cflag
= strtol(optarg
, &endp
, 10);
1507 if (endp
== optarg
|| errno
!= 0 || Cflag
<= 0)
1508 error("invalid file size %s", optarg
);
1510 if (*endp
== '\0') {
1512 * There's nothing after the file size,
1513 * so the size is in units of 1 MB
1514 * (1,000,000 bytes).
1516 Cflagmult
= 1000000;
1519 * There's something after the file
1522 * If it's a single letter, then:
1524 * if the letter is k or K, the size
1525 * is in units of 1 KiB (1024 bytes);
1527 * if the letter is m or M, the size
1528 * is in units of 1 MiB (1,048,576 bytes);
1530 * if the letter is g or G, the size
1531 * is in units of 1 GiB (1,073,741,824 bytes).
1533 * Otherwise, it's an error.
1544 Cflagmult
= 1024*1024;
1549 Cflagmult
= 1024*1024*1024;
1553 error("invalid file size %s", optarg
);
1557 * OK, there was a letter that we treat
1558 * as a units indication; was there
1559 * anything after it?
1562 if (*endp
!= '\0') {
1564 error("invalid file size %s", optarg
);
1569 * Will multiplying it by multiplier overflow?
1571 #ifdef HAVE_PCAP_DUMP_FTELL64
1572 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / Cflagmult
)
1574 if (Cflag
> LONG_MAX
/ Cflagmult
)
1576 error("file size %s is too large", optarg
);
1588 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1589 case OPTION_LIST_REMOTE_INTERFACES
:
1590 remote_interfaces_source
= optarg
;
1603 #ifndef HAVE_LIBCRYPTO
1604 warning("crypto code not compiled in");
1606 ndo
->ndo_espsecret
= optarg
;
1618 Gflag
= atoi(optarg
);
1620 error("invalid number of seconds %s", optarg
);
1622 /* We will create one file initially. */
1625 /* Grab the current time for rotation use. */
1626 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1627 error("%s: can't get current time: %s",
1628 __func__
, pcap_strerror(errno
));
1633 print_usage(stdout
);
1634 exit_tcpdump(S_SUCCESS
);
1649 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1651 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1653 error("invalid time stamp type %s", optarg
);
1664 * _IOLBF is the same as _IOFBF in Microsoft's C
1665 * libraries; the only alternative they offer
1668 * XXX - this should really be checking for MSVC++,
1669 * not _WIN32, if, for example, MinGW has its own
1670 * C library that is more UNIX-compatible.
1672 setvbuf(stdout
, NULL
, _IONBF
, 0);
1674 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1684 if (nd_have_smi_support()) {
1685 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1688 (void)fprintf(stderr
, "%s: ignoring option '-m %s' ",
1689 program_name
, optarg
);
1690 (void)fprintf(stderr
, "(no libsmi support)\n");
1695 /* TCP-MD5 shared secret */
1696 #ifndef HAVE_LIBCRYPTO
1697 warning("crypto code not compiled in");
1699 ndo
->ndo_sigsecret
= optarg
;
1720 ++ndo
->ndo_suppress_default_print
;
1724 if (ascii_strcasecmp(optarg
, "in") == 0)
1726 else if (ascii_strcasecmp(optarg
, "out") == 0)
1728 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1729 Qflag
= PCAP_D_INOUT
;
1731 error("unknown capture direction '%s'", optarg
);
1739 ndo
->ndo_snaplen
= (int)strtol(optarg
, &end
, 0);
1740 if (optarg
== end
|| *end
!= '\0'
1741 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1742 error("invalid snaplen %s (must be >= 0 and <= %d)",
1743 optarg
, MAXIMUM_SNAPLEN
);
1755 if (ascii_strcasecmp(optarg
, "vat") == 0)
1756 ndo
->ndo_packettype
= PT_VAT
;
1757 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1758 ndo
->ndo_packettype
= PT_WB
;
1759 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1760 ndo
->ndo_packettype
= PT_RPC
;
1761 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1762 ndo
->ndo_packettype
= PT_RTP
;
1763 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1764 ndo
->ndo_packettype
= PT_RTCP
;
1765 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1766 ndo
->ndo_packettype
= PT_SNMP
;
1767 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1768 ndo
->ndo_packettype
= PT_CNFP
;
1769 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1770 ndo
->ndo_packettype
= PT_TFTP
;
1771 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1772 ndo
->ndo_packettype
= PT_AODV
;
1773 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1774 ndo
->ndo_packettype
= PT_CARP
;
1775 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1776 ndo
->ndo_packettype
= PT_RADIUS
;
1777 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1778 ndo
->ndo_packettype
= PT_ZMTP1
;
1779 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1780 ndo
->ndo_packettype
= PT_VXLAN
;
1781 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1782 ndo
->ndo_packettype
= PT_PGM
;
1783 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1784 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1785 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1786 ndo
->ndo_packettype
= PT_LMP
;
1787 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1788 ndo
->ndo_packettype
= PT_RESP
;
1789 else if (ascii_strcasecmp(optarg
, "ptp") == 0)
1790 ndo
->ndo_packettype
= PT_PTP
;
1791 else if (ascii_strcasecmp(optarg
, "someip") == 0)
1792 ndo
->ndo_packettype
= PT_SOMEIP
;
1793 else if (ascii_strcasecmp(optarg
, "domain") == 0)
1794 ndo
->ndo_packettype
= PT_DOMAIN
;
1795 else if (ascii_strcasecmp(optarg
, "quic") == 0)
1796 ndo
->ndo_packettype
= PT_QUIC
;
1798 error("unknown packet type '%s'", optarg
);
1822 Wflag
= atoi(optarg
);
1824 error("invalid number of output files %s", optarg
);
1825 WflagChars
= getWflagChars(Wflag
);
1830 ++ndo
->ndo_suppress_default_print
;
1835 ++ndo
->ndo_suppress_default_print
;
1839 yflag_dlt_name
= optarg
;
1841 pcap_datalink_name_to_val(yflag_dlt_name
);
1843 error("invalid data link type %s", yflag_dlt_name
);
1846 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1849 /* Undocumented flag */
1850 pcap_set_parser_debug(1);
1863 ndo
->ndo_packet_number
= 1;
1866 case OPTION_LENGTHS
:
1867 ndo
->ndo_lengths
= 1;
1870 case OPTION_VERSION
:
1871 print_version(stdout
);
1872 exit_tcpdump(S_SUCCESS
);
1875 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1876 case OPTION_TSTAMP_PRECISION
:
1877 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1878 if (ndo
->ndo_tstamp_precision
< 0)
1879 error("unsupported time stamp precision");
1883 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1884 case OPTION_IMMEDIATE_MODE
:
1893 case OPTION_PRINT_SAMPLING
:
1896 ndo
->ndo_print_sampling
= atoi(optarg
);
1897 if (ndo
->ndo_print_sampling
<= 0)
1898 error("invalid print sampling %s", optarg
);
1901 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1902 case OPTION_TSTAMP_MICRO
:
1903 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
1906 case OPTION_TSTAMP_NANO
:
1907 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_NANO
;
1911 case OPTION_FP_TYPE
:
1913 * Print out the type of floating-point arithmetic
1914 * we're doing; it's probably IEEE, unless somebody
1915 * tries to run this on a VAX, but the precision
1916 * may differ (e.g., it might be 32-bit, 64-bit,
1919 float_type_check(0x4e93312d);
1927 print_usage(stderr
);
1928 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1933 show_devices_and_exit();
1934 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1935 if (remote_interfaces_source
!= NULL
)
1936 show_remote_devices_and_exit();
1939 switch (ndo
->ndo_tflag
) {
1941 case 0: /* Default */
1942 case 1: /* No time stamp */
1943 case 2: /* Unix timeval style */
1944 case 3: /* Microseconds/nanoseconds since previous packet */
1945 case 4: /* Date + Default */
1946 case 5: /* Microseconds/nanoseconds since first packet */
1949 default: /* Not supported */
1950 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1954 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1955 error("-f can not be used with -V or -r");
1957 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1958 error("-V and -r are mutually exclusive.");
1961 * If we're printing dissected packets to the standard output,
1962 * and either the standard output is a terminal or we're doing
1963 * "line" buffering, set the capture timeout to .1 second rather
1964 * than 1 second, as the user's probably expecting to see packets
1965 * pop up immediately shortly after they arrive.
1967 * XXX - would there be some value appropriate for all cases,
1968 * based on, say, the buffer size and packet input rate?
1970 if ((WFileName
== NULL
|| print
) && (isatty(1) || lflag
))
1974 /* if run as root, prepare for chrooting */
1975 if (getuid() == 0 || geteuid() == 0) {
1976 /* future extensibility for cmd-line arguments */
1978 chroot_dir
= WITH_CHROOT
;
1983 /* if run as root, prepare for dropping root privileges */
1984 if (getuid() == 0 || geteuid() == 0) {
1985 /* Run with '-Z root' to restore old behaviour */
1987 username
= WITH_USER
;
1988 else if (strcmp(username
, "root") == 0)
1993 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1995 * If RFileName is non-null, it's the pathname of a
1996 * savefile to read. If VFileName is non-null, it's
1997 * the pathname of a file containing a list of pathnames
1998 * (one per line) of savefiles to read.
2000 * In either case, we're reading a savefile, not doing
2005 * We don't need network access, so relinquish any set-UID
2006 * or set-GID privileges we have (if any).
2008 * We do *not* want set-UID privileges when opening a
2009 * trace file, as that might let the user read other
2010 * people's trace files (especially if we're set-UID
2013 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2014 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2016 if (VFileName
!= NULL
) {
2017 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
2020 VFile
= fopen(VFileName
, "r");
2023 error("Unable to open file: %s\n", pcap_strerror(errno
));
2025 ret
= get_next_file(VFile
, VFileLine
);
2027 error("Nothing in %s\n", VFileName
);
2028 RFileName
= VFileLine
;
2031 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2032 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
2033 ndo
->ndo_tstamp_precision
, ebuf
);
2035 pd
= pcap_open_offline(RFileName
, ebuf
);
2040 #ifdef HAVE_CAPSICUM
2041 cap_rights_init(&rights
, CAP_READ
);
2042 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
2044 error("unable to limit pcap descriptor");
2047 dlt
= pcap_datalink(pd
);
2048 dlt_name
= pcap_datalink_val_to_name(dlt
);
2049 fprintf(stderr
, "reading from file %s", RFileName
);
2050 if (dlt_name
== NULL
) {
2051 fprintf(stderr
, ", link-type %u", dlt
);
2053 fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2054 pcap_datalink_val_to_description(dlt
));
2056 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2057 #if defined(DLT_LINUX_SLL2) && defined(__linux__)
2058 if (dlt
== DLT_LINUX_SLL2
)
2059 fprintf(stderr
, "Warning: interface names might be incorrect\n");
2061 } else if (dflag
&& !device
) {
2062 int dump_dlt
= DLT_EN10MB
;
2064 * We're dumping the compiled code without an explicit
2065 * device specification. (If a device is specified, we
2066 * definitely want to open it to use the DLT of that device.)
2067 * Either default to DLT_EN10MB with a warning, or use
2068 * the user-specified value if supplied.
2071 * If no snapshot length was specified, or a length of 0 was
2072 * specified, default to 256KB.
2074 if (ndo
->ndo_snaplen
== 0)
2075 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
2077 * If a DLT was specified with the -y flag, use that instead.
2079 if (yflag_dlt
!= -1)
2080 dump_dlt
= yflag_dlt
;
2082 fprintf(stderr
, "Warning: assuming Ethernet\n");
2083 pd
= pcap_open_dead(dump_dlt
, ndo
->ndo_snaplen
);
2086 * We're doing a live capture.
2088 if (device
== NULL
) {
2090 * No interface was specified. Pick one.
2093 * Find the list of interfaces, and pick
2094 * the first interface.
2096 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2098 if (devlist
== NULL
)
2099 error("no interfaces available for capture");
2100 device
= strdup(devlist
->name
);
2101 pcap_freealldevs(devlist
);
2105 * Try to open the interface with the specified name.
2107 pd
= open_interface(device
, ndo
, ebuf
);
2110 * That failed. If we can get a list of
2111 * interfaces, and the interface name
2112 * is purely numeric, try to use it as
2113 * a 1-based index in the list of
2116 devnum
= parse_interface_number(device
);
2119 * It's not a number; just report
2120 * the open error and fail.
2126 * OK, it's a number; try to find the
2127 * interface with that index, and try
2130 * find_interface_by_number() exits if it
2131 * couldn't be found.
2133 device
= find_interface_by_number(device
, devnum
);
2134 pd
= open_interface(device
, ndo
, ebuf
);
2140 * Let user own process after capture device has
2144 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2145 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2148 show_dlts_and_exit(pd
, device
);
2149 if (yflag_dlt
>= 0) {
2150 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2151 error("%s", pcap_geterr(pd
));
2152 (void)fprintf(stderr
, "%s: data link type %s\n",
2154 pcap_datalink_val_to_name(yflag_dlt
));
2155 (void)fflush(stderr
);
2157 #if defined(DLT_LINUX_SLL2)
2160 * Attempt to set default linktype to
2161 * DLT_LINUX_SLL2 when capturing on the
2164 * If the attempt fails, just quietly drive
2165 * on; this may be a non-Linux "any" device
2166 * that doesn't support DLT_LINUX_SLL2.
2168 if (strcmp(device
, "any") == 0) {
2169 DIAG_OFF_WARN_UNUSED_RESULT
2170 (void) pcap_set_datalink(pd
, DLT_LINUX_SLL2
);
2171 DIAG_ON_WARN_UNUSED_RESULT
2175 i
= pcap_snapshot(pd
);
2176 if (ndo
->ndo_snaplen
< i
) {
2177 if (ndo
->ndo_snaplen
!= 0)
2178 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2179 ndo
->ndo_snaplen
= i
;
2180 } else if (ndo
->ndo_snaplen
> i
) {
2181 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2182 ndo
->ndo_snaplen
= i
;
2184 if(ndo
->ndo_fflag
!= 0) {
2185 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2186 warning("foreign (-f) flag used but: %s", ebuf
);
2192 cmdbuf
= read_infile(infile
);
2194 cmdbuf
= copy_argv(&argv
[optind
]);
2196 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2197 pcap_set_optimizer_debug(dflag
);
2199 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2200 error("%s", pcap_geterr(pd
));
2202 bpf_dump(&fcode
, dflag
);
2205 pcap_freecode(&fcode
);
2206 exit_tcpdump(S_SUCCESS
);
2210 if (!ndo
->ndo_nflag
)
2211 capdns
= capdns_setup();
2212 #endif /* HAVE_CASPER */
2214 init_print(ndo
, localnet
, netmask
);
2217 (void)setsignal(SIGPIPE
, cleanup
);
2218 (void)setsignal(SIGTERM
, cleanup
);
2220 (void)setsignal(SIGINT
, cleanup
);
2221 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2222 (void)setsignal(SIGCHLD
, child_cleanup
);
2224 /* Cooperate with nohup(1) */
2227 * In illumos /usr/include/sys/iso/signal_iso.h causes Clang to
2228 * generate a -Wstrict-prototypes warning here, see [1]. The
2229 * __illumos__ macro is available since at least GCC 11 and Clang 13,
2231 * 1: https://www.illumos.org/issues/16344
2232 * 2: https://www.illumos.org/issues/13726
2235 DIAG_OFF_STRICT_PROTOTYPES
2236 #endif /* __illumos__ */
2237 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2239 DIAG_ON_STRICT_PROTOTYPES
2240 #endif /* __illumos__ */
2241 (void)setsignal(SIGHUP
, oldhandler
);
2246 * If a user name was specified with "-Z", attempt to switch to
2247 * that user's UID. This would probably be used with sudo,
2248 * to allow tcpdump to be run in a special restricted
2249 * account (if you just want to allow users to open capture
2250 * devices, and can't just give users that permission,
2251 * you'd make tcpdump set-UID or set-GID).
2253 * tcpdump doesn't necessarily write only to one savefile;
2254 * the general only way to allow a -Z instance to write to
2255 * savefiles as the user under whose UID it's run, rather
2256 * than as the user specified with -Z, would thus be to switch
2257 * to the original user ID before opening a capture file and
2258 * then switch back to the -Z user ID after opening the savefile.
2259 * Switching to the -Z user ID only after opening the first
2260 * savefile doesn't handle the general case.
2263 if (getuid() == 0 || geteuid() == 0) {
2264 #ifdef HAVE_LIBCAP_NG
2265 /* Initialize capng */
2266 capng_clear(CAPNG_SELECT_BOTH
);
2268 DIAG_OFF_ASSIGN_ENUM
2271 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2278 DIAG_OFF_ASSIGN_ENUM
2281 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2288 DIAG_OFF_ASSIGN_ENUM
2291 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2296 capng_apply(CAPNG_SELECT_BOTH
);
2297 #endif /* HAVE_LIBCAP_NG */
2298 if (username
|| chroot_dir
)
2299 droproot(username
, chroot_dir
);
2304 if (pcap_setfilter(pd
, &fcode
) < 0)
2305 error("%s", pcap_geterr(pd
));
2306 #ifdef HAVE_CAPSICUM
2307 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2308 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2311 * The various libpcap devices use a combination of
2312 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2313 * so we add the relevant access rights.
2315 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2316 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2318 error("unable to limit pcap descriptor");
2320 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2321 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2322 error("unable to limit ioctls on pcap descriptor");
2327 /* Do not exceed the default PATH_MAX for files. */
2328 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2330 if (dumpinfo
.CurrentFileName
== NULL
)
2331 error("malloc of dumpinfo.CurrentFileName");
2333 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2335 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2337 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2339 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2340 #ifdef HAVE_LIBCAP_NG
2341 /* Give up CAP_DAC_OVERRIDE capability.
2342 * Only allow it to be restored if the -C or -G flag have been
2343 * set since we may need to create more files later on.
2347 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2351 capng_apply(CAPNG_SELECT_BOTH
);
2352 #endif /* HAVE_LIBCAP_NG */
2354 error("%s", pcap_geterr(pd
));
2355 #ifdef HAVE_CAPSICUM
2356 set_dumper_capsicum_rights(pdd
);
2358 if (Cflag
!= 0 || Gflag
!= 0) {
2359 #ifdef HAVE_CAPSICUM
2361 * basename() and dirname() may modify their input buffer
2362 * and they do since FreeBSD 12.0, but they didn't before.
2363 * Hence use the return value only, but always assume the
2364 * input buffer has been modified and would need to be
2365 * reset before the next use.
2367 char *WFileName_copy
;
2369 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2370 error("Unable to allocate memory for file %s",
2373 DIAG_OFF_C11_EXTENSIONS
2374 dumpinfo
.WFileName
= strdup(basename(WFileName_copy
));
2375 DIAG_ON_C11_EXTENSIONS
2376 if (dumpinfo
.WFileName
== NULL
) {
2377 error("Unable to allocate memory for file %s",
2380 free(WFileName_copy
);
2382 if ((WFileName_copy
= strdup(WFileName
)) == NULL
) {
2383 error("Unable to allocate memory for file %s",
2386 DIAG_OFF_C11_EXTENSIONS
2387 char *WFileName_dirname
= dirname(WFileName_copy
);
2388 DIAG_ON_C11_EXTENSIONS
2389 dumpinfo
.dirfd
= open(WFileName_dirname
,
2390 O_DIRECTORY
| O_RDONLY
);
2391 if (dumpinfo
.dirfd
< 0) {
2392 error("unable to open directory %s",
2395 free(WFileName_dirname
);
2396 free(WFileName_copy
);
2398 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2399 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2400 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2402 error("unable to limit directory rights");
2404 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2406 error("unable to limit dump descriptor fcntls");
2408 #else /* !HAVE_CAPSICUM */
2409 dumpinfo
.WFileName
= WFileName
;
2411 callback
= dump_packet_and_trunc
;
2414 pcap_userdata
= (u_char
*)&dumpinfo
;
2416 callback
= dump_packet
;
2417 dumpinfo
.WFileName
= WFileName
;
2420 pcap_userdata
= (u_char
*)&dumpinfo
;
2423 dlt
= pcap_datalink(pd
);
2424 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2427 dumpinfo
.ndo
= NULL
;
2430 pcap_dump_flush(pdd
);
2432 dlt
= pcap_datalink(pd
);
2433 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2434 callback
= print_packet
;
2435 pcap_userdata
= (u_char
*)ndo
;
2438 #ifdef SIGNAL_REQ_INFO
2440 * We can't get statistics when reading from a file rather
2441 * than capturing from a device.
2443 if (RFileName
== NULL
)
2444 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2446 #ifdef SIGNAL_FLUSH_PCAP
2447 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2450 if (ndo
->ndo_vflag
> 0 && WFileName
&& RFileName
== NULL
&& !print
) {
2452 * When capturing to a file, if "--print" wasn't specified,
2453 *"-v" means tcpdump should, once per second,
2454 * "v"erbosely report the number of packets captured.
2455 * Except when reading from a file, because -r, -w and -v
2456 * together used to make a corner case, in which pcap_loop()
2457 * errored due to EINTR (see GH #155 for details).
2461 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2463 * suggests that this dates back to W2K.
2465 * I don't know what a "long wait" is, but we'll assume
2466 * that printing the stats could be a "long wait".
2468 CreateTimerQueueTimer(&timer_handle
, NULL
,
2469 verbose_stats_dump
, NULL
, 1000, 1000,
2470 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2471 setvbuf(stderr
, NULL
, _IONBF
, 0);
2474 * Assume this is UN*X, and that it has setitimer(); that
2475 * dates back to UNIX 95.
2477 struct itimerval timer
;
2478 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2479 timer
.it_interval
.tv_sec
= 1;
2480 timer
.it_interval
.tv_usec
= 0;
2481 timer
.it_value
.tv_sec
= 1;
2482 timer
.it_value
.tv_usec
= 1;
2483 setitimer(ITIMER_REAL
, &timer
, NULL
);
2487 if (RFileName
== NULL
) {
2489 * Live capture (if -V was specified, we set RFileName
2490 * to a file from the -V file). Print a message to
2491 * the standard error on UN*X.
2493 if (!ndo
->ndo_vflag
&& !WFileName
) {
2494 (void)fprintf(stderr
,
2495 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2498 (void)fprintf(stderr
, "%s: ", program_name
);
2499 dlt
= pcap_datalink(pd
);
2500 dlt_name
= pcap_datalink_val_to_name(dlt
);
2501 (void)fprintf(stderr
, "listening on %s", device
);
2502 if (dlt_name
== NULL
) {
2503 (void)fprintf(stderr
, ", link-type %u", dlt
);
2505 (void)fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2506 pcap_datalink_val_to_description(dlt
));
2508 (void)fprintf(stderr
, ", snapshot length %d bytes\n", ndo
->ndo_snaplen
);
2509 (void)fflush(stderr
);
2512 #ifdef HAVE_CAPSICUM
2513 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2515 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2517 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2518 #endif /* HAVE_CASPER */
2519 cansandbox
= (cansandbox
&& (pcap_fileno(pd
) != -1 ||
2520 RFileName
!= NULL
));
2522 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2523 error("unable to enter the capability mode");
2524 #endif /* HAVE_CAPSICUM */
2527 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2528 if (WFileName
== NULL
) {
2530 * We're printing packets. Flush the printed output,
2531 * so it doesn't get intermingled with error output.
2535 * We got interrupted, so perhaps we didn't
2536 * manage to finish a line we were printing.
2537 * Print an extra newline, just in case.
2541 (void)fflush(stdout
);
2545 * We got interrupted. If we are reading multiple
2546 * files (via -V) set these so that we stop.
2555 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2556 program_name
, pcap_geterr(pd
));
2558 if (RFileName
== NULL
) {
2560 * We're doing a live capture. Report the capture
2566 if (VFileName
!= NULL
) {
2567 ret
= get_next_file(VFile
, VFileLine
);
2571 RFileName
= VFileLine
;
2572 pd
= pcap_open_offline(RFileName
, ebuf
);
2575 #ifdef HAVE_CAPSICUM
2576 cap_rights_init(&rights
, CAP_READ
);
2577 if (cap_rights_limit(fileno(pcap_file(pd
)),
2578 &rights
) < 0 && errno
!= ENOSYS
) {
2579 error("unable to limit pcap descriptor");
2582 new_dlt
= pcap_datalink(pd
);
2583 if (new_dlt
!= dlt
) {
2585 * The new file has a different
2586 * link-layer header type from the
2589 if (WFileName
!= NULL
) {
2591 * We're writing raw packets
2592 * that match the filter to
2593 * a pcap file. pcap files
2594 * don't support multiple
2595 * different link-layer
2596 * header types, so we fail
2599 error("%s: new dlt does not match original", RFileName
);
2603 * We're printing the decoded packets;
2604 * switch to the new DLT.
2606 * To do that, we need to change
2607 * the printer, change the DLT name,
2608 * and recompile the filter with
2612 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2613 /* Free the old filter */
2614 pcap_freecode(&fcode
);
2615 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2616 error("%s", pcap_geterr(pd
));
2620 * Set the filter on the new file.
2622 if (pcap_setfilter(pd
, &fcode
) < 0)
2623 error("%s", pcap_geterr(pd
));
2626 * Report the new file.
2628 dlt_name
= pcap_datalink_val_to_name(dlt
);
2629 fprintf(stderr
, "reading from file %s", RFileName
);
2630 if (dlt_name
== NULL
) {
2631 fprintf(stderr
, ", link-type %u", dlt
);
2633 fprintf(stderr
, ", link-type %s (%s)",
2635 pcap_datalink_val_to_description(dlt
));
2637 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2641 while (ret
!= NULL
);
2643 if (count_mode
&& RFileName
!= NULL
)
2644 fprintf(stdout
, "%u packet%s\n", packets_captured
,
2645 PLURAL_SUFFIX(packets_captured
));
2648 pcap_freecode(&fcode
);
2649 exit_tcpdump(status
== -1 ? S_ERR_HOST_PROGRAM
: S_SUCCESS
);
2656 (*setsignal (int sig
, void (*func
)(int)))(int)
2659 return (signal(sig
, func
));
2661 struct sigaction old
, new;
2663 memset(&new, 0, sizeof(new));
2664 new.sa_handler
= func
;
2665 if ((sig
== SIGCHLD
)
2666 # ifdef SIGNAL_REQ_INFO
2667 || (sig
== SIGNAL_REQ_INFO
)
2669 # ifdef SIGNAL_FLUSH_PCAP
2670 || (sig
== SIGNAL_FLUSH_PCAP
)
2673 new.sa_flags
= SA_RESTART
;
2674 if (sigaction(sig
, &new, &old
) < 0)
2675 /* The same workaround as for SIG_DFL above. */
2677 DIAG_OFF_STRICT_PROTOTYPES
2678 #endif /* __illumos__ */
2681 DIAG_ON_STRICT_PROTOTYPES
2682 #endif /* __illumos__ */
2683 return (old
.sa_handler
);
2687 /* make a clean exit on interrupts */
2689 cleanup(int signo _U_
)
2692 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2693 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2694 CloseHandle(timer_handle
);
2695 timer_handle
= INVALID_HANDLE_VALUE
;
2698 struct itimerval timer
;
2700 timer
.it_interval
.tv_sec
= 0;
2701 timer
.it_interval
.tv_usec
= 0;
2702 timer
.it_value
.tv_sec
= 0;
2703 timer
.it_value
.tv_usec
= 0;
2704 setitimer(ITIMER_REAL
, &timer
, NULL
);
2708 * We have "pcap_breakloop()"; use it, so that we do as little
2709 * as possible in the signal handler (it's probably not safe
2710 * to do anything with standard I/O streams in a signal handler -
2711 * the ANSI C standard doesn't say it is).
2717 On windows, we do not use a fork, so we do not care less about
2718 waiting a child processes to die
2720 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2722 child_cleanup(int signo _U_
)
2724 while (waitpid(-1, NULL
, WNOHANG
) >= 0);
2726 #endif /* HAVE_FORK && HAVE_VFORK */
2731 struct pcap_stat stats
;
2734 * Older versions of libpcap didn't set ps_ifdrop on some
2735 * platforms; initialize it to 0 to handle that.
2737 stats
.ps_ifdrop
= 0;
2738 if (pcap_stats(pd
, &stats
) < 0) {
2739 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2745 fprintf(stderr
, "%s: ", program_name
);
2747 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2748 PLURAL_SUFFIX(packets_captured
));
2750 fputs(", ", stderr
);
2753 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2754 PLURAL_SUFFIX(stats
.ps_recv
));
2756 fputs(", ", stderr
);
2759 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2760 PLURAL_SUFFIX(stats
.ps_drop
));
2761 if (stats
.ps_ifdrop
!= 0) {
2763 fputs(", ", stderr
);
2766 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2767 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2773 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2775 #define fork_subprocess() fork()
2777 #define fork_subprocess() vfork()
2780 compress_savefile(const char *filename
)
2784 child
= fork_subprocess();
2787 "compress_savefile: fork failed: %s\n",
2788 pcap_strerror(errno
));
2792 /* Parent process. */
2798 * Set to lowest priority so that this doesn't disturb the capture.
2801 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2803 setpriority(PRIO_PROCESS
, 0, 19);
2805 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2807 "compress_savefile: execlp(%s, %s) failed: %s\n",
2810 pcap_strerror(errno
));
2812 exit(S_ERR_HOST_PROGRAM
);
2814 _exit(S_ERR_HOST_PROGRAM
);
2817 #else /* HAVE_FORK && HAVE_VFORK */
2819 compress_savefile(const char *filename
)
2822 "compress_savefile failed. Functionality not implemented under your system\n");
2824 #endif /* HAVE_FORK && HAVE_VFORK */
2827 close_old_dump_file(struct dump_info
*dump_info
)
2830 * Close the current file and open a new one.
2832 pcap_dump_close(dump_info
->pdd
);
2835 * Compress the file we just closed, if the user asked for it.
2838 compress_savefile(dump_info
->CurrentFileName
);
2842 open_new_dump_file(struct dump_info
*dump_info
)
2844 #ifdef HAVE_CAPSICUM
2849 #ifdef HAVE_LIBCAP_NG
2850 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2851 capng_apply(CAPNG_SELECT_BOTH
);
2852 #endif /* HAVE_LIBCAP_NG */
2853 #ifdef HAVE_CAPSICUM
2854 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2855 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2857 error("unable to open file %s", dump_info
->CurrentFileName
);
2859 fp
= fdopen(fd
, "w");
2861 error("unable to fdopen file %s", dump_info
->CurrentFileName
);
2863 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2864 #else /* !HAVE_CAPSICUM */
2865 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2867 #ifdef HAVE_LIBCAP_NG
2868 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2869 capng_apply(CAPNG_SELECT_BOTH
);
2870 #endif /* HAVE_LIBCAP_NG */
2871 if (dump_info
->pdd
== NULL
)
2872 error("%s", pcap_geterr(pd
));
2873 #ifdef HAVE_CAPSICUM
2874 set_dumper_capsicum_rights(dump_info
->pdd
);
2879 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2881 struct dump_info
*dump_info
;
2887 dump_info
= (struct dump_info
*)user
;
2890 * XXX - this won't force the file to rotate on the specified time
2891 * boundary, but it will rotate on the first packet received after the
2892 * specified Gflag number of seconds. Note: if a Gflag time boundary
2893 * and a Cflag size boundary coincide, the time rotation will occur
2894 * first thereby cancelling the Cflag boundary (since the file should
2898 /* Check if it is time to rotate */
2901 /* Get the current time */
2902 if ((t
= time(NULL
)) == (time_t)-1) {
2903 error("%s: can't get current_time: %s",
2904 __func__
, pcap_strerror(errno
));
2908 /* If the time is greater than the specified window, rotate */
2909 if (t
- Gflag_time
>= Gflag
) {
2910 /* Update the Gflag_time */
2912 /* Update Gflag_count */
2915 close_old_dump_file(dump_info
);
2918 * Check to see if we've exceeded the Wflag (when
2921 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2922 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2925 exit_tcpdump(S_SUCCESS
);
2928 if (dump_info
->CurrentFileName
!= NULL
)
2929 free(dump_info
->CurrentFileName
);
2930 /* Allocate space for max filename + \0. */
2931 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2932 if (dump_info
->CurrentFileName
== NULL
)
2933 error("dump_packet_and_trunc: malloc");
2935 * Gflag was set otherwise we wouldn't be here. Reset the count
2936 * so multiple files would end with 1,2,3 in the filename.
2937 * The counting is handled with the -C flow after this.
2942 * This is always the first file in the Cflag
2944 * We also don't need numbering if Cflag is not set.
2947 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2950 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2952 open_new_dump_file(dump_info
);
2957 * XXX - this won't prevent capture files from getting
2958 * larger than Cflag - the last packet written to the
2959 * file could put it over Cflag.
2962 #ifdef HAVE_PCAP_DUMP_FTELL64
2963 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
2966 * XXX - this only handles a Cflag value > 2^31-1 on
2967 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2968 * Windows) or LLP64 (64-bit Windows) would require
2969 * a version of libpcap with pcap_dump_ftell64().
2971 long size
= pcap_dump_ftell(dump_info
->pdd
);
2975 error("ftell fails on output file");
2977 close_old_dump_file(dump_info
);
2981 if (Cflag_count
>= Wflag
)
2984 if (dump_info
->CurrentFileName
!= NULL
)
2985 free(dump_info
->CurrentFileName
);
2986 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2987 if (dump_info
->CurrentFileName
== NULL
)
2988 error("%s: malloc", __func__
);
2989 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2991 open_new_dump_file(dump_info
);
2995 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2997 pcap_dump_flush(dump_info
->pdd
);
2999 if (dump_info
->ndo
!= NULL
)
3000 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3008 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3010 struct dump_info
*dump_info
;
3016 dump_info
= (struct dump_info
*)user
;
3018 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3020 pcap_dump_flush(dump_info
->pdd
);
3022 if (dump_info
->ndo
!= NULL
)
3023 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3031 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3038 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
3045 #ifdef SIGNAL_REQ_INFO
3047 requestinfo(int signo _U_
)
3056 #ifdef SIGNAL_FLUSH_PCAP
3058 flushpcap(int signo _U_
)
3061 pcap_dump_flush(pdd
);
3066 print_packets_captured (void)
3068 static u_int prev_packets_captured
, first
= 1;
3070 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
3071 fprintf(stderr
, "Got %u\r", packets_captured
);
3073 prev_packets_captured
= packets_captured
;
3078 * Called once each second in verbose mode while dumping to file
3081 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
3082 BOOLEAN timer_fired _U_
)
3084 print_packets_captured();
3087 static void verbose_stats_dump(int sig _U_
)
3089 print_packets_captured();
3093 DIAG_OFF_DEPRECATION
3095 print_version(FILE *f
)
3097 const char *smi_version_string
;
3099 (void)fprintf(f
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3100 (void)fprintf(f
, "%s\n", pcap_lib_version());
3102 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3103 (void)fprintf (f
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3106 smi_version_string
= nd_smi_version_string();
3107 if (smi_version_string
!= NULL
)
3108 (void)fprintf (f
, "SMI-library: %s\n", smi_version_string
);
3110 #if defined(__SANITIZE_ADDRESS__)
3111 (void)fprintf (f
, "Compiled with AddressSanitizer/GCC.\n");
3112 #elif defined(__has_feature)
3113 # if __has_feature(address_sanitizer)
3114 (void)fprintf (f
, "Compiled with AddressSanitizer/Clang.\n");
3115 # elif __has_feature(memory_sanitizer)
3116 (void)fprintf (f
, "Compiled with MemorySanitizer/Clang.\n");
3118 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3119 (void)fprintf (f
, "%zu-bit build, %zu-bit time_t\n",
3120 sizeof(void *) * 8, sizeof(time_t) * 8);
3125 print_usage(FILE *f
)
3129 "Usage: %s [-AbdDefhHI" J_FLAG
"KlLnNOpqStuUvxX#] [ -B size ] [ -c count ] [--count]\n", program_name
);
3131 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3133 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3135 "\t\t[ --lengths ]" LIST_REMOTE_INTERFACES_USAGE
"\n");
3138 "\t\t" m_FLAG_USAGE
"\n");
3141 "\t\t[ -M secret ] [ --number ] [ --print ]\n");
3143 "\t\t[ --print-sampling nth ] [ -Q in|out|inout ] [ -r file ]\n");
3145 "\t\t[ -s snaplen ] [ -T type ] [ --version ]\n");
3147 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3148 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3150 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3153 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");