2 * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 * Support for splitting captures into multiple files with a maximum
25 * Seth Webster <swebster@sst.ll.mit.edu>
29 * tcpdump - dump traffic on a network
31 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
32 * Mercilessly hacked and occasionally improved since then via the
33 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
41 * Some older versions of Mac OS X may ship pcap.h from libpcap 0.6 with a
42 * libpcap based on 0.8. That means it has pcap_findalldevs() but the
43 * header doesn't define pcap_if_t, meaning that we can't actually *use*
46 #ifdef HAVE_PCAP_FINDALLDEVS
47 #ifndef HAVE_PCAP_IF_T
48 #undef HAVE_PCAP_FINDALLDEVS
52 #include "netdissect-stdinc.h"
55 * This must appear after including netdissect-stdinc.h, so that _U_ is
59 static const char copyright
[] _U_
=
60 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
61 The Regents of the University of California. All rights reserved.\n";
71 #include <openssl/crypto.h>
74 #ifdef HAVE_GETOPT_LONG
77 #include "missing/getopt_long.h"
79 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
80 * to compile if <pcap.h> has already been included; including the headers
81 * in the opposite order works fine.
84 #include <sys/capsicum.h>
85 #include <sys/ioccom.h>
89 #include <libcasper.h>
90 #include <casper/cap_dns.h>
92 #endif /* HAVE_CASPER */
93 #endif /* HAVE_CAPSICUM */
96 * We found pcap_open() in the capture library, so we'll be using
97 * the remote capture APIs; define PCAP_REMOTE before we include pcap.h,
98 * so we get those APIs declared, and the types and #defines that they
101 * WinPcap's headers require that PCAP_REMOTE be defined in order to get
102 * remote-capture APIs declared and types and #defines that they use
105 * (Versions of libpcap with those APIs, and thus Npcap, which is based on
106 * those versions of libpcap, don't require it.)
120 #include <sys/time.h>
121 #include <sys/wait.h>
122 #include <sys/resource.h>
128 * Pathname separator.
129 * Use this in pathnames, but do *not* use it in URLs.
132 #define PATH_SEPARATOR '\\'
134 #define PATH_SEPARATOR '/'
137 /* capabilities convenience library */
138 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
139 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
140 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
142 #ifdef HAVE_LIBCAP_NG
146 #undef HAVE_LIBCAP_NG
147 #endif /* HAVE_CAP_NG_H */
148 #endif /* HAVE_LIBCAP_NG */
151 #include <sys/sysctl.h>
152 #endif /* __FreeBSD__ */
154 #include "netdissect-stdinc.h"
155 #include "netdissect.h"
156 #include "interface.h"
157 #include "addrtoname.h"
159 #include "pcap-missing.h"
160 #include "ascii_strcasecmp.h"
164 #include "diag-control.h"
169 #define PATH_MAX 1024
173 #define SIGNAL_REQ_INFO SIGINFO
174 #elif defined(SIGUSR1)
175 #define SIGNAL_REQ_INFO SIGUSR1
178 #if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
179 #define SIGNAL_FLUSH_PCAP SIGUSR2
182 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
183 static int Bflag
; /* buffer size */
185 #ifdef HAVE_PCAP_DUMP_FTELL64
186 static int64_t Cflag
; /* rotate dump files after this many bytes */
188 static long Cflag
; /* rotate dump files after this many bytes */
190 static int Cflag_count
; /* Keep track of which file number we're writing */
191 #ifdef HAVE_PCAP_FINDALLDEVS
192 static int Dflag
; /* list available devices and exit */
194 #ifdef HAVE_PCAP_FINDALLDEVS_EX
195 static char *remote_interfaces_source
; /* list available devices from this source and exit */
199 * This is exported because, in some versions of libpcap, if libpcap
200 * is built with optimizer debugging code (which is *NOT* the default
201 * configuration!), the library *imports*(!) a variable named dflag,
202 * under the expectation that tcpdump is exporting it, to govern
203 * how much debugging information to print when optimizing
204 * the generated BPF code.
206 * This is a horrible hack; newer versions of libpcap don't import
207 * dflag but, instead, *if* built with optimizer debugging code,
208 * *export* a routine to set that flag.
211 int dflag
; /* print filter code */
212 static int Gflag
; /* rotate dump files after this many seconds */
213 static int Gflag_count
; /* number of files created with Gflag rotation */
214 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
215 static int Lflag
; /* list available data link types and exit */
216 static int Iflag
; /* rfmon (monitor) mode */
217 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
218 static int Jflag
; /* list available time stamp types */
219 static int jflag
= -1; /* packet time stamp source */
221 static int lflag
; /* line-buffered output */
222 static int pflag
; /* don't go promiscuous */
223 #ifdef HAVE_PCAP_SETDIRECTION
224 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
226 #ifdef HAVE_PCAP_DUMP_FLUSH
227 static int Uflag
; /* "unbuffered" output of dump files */
229 static int Wflag
; /* recycle output files after this number of files */
230 static int WflagChars
;
231 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
232 static int timeout
= 1000; /* default timeout = 1000 ms = 1 s */
233 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
234 static int immediate_mode
;
236 static int count_mode
;
238 static int infodelay
;
239 static int infoprint
;
244 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
245 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
246 static NORETURN
void exit_tcpdump(int);
247 static void (*setsignal (int sig
, void (*func
)(int)))(int);
248 static void cleanup(int);
249 static void child_cleanup(int);
250 static void print_version(FILE *);
251 static void print_usage(FILE *);
252 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
253 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
255 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
256 #ifdef HAVE_PCAP_FINDALLDEVS
257 static NORETURN
void show_devices_and_exit(void);
259 #ifdef HAVE_PCAP_FINDALLDEVS_EX
260 static NORETURN
void show_remote_devices_and_exit(void);
263 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
264 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
265 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
266 static void droproot(const char *, const char *);
268 #ifdef SIGNAL_REQ_INFO
269 static void requestinfo(int);
272 #ifdef SIGNAL_FLUSH_PCAP
273 static void flushpcap(int);
277 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
278 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
280 static void verbose_stats_dump(int sig
);
283 static void info(int);
284 static u_int packets_captured
;
286 #ifdef HAVE_PCAP_FINDALLDEVS
287 static const struct tok status_flags
[] = {
289 { PCAP_IF_UP
, "Up" },
291 #ifdef PCAP_IF_RUNNING
292 { PCAP_IF_RUNNING
, "Running" },
294 { PCAP_IF_LOOPBACK
, "Loopback" },
295 #ifdef PCAP_IF_WIRELESS
296 { PCAP_IF_WIRELESS
, "Wireless" },
303 static pcap_dumper_t
*pdd
= NULL
;
305 static int supports_monitor_mode
;
313 char *CurrentFileName
;
316 netdissect_options
*ndo
;
322 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
324 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
325 * by any libpcap header, because it's a special hack, only available if
326 * libpcap was configured to include it, and only intended for use by
327 * libpcap developers trying to debug the parser for filter expressions).
330 __declspec(dllimport
)
334 void pcap_set_parser_debug(int);
335 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
337 * We don't have pcap_set_parser_debug() in libpcap, but we do have
338 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
339 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
342 pcap_set_parser_debug(int value
)
344 #ifdef HAVE_PCAP_DEBUG
345 extern int pcap_debug
;
348 #else /* HAVE_PCAP_DEBUG */
352 #endif /* HAVE_PCAP_DEBUG */
355 #define HAVE_PCAP_SET_PARSER_DEBUG
358 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
360 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
361 * by any libpcap header, because it's a special hack, only available if
362 * libpcap was configured to include it, and only intended for use by
363 * libpcap developers trying to debug the optimizer for filter expressions).
366 __declspec(dllimport
)
370 void pcap_set_optimizer_debug(int);
375 error(const char *fmt
, ...)
379 (void)fprintf(stderr
, "%s: ", program_name
);
381 (void)vfprintf(stderr
, fmt
, ap
);
386 (void)fputc('\n', stderr
);
388 exit_tcpdump(S_ERR_HOST_PROGRAM
);
394 warning(const char *fmt
, ...)
398 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
400 (void)vfprintf(stderr
, fmt
, ap
);
405 (void)fputc('\n', stderr
);
410 exit_tcpdump(int status
)
416 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
418 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
421 int *tstamp_types
= 0;
422 const char *tstamp_type_name
;
425 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
426 if (n_tstamp_types
< 0)
427 error("%s", pcap_geterr(pc
));
429 if (n_tstamp_types
== 0) {
430 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
432 exit_tcpdump(S_SUCCESS
);
434 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
436 for (i
= 0; i
< n_tstamp_types
; i
++) {
437 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
438 if (tstamp_type_name
!= NULL
) {
439 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
440 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
442 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
445 pcap_free_tstamp_types(tstamp_types
);
446 exit_tcpdump(S_SUCCESS
);
451 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
455 const char *dlt_name
;
457 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
459 error("%s", pcap_geterr(pc
));
460 else if (n_dlts
== 0 || !dlts
)
461 error("No data link types.");
464 * If the interface is known to support monitor mode, indicate
465 * whether these are the data link types available when not in
466 * monitor mode, if -I wasn't specified, or when in monitor mode,
467 * when -I was specified (the link-layer types available in
468 * monitor mode might be different from the ones available when
469 * not in monitor mode).
471 if (supports_monitor_mode
)
472 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
474 Iflag
? "when in monitor mode" : "when not in monitor mode");
476 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
479 for (i
= 0; i
< n_dlts
; i
++) {
480 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
481 if (dlt_name
!= NULL
) {
482 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
483 pcap_datalink_val_to_description(dlts
[i
]));
486 * OK, does tcpdump handle that type?
488 if (!has_printer(dlts
[i
]))
489 (void) fprintf(stderr
, " (printing not supported)");
490 fprintf(stderr
, "\n");
492 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
496 #ifdef HAVE_PCAP_FREE_DATALINKS
497 pcap_free_datalinks(dlts
);
499 exit_tcpdump(S_SUCCESS
);
502 #ifdef HAVE_PCAP_FINDALLDEVS
504 show_devices_and_exit(void)
506 pcap_if_t
*dev
, *devlist
;
507 char ebuf
[PCAP_ERRBUF_SIZE
];
510 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
512 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
513 printf("%d.%s", i
+1, dev
->name
);
514 if (dev
->description
!= NULL
)
515 printf(" (%s)", dev
->description
);
516 if (dev
->flags
!= 0) {
518 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
519 #ifdef PCAP_IF_WIRELESS
520 if (dev
->flags
& PCAP_IF_WIRELESS
) {
521 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
523 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
524 printf(", Association status unknown");
527 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
528 printf(", Associated");
531 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
532 printf(", Not associated");
535 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
539 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
541 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
542 printf(", Connection status unknown");
545 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
546 printf(", Connected");
549 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
550 printf(", Disconnected");
553 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
562 pcap_freealldevs(devlist
);
563 exit_tcpdump(S_SUCCESS
);
565 #endif /* HAVE_PCAP_FINDALLDEVS */
567 #ifdef HAVE_PCAP_FINDALLDEVS_EX
569 show_remote_devices_and_exit(void)
571 pcap_if_t
*dev
, *devlist
;
572 char ebuf
[PCAP_ERRBUF_SIZE
];
575 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
578 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
579 printf("%d.%s", i
+1, dev
->name
);
580 if (dev
->description
!= NULL
)
581 printf(" (%s)", dev
->description
);
583 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
586 pcap_freealldevs(devlist
);
587 exit_tcpdump(S_SUCCESS
);
589 #endif /* HAVE_PCAP_FINDALLDEVS */
594 * Note that there we use all letters for short options except for g, k,
595 * o, and P, and those are used by other versions of tcpdump, and we should
596 * only use them for the same purposes that the other versions of tcpdump
599 * macOS tcpdump uses -g to force non--v output for IP to be on one
600 * line, making it more "g"repable;
602 * macOS tcpdump uses -k to specify that packet comments in pcapng files
605 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
606 * for hosts sending TCP SYN packets;
608 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
611 * macOS tcpdump also uses -Q to specify expressions that match packet
612 * metadata, including but not limited to the packet direction.
613 * The expression syntax is different from a simple "in|out|inout",
614 * and those expressions aren't accepted by macOS tcpdump, but the
615 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
616 * "inout" = "dir=in or dir=out", and the parser could conceivably
617 * special-case "in", "out", and "inout" as expressions for backwards
618 * compatibility, so all is not (yet) lost.
622 * Set up flags that might or might not be supported depending on the
623 * version of libpcap we're using.
625 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
627 #define B_FLAG_USAGE " [ -B size ]"
628 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
631 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
633 #ifdef HAVE_PCAP_FINDALLDEVS
639 #ifdef HAVE_PCAP_CREATE
641 #else /* HAVE_PCAP_CREATE */
643 #endif /* HAVE_PCAP_CREATE */
645 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
647 #define j_FLAG_USAGE " [ -j tstamptype ]"
649 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
653 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
656 #define m_FLAG_USAGE "[ -m module ] ..."
659 #ifdef HAVE_PCAP_SETDIRECTION
661 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
667 #ifdef HAVE_PCAP_DUMP_FLUSH
673 #define SHORTOPTS "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpq" Q_FLAG "r:s:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:#"
678 * We do not currently have long options corresponding to all short
679 * options; we should probably pick appropriate option names for them.
681 * However, the short options where the number of times the option is
682 * specified matters, such as -v and -d and -t, should probably not
683 * just map to a long option, as saying
685 * tcpdump --verbose --verbose
687 * doesn't make sense; it should be --verbosity={N} or something such
690 * For long options with no corresponding short options, we define values
691 * outside the range of ASCII graphic characters, make that the last
692 * component of the entry for the long option, and have a case for that
693 * option in the switch statement.
695 #define OPTION_VERSION 128
696 #define OPTION_TSTAMP_PRECISION 129
697 #define OPTION_IMMEDIATE_MODE 130
698 #define OPTION_PRINT 131
699 #define OPTION_LIST_REMOTE_INTERFACES 132
700 #define OPTION_TSTAMP_MICRO 133
701 #define OPTION_TSTAMP_NANO 134
702 #define OPTION_FP_TYPE 135
703 #define OPTION_COUNT 136
705 static const struct option longopts
[] = {
706 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
707 { "buffer-size", required_argument
, NULL
, 'B' },
709 { "list-interfaces", no_argument
, NULL
, 'D' },
710 #ifdef HAVE_PCAP_FINDALLDEVS_EX
711 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
713 { "help", no_argument
, NULL
, 'h' },
714 { "interface", required_argument
, NULL
, 'i' },
715 #ifdef HAVE_PCAP_CREATE
716 { "monitor-mode", no_argument
, NULL
, 'I' },
718 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
719 { "time-stamp-type", required_argument
, NULL
, 'j' },
720 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
722 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
723 { "micro", no_argument
, NULL
, OPTION_TSTAMP_MICRO
},
724 { "nano", no_argument
, NULL
, OPTION_TSTAMP_NANO
},
725 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
727 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
728 { "list-data-link-types", no_argument
, NULL
, 'L' },
729 { "no-optimize", no_argument
, NULL
, 'O' },
730 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
731 #ifdef HAVE_PCAP_SETDIRECTION
732 { "direction", required_argument
, NULL
, 'Q' },
734 { "snapshot-length", required_argument
, NULL
, 's' },
735 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
736 #ifdef HAVE_PCAP_DUMP_FLUSH
737 { "packet-buffered", no_argument
, NULL
, 'U' },
739 { "linktype", required_argument
, NULL
, 'y' },
740 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
741 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
743 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
744 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
746 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
747 { "count", no_argument
, NULL
, OPTION_COUNT
},
748 { "fp-type", no_argument
, NULL
, OPTION_FP_TYPE
},
749 { "number", no_argument
, NULL
, '#' },
750 { "print", no_argument
, NULL
, OPTION_PRINT
},
751 { "version", no_argument
, NULL
, OPTION_VERSION
},
755 #ifdef HAVE_PCAP_FINDALLDEVS_EX
756 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
758 #define LIST_REMOTE_INTERFACES_USAGE
761 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
762 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
764 #define IMMEDIATE_MODE_USAGE ""
768 /* Drop root privileges and chroot if necessary */
770 droproot(const char *username
, const char *chroot_dir
)
772 struct passwd
*pw
= NULL
;
774 if (chroot_dir
&& !username
)
775 error("Chroot without dropping root is insecure");
777 pw
= getpwnam(username
);
780 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
781 error("Couldn't chroot/chdir to '%.64s': %s",
782 chroot_dir
, pcap_strerror(errno
));
784 #ifdef HAVE_LIBCAP_NG
786 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
788 error("capng_change_id(): return %d\n", ret
);
790 fprintf(stderr
, "dropped privs to %s\n", username
);
793 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
794 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
795 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
797 (unsigned long)pw
->pw_uid
,
798 (unsigned long)pw
->pw_gid
,
799 pcap_strerror(errno
));
801 fprintf(stderr
, "dropped privs to %s\n", username
);
803 #endif /* HAVE_LIBCAP_NG */
805 error("Couldn't find user '%.32s'", username
);
806 #ifdef HAVE_LIBCAP_NG
807 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
811 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
817 capng_apply(CAPNG_SELECT_BOTH
);
818 #endif /* HAVE_LIBCAP_NG */
839 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
841 char *filename
= malloc(PATH_MAX
+ 1);
842 if (filename
== NULL
)
843 error("%s: malloc", __func__
);
845 /* Process with strftime if Gflag is set. */
849 /* Convert Gflag_time to a usable format */
850 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
851 error("%s: localtime", __func__
);
854 /* There's no good way to detect an error in strftime since a return
855 * value of 0 isn't necessarily failure.
857 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
859 strncpy(filename
, orig_name
, PATH_MAX
);
862 if (cnt
== 0 && max_chars
== 0)
863 strncpy(buffer
, filename
, PATH_MAX
+ 1);
865 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
866 /* Report an error if the filename is too large */
867 error("too many output files or filename is too long (> %d)", PATH_MAX
);
872 get_next_file(FILE *VFile
, char *ptr
)
877 ret
= fgets(ptr
, PATH_MAX
, VFile
);
882 if (len
> 0 && ptr
[len
- 1] == '\n')
889 static cap_channel_t
*
892 cap_channel_t
*capcas
, *capdnsloc
;
893 const char *types
[1];
898 error("unable to create casper process");
899 capdnsloc
= cap_service_open(capcas
, "system.dns");
900 /* Casper capability no longer needed. */
902 if (capdnsloc
== NULL
)
903 error("unable to open system.dns service");
904 /* Limit system.dns to reverse DNS lookups. */
906 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
907 error("unable to limit access to system.dns service");
908 families
[0] = AF_INET
;
909 families
[1] = AF_INET6
;
910 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
911 error("unable to limit access to system.dns service");
915 #endif /* HAVE_CASPER */
917 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
919 tstamp_precision_from_string(const char *precision
)
921 if (strncmp(precision
, "nano", strlen("nano")) == 0)
922 return PCAP_TSTAMP_PRECISION_NANO
;
924 if (strncmp(precision
, "micro", strlen("micro")) == 0)
925 return PCAP_TSTAMP_PRECISION_MICRO
;
931 tstamp_precision_to_string(int precision
)
935 case PCAP_TSTAMP_PRECISION_MICRO
:
938 case PCAP_TSTAMP_PRECISION_NANO
:
949 * Ensure that, on a dump file's descriptor, we have all the rights
950 * necessary to make the standard I/O library work with an fdopen()ed
951 * FILE * from that descriptor.
953 * A long time ago in a galaxy far, far away, AT&T decided that, instead
954 * of providing separate APIs for getting and setting the FD_ flags on a
955 * descriptor, getting and setting the O_ flags on a descriptor, and
956 * locking files, they'd throw them all into a kitchen-sink fcntl() call
957 * along the lines of ioctl(), the fact that ioctl() operations are
958 * largely specific to particular character devices but fcntl() operations
959 * are either generic to all descriptors or generic to all descriptors for
960 * regular files nonwithstanding.
962 * The Capsicum people decided that fine-grained control of descriptor
963 * operations was required, so that you need to grant permission for
964 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
965 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
966 * collection of things, so there are *individual* fcntls for which
967 * permission needs to be granted.
969 * The FreeBSD standard I/O people implemented some optimizations that
970 * requires that the standard I/O routines be able to determine whether
971 * the descriptor for the FILE * is open append-only or not; as that
972 * descriptor could have come from an open() rather than an fopen(),
973 * that requires that it be able to do an F_GETFL fcntl() to read
976 * Tcpdump uses ftell() to determine how much data has been written
977 * to a file in order to, when used with -C, determine when it's time
978 * to rotate capture files. ftell() therefore needs to do an lseek()
979 * to find out the file offset and must, thanks to the aforementioned
980 * optimization, also know whether the descriptor is open append-only
983 * The net result of all the above is that we need to grant CAP_SEEK,
984 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
986 * Perhaps this is the universe's way of saying that either
988 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
989 * using it, so that Capsicum-capable tcpdump wouldn't need to do
994 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
995 * I/O library that knows what rights are needed by the standard
996 * I/O library, based on the open mode, and assigns them, perhaps
997 * with an additional argument indicating, for example, whether
998 * seeking should be allowed, so that tcpdump doesn't need to know
999 * what the standard I/O library happens to require this week.
1002 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
1004 int fd
= fileno(pcap_dump_file(p
));
1005 cap_rights_t rights
;
1007 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
1008 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
1009 error("unable to limit dump descriptor");
1011 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
1012 error("unable to limit dump descriptor fcntls");
1018 * Copy arg vector into a new buffer, concatenating arguments with spaces.
1021 copy_argv(char **argv
)
1033 len
+= strlen(*p
++) + 1;
1035 buf
= (char *)malloc(len
);
1037 error("%s: malloc", __func__
);
1041 while ((src
= *p
++) != NULL
) {
1042 while ((*dst
++ = *src
++) != '\0')
1052 * On Windows, we need to open the file in binary mode, so that
1053 * we get all the bytes specified by the size we get from "fstat()".
1054 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1055 * we define it as 0 if it's not defined, so it does nothing.
1062 read_infile(char *fname
)
1069 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1071 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1073 if (our_fstat(fd
, &buf
) < 0)
1074 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1077 * Reject files whose size doesn't fit into an int; a filter
1078 * *that* large will probably be too big.
1080 if (buf
.st_size
> INT_MAX
)
1081 error("%s is too large", fname
);
1083 cp
= malloc((u_int
)buf
.st_size
+ 1);
1085 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1086 fname
, pcap_strerror(errno
));
1087 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1089 error("read %s: %s", fname
, pcap_strerror(errno
));
1090 if (cc
!= buf
.st_size
)
1091 error("short read %s (%d != %d)", fname
, (int) cc
,
1095 /* replace "# comment" with spaces */
1096 for (i
= 0; i
< cc
; i
++) {
1098 while (i
< cc
&& cp
[i
] != '\n')
1105 #ifdef HAVE_PCAP_FINDALLDEVS
1107 parse_interface_number(const char *device
)
1114 * Search for a colon, terminating any scheme at the beginning
1117 p
= strchr(device
, ':');
1120 * We found it. Is it followed by "//"?
1122 p
++; /* skip the : */
1123 if (strncmp(p
, "//", 2) == 0) {
1125 * Yes. Search for the next /, at the end of the
1126 * authority part of the URL.
1128 p
+= 2; /* skip the // */
1132 * OK, past the / is the path.
1138 devnum
= strtol(device
, &end
, 10);
1139 if (device
!= end
&& *end
== '\0') {
1141 * It's all-numeric, but is it a valid number?
1145 * No, it's not an ordinal.
1147 error("Invalid adapter index");
1152 * It's not all-numeric; return -1, so our caller
1160 find_interface_by_number(const char *url
1161 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1166 pcap_if_t
*dev
, *devlist
;
1168 char ebuf
[PCAP_ERRBUF_SIZE
];
1170 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1176 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1178 * Search for a colon, terminating any scheme at the beginning
1181 endp
= strchr(url
, ':');
1184 * We found it. Is it followed by "//"?
1186 endp
++; /* skip the : */
1187 if (strncmp(endp
, "//", 2) == 0) {
1189 * Yes. Search for the next /, at the end of the
1190 * authority part of the URL.
1192 endp
+= 2; /* skip the // */
1193 endp
= strchr(endp
, '/');
1199 * OK, everything from device to endp is a URL to hand
1200 * to pcap_findalldevs_ex().
1202 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1203 host_url
= malloc(endp
- url
+ 1);
1204 if (host_url
== NULL
&& (endp
- url
+ 1) > 0)
1205 error("Invalid allocation for host");
1207 memcpy(host_url
, url
, endp
- url
);
1208 host_url
[endp
- url
] = '\0';
1209 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1213 status
= pcap_findalldevs(&devlist
, ebuf
);
1217 * Look for the devnum-th entry in the list of devices (1-based).
1219 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1220 i
++, dev
= dev
->next
)
1223 error("Invalid adapter index");
1224 device
= strdup(dev
->name
);
1225 pcap_freealldevs(devlist
);
1230 #ifdef HAVE_PCAP_OPEN
1232 * Prefixes for rpcap URLs.
1234 static char rpcap_prefix
[] = "rpcap://";
1235 static char rpcap_ssl_prefix
[] = "rpcaps://";
1239 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1242 #ifdef HAVE_PCAP_CREATE
1247 #ifdef HAVE_PCAP_OPEN
1249 * Is this an rpcap URL?
1251 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0 ||
1252 strncmp(device
, rpcap_ssl_prefix
, sizeof(rpcap_ssl_prefix
) - 1) == 0) {
1254 * Yes. Open it with pcap_open().
1257 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1258 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, timeout
, NULL
,
1262 * If this failed with "No such device" or "The system
1263 * cannot find the device specified", that means
1264 * the interface doesn't exist; return NULL, so that
1265 * the caller can see whether the device name is
1266 * actually an interface index.
1268 if (strstr(ebuf
, "No such device") != NULL
||
1269 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1274 warning("%s", ebuf
);
1277 #endif /* HAVE_PCAP_OPEN */
1279 #ifdef HAVE_PCAP_CREATE
1280 pc
= pcap_create(device
, ebuf
);
1283 * If this failed with "No such device", that means
1284 * the interface doesn't exist; return NULL, so that
1285 * the caller can see whether the device name is
1286 * actually an interface index.
1288 if (strstr(ebuf
, "No such device") != NULL
)
1292 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1294 show_tstamp_types_and_exit(pc
, device
);
1296 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1297 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1299 error("%s: Can't set %ssecond time stamp precision: %s",
1301 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1302 pcap_statustostr(status
));
1305 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1306 if (immediate_mode
) {
1307 status
= pcap_set_immediate_mode(pc
, 1);
1309 error("%s: Can't set immediate mode: %s",
1310 device
, pcap_statustostr(status
));
1314 * Is this an interface that supports monitor mode?
1316 if (pcap_can_set_rfmon(pc
) == 1)
1317 supports_monitor_mode
= 1;
1319 supports_monitor_mode
= 0;
1320 if (ndo
->ndo_snaplen
!= 0) {
1322 * A snapshot length was explicitly specified;
1325 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1327 error("%s: Can't set snapshot length: %s",
1328 device
, pcap_statustostr(status
));
1330 status
= pcap_set_promisc(pc
, !pflag
);
1332 error("%s: Can't set promiscuous mode: %s",
1333 device
, pcap_statustostr(status
));
1335 status
= pcap_set_rfmon(pc
, 1);
1337 error("%s: Can't set monitor mode: %s",
1338 device
, pcap_statustostr(status
));
1340 status
= pcap_set_timeout(pc
, timeout
);
1342 error("%s: pcap_set_timeout failed: %s",
1343 device
, pcap_statustostr(status
));
1345 status
= pcap_set_buffer_size(pc
, Bflag
);
1347 error("%s: Can't set buffer size: %s",
1348 device
, pcap_statustostr(status
));
1350 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1352 status
= pcap_set_tstamp_type(pc
, jflag
);
1354 error("%s: Can't set time stamp type: %s",
1355 device
, pcap_statustostr(status
));
1356 else if (status
> 0)
1357 warning("When trying to set timestamp type '%s' on %s: %s",
1358 pcap_tstamp_type_val_to_name(jflag
), device
,
1359 pcap_statustostr(status
));
1362 status
= pcap_activate(pc
);
1365 * pcap_activate() failed.
1367 cp
= pcap_geterr(pc
);
1368 if (status
== PCAP_ERROR
)
1370 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1372 * Return an error for our caller to handle.
1374 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1375 device
, pcap_statustostr(status
), cp
);
1376 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1377 error("%s: %s\n(%s)", device
,
1378 pcap_statustostr(status
), cp
);
1380 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1381 strncmp(device
, "wlan", 4) == 0) {
1382 char parent
[8], newdev
[8];
1384 size_t s
= sizeof(parent
);
1386 snprintf(sysctl
, sizeof(sysctl
),
1387 "net.wlan.%d.%%parent", atoi(device
+ 4));
1388 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1389 strlcpy(newdev
, device
, sizeof(newdev
));
1390 /* Suggest a new wlan device. */
1391 /* FIXME: incrementing the index this way is not going to work well
1392 * when the index is 9 or greater but the only consequence in this
1393 * specific case would be an error message that looks a bit odd.
1395 newdev
[strlen(newdev
)-1]++;
1396 error("%s is not a monitor mode VAP\n"
1397 "To create a new monitor mode VAP use:\n"
1398 " ifconfig %s create wlandev %s wlanmode monitor\n"
1399 "and use %s as the tcpdump interface",
1400 device
, newdev
, parent
, newdev
);
1404 error("%s: %s", device
,
1405 pcap_statustostr(status
));
1408 } else if (status
> 0) {
1410 * pcap_activate() succeeded, but it's warning us
1411 * of a problem it had.
1413 cp
= pcap_geterr(pc
);
1414 if (status
== PCAP_WARNING
)
1416 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1418 warning("%s: %s\n(%s)", device
,
1419 pcap_statustostr(status
), cp
);
1421 warning("%s: %s", device
,
1422 pcap_statustostr(status
));
1424 #ifdef HAVE_PCAP_SETDIRECTION
1426 status
= pcap_setdirection(pc
, Qflag
);
1428 error("%s: pcap_setdirection() failed: %s",
1429 device
, pcap_geterr(pc
));
1431 #endif /* HAVE_PCAP_SETDIRECTION */
1432 #else /* HAVE_PCAP_CREATE */
1435 * If no snapshot length was specified, or a length of 0 was
1436 * specified, default to 256KB.
1438 if (ndo
->ndo_snaplen
== 0)
1439 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
1440 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, timeout
, ebuf
);
1443 * If this failed with "No such device", that means
1444 * the interface doesn't exist; return NULL, so that
1445 * the caller can see whether the device name is
1446 * actually an interface index.
1448 if (strstr(ebuf
, "No such device") != NULL
)
1453 warning("%s", ebuf
);
1454 #endif /* HAVE_PCAP_CREATE */
1460 main(int argc
, char **argv
)
1463 bpf_u_int32 localnet
= 0, netmask
= 0;
1464 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1466 pcap_handler callback
;
1468 const char *dlt_name
;
1469 struct bpf_program fcode
;
1471 void (*oldhandler
)(int);
1473 struct dump_info dumpinfo
;
1474 u_char
*pcap_userdata
;
1475 char ebuf
[PCAP_ERRBUF_SIZE
];
1476 char VFileLine
[PATH_MAX
+ 1];
1477 const char *username
= NULL
;
1479 const char *chroot_dir
= NULL
;
1483 #ifdef HAVE_PCAP_FINDALLDEVS
1489 #ifdef HAVE_CAPSICUM
1490 cap_rights_t rights
;
1492 #endif /* HAVE_CAPSICUM */
1493 int Oflag
= 1; /* run filter code optimizer */
1495 const char *yflag_dlt_name
= NULL
;
1498 netdissect_options Ndo
;
1499 netdissect_options
*ndo
= &Ndo
;
1502 * Initialize the netdissect code.
1504 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1507 memset(ndo
, 0, sizeof(*ndo
));
1508 ndo_set_function_pointers(ndo
);
1518 if ((cp
= strrchr(argv
[0], PATH_SEPARATOR
)) != NULL
)
1519 ndo
->program_name
= program_name
= cp
+ 1;
1521 ndo
->program_name
= program_name
= argv
[0];
1523 #if defined(HAVE_PCAP_WSOCKINIT)
1524 if (pcap_wsockinit() != 0)
1525 error("Attempting to initialize Winsock failed");
1526 #elif defined(HAVE_WSOCKINIT)
1527 if (wsockinit() != 0)
1528 error("Attempting to initialize Winsock failed");
1532 * On platforms where the CPU doesn't support unaligned loads,
1533 * force unaligned accesses to abort with SIGBUS, rather than
1534 * being fixed up (slowly) by the OS kernel; on those platforms,
1535 * misaligned accesses are bugs, and we want tcpdump to crash so
1536 * that the bugs are reported.
1538 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1542 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1546 /* compatibility for old -a */
1557 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1559 Bflag
= atoi(optarg
)*1024;
1561 error("invalid packet buffer size %s", optarg
);
1563 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1568 error("invalid packet count %s", optarg
);
1573 #ifdef HAVE_PCAP_DUMP_FTELL64
1574 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1576 Cflag
= strtol(optarg
, &endp
, 10);
1578 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1580 error("invalid file size %s", optarg
);
1582 * Will multiplying it by 1000000 overflow?
1584 #ifdef HAVE_PCAP_DUMP_FTELL64
1585 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1587 if (Cflag
> LONG_MAX
/ 1000000)
1589 error("file size %s is too large", optarg
);
1597 #ifdef HAVE_PCAP_FINDALLDEVS
1603 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1604 case OPTION_LIST_REMOTE_INTERFACES
:
1605 remote_interfaces_source
= optarg
;
1618 #ifndef HAVE_LIBCRYPTO
1619 warning("crypto code not compiled in");
1621 ndo
->ndo_espsecret
= optarg
;
1633 Gflag
= atoi(optarg
);
1635 error("invalid number of seconds %s", optarg
);
1637 /* We will create one file initially. */
1640 /* Grab the current time for rotation use. */
1641 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1642 error("%s: can't get current time: %s",
1643 __func__
, pcap_strerror(errno
));
1648 print_usage(stdout
);
1649 exit_tcpdump(S_SUCCESS
);
1660 #ifdef HAVE_PCAP_CREATE
1664 #endif /* HAVE_PCAP_CREATE */
1666 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1668 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1670 error("invalid time stamp type %s", optarg
);
1681 * _IOLBF is the same as _IOFBF in Microsoft's C
1682 * libraries; the only alternative they offer
1685 * XXX - this should really be checking for MSVC++,
1686 * not _WIN32, if, for example, MinGW has its own
1687 * C library that is more UNIX-compatible.
1689 setvbuf(stdout
, NULL
, _IONBF
, 0);
1691 #ifdef HAVE_SETLINEBUF
1694 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1705 if (nd_have_smi_support()) {
1706 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1709 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1710 program_name
, optarg
);
1711 (void)fprintf(stderr
, "(no libsmi support)\n");
1716 /* TCP-MD5 shared secret */
1717 #ifndef HAVE_LIBCRYPTO
1718 warning("crypto code not compiled in");
1720 ndo
->ndo_sigsecret
= optarg
;
1741 ++ndo
->ndo_suppress_default_print
;
1744 #ifdef HAVE_PCAP_SETDIRECTION
1746 if (ascii_strcasecmp(optarg
, "in") == 0)
1748 else if (ascii_strcasecmp(optarg
, "out") == 0)
1750 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1751 Qflag
= PCAP_D_INOUT
;
1753 error("unknown capture direction `%s'", optarg
);
1755 #endif /* HAVE_PCAP_SETDIRECTION */
1762 ndo
->ndo_snaplen
= (int)strtol(optarg
, &end
, 0);
1763 if (optarg
== end
|| *end
!= '\0'
1764 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1765 error("invalid snaplen %s (must be >= 0 and <= %d)",
1766 optarg
, MAXIMUM_SNAPLEN
);
1778 if (ascii_strcasecmp(optarg
, "vat") == 0)
1779 ndo
->ndo_packettype
= PT_VAT
;
1780 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1781 ndo
->ndo_packettype
= PT_WB
;
1782 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1783 ndo
->ndo_packettype
= PT_RPC
;
1784 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1785 ndo
->ndo_packettype
= PT_RTP
;
1786 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1787 ndo
->ndo_packettype
= PT_RTCP
;
1788 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1789 ndo
->ndo_packettype
= PT_SNMP
;
1790 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1791 ndo
->ndo_packettype
= PT_CNFP
;
1792 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1793 ndo
->ndo_packettype
= PT_TFTP
;
1794 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1795 ndo
->ndo_packettype
= PT_AODV
;
1796 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1797 ndo
->ndo_packettype
= PT_CARP
;
1798 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1799 ndo
->ndo_packettype
= PT_RADIUS
;
1800 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1801 ndo
->ndo_packettype
= PT_ZMTP1
;
1802 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1803 ndo
->ndo_packettype
= PT_VXLAN
;
1804 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1805 ndo
->ndo_packettype
= PT_PGM
;
1806 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1807 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1808 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1809 ndo
->ndo_packettype
= PT_LMP
;
1810 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1811 ndo
->ndo_packettype
= PT_RESP
;
1812 else if (ascii_strcasecmp(optarg
, "ptp") == 0)
1813 ndo
->ndo_packettype
= PT_PTP
;
1814 else if (ascii_strcasecmp(optarg
, "someip") == 0)
1815 ndo
->ndo_packettype
= PT_SOMEIP
;
1816 else if (ascii_strcasecmp(optarg
, "domain") == 0)
1817 ndo
->ndo_packettype
= PT_DOMAIN
;
1819 error("unknown packet type `%s'", optarg
);
1826 #ifdef HAVE_PCAP_DUMP_FLUSH
1845 Wflag
= atoi(optarg
);
1847 error("invalid number of output files %s", optarg
);
1848 WflagChars
= getWflagChars(Wflag
);
1853 ++ndo
->ndo_suppress_default_print
;
1858 ++ndo
->ndo_suppress_default_print
;
1862 yflag_dlt_name
= optarg
;
1864 pcap_datalink_name_to_val(yflag_dlt_name
);
1866 error("invalid data link type %s", yflag_dlt_name
);
1869 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1872 /* Undocumented flag */
1873 pcap_set_parser_debug(1);
1886 ndo
->ndo_packet_number
= 1;
1889 case OPTION_VERSION
:
1890 print_version(stdout
);
1891 exit_tcpdump(S_SUCCESS
);
1894 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1895 case OPTION_TSTAMP_PRECISION
:
1896 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1897 if (ndo
->ndo_tstamp_precision
< 0)
1898 error("unsupported time stamp precision");
1902 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1903 case OPTION_IMMEDIATE_MODE
:
1912 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1913 case OPTION_TSTAMP_MICRO
:
1914 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
1917 case OPTION_TSTAMP_NANO
:
1918 ndo
->ndo_tstamp_precision
= PCAP_TSTAMP_PRECISION_NANO
;
1922 case OPTION_FP_TYPE
:
1924 * Print out the type of floating-point arithmetic
1925 * we're doing; it's probably IEEE, unless somebody
1926 * tries to run this on a VAX, but the precision
1927 * may differ (e.g., it might be 32-bit, 64-bit,
1930 float_type_check(0x4e93312d);
1938 print_usage(stderr
);
1939 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1943 #ifdef HAVE_PCAP_FINDALLDEVS
1945 show_devices_and_exit();
1947 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1948 if (remote_interfaces_source
!= NULL
)
1949 show_remote_devices_and_exit();
1952 #if defined(DLT_LINUX_SLL2) && defined(HAVE_PCAP_SET_DATALINK)
1953 /* Set default linktype DLT_LINUX_SLL2 when capturing on the "any" device */
1954 if (device
!= NULL
&&
1955 strncmp (device
, "any", strlen("any")) == 0
1957 yflag_dlt
= DLT_LINUX_SLL2
;
1960 switch (ndo
->ndo_tflag
) {
1962 case 0: /* Default */
1963 case 1: /* No time stamp */
1964 case 2: /* Unix timeval style */
1965 case 3: /* Microseconds/nanoseconds since previous packet */
1966 case 4: /* Date + Default */
1967 case 5: /* Microseconds/nanoseconds since first packet */
1970 default: /* Not supported */
1971 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1975 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1976 error("-f can not be used with -V or -r");
1978 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1979 error("-V and -r are mutually exclusive.");
1982 * If we're printing dissected packets to the standard output,
1983 * and either the standard output is a terminal or we're doing
1984 * "line" buffering, set the capture timeout to .1 second rather
1985 * than 1 second, as the user's probably expecting to see packets
1986 * pop up immediately shortly after they arrive.
1988 * XXX - would there be some value appropriate for all cases,
1989 * based on, say, the buffer size and packet input rate?
1991 if ((WFileName
== NULL
|| print
) && (isatty(1) || lflag
))
1995 /* if run as root, prepare for chrooting */
1996 if (getuid() == 0 || geteuid() == 0) {
1997 /* future extensibility for cmd-line arguments */
1999 chroot_dir
= WITH_CHROOT
;
2004 /* if run as root, prepare for dropping root privileges */
2005 if (getuid() == 0 || geteuid() == 0) {
2006 /* Run with '-Z root' to restore old behaviour */
2008 username
= WITH_USER
;
2012 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
2014 * If RFileName is non-null, it's the pathname of a
2015 * savefile to read. If VFileName is non-null, it's
2016 * the pathname of a file containing a list of pathnames
2017 * (one per line) of savefiles to read.
2019 * In either case, we're reading a savefile, not doing
2024 * We don't need network access, so relinquish any set-UID
2025 * or set-GID privileges we have (if any).
2027 * We do *not* want set-UID privileges when opening a
2028 * trace file, as that might let the user read other
2029 * people's trace files (especially if we're set-UID
2032 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
2033 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2035 if (VFileName
!= NULL
) {
2036 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
2039 VFile
= fopen(VFileName
, "r");
2042 error("Unable to open file: %s\n", pcap_strerror(errno
));
2044 ret
= get_next_file(VFile
, VFileLine
);
2046 error("Nothing in %s\n", VFileName
);
2047 RFileName
= VFileLine
;
2050 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2051 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
2052 ndo
->ndo_tstamp_precision
, ebuf
);
2054 pd
= pcap_open_offline(RFileName
, ebuf
);
2059 #ifdef HAVE_CAPSICUM
2060 cap_rights_init(&rights
, CAP_READ
);
2061 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
2063 error("unable to limit pcap descriptor");
2066 dlt
= pcap_datalink(pd
);
2067 dlt_name
= pcap_datalink_val_to_name(dlt
);
2068 fprintf(stderr
, "reading from file %s", RFileName
);
2069 if (dlt_name
== NULL
) {
2070 fprintf(stderr
, ", link-type %u", dlt
);
2072 fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2073 pcap_datalink_val_to_description(dlt
));
2075 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2076 #ifdef DLT_LINUX_SLL2
2077 if (dlt
== DLT_LINUX_SLL2
)
2078 fprintf(stderr
, "Warning: interface names might be incorrect\n");
2080 } else if (dflag
&& !device
) {
2081 int dump_dlt
= DLT_EN10MB
;
2083 * We're dumping the compiled code without an explicit
2084 * device specification. (If a device is specified, we
2085 * definitely want to open it to use the DLT of that device.)
2086 * Either default to DLT_EN10MB with a warning, or use
2087 * the user-specified value if supplied.
2090 * If no snapshot length was specified, or a length of 0 was
2091 * specified, default to 256KB.
2093 if (ndo
->ndo_snaplen
== 0)
2094 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
2096 * If a DLT was specified with the -y flag, use that instead.
2098 if (yflag_dlt
!= -1)
2099 dump_dlt
= yflag_dlt
;
2101 fprintf(stderr
, "Warning: assuming Ethernet\n");
2102 pd
= pcap_open_dead(dump_dlt
, ndo
->ndo_snaplen
);
2105 * We're doing a live capture.
2107 if (device
== NULL
) {
2109 * No interface was specified. Pick one.
2111 #ifdef HAVE_PCAP_FINDALLDEVS
2113 * Find the list of interfaces, and pick
2114 * the first interface.
2116 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2118 if (devlist
== NULL
)
2119 error("no interfaces available for capture");
2120 device
= strdup(devlist
->name
);
2121 pcap_freealldevs(devlist
);
2122 #else /* HAVE_PCAP_FINDALLDEVS */
2124 * Use whatever interface pcap_lookupdev()
2127 device
= pcap_lookupdev(ebuf
);
2134 * Try to open the interface with the specified name.
2136 pd
= open_interface(device
, ndo
, ebuf
);
2139 * That failed. If we can get a list of
2140 * interfaces, and the interface name
2141 * is purely numeric, try to use it as
2142 * a 1-based index in the list of
2145 #ifdef HAVE_PCAP_FINDALLDEVS
2146 devnum
= parse_interface_number(device
);
2149 * It's not a number; just report
2150 * the open error and fail.
2156 * OK, it's a number; try to find the
2157 * interface with that index, and try
2160 * find_interface_by_number() exits if it
2161 * couldn't be found.
2163 device
= find_interface_by_number(device
, devnum
);
2164 pd
= open_interface(device
, ndo
, ebuf
);
2167 #else /* HAVE_PCAP_FINDALLDEVS */
2169 * We can't get a list of interfaces; just
2173 #endif /* HAVE_PCAP_FINDALLDEVS */
2177 * Let user own process after capture device has
2181 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2182 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2184 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2186 if(pcap_setbuff(pd
, Bflag
)==-1){
2187 error("%s", pcap_geterr(pd
));
2189 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2191 show_dlts_and_exit(pd
, device
);
2192 if (yflag_dlt
>= 0) {
2193 #ifdef HAVE_PCAP_SET_DATALINK
2194 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2195 error("%s", pcap_geterr(pd
));
2198 * We don't actually support changing the
2199 * data link type, so we only let them
2200 * set it to what it already is.
2202 if (yflag_dlt
!= pcap_datalink(pd
)) {
2203 error("%s is not one of the DLTs supported by this device\n",
2207 (void)fprintf(stderr
, "%s: data link type %s\n",
2209 pcap_datalink_val_to_name(yflag_dlt
));
2210 (void)fflush(stderr
);
2212 i
= pcap_snapshot(pd
);
2213 if (ndo
->ndo_snaplen
< i
) {
2214 if (ndo
->ndo_snaplen
!= 0)
2215 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2216 ndo
->ndo_snaplen
= i
;
2217 } else if (ndo
->ndo_snaplen
> i
) {
2218 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2219 ndo
->ndo_snaplen
= i
;
2221 if(ndo
->ndo_fflag
!= 0) {
2222 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2223 warning("foreign (-f) flag used but: %s", ebuf
);
2229 cmdbuf
= read_infile(infile
);
2231 cmdbuf
= copy_argv(&argv
[optind
]);
2233 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2234 pcap_set_optimizer_debug(dflag
);
2236 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2237 error("%s", pcap_geterr(pd
));
2239 bpf_dump(&fcode
, dflag
);
2242 pcap_freecode(&fcode
);
2243 exit_tcpdump(S_SUCCESS
);
2247 if (!ndo
->ndo_nflag
)
2248 capdns
= capdns_setup();
2249 #endif /* HAVE_CASPER */
2251 init_print(ndo
, localnet
, netmask
);
2254 (void)setsignal(SIGPIPE
, cleanup
);
2255 (void)setsignal(SIGTERM
, cleanup
);
2257 (void)setsignal(SIGINT
, cleanup
);
2258 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2259 (void)setsignal(SIGCHLD
, child_cleanup
);
2261 /* Cooperate with nohup(1) */
2263 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2264 (void)setsignal(SIGHUP
, oldhandler
);
2269 * If a user name was specified with "-Z", attempt to switch to
2270 * that user's UID. This would probably be used with sudo,
2271 * to allow tcpdump to be run in a special restricted
2272 * account (if you just want to allow users to open capture
2273 * devices, and can't just give users that permission,
2274 * you'd make tcpdump set-UID or set-GID).
2276 * Tcpdump doesn't necessarily write only to one savefile;
2277 * the general only way to allow a -Z instance to write to
2278 * savefiles as the user under whose UID it's run, rather
2279 * than as the user specified with -Z, would thus be to switch
2280 * to the original user ID before opening a capture file and
2281 * then switch back to the -Z user ID after opening the savefile.
2282 * Switching to the -Z user ID only after opening the first
2283 * savefile doesn't handle the general case.
2286 if (getuid() == 0 || geteuid() == 0) {
2287 #ifdef HAVE_LIBCAP_NG
2288 /* Initialize capng */
2289 capng_clear(CAPNG_SELECT_BOTH
);
2291 DIAG_OFF_ASSIGN_ENUM
2294 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2301 DIAG_OFF_ASSIGN_ENUM
2304 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2311 DIAG_OFF_ASSIGN_ENUM
2314 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2319 capng_apply(CAPNG_SELECT_BOTH
);
2320 #endif /* HAVE_LIBCAP_NG */
2321 if (username
|| chroot_dir
)
2322 droproot(username
, chroot_dir
);
2327 if (pcap_setfilter(pd
, &fcode
) < 0)
2328 error("%s", pcap_geterr(pd
));
2329 #ifdef HAVE_CAPSICUM
2330 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2331 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2334 * The various libpcap devices use a combination of
2335 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2336 * so we add the relevant access rights.
2338 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2339 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2341 error("unable to limit pcap descriptor");
2343 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2344 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2345 error("unable to limit ioctls on pcap descriptor");
2350 /* Do not exceed the default PATH_MAX for files. */
2351 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2353 if (dumpinfo
.CurrentFileName
== NULL
)
2354 error("malloc of dumpinfo.CurrentFileName");
2356 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2358 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2360 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2362 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2363 #ifdef HAVE_LIBCAP_NG
2364 /* Give up CAP_DAC_OVERRIDE capability.
2365 * Only allow it to be restored if the -C or -G flag have been
2366 * set since we may need to create more files later on.
2370 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2374 capng_apply(CAPNG_SELECT_BOTH
);
2375 #endif /* HAVE_LIBCAP_NG */
2377 error("%s", pcap_geterr(pd
));
2378 #ifdef HAVE_CAPSICUM
2379 set_dumper_capsicum_rights(pdd
);
2381 if (Cflag
!= 0 || Gflag
!= 0) {
2382 #ifdef HAVE_CAPSICUM
2383 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2384 if (dumpinfo
.WFileName
== NULL
) {
2385 error("Unable to allocate memory for file %s",
2388 dumpinfo
.dirfd
= open(dirname(WFileName
),
2389 O_DIRECTORY
| O_RDONLY
);
2390 if (dumpinfo
.dirfd
< 0) {
2391 error("unable to open directory %s",
2392 dirname(WFileName
));
2394 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2395 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2396 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2398 error("unable to limit directory rights");
2400 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2402 error("unable to limit dump descriptor fcntls");
2404 #else /* !HAVE_CAPSICUM */
2405 dumpinfo
.WFileName
= WFileName
;
2407 callback
= dump_packet_and_trunc
;
2410 pcap_userdata
= (u_char
*)&dumpinfo
;
2412 callback
= dump_packet
;
2413 dumpinfo
.WFileName
= WFileName
;
2416 pcap_userdata
= (u_char
*)&dumpinfo
;
2419 dlt
= pcap_datalink(pd
);
2420 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2423 dumpinfo
.ndo
= NULL
;
2425 #ifdef HAVE_PCAP_DUMP_FLUSH
2427 pcap_dump_flush(pdd
);
2430 dlt
= pcap_datalink(pd
);
2431 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2432 callback
= print_packet
;
2433 pcap_userdata
= (u_char
*)ndo
;
2436 #ifdef SIGNAL_REQ_INFO
2438 * We can't get statistics when reading from a file rather
2439 * than capturing from a device.
2441 if (RFileName
== NULL
)
2442 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2444 #ifdef SIGNAL_FLUSH_PCAP
2445 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2448 if (ndo
->ndo_vflag
> 0 && WFileName
&& RFileName
== NULL
&& !print
) {
2450 * When capturing to a file, if "--print" wasn't specified,
2451 *"-v" means tcpdump should, once per second,
2452 * "v"erbosely report the number of packets captured.
2453 * Except when reading from a file, because -r, -w and -v
2454 * together used to make a corner case, in which pcap_loop()
2455 * errored due to EINTR (see GH #155 for details).
2459 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2461 * suggests that this dates back to W2K.
2463 * I don't know what a "long wait" is, but we'll assume
2464 * that printing the stats could be a "long wait".
2466 CreateTimerQueueTimer(&timer_handle
, NULL
,
2467 verbose_stats_dump
, NULL
, 1000, 1000,
2468 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2469 setvbuf(stderr
, NULL
, _IONBF
, 0);
2472 * Assume this is UN*X, and that it has setitimer(); that
2473 * dates back to UNIX 95.
2475 struct itimerval timer
;
2476 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2477 timer
.it_interval
.tv_sec
= 1;
2478 timer
.it_interval
.tv_usec
= 0;
2479 timer
.it_value
.tv_sec
= 1;
2480 timer
.it_value
.tv_usec
= 1;
2481 setitimer(ITIMER_REAL
, &timer
, NULL
);
2485 if (RFileName
== NULL
) {
2487 * Live capture (if -V was specified, we set RFileName
2488 * to a file from the -V file). Print a message to
2489 * the standard error on UN*X.
2491 if (!ndo
->ndo_vflag
&& !WFileName
) {
2492 (void)fprintf(stderr
,
2493 "%s: verbose output suppressed, use -v[v]... for full protocol decode\n",
2496 (void)fprintf(stderr
, "%s: ", program_name
);
2497 dlt
= pcap_datalink(pd
);
2498 dlt_name
= pcap_datalink_val_to_name(dlt
);
2499 (void)fprintf(stderr
, "listening on %s", device
);
2500 if (dlt_name
== NULL
) {
2501 (void)fprintf(stderr
, ", link-type %u", dlt
);
2503 (void)fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2504 pcap_datalink_val_to_description(dlt
));
2506 (void)fprintf(stderr
, ", snapshot length %d bytes\n", ndo
->ndo_snaplen
);
2507 (void)fflush(stderr
);
2510 #ifdef HAVE_CAPSICUM
2511 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2513 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2515 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2516 #endif /* HAVE_CASPER */
2517 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2518 error("unable to enter the capability mode");
2519 #endif /* HAVE_CAPSICUM */
2522 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2523 if (WFileName
== NULL
) {
2525 * We're printing packets. Flush the printed output,
2526 * so it doesn't get intermingled with error output.
2530 * We got interrupted, so perhaps we didn't
2531 * manage to finish a line we were printing.
2532 * Print an extra newline, just in case.
2536 (void)fflush(stdout
);
2540 * We got interrupted. If we are reading multiple
2541 * files (via -V) set these so that we stop.
2550 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2551 program_name
, pcap_geterr(pd
));
2553 if (RFileName
== NULL
) {
2555 * We're doing a live capture. Report the capture
2561 if (VFileName
!= NULL
) {
2562 ret
= get_next_file(VFile
, VFileLine
);
2566 RFileName
= VFileLine
;
2567 pd
= pcap_open_offline(RFileName
, ebuf
);
2570 #ifdef HAVE_CAPSICUM
2571 cap_rights_init(&rights
, CAP_READ
);
2572 if (cap_rights_limit(fileno(pcap_file(pd
)),
2573 &rights
) < 0 && errno
!= ENOSYS
) {
2574 error("unable to limit pcap descriptor");
2577 new_dlt
= pcap_datalink(pd
);
2578 if (new_dlt
!= dlt
) {
2580 * The new file has a different
2581 * link-layer header type from the
2584 if (WFileName
!= NULL
) {
2586 * We're writing raw packets
2587 * that match the filter to
2588 * a pcap file. pcap files
2589 * don't support multiple
2590 * different link-layer
2591 * header types, so we fail
2594 error("%s: new dlt does not match original", RFileName
);
2598 * We're printing the decoded packets;
2599 * switch to the new DLT.
2601 * To do that, we need to change
2602 * the printer, change the DLT name,
2603 * and recompile the filter with
2607 ndo
->ndo_if_printer
= get_if_printer(dlt
);
2608 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2609 error("%s", pcap_geterr(pd
));
2613 * Set the filter on the new file.
2615 if (pcap_setfilter(pd
, &fcode
) < 0)
2616 error("%s", pcap_geterr(pd
));
2619 * Report the new file.
2621 dlt_name
= pcap_datalink_val_to_name(dlt
);
2622 fprintf(stderr
, "reading from file %s", RFileName
);
2623 if (dlt_name
== NULL
) {
2624 fprintf(stderr
, ", link-type %u", dlt
);
2626 fprintf(stderr
, ", link-type %s (%s)",
2628 pcap_datalink_val_to_description(dlt
));
2630 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2634 while (ret
!= NULL
);
2636 if (count_mode
&& RFileName
!= NULL
)
2637 fprintf(stdout
, "%u packet%s\n", packets_captured
,
2638 PLURAL_SUFFIX(packets_captured
));
2641 pcap_freecode(&fcode
);
2642 exit_tcpdump(status
== -1 ? 1 : 0);
2649 (*setsignal (int sig
, void (*func
)(int)))(int)
2652 return (signal(sig
, func
));
2654 struct sigaction old
, new;
2656 memset(&new, 0, sizeof(new));
2657 new.sa_handler
= func
;
2659 new.sa_flags
= SA_RESTART
;
2660 if (sigaction(sig
, &new, &old
) < 0)
2662 return (old
.sa_handler
);
2666 /* make a clean exit on interrupts */
2668 cleanup(int signo _U_
)
2671 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2672 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2673 CloseHandle(timer_handle
);
2674 timer_handle
= INVALID_HANDLE_VALUE
;
2677 struct itimerval timer
;
2679 timer
.it_interval
.tv_sec
= 0;
2680 timer
.it_interval
.tv_usec
= 0;
2681 timer
.it_value
.tv_sec
= 0;
2682 timer
.it_value
.tv_usec
= 0;
2683 setitimer(ITIMER_REAL
, &timer
, NULL
);
2686 #ifdef HAVE_PCAP_BREAKLOOP
2688 * We have "pcap_breakloop()"; use it, so that we do as little
2689 * as possible in the signal handler (it's probably not safe
2690 * to do anything with standard I/O streams in a signal handler -
2691 * the ANSI C standard doesn't say it is).
2696 * We don't have "pcap_breakloop()"; this isn't safe, but
2697 * it's the best we can do. Print the summary if we're
2698 * not reading from a savefile - i.e., if we're doing a
2699 * live capture - and exit.
2701 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2703 * We got interrupted, so perhaps we didn't
2704 * manage to finish a line we were printing.
2705 * Print an extra newline, just in case.
2708 (void)fflush(stdout
);
2711 exit_tcpdump(S_SUCCESS
);
2716 On windows, we do not use a fork, so we do not care less about
2717 waiting a child processes to die
2719 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2721 child_cleanup(int signo _U_
)
2725 #endif /* HAVE_FORK && HAVE_VFORK */
2730 struct pcap_stat stats
;
2733 * Older versions of libpcap didn't set ps_ifdrop on some
2734 * platforms; initialize it to 0 to handle that.
2736 stats
.ps_ifdrop
= 0;
2737 if (pcap_stats(pd
, &stats
) < 0) {
2738 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2744 fprintf(stderr
, "%s: ", program_name
);
2746 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2747 PLURAL_SUFFIX(packets_captured
));
2749 fputs(", ", stderr
);
2752 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2753 PLURAL_SUFFIX(stats
.ps_recv
));
2755 fputs(", ", stderr
);
2758 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2759 PLURAL_SUFFIX(stats
.ps_drop
));
2760 if (stats
.ps_ifdrop
!= 0) {
2762 fputs(", ", stderr
);
2765 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2766 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2772 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2774 #define fork_subprocess() fork()
2776 #define fork_subprocess() vfork()
2779 compress_savefile(const char *filename
)
2783 child
= fork_subprocess();
2786 "compress_savefile: fork failed: %s\n",
2787 pcap_strerror(errno
));
2791 /* Parent process. */
2797 * Set to lowest priority so that this doesn't disturb the capture.
2800 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2802 setpriority(PRIO_PROCESS
, 0, 19);
2804 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2806 "compress_savefile: execlp(%s, %s) failed: %s\n",
2809 pcap_strerror(errno
));
2811 exit(S_ERR_HOST_PROGRAM
);
2813 _exit(S_ERR_HOST_PROGRAM
);
2816 #else /* HAVE_FORK && HAVE_VFORK */
2818 compress_savefile(const char *filename
)
2821 "compress_savefile failed. Functionality not implemented under your system\n");
2823 #endif /* HAVE_FORK && HAVE_VFORK */
2826 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2828 struct dump_info
*dump_info
;
2834 dump_info
= (struct dump_info
*)user
;
2837 * XXX - this won't force the file to rotate on the specified time
2838 * boundary, but it will rotate on the first packet received after the
2839 * specified Gflag number of seconds. Note: if a Gflag time boundary
2840 * and a Cflag size boundary coincide, the time rotation will occur
2841 * first thereby cancelling the Cflag boundary (since the file should
2845 /* Check if it is time to rotate */
2848 /* Get the current time */
2849 if ((t
= time(NULL
)) == (time_t)-1) {
2850 error("%s: can't get current_time: %s",
2851 __func__
, pcap_strerror(errno
));
2855 /* If the time is greater than the specified window, rotate */
2856 if (t
- Gflag_time
>= Gflag
) {
2857 #ifdef HAVE_CAPSICUM
2862 /* Update the Gflag_time */
2864 /* Update Gflag_count */
2867 * Close the current file and open a new one.
2869 pcap_dump_close(dump_info
->pdd
);
2872 * Compress the file we just closed, if the user asked for it
2875 compress_savefile(dump_info
->CurrentFileName
);
2878 * Check to see if we've exceeded the Wflag (when
2881 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2882 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2885 exit_tcpdump(S_SUCCESS
);
2888 if (dump_info
->CurrentFileName
!= NULL
)
2889 free(dump_info
->CurrentFileName
);
2890 /* Allocate space for max filename + \0. */
2891 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2892 if (dump_info
->CurrentFileName
== NULL
)
2893 error("dump_packet_and_trunc: malloc");
2895 * Gflag was set otherwise we wouldn't be here. Reset the count
2896 * so multiple files would end with 1,2,3 in the filename.
2897 * The counting is handled with the -C flow after this.
2902 * This is always the first file in the Cflag
2904 * We also don't need numbering if Cflag is not set.
2907 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2910 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2912 #ifdef HAVE_LIBCAP_NG
2913 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2914 capng_apply(CAPNG_SELECT_BOTH
);
2915 #endif /* HAVE_LIBCAP_NG */
2916 #ifdef HAVE_CAPSICUM
2917 fd
= openat(dump_info
->dirfd
,
2918 dump_info
->CurrentFileName
,
2919 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2921 error("unable to open file %s",
2922 dump_info
->CurrentFileName
);
2924 fp
= fdopen(fd
, "w");
2926 error("unable to fdopen file %s",
2927 dump_info
->CurrentFileName
);
2929 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2930 #else /* !HAVE_CAPSICUM */
2931 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2933 #ifdef HAVE_LIBCAP_NG
2934 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2935 capng_apply(CAPNG_SELECT_BOTH
);
2936 #endif /* HAVE_LIBCAP_NG */
2937 if (dump_info
->pdd
== NULL
)
2938 error("%s", pcap_geterr(pd
));
2939 #ifdef HAVE_CAPSICUM
2940 set_dumper_capsicum_rights(dump_info
->pdd
);
2946 * XXX - this won't prevent capture files from getting
2947 * larger than Cflag - the last packet written to the
2948 * file could put it over Cflag.
2951 #ifdef HAVE_PCAP_DUMP_FTELL64
2952 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
2955 * XXX - this only handles a Cflag value > 2^31-1 on
2956 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2957 * Windows) or LLP64 (64-bit Windows) would require
2958 * a version of libpcap with pcap_dump_ftell64().
2960 long size
= pcap_dump_ftell(dump_info
->pdd
);
2964 error("ftell fails on output file");
2966 #ifdef HAVE_CAPSICUM
2972 * Close the current file and open a new one.
2974 pcap_dump_close(dump_info
->pdd
);
2977 * Compress the file we just closed, if the user
2981 compress_savefile(dump_info
->CurrentFileName
);
2985 if (Cflag_count
>= Wflag
)
2988 if (dump_info
->CurrentFileName
!= NULL
)
2989 free(dump_info
->CurrentFileName
);
2990 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2991 if (dump_info
->CurrentFileName
== NULL
)
2992 error("%s: malloc", __func__
);
2993 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2994 #ifdef HAVE_LIBCAP_NG
2995 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2996 capng_apply(CAPNG_SELECT_BOTH
);
2997 #endif /* HAVE_LIBCAP_NG */
2998 #ifdef HAVE_CAPSICUM
2999 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
3000 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
3002 error("unable to open file %s",
3003 dump_info
->CurrentFileName
);
3005 fp
= fdopen(fd
, "w");
3007 error("unable to fdopen file %s",
3008 dump_info
->CurrentFileName
);
3010 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
3011 #else /* !HAVE_CAPSICUM */
3012 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
3014 #ifdef HAVE_LIBCAP_NG
3015 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
3016 capng_apply(CAPNG_SELECT_BOTH
);
3017 #endif /* HAVE_LIBCAP_NG */
3018 if (dump_info
->pdd
== NULL
)
3019 error("%s", pcap_geterr(pd
));
3020 #ifdef HAVE_CAPSICUM
3021 set_dumper_capsicum_rights(dump_info
->pdd
);
3026 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3027 #ifdef HAVE_PCAP_DUMP_FLUSH
3029 pcap_dump_flush(dump_info
->pdd
);
3032 if (dump_info
->ndo
!= NULL
)
3033 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3041 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3043 struct dump_info
*dump_info
;
3049 dump_info
= (struct dump_info
*)user
;
3051 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
3052 #ifdef HAVE_PCAP_DUMP_FLUSH
3054 pcap_dump_flush(dump_info
->pdd
);
3057 if (dump_info
->ndo
!= NULL
)
3058 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
3066 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
3073 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
3080 #ifdef SIGNAL_REQ_INFO
3082 requestinfo(int signo _U_
)
3091 #ifdef SIGNAL_FLUSH_PCAP
3093 flushpcap(int signo _U_
)
3096 pcap_dump_flush(pdd
);
3101 print_packets_captured (void)
3103 static u_int prev_packets_captured
, first
= 1;
3105 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
3106 fprintf(stderr
, "Got %u\r", packets_captured
);
3108 prev_packets_captured
= packets_captured
;
3113 * Called once each second in verbose mode while dumping to file
3116 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
3117 BOOLEAN timer_fired _U_
)
3119 print_packets_captured();
3122 static void verbose_stats_dump(int sig _U_
)
3124 print_packets_captured();
3128 DIAG_OFF_DEPRECATION
3130 print_version(FILE *f
)
3132 #ifndef HAVE_PCAP_LIB_VERSION
3133 #ifdef HAVE_PCAP_VERSION
3134 extern char pcap_version
[];
3135 #else /* HAVE_PCAP_VERSION */
3136 static char pcap_version
[] = "unknown";
3137 #endif /* HAVE_PCAP_VERSION */
3138 #endif /* HAVE_PCAP_LIB_VERSION */
3139 const char *smi_version_string
;
3141 (void)fprintf(f
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3142 #ifdef HAVE_PCAP_LIB_VERSION
3143 (void)fprintf(f
, "%s\n", pcap_lib_version());
3144 #else /* HAVE_PCAP_LIB_VERSION */
3145 (void)fprintf(f
, "libpcap version %s\n", pcap_version
);
3146 #endif /* HAVE_PCAP_LIB_VERSION */
3148 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3149 (void)fprintf (f
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3152 smi_version_string
= nd_smi_version_string();
3153 if (smi_version_string
!= NULL
)
3154 (void)fprintf (f
, "SMI-library: %s\n", smi_version_string
);
3156 #if defined(__SANITIZE_ADDRESS__)
3157 (void)fprintf (f
, "Compiled with AddressSanitizer/GCC.\n");
3158 #elif defined(__has_feature)
3159 # if __has_feature(address_sanitizer)
3160 (void)fprintf (f
, "Compiled with AddressSanitizer/Clang.\n");
3161 # elif __has_feature(memory_sanitizer)
3162 (void)fprintf (f
, "Compiled with MemorySanitizer/Clang.\n");
3164 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3169 print_usage(FILE *f
)
3173 "Usage: %s [-Abd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ] [--count]\n", program_name
);
3175 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3177 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3178 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3180 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
3184 "\t\t" m_FLAG_USAGE
"\n");
3187 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
3189 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ --version ]\n");
3191 "\t\t[ -V file ] [ -w file ] [ -W filecount ] [ -y datalinktype ]\n");
3192 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3194 "\t\t[ --time-stamp-precision precision ] [ --micro ] [ --nano ]\n");
3197 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");