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 */
107 #include <sys/time.h>
108 #include <sys/wait.h>
109 #include <sys/resource.h>
114 /* capabilities convenience library */
115 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
116 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
117 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
119 #ifdef HAVE_LIBCAP_NG
123 #undef HAVE_LIBCAP_NG
124 #endif /* HAVE_CAP_NG_H */
125 #endif /* HAVE_LIBCAP_NG */
128 #include <sys/sysctl.h>
129 #endif /* __FreeBSD__ */
131 #include "netdissect.h"
132 #include "interface.h"
133 #include "addrtoname.h"
135 #include "pcap-missing.h"
136 #include "ascii_strcasecmp.h"
141 #define PATH_MAX 1024
145 #define SIGNAL_REQ_INFO SIGINFO
146 #elif defined(SIGUSR1)
147 #define SIGNAL_REQ_INFO SIGUSR1
150 #if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
151 #define SIGNAL_FLUSH_PCAP SIGUSR2
154 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
155 static int Bflag
; /* buffer size */
157 #ifdef HAVE_PCAP_DUMP_FTELL64
158 static int64_t Cflag
; /* rotate dump files after this many bytes */
160 static long Cflag
; /* rotate dump files after this many bytes */
162 static int Cflag_count
; /* Keep track of which file number we're writing */
163 #ifdef HAVE_PCAP_FINDALLDEVS
164 static int Dflag
; /* list available devices and exit */
166 #ifdef HAVE_PCAP_FINDALLDEVS_EX
167 static char *remote_interfaces_source
; /* list available devices from this source and exit */
171 * This is exported because, in some versions of libpcap, if libpcap
172 * is built with optimizer debugging code (which is *NOT* the default
173 * configuration!), the library *imports*(!) a variable named dflag,
174 * under the expectation that tcpdump is exporting it, to govern
175 * how much debugging information to print when optimizing
176 * the generated BPF code.
178 * This is a horrible hack; newer versions of libpcap don't import
179 * dflag but, instead, *if* built with optimizer debugging code,
180 * *export* a routine to set that flag.
182 int dflag
; /* print filter code */
183 static int Gflag
; /* rotate dump files after this many seconds */
184 static int Gflag_count
; /* number of files created with Gflag rotation */
185 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
186 static int Lflag
; /* list available data link types and exit */
187 static int Iflag
; /* rfmon (monitor) mode */
188 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
189 static int Jflag
; /* list available time stamp types */
190 static int jflag
= -1; /* packet time stamp source */
192 static int pflag
; /* don't go promiscuous */
193 #ifdef HAVE_PCAP_SETDIRECTION
194 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
196 #ifdef HAVE_PCAP_DUMP_FLUSH
197 static int Uflag
; /* "unbuffered" output of dump files */
199 static int Wflag
; /* recycle output files after this number of files */
200 static int WflagChars
;
201 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
202 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
203 static int immediate_mode
;
206 static int infodelay
;
207 static int infoprint
;
212 cap_channel_t
*capdns
;
216 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
217 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
218 static NORETURN
void exit_tcpdump(int);
219 static void (*setsignal (int sig
, void (*func
)(int)))(int);
220 static void cleanup(int);
221 static void child_cleanup(int);
222 static void print_version(void);
223 static void print_usage(void);
224 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
225 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
227 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
228 #ifdef HAVE_PCAP_FINDALLDEVS
229 static NORETURN
void show_devices_and_exit(void);
231 #ifdef HAVE_PCAP_FINDALLDEVS_EX
232 static NORETURN
void show_remote_devices_and_exit(void);
235 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
236 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
237 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
238 static void droproot(const char *, const char *);
240 #ifdef SIGNAL_REQ_INFO
241 static void requestinfo(int);
244 #ifdef SIGNAL_FLUSH_PCAP
245 static void flushpcap(int);
249 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
250 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
252 static void verbose_stats_dump(int sig
);
255 static void info(int);
256 static u_int packets_captured
;
258 #ifdef HAVE_PCAP_FINDALLDEVS
259 static const struct tok status_flags
[] = {
261 { PCAP_IF_UP
, "Up" },
263 #ifdef PCAP_IF_RUNNING
264 { PCAP_IF_RUNNING
, "Running" },
266 { PCAP_IF_LOOPBACK
, "Loopback" },
267 #ifdef PCAP_IF_WIRELESS
268 { PCAP_IF_WIRELESS
, "Wireless" },
275 static pcap_dumper_t
*pdd
= NULL
;
277 static int supports_monitor_mode
;
285 char *CurrentFileName
;
288 netdissect_options
*ndo
;
294 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
296 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
297 * by any libpcap header, because it's a special hack, only available if
298 * libpcap was configured to include it, and only intended for use by
299 * libpcap developers trying to debug the parser for filter expressions).
302 __declspec(dllimport
)
306 void pcap_set_parser_debug(int);
307 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
309 * We don't have pcap_set_parser_debug() in libpcap, but we do have
310 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
311 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
314 pcap_set_parser_debug(int value
)
316 #ifdef HAVE_PCAP_DEBUG
317 extern int pcap_debug
;
320 #else /* HAVE_PCAP_DEBUG */
324 #endif /* HAVE_PCAP_DEBUG */
327 #define HAVE_PCAP_SET_PARSER_DEBUG
330 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
332 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
333 * by any libpcap header, because it's a special hack, only available if
334 * libpcap was configured to include it, and only intended for use by
335 * libpcap developers trying to debug the optimizer for filter expressions).
338 __declspec(dllimport
)
342 void pcap_set_optimizer_debug(int);
347 error(const char *fmt
, ...)
351 (void)fprintf(stderr
, "%s: ", program_name
);
353 (void)vfprintf(stderr
, fmt
, ap
);
358 (void)fputc('\n', stderr
);
360 exit_tcpdump(S_ERR_HOST_PROGRAM
);
366 warning(const char *fmt
, ...)
370 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
372 (void)vfprintf(stderr
, fmt
, ap
);
377 (void)fputc('\n', stderr
);
382 exit_tcpdump(int status
)
388 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
390 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
393 int *tstamp_types
= 0;
394 const char *tstamp_type_name
;
397 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
398 if (n_tstamp_types
< 0)
399 error("%s", pcap_geterr(pc
));
401 if (n_tstamp_types
== 0) {
402 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
404 exit_tcpdump(S_SUCCESS
);
406 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
408 for (i
= 0; i
< n_tstamp_types
; i
++) {
409 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
410 if (tstamp_type_name
!= NULL
) {
411 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
412 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
414 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
417 pcap_free_tstamp_types(tstamp_types
);
418 exit_tcpdump(S_SUCCESS
);
423 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
427 const char *dlt_name
;
429 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
431 error("%s", pcap_geterr(pc
));
432 else if (n_dlts
== 0 || !dlts
)
433 error("No data link types.");
436 * If the interface is known to support monitor mode, indicate
437 * whether these are the data link types available when not in
438 * monitor mode, if -I wasn't specified, or when in monitor mode,
439 * when -I was specified (the link-layer types available in
440 * monitor mode might be different from the ones available when
441 * not in monitor mode).
443 if (supports_monitor_mode
)
444 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
446 Iflag
? "when in monitor mode" : "when not in monitor mode");
448 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
451 for (i
= 0; i
< n_dlts
; i
++) {
452 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
453 if (dlt_name
!= NULL
) {
454 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
455 pcap_datalink_val_to_description(dlts
[i
]));
458 * OK, does tcpdump handle that type?
460 if (!has_printer(dlts
[i
]))
461 (void) fprintf(stderr
, " (printing not supported)");
462 fprintf(stderr
, "\n");
464 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
468 #ifdef HAVE_PCAP_FREE_DATALINKS
469 pcap_free_datalinks(dlts
);
471 exit_tcpdump(S_SUCCESS
);
474 #ifdef HAVE_PCAP_FINDALLDEVS
476 show_devices_and_exit(void)
478 pcap_if_t
*dev
, *devlist
;
479 char ebuf
[PCAP_ERRBUF_SIZE
];
482 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
484 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
485 printf("%d.%s", i
+1, dev
->name
);
486 if (dev
->description
!= NULL
)
487 printf(" (%s)", dev
->description
);
488 if (dev
->flags
!= 0) {
490 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
491 #ifdef PCAP_IF_WIRELESS
492 if (dev
->flags
& PCAP_IF_WIRELESS
) {
493 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
495 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
496 printf(", Association status unknown");
499 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
500 printf(", Associated");
503 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
504 printf(", Not associated");
507 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
511 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
513 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
514 printf(", Connection status unknown");
517 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
518 printf(", Connected");
521 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
522 printf(", Disconnected");
525 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
534 pcap_freealldevs(devlist
);
535 exit_tcpdump(S_SUCCESS
);
537 #endif /* HAVE_PCAP_FINDALLDEVS */
539 #ifdef HAVE_PCAP_FINDALLDEVS_EX
541 show_remote_devices_and_exit(void)
543 pcap_if_t
*dev
, *devlist
;
544 char ebuf
[PCAP_ERRBUF_SIZE
];
547 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
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 */
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 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
599 #define B_FLAG_USAGE " [ -B size ]"
600 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
603 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
605 #ifdef HAVE_PCAP_FINDALLDEVS
611 #ifdef HAVE_PCAP_CREATE
613 #else /* HAVE_PCAP_CREATE */
615 #endif /* HAVE_PCAP_CREATE */
617 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
619 #define j_FLAG_USAGE " [ -j tstamptype ]"
621 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
625 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
628 #define m_FLAG_USAGE "[ -m module ] ..."
631 #ifdef HAVE_PCAP_SETDIRECTION
633 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
639 #ifdef HAVE_PCAP_DUMP_FLUSH
645 #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:#"
650 * We do not currently have long options corresponding to all short
651 * options; we should probably pick appropriate option names for them.
653 * However, the short options where the number of times the option is
654 * specified matters, such as -v and -d and -t, should probably not
655 * just map to a long option, as saying
657 * tcpdump --verbose --verbose
659 * doesn't make sense; it should be --verbosity={N} or something such
662 * For long options with no corresponding short options, we define values
663 * outside the range of ASCII graphic characters, make that the last
664 * component of the entry for the long option, and have a case for that
665 * option in the switch statement.
667 #define OPTION_VERSION 128
668 #define OPTION_TSTAMP_PRECISION 129
669 #define OPTION_IMMEDIATE_MODE 130
670 #define OPTION_PRINT 131
671 #define OPTION_LIST_REMOTE_INTERFACES 132
673 static const struct option longopts
[] = {
674 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
675 { "buffer-size", required_argument
, NULL
, 'B' },
677 { "list-interfaces", no_argument
, NULL
, 'D' },
678 #ifdef HAVE_PCAP_FINDALLDEVS_EX
679 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
681 { "help", no_argument
, NULL
, 'h' },
682 { "interface", required_argument
, NULL
, 'i' },
683 #ifdef HAVE_PCAP_CREATE
684 { "monitor-mode", no_argument
, NULL
, 'I' },
686 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
687 { "time-stamp-type", required_argument
, NULL
, 'j' },
688 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
690 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
691 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
693 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
694 { "list-data-link-types", no_argument
, NULL
, 'L' },
695 { "no-optimize", no_argument
, NULL
, 'O' },
696 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
697 #ifdef HAVE_PCAP_SETDIRECTION
698 { "direction", required_argument
, NULL
, 'Q' },
700 { "snapshot-length", required_argument
, NULL
, 's' },
701 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
702 #ifdef HAVE_PCAP_DUMP_FLUSH
703 { "packet-buffered", no_argument
, NULL
, 'U' },
705 { "linktype", required_argument
, NULL
, 'y' },
706 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
707 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
709 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
710 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
712 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
713 { "number", no_argument
, NULL
, '#' },
714 { "print", no_argument
, NULL
, OPTION_PRINT
},
715 { "version", no_argument
, NULL
, OPTION_VERSION
},
719 #ifdef HAVE_PCAP_FINDALLDEVS_EX
720 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
722 #define LIST_REMOTE_INTERFACES_USAGE
725 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
726 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
728 #define IMMEDIATE_MODE_USAGE ""
731 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
732 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
734 #define TIME_STAMP_PRECISION_USAGE
738 /* Drop root privileges and chroot if necessary */
740 droproot(const char *username
, const char *chroot_dir
)
742 struct passwd
*pw
= NULL
;
744 if (chroot_dir
&& !username
)
745 error("Chroot without dropping root is insecure");
747 pw
= getpwnam(username
);
750 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
751 error("Couldn't chroot/chdir to '%.64s': %s",
752 chroot_dir
, pcap_strerror(errno
));
754 #ifdef HAVE_LIBCAP_NG
756 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
758 error("capng_change_id(): return %d\n", ret
);
760 fprintf(stderr
, "dropped privs to %s\n", username
);
763 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
764 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
765 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
767 (unsigned long)pw
->pw_uid
,
768 (unsigned long)pw
->pw_gid
,
769 pcap_strerror(errno
));
771 fprintf(stderr
, "dropped privs to %s\n", username
);
773 #endif /* HAVE_LIBCAP_NG */
775 error("Couldn't find user '%.32s'", username
);
776 #ifdef HAVE_LIBCAP_NG
777 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
778 DIAG_OFF_CLANG(assign
-enum)
781 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
786 DIAG_ON_CLANG(assign
-enum)
787 capng_apply(CAPNG_SELECT_BOTH
);
788 #endif /* HAVE_LIBCAP_NG */
809 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
811 char *filename
= malloc(PATH_MAX
+ 1);
812 if (filename
== NULL
)
813 error("Makefilename: malloc");
815 /* Process with strftime if Gflag is set. */
819 /* Convert Gflag_time to a usable format */
820 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
821 error("MakeTimedFilename: localtime");
824 /* There's no good way to detect an error in strftime since a return
825 * value of 0 isn't necessarily failure.
827 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
829 strncpy(filename
, orig_name
, PATH_MAX
);
832 if (cnt
== 0 && max_chars
== 0)
833 strncpy(buffer
, filename
, PATH_MAX
+ 1);
835 if (nd_snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
836 /* Report an error if the filename is too large */
837 error("too many output files or filename is too long (> %d)", PATH_MAX
);
842 get_next_file(FILE *VFile
, char *ptr
)
846 ret
= fgets(ptr
, PATH_MAX
, VFile
);
850 if (ptr
[strlen(ptr
) - 1] == '\n')
851 ptr
[strlen(ptr
) - 1] = '\0';
857 static cap_channel_t
*
860 cap_channel_t
*capcas
, *capdnsloc
;
861 const char *types
[1];
866 error("unable to create casper process");
867 capdnsloc
= cap_service_open(capcas
, "system.dns");
868 /* Casper capability no longer needed. */
870 if (capdnsloc
== NULL
)
871 error("unable to open system.dns service");
872 /* Limit system.dns to reverse DNS lookups. */
874 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
875 error("unable to limit access to system.dns service");
876 families
[0] = AF_INET
;
877 families
[1] = AF_INET6
;
878 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
879 error("unable to limit access to system.dns service");
883 #endif /* HAVE_CASPER */
885 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
887 tstamp_precision_from_string(const char *precision
)
889 if (strncmp(precision
, "nano", strlen("nano")) == 0)
890 return PCAP_TSTAMP_PRECISION_NANO
;
892 if (strncmp(precision
, "micro", strlen("micro")) == 0)
893 return PCAP_TSTAMP_PRECISION_MICRO
;
899 tstamp_precision_to_string(int precision
)
903 case PCAP_TSTAMP_PRECISION_MICRO
:
906 case PCAP_TSTAMP_PRECISION_NANO
:
917 * Ensure that, on a dump file's descriptor, we have all the rights
918 * necessary to make the standard I/O library work with an fdopen()ed
919 * FILE * from that descriptor.
921 * A long time ago, in a galaxy far far away, AT&T decided that, instead
922 * of providing separate APIs for getting and setting the FD_ flags on a
923 * descriptor, getting and setting the O_ flags on a descriptor, and
924 * locking files, they'd throw them all into a kitchen-sink fcntl() call
925 * along the lines of ioctl(), the fact that ioctl() operations are
926 * largely specific to particular character devices but fcntl() operations
927 * are either generic to all descriptors or generic to all descriptors for
928 * regular files nonwithstanding.
930 * The Capsicum people decided that fine-grained control of descriptor
931 * operations was required, so that you need to grant permission for
932 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
933 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
934 * collection of things, so there are *individual* fcntls for which
935 * permission needs to be granted.
937 * The FreeBSD standard I/O people implemented some optimizations that
938 * requires that the standard I/O routines be able to determine whether
939 * the descriptor for the FILE * is open append-only or not; as that
940 * descriptor could have come from an open() rather than an fopen(),
941 * that requires that it be able to do an F_GETFL fcntl() to read
944 * Tcpdump uses ftell() to determine how much data has been written
945 * to a file in order to, when used with -C, determine when it's time
946 * to rotate capture files. ftell() therefore needs to do an lseek()
947 * to find out the file offset and must, thanks to the aforementioned
948 * optimization, also know whether the descriptor is open append-only
951 * The net result of all the above is that we need to grant CAP_SEEK,
952 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
954 * Perhaps this is the universe's way of saying that either
956 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
957 * using it, so that Capsicum-capable tcpdump wouldn't need to do
962 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
963 * I/O library that knows what rights are needed by the standard
964 * I/O library, based on the open mode, and assigns them, perhaps
965 * with an additional argument indicating, for example, whether
966 * seeking should be allowed, so that tcpdump doesn't need to know
967 * what the standard I/O library happens to require this week.
970 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
972 int fd
= fileno(pcap_dump_file(p
));
975 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
976 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
977 error("unable to limit dump descriptor");
979 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
980 error("unable to limit dump descriptor fcntls");
986 * Copy arg vector into a new buffer, concatenating arguments with spaces.
989 copy_argv(char **argv
)
1001 len
+= strlen(*p
++) + 1;
1003 buf
= (char *)malloc(len
);
1005 error("copy_argv: malloc");
1009 while ((src
= *p
++) != NULL
) {
1010 while ((*dst
++ = *src
++) != '\0')
1020 * On Windows, we need to open the file in binary mode, so that
1021 * we get all the bytes specified by the size we get from "fstat()".
1022 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1023 * we define it as 0 if it's not defined, so it does nothing.
1030 read_infile(char *fname
)
1036 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1038 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1040 if (fstat(fd
, &buf
) < 0)
1041 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1043 cp
= malloc((u_int
)buf
.st_size
+ 1);
1045 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1046 fname
, pcap_strerror(errno
));
1047 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1049 error("read %s: %s", fname
, pcap_strerror(errno
));
1050 if (cc
!= buf
.st_size
)
1051 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
1054 /* replace "# comment" with spaces */
1055 for (i
= 0; i
< cc
; i
++) {
1057 while (i
< cc
&& cp
[i
] != '\n')
1064 #ifdef HAVE_PCAP_FINDALLDEVS
1066 parse_interface_number(const char *device
)
1073 * Search for a colon, terminating any scheme at the beginning
1076 p
= strchr(device
, ':');
1079 * We found it. Is it followed by "//"?
1081 p
++; /* skip the : */
1082 if (strncmp(p
, "//", 2) == 0) {
1084 * Yes. Search for the next /, at the end of the
1085 * authority part of the URL.
1087 p
+= 2; /* skip the // */
1091 * OK, past the / is the path.
1097 devnum
= strtol(device
, &end
, 10);
1098 if (device
!= end
&& *end
== '\0') {
1100 * It's all-numeric, but is it a valid number?
1104 * No, it's not an ordinal.
1106 error("Invalid adapter index");
1111 * It's not all-numeric; return -1, so our caller
1119 find_interface_by_number(const char *url
1120 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1125 pcap_if_t
*dev
, *devlist
;
1127 char ebuf
[PCAP_ERRBUF_SIZE
];
1129 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1135 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1137 * Search for a colon, terminating any scheme at the beginning
1140 endp
= strchr(url
, ':');
1143 * We found it. Is it followed by "//"?
1145 endp
++; /* skip the : */
1146 if (strncmp(endp
, "//", 2) == 0) {
1148 * Yes. Search for the next /, at the end of the
1149 * authority part of the URL.
1151 endp
+= 2; /* skip the // */
1152 endp
= strchr(endp
, '/');
1158 * OK, everything from device to endp is a URL to hand
1159 * to pcap_findalldevs_ex().
1161 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1162 host_url
= malloc(endp
- url
+ 1);
1163 if (host_url
== NULL
&& (endp
- url
+ 1) > 0)
1164 error("Invalid allocation for host");
1166 memcpy(host_url
, url
, endp
- url
);
1167 host_url
[endp
- url
] = '\0';
1168 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1172 status
= pcap_findalldevs(&devlist
, ebuf
);
1176 * Look for the devnum-th entry in the list of devices (1-based).
1178 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1179 i
++, dev
= dev
->next
)
1182 error("Invalid adapter index");
1183 device
= strdup(dev
->name
);
1184 pcap_freealldevs(devlist
);
1189 #ifdef HAVE_PCAP_OPEN
1191 * Prefixes for rpcap URLs.
1193 static char rpcap_prefix
[] = "rpcap://";
1194 static char rpcap_ssl_prefix
[] = "rpcaps://";
1198 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1201 #ifdef HAVE_PCAP_CREATE
1206 #ifdef HAVE_PCAP_OPEN
1208 * Is this an rpcap URL?
1210 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0 ||
1211 strncmp(device
, rpcap_ssl_prefix
, sizeof(rpcap_ssl_prefix
) - 1) == 0) {
1213 * Yes. Open it with pcap_open().
1216 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1217 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1221 * If this failed with "No such device" or "The system
1222 * cannot find the device specified", that means
1223 * the interface doesn't exist; return NULL, so that
1224 * the caller can see whether the device name is
1225 * actually an interface index.
1227 if (strstr(ebuf
, "No such device") != NULL
||
1228 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1233 warning("%s", ebuf
);
1236 #endif /* HAVE_PCAP_OPEN */
1238 #ifdef HAVE_PCAP_CREATE
1239 pc
= pcap_create(device
, ebuf
);
1242 * If this failed with "No such device", that means
1243 * the interface doesn't exist; return NULL, so that
1244 * the caller can see whether the device name is
1245 * actually an interface index.
1247 if (strstr(ebuf
, "No such device") != NULL
)
1251 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1253 show_tstamp_types_and_exit(pc
, device
);
1255 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1256 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1258 error("%s: Can't set %ssecond time stamp precision: %s",
1260 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1261 pcap_statustostr(status
));
1264 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1265 if (immediate_mode
) {
1266 status
= pcap_set_immediate_mode(pc
, 1);
1268 error("%s: Can't set immediate mode: %s",
1269 device
, pcap_statustostr(status
));
1273 * Is this an interface that supports monitor mode?
1275 if (pcap_can_set_rfmon(pc
) == 1)
1276 supports_monitor_mode
= 1;
1278 supports_monitor_mode
= 0;
1279 if (ndo
->ndo_snaplen
!= 0) {
1281 * A snapshot length was explicitly specified;
1284 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1286 error("%s: Can't set snapshot length: %s",
1287 device
, pcap_statustostr(status
));
1289 status
= pcap_set_promisc(pc
, !pflag
);
1291 error("%s: Can't set promiscuous mode: %s",
1292 device
, pcap_statustostr(status
));
1294 status
= pcap_set_rfmon(pc
, 1);
1296 error("%s: Can't set monitor mode: %s",
1297 device
, pcap_statustostr(status
));
1299 status
= pcap_set_timeout(pc
, 1000);
1301 error("%s: pcap_set_timeout failed: %s",
1302 device
, pcap_statustostr(status
));
1304 status
= pcap_set_buffer_size(pc
, Bflag
);
1306 error("%s: Can't set buffer size: %s",
1307 device
, pcap_statustostr(status
));
1309 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1311 status
= pcap_set_tstamp_type(pc
, jflag
);
1313 error("%s: Can't set time stamp type: %s",
1314 device
, pcap_statustostr(status
));
1315 else if (status
> 0)
1316 warning("When trying to set timestamp type '%s' on %s: %s",
1317 pcap_tstamp_type_val_to_name(jflag
), device
,
1318 pcap_statustostr(status
));
1321 status
= pcap_activate(pc
);
1324 * pcap_activate() failed.
1326 cp
= pcap_geterr(pc
);
1327 if (status
== PCAP_ERROR
)
1329 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1331 * Return an error for our caller to handle.
1333 nd_snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1334 device
, pcap_statustostr(status
), cp
);
1337 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1338 error("%s: %s\n(%s)", device
,
1339 pcap_statustostr(status
), cp
);
1341 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1342 strncmp(device
, "wlan", 4) == 0) {
1343 char parent
[8], newdev
[8];
1345 size_t s
= sizeof(parent
);
1347 nd_snprintf(sysctl
, sizeof(sysctl
),
1348 "net.wlan.%d.%%parent", atoi(device
+ 4));
1349 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1350 strlcpy(newdev
, device
, sizeof(newdev
));
1351 /* Suggest a new wlan device. */
1352 /* FIXME: incrementing the index this way is not going to work well
1353 * when the index is 9 or greater but the only consequence in this
1354 * specific case would be an error message that looks a bit odd.
1356 newdev
[strlen(newdev
)-1]++;
1357 error("%s is not a monitor mode VAP\n"
1358 "To create a new monitor mode VAP use:\n"
1359 " ifconfig %s create wlandev %s wlanmode monitor\n"
1360 "and use %s as the tcpdump interface",
1361 device
, newdev
, parent
, newdev
);
1365 error("%s: %s", device
,
1366 pcap_statustostr(status
));
1367 } else if (status
> 0) {
1369 * pcap_activate() succeeded, but it's warning us
1370 * of a problem it had.
1372 cp
= pcap_geterr(pc
);
1373 if (status
== PCAP_WARNING
)
1375 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1377 warning("%s: %s\n(%s)", device
,
1378 pcap_statustostr(status
), cp
);
1380 warning("%s: %s", device
,
1381 pcap_statustostr(status
));
1383 #ifdef HAVE_PCAP_SETDIRECTION
1385 status
= pcap_setdirection(pc
, Qflag
);
1387 error("%s: pcap_setdirection() failed: %s",
1388 device
, pcap_geterr(pc
));
1390 #endif /* HAVE_PCAP_SETDIRECTION */
1391 #else /* HAVE_PCAP_CREATE */
1394 * If no snapshot length was specified, or a length of 0 was
1395 * specified, default to 256KB.
1397 if (ndo
->ndo_snaplen
== 0)
1398 ndo
->ndo_snaplen
= 262144;
1399 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1402 * If this failed with "No such device", that means
1403 * the interface doesn't exist; return NULL, so that
1404 * the caller can see whether the device name is
1405 * actually an interface index.
1407 if (strstr(ebuf
, "No such device") != NULL
)
1412 warning("%s", ebuf
);
1413 #endif /* HAVE_PCAP_CREATE */
1419 main(int argc
, char **argv
)
1422 bpf_u_int32 localnet
= 0, netmask
= 0;
1423 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1425 pcap_handler callback
;
1427 const char *dlt_name
;
1428 struct bpf_program fcode
;
1430 void (*oldhandler
)(int);
1432 struct dump_info dumpinfo
;
1433 u_char
*pcap_userdata
;
1434 char ebuf
[PCAP_ERRBUF_SIZE
];
1435 char VFileLine
[PATH_MAX
+ 1];
1436 char *username
= NULL
;
1437 char *chroot_dir
= NULL
;
1440 #ifdef HAVE_PCAP_FINDALLDEVS
1446 #ifdef HAVE_CAPSICUM
1447 cap_rights_t rights
;
1449 #endif /* HAVE_CAPSICUM */
1450 int Oflag
= 1; /* run filter code optimizer */
1452 const char *yflag_dlt_name
= NULL
;
1455 netdissect_options Ndo
;
1456 netdissect_options
*ndo
= &Ndo
;
1459 * Initialize the netdissect code.
1461 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1464 memset(ndo
, 0, sizeof(*ndo
));
1465 ndo_set_function_pointers(ndo
);
1475 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1476 ndo
->program_name
= program_name
= cp
+ 1;
1478 ndo
->program_name
= program_name
= argv
[0];
1480 #if defined(HAVE_PCAP_WSOCKINIT)
1481 if (pcap_wsockinit() != 0)
1482 error("Attempting to initialize Winsock failed");
1483 #elif defined(HAVE_WSOCKINIT)
1484 if (wsockinit() != 0)
1485 error("Attempting to initialize Winsock failed");
1489 * On platforms where the CPU doesn't support unaligned loads,
1490 * force unaligned accesses to abort with SIGBUS, rather than
1491 * being fixed up (slowly) by the OS kernel; on those platforms,
1492 * misaligned accesses are bugs, and we want tcpdump to crash so
1493 * that the bugs are reported.
1495 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1499 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1503 /* compatibility for old -a */
1514 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1516 Bflag
= atoi(optarg
)*1024;
1518 error("invalid packet buffer size %s", optarg
);
1520 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1525 error("invalid packet count %s", optarg
);
1530 #ifdef HAVE_PCAP_DUMP_FTELL64
1531 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1533 Cflag
= strtol(optarg
, &endp
, 10);
1535 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1537 error("invalid file size %s", optarg
);
1539 * Will multiplying it by 1000000 overflow?
1541 #ifdef HAVE_PCAP_DUMP_FTELL64
1542 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1544 if (Cflag
> LONG_MAX
/ 1000000)
1546 error("file size %s is too large", optarg
);
1554 #ifdef HAVE_PCAP_FINDALLDEVS
1560 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1561 case OPTION_LIST_REMOTE_INTERFACES
:
1562 remote_interfaces_source
= optarg
;
1575 #ifndef HAVE_LIBCRYPTO
1576 warning("crypto code not compiled in");
1578 ndo
->ndo_espsecret
= optarg
;
1590 Gflag
= atoi(optarg
);
1592 error("invalid number of seconds %s", optarg
);
1594 /* We will create one file initially. */
1597 /* Grab the current time for rotation use. */
1598 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1599 error("main: can't get current time: %s",
1600 pcap_strerror(errno
));
1606 exit_tcpdump(S_SUCCESS
);
1617 #ifdef HAVE_PCAP_CREATE
1621 #endif /* HAVE_PCAP_CREATE */
1623 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1625 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1627 error("invalid time stamp type %s", optarg
);
1638 * _IOLBF is the same as _IOFBF in Microsoft's C
1639 * libraries; the only alternative they offer
1642 * XXX - this should really be checking for MSVC++,
1643 * not _WIN32, if, for example, MinGW has its own
1644 * C library that is more UNIX-compatible.
1646 setvbuf(stdout
, NULL
, _IONBF
, 0);
1648 #ifdef HAVE_SETLINEBUF
1651 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1661 if (nd_have_smi_support()) {
1662 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1665 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1666 program_name
, optarg
);
1667 (void)fprintf(stderr
, "(no libsmi support)\n");
1672 /* TCP-MD5 shared secret */
1673 #ifndef HAVE_LIBCRYPTO
1674 warning("crypto code not compiled in");
1676 ndo
->ndo_sigsecret
= optarg
;
1697 ++ndo
->ndo_suppress_default_print
;
1700 #ifdef HAVE_PCAP_SETDIRECTION
1702 if (ascii_strcasecmp(optarg
, "in") == 0)
1704 else if (ascii_strcasecmp(optarg
, "out") == 0)
1706 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1707 Qflag
= PCAP_D_INOUT
;
1709 error("unknown capture direction `%s'", optarg
);
1711 #endif /* HAVE_PCAP_SETDIRECTION */
1718 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1719 if (optarg
== end
|| *end
!= '\0'
1720 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1721 error("invalid snaplen %s (must be >= 0 and <= %d)",
1722 optarg
, MAXIMUM_SNAPLEN
);
1734 if (ascii_strcasecmp(optarg
, "vat") == 0)
1735 ndo
->ndo_packettype
= PT_VAT
;
1736 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1737 ndo
->ndo_packettype
= PT_WB
;
1738 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1739 ndo
->ndo_packettype
= PT_RPC
;
1740 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1741 ndo
->ndo_packettype
= PT_RTP
;
1742 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1743 ndo
->ndo_packettype
= PT_RTCP
;
1744 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1745 ndo
->ndo_packettype
= PT_SNMP
;
1746 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1747 ndo
->ndo_packettype
= PT_CNFP
;
1748 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1749 ndo
->ndo_packettype
= PT_TFTP
;
1750 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1751 ndo
->ndo_packettype
= PT_AODV
;
1752 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1753 ndo
->ndo_packettype
= PT_CARP
;
1754 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1755 ndo
->ndo_packettype
= PT_RADIUS
;
1756 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1757 ndo
->ndo_packettype
= PT_ZMTP1
;
1758 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1759 ndo
->ndo_packettype
= PT_VXLAN
;
1760 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1761 ndo
->ndo_packettype
= PT_PGM
;
1762 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1763 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1764 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1765 ndo
->ndo_packettype
= PT_LMP
;
1766 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1767 ndo
->ndo_packettype
= PT_RESP
;
1769 error("unknown packet type `%s'", optarg
);
1776 #ifdef HAVE_PCAP_DUMP_FLUSH
1795 Wflag
= atoi(optarg
);
1797 error("invalid number of output files %s", optarg
);
1798 WflagChars
= getWflagChars(Wflag
);
1803 ++ndo
->ndo_suppress_default_print
;
1808 ++ndo
->ndo_suppress_default_print
;
1812 yflag_dlt_name
= optarg
;
1814 pcap_datalink_name_to_val(yflag_dlt_name
);
1816 error("invalid data link type %s", yflag_dlt_name
);
1819 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1822 /* Undocumented flag */
1823 pcap_set_parser_debug(1);
1836 ndo
->ndo_packet_number
= 1;
1839 case OPTION_VERSION
:
1841 exit_tcpdump(S_SUCCESS
);
1844 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1845 case OPTION_TSTAMP_PRECISION
:
1846 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1847 if (ndo
->ndo_tstamp_precision
< 0)
1848 error("unsupported time stamp precision");
1852 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1853 case OPTION_IMMEDIATE_MODE
:
1864 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1868 #ifdef HAVE_PCAP_FINDALLDEVS
1870 show_devices_and_exit();
1872 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1873 if (remote_interfaces_source
!= NULL
)
1874 show_remote_devices_and_exit();
1877 switch (ndo
->ndo_tflag
) {
1879 case 0: /* Default */
1880 case 1: /* No time stamp */
1881 case 2: /* Unix timeval style */
1882 case 3: /* Microseconds/nanoseconds since previous packet */
1883 case 4: /* Date + Default */
1884 case 5: /* Microseconds/nanoseconds since first packet */
1887 default: /* Not supported */
1888 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1892 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1893 error("-f can not be used with -V or -r");
1895 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1896 error("-V and -r are mutually exclusive.");
1898 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1900 * If we're printing dissected packets to the standard output
1901 * and the standard output is a terminal, use immediate mode,
1902 * as the user's probably expecting to see packets pop up
1905 * XXX - set the timeout to a lower value, instead? If so,
1906 * what value would be appropriate?
1908 if ((WFileName
== NULL
|| print
) && isatty(1))
1913 /* if run as root, prepare for chrooting */
1914 if (getuid() == 0 || geteuid() == 0) {
1915 /* future extensibility for cmd-line arguments */
1917 chroot_dir
= WITH_CHROOT
;
1922 /* if run as root, prepare for dropping root privileges */
1923 if (getuid() == 0 || geteuid() == 0) {
1924 /* Run with '-Z root' to restore old behaviour */
1926 username
= WITH_USER
;
1930 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1932 * If RFileName is non-null, it's the pathname of a
1933 * savefile to read. If VFileName is non-null, it's
1934 * the pathname of a file containing a list of pathnames
1935 * (one per line) of savefiles to read.
1937 * In either case, we're reading a savefile, not doing
1942 * We don't need network access, so relinquish any set-UID
1943 * or set-GID privileges we have (if any).
1945 * We do *not* want set-UID privileges when opening a
1946 * trace file, as that might let the user read other
1947 * people's trace files (especially if we're set-UID
1950 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1951 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1953 if (VFileName
!= NULL
) {
1954 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1957 VFile
= fopen(VFileName
, "r");
1960 error("Unable to open file: %s\n", pcap_strerror(errno
));
1962 ret
= get_next_file(VFile
, VFileLine
);
1964 error("Nothing in %s\n", VFileName
);
1965 RFileName
= VFileLine
;
1968 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1969 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1970 ndo
->ndo_tstamp_precision
, ebuf
);
1972 pd
= pcap_open_offline(RFileName
, ebuf
);
1977 #ifdef HAVE_CAPSICUM
1978 cap_rights_init(&rights
, CAP_READ
);
1979 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1981 error("unable to limit pcap descriptor");
1984 dlt
= pcap_datalink(pd
);
1985 dlt_name
= pcap_datalink_val_to_name(dlt
);
1986 fprintf(stderr
, "reading from file %s", RFileName
);
1987 if (dlt_name
== NULL
) {
1988 fprintf(stderr
, ", link-type %u", dlt
);
1990 fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
1991 pcap_datalink_val_to_description(dlt
));
1993 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
1994 #ifdef DLT_LINUX_SLL2
1995 if (dlt
== DLT_LINUX_SLL2
)
1996 fprintf(stderr
, "Warning: interface names might be incorrect\n");
2000 * We're doing a live capture.
2002 if (device
== NULL
) {
2004 * No interface was specified. Pick one.
2006 #ifdef HAVE_PCAP_FINDALLDEVS
2008 * Find the list of interfaces, and pick
2009 * the first interface.
2011 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2013 if (devlist
== NULL
)
2014 error("no interfaces available for capture");
2015 device
= strdup(devlist
->name
);
2016 pcap_freealldevs(devlist
);
2017 #else /* HAVE_PCAP_FINDALLDEVS */
2019 * Use whatever interface pcap_lookupdev()
2022 device
= pcap_lookupdev(ebuf
);
2029 * Try to open the interface with the specified name.
2031 pd
= open_interface(device
, ndo
, ebuf
);
2034 * That failed. If we can get a list of
2035 * interfaces, and the interface name
2036 * is purely numeric, try to use it as
2037 * a 1-based index in the list of
2040 #ifdef HAVE_PCAP_FINDALLDEVS
2041 devnum
= parse_interface_number(device
);
2044 * It's not a number; just report
2045 * the open error and fail.
2051 * OK, it's a number; try to find the
2052 * interface with that index, and try
2055 * find_interface_by_number() exits if it
2056 * couldn't be found.
2058 device
= find_interface_by_number(device
, devnum
);
2059 pd
= open_interface(device
, ndo
, ebuf
);
2062 #else /* HAVE_PCAP_FINDALLDEVS */
2064 * We can't get a list of interfaces; just
2068 #endif /* HAVE_PCAP_FINDALLDEVS */
2072 * Let user own process after capture device has
2076 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2077 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2079 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2081 if(pcap_setbuff(pd
, Bflag
)==-1){
2082 error("%s", pcap_geterr(pd
));
2084 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2086 show_dlts_and_exit(pd
, device
);
2087 if (yflag_dlt
>= 0) {
2088 #ifdef HAVE_PCAP_SET_DATALINK
2089 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2090 error("%s", pcap_geterr(pd
));
2093 * We don't actually support changing the
2094 * data link type, so we only let them
2095 * set it to what it already is.
2097 if (yflag_dlt
!= pcap_datalink(pd
)) {
2098 error("%s is not one of the DLTs supported by this device\n",
2102 (void)fprintf(stderr
, "%s: data link type %s\n",
2103 program_name
, yflag_dlt_name
);
2104 (void)fflush(stderr
);
2106 i
= pcap_snapshot(pd
);
2107 if (ndo
->ndo_snaplen
< i
) {
2108 if (ndo
->ndo_snaplen
!= 0)
2109 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2110 ndo
->ndo_snaplen
= i
;
2111 } else if (ndo
->ndo_snaplen
> i
) {
2112 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2113 ndo
->ndo_snaplen
= i
;
2115 if(ndo
->ndo_fflag
!= 0) {
2116 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2117 warning("foreign (-f) flag used but: %s", ebuf
);
2123 cmdbuf
= read_infile(infile
);
2125 cmdbuf
= copy_argv(&argv
[optind
]);
2127 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2128 pcap_set_optimizer_debug(dflag
);
2130 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2131 error("%s", pcap_geterr(pd
));
2133 bpf_dump(&fcode
, dflag
);
2136 pcap_freecode(&fcode
);
2137 exit_tcpdump(S_SUCCESS
);
2141 if (!ndo
->ndo_nflag
)
2142 capdns
= capdns_setup();
2143 #endif /* HAVE_CASPER */
2145 init_print(ndo
, localnet
, netmask
);
2148 (void)setsignal(SIGPIPE
, cleanup
);
2149 (void)setsignal(SIGTERM
, cleanup
);
2151 (void)setsignal(SIGINT
, cleanup
);
2152 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2153 (void)setsignal(SIGCHLD
, child_cleanup
);
2155 /* Cooperate with nohup(1) */
2157 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2158 (void)setsignal(SIGHUP
, oldhandler
);
2163 * If a user name was specified with "-Z", attempt to switch to
2164 * that user's UID. This would probably be used with sudo,
2165 * to allow tcpdump to be run in a special restricted
2166 * account (if you just want to allow users to open capture
2167 * devices, and can't just give users that permission,
2168 * you'd make tcpdump set-UID or set-GID).
2170 * Tcpdump doesn't necessarily write only to one savefile;
2171 * the general only way to allow a -Z instance to write to
2172 * savefiles as the user under whose UID it's run, rather
2173 * than as the user specified with -Z, would thus be to switch
2174 * to the original user ID before opening a capture file and
2175 * then switch back to the -Z user ID after opening the savefile.
2176 * Switching to the -Z user ID only after opening the first
2177 * savefile doesn't handle the general case.
2180 if (getuid() == 0 || geteuid() == 0) {
2181 #ifdef HAVE_LIBCAP_NG
2182 /* Initialize capng */
2183 capng_clear(CAPNG_SELECT_BOTH
);
2185 DIAG_OFF_CLANG(assign
-enum)
2188 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2192 DIAG_ON_CLANG(assign
-enum)
2195 DIAG_OFF_CLANG(assign
-enum)
2198 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2201 DIAG_ON_CLANG(assign
-enum)
2205 DIAG_OFF_CLANG(assign
-enum)
2208 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2211 DIAG_ON_CLANG(assign
-enum)
2213 capng_apply(CAPNG_SELECT_BOTH
);
2214 #endif /* HAVE_LIBCAP_NG */
2215 if (username
|| chroot_dir
)
2216 droproot(username
, chroot_dir
);
2221 if (pcap_setfilter(pd
, &fcode
) < 0)
2222 error("%s", pcap_geterr(pd
));
2223 #ifdef HAVE_CAPSICUM
2224 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2225 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2228 * The various libpcap devices use a combination of
2229 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2230 * so we add the relevant access rights.
2232 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2233 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2235 error("unable to limit pcap descriptor");
2237 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2238 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2239 error("unable to limit ioctls on pcap descriptor");
2244 /* Do not exceed the default PATH_MAX for files. */
2245 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2247 if (dumpinfo
.CurrentFileName
== NULL
)
2248 error("malloc of dumpinfo.CurrentFileName");
2250 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2252 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2254 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2256 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2257 #ifdef HAVE_LIBCAP_NG
2258 /* Give up CAP_DAC_OVERRIDE capability.
2259 * Only allow it to be restored if the -C or -G flag have been
2260 * set since we may need to create more files later on.
2264 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2268 capng_apply(CAPNG_SELECT_BOTH
);
2269 #endif /* HAVE_LIBCAP_NG */
2271 error("%s", pcap_geterr(pd
));
2272 #ifdef HAVE_CAPSICUM
2273 set_dumper_capsicum_rights(pdd
);
2275 if (Cflag
!= 0 || Gflag
!= 0) {
2276 #ifdef HAVE_CAPSICUM
2277 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2278 if (dumpinfo
.WFileName
== NULL
) {
2279 error("Unable to allocate memory for file %s",
2282 dumpinfo
.dirfd
= open(dirname(WFileName
),
2283 O_DIRECTORY
| O_RDONLY
);
2284 if (dumpinfo
.dirfd
< 0) {
2285 error("unable to open directory %s",
2286 dirname(WFileName
));
2288 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2289 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2290 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2292 error("unable to limit directory rights");
2294 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2296 error("unable to limit dump descriptor fcntls");
2298 #else /* !HAVE_CAPSICUM */
2299 dumpinfo
.WFileName
= WFileName
;
2301 callback
= dump_packet_and_trunc
;
2304 pcap_userdata
= (u_char
*)&dumpinfo
;
2306 callback
= dump_packet
;
2307 dumpinfo
.WFileName
= WFileName
;
2310 pcap_userdata
= (u_char
*)&dumpinfo
;
2313 dlt
= pcap_datalink(pd
);
2314 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2317 dumpinfo
.ndo
= NULL
;
2319 #ifdef HAVE_PCAP_DUMP_FLUSH
2321 pcap_dump_flush(pdd
);
2324 dlt
= pcap_datalink(pd
);
2325 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2326 callback
= print_packet
;
2327 pcap_userdata
= (u_char
*)ndo
;
2330 #ifdef SIGNAL_REQ_INFO
2332 * We can't get statistics when reading from a file rather
2333 * than capturing from a device.
2335 if (RFileName
== NULL
)
2336 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2338 #ifdef SIGNAL_FLUSH_PCAP
2339 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2342 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2344 * When capturing to a file, if "--print" wasn't specified,
2345 *"-v" means tcpdump should, once per second,
2346 * "v"erbosely report the number of packets captured.
2350 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2352 * suggests that this dates back to W2K.
2354 * I don't know what a "long wait" is, but we'll assume
2355 * that printing the stats could be a "long wait".
2357 CreateTimerQueueTimer(&timer_handle
, NULL
,
2358 verbose_stats_dump
, NULL
, 1000, 1000,
2359 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2360 setvbuf(stderr
, NULL
, _IONBF
, 0);
2363 * Assume this is UN*X, and that it has setitimer(); that
2364 * dates back to UNIX 95.
2366 struct itimerval timer
;
2367 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2368 timer
.it_interval
.tv_sec
= 1;
2369 timer
.it_interval
.tv_usec
= 0;
2370 timer
.it_value
.tv_sec
= 1;
2371 timer
.it_value
.tv_usec
= 1;
2372 setitimer(ITIMER_REAL
, &timer
, NULL
);
2376 if (RFileName
== NULL
) {
2378 * Live capture (if -V was specified, we set RFileName
2379 * to a file from the -V file). Print a message to
2380 * the standard error on UN*X.
2382 if (!ndo
->ndo_vflag
&& !WFileName
) {
2383 (void)fprintf(stderr
,
2384 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2387 (void)fprintf(stderr
, "%s: ", program_name
);
2388 dlt
= pcap_datalink(pd
);
2389 dlt_name
= pcap_datalink_val_to_name(dlt
);
2390 (void)fprintf(stderr
, "listening on %s", device
);
2391 if (dlt_name
== NULL
) {
2392 (void)fprintf(stderr
, ", link-type %u", dlt
);
2394 (void)fprintf(stderr
, ", link-type %s (%s)", dlt_name
,
2395 pcap_datalink_val_to_description(dlt
));
2397 (void)fprintf(stderr
, ", snapshot length %d bytes\n", ndo
->ndo_snaplen
);
2398 (void)fflush(stderr
);
2401 #ifdef HAVE_CAPSICUM
2402 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2404 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2406 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2407 #endif /* HAVE_CASPER */
2408 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2409 error("unable to enter the capability mode");
2410 #endif /* HAVE_CAPSICUM */
2413 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2414 if (WFileName
== NULL
) {
2416 * We're printing packets. Flush the printed output,
2417 * so it doesn't get intermingled with error output.
2421 * We got interrupted, so perhaps we didn't
2422 * manage to finish a line we were printing.
2423 * Print an extra newline, just in case.
2427 (void)fflush(stdout
);
2431 * We got interrupted. If we are reading multiple
2432 * files (via -V) set these so that we stop.
2441 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2442 program_name
, pcap_geterr(pd
));
2444 if (RFileName
== NULL
) {
2446 * We're doing a live capture. Report the capture
2452 if (VFileName
!= NULL
) {
2453 ret
= get_next_file(VFile
, VFileLine
);
2457 RFileName
= VFileLine
;
2458 pd
= pcap_open_offline(RFileName
, ebuf
);
2461 #ifdef HAVE_CAPSICUM
2462 cap_rights_init(&rights
, CAP_READ
);
2463 if (cap_rights_limit(fileno(pcap_file(pd
)),
2464 &rights
) < 0 && errno
!= ENOSYS
) {
2465 error("unable to limit pcap descriptor");
2468 new_dlt
= pcap_datalink(pd
);
2469 if (new_dlt
!= dlt
) {
2471 * The new file has a different
2472 * link-layer header type from the
2475 if (WFileName
!= NULL
) {
2477 * We're writing raw packets
2478 * that match the filter to
2479 * a pcap file. pcap files
2480 * don't support multiple
2481 * different link-layer
2482 * header types, so we fail
2485 error("%s: new dlt does not match original", RFileName
);
2489 * We're printing the decoded packets;
2490 * switch to the new DLT.
2492 * To do that, we need to change
2493 * the printer, change the DLT name,
2494 * and recompile the filter with
2498 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2499 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2500 error("%s", pcap_geterr(pd
));
2504 * Set the filter on the new file.
2506 if (pcap_setfilter(pd
, &fcode
) < 0)
2507 error("%s", pcap_geterr(pd
));
2510 * Report the new file.
2512 dlt_name
= pcap_datalink_val_to_name(dlt
);
2513 fprintf(stderr
, "reading from file %s", RFileName
);
2514 if (dlt_name
== NULL
) {
2515 fprintf(stderr
, ", link-type %u", dlt
);
2517 fprintf(stderr
, ", link-type %s (%s)",
2519 pcap_datalink_val_to_description(dlt
));
2521 fprintf(stderr
, ", snapshot length %d\n", pcap_snapshot(pd
));
2525 while (ret
!= NULL
);
2528 pcap_freecode(&fcode
);
2529 exit_tcpdump(status
== -1 ? 1 : 0);
2536 (*setsignal (int sig
, void (*func
)(int)))(int)
2539 return (signal(sig
, func
));
2541 struct sigaction old
, new;
2543 memset(&new, 0, sizeof(new));
2544 new.sa_handler
= func
;
2546 new.sa_flags
= SA_RESTART
;
2547 if (sigaction(sig
, &new, &old
) < 0)
2549 return (old
.sa_handler
);
2553 /* make a clean exit on interrupts */
2555 cleanup(int signo _U_
)
2558 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2559 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2560 CloseHandle(timer_handle
);
2561 timer_handle
= INVALID_HANDLE_VALUE
;
2564 struct itimerval timer
;
2566 timer
.it_interval
.tv_sec
= 0;
2567 timer
.it_interval
.tv_usec
= 0;
2568 timer
.it_value
.tv_sec
= 0;
2569 timer
.it_value
.tv_usec
= 0;
2570 setitimer(ITIMER_REAL
, &timer
, NULL
);
2573 #ifdef HAVE_PCAP_BREAKLOOP
2575 * We have "pcap_breakloop()"; use it, so that we do as little
2576 * as possible in the signal handler (it's probably not safe
2577 * to do anything with standard I/O streams in a signal handler -
2578 * the ANSI C standard doesn't say it is).
2583 * We don't have "pcap_breakloop()"; this isn't safe, but
2584 * it's the best we can do. Print the summary if we're
2585 * not reading from a savefile - i.e., if we're doing a
2586 * live capture - and exit.
2588 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2590 * We got interrupted, so perhaps we didn't
2591 * manage to finish a line we were printing.
2592 * Print an extra newline, just in case.
2595 (void)fflush(stdout
);
2598 exit_tcpdump(S_SUCCESS
);
2603 On windows, we do not use a fork, so we do not care less about
2604 waiting a child processes to die
2606 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2608 child_cleanup(int signo _U_
)
2612 #endif /* HAVE_FORK && HAVE_VFORK */
2617 struct pcap_stat stats
;
2620 * Older versions of libpcap didn't set ps_ifdrop on some
2621 * platforms; initialize it to 0 to handle that.
2623 stats
.ps_ifdrop
= 0;
2624 if (pcap_stats(pd
, &stats
) < 0) {
2625 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2631 fprintf(stderr
, "%s: ", program_name
);
2633 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2634 PLURAL_SUFFIX(packets_captured
));
2636 fputs(", ", stderr
);
2639 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2640 PLURAL_SUFFIX(stats
.ps_recv
));
2642 fputs(", ", stderr
);
2645 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2646 PLURAL_SUFFIX(stats
.ps_drop
));
2647 if (stats
.ps_ifdrop
!= 0) {
2649 fputs(", ", stderr
);
2652 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2653 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2659 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2661 #define fork_subprocess() fork()
2663 #define fork_subprocess() vfork()
2666 compress_savefile(const char *filename
)
2670 child
= fork_subprocess();
2673 "compress_savefile: fork failed: %s\n",
2674 pcap_strerror(errno
));
2678 /* Parent process. */
2684 * Set to lowest priority so that this doesn't disturb the capture.
2687 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2689 setpriority(PRIO_PROCESS
, 0, 19);
2691 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2693 "compress_savefile: execlp(%s, %s) failed: %s\n",
2696 pcap_strerror(errno
));
2698 exit(S_ERR_HOST_PROGRAM
);
2700 _exit(S_ERR_HOST_PROGRAM
);
2703 #else /* HAVE_FORK && HAVE_VFORK */
2705 compress_savefile(const char *filename
)
2708 "compress_savefile failed. Functionality not implemented under your system\n");
2710 #endif /* HAVE_FORK && HAVE_VFORK */
2713 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2715 struct dump_info
*dump_info
;
2721 dump_info
= (struct dump_info
*)user
;
2724 * XXX - this won't force the file to rotate on the specified time
2725 * boundary, but it will rotate on the first packet received after the
2726 * specified Gflag number of seconds. Note: if a Gflag time boundary
2727 * and a Cflag size boundary coincide, the time rotation will occur
2728 * first thereby cancelling the Cflag boundary (since the file should
2732 /* Check if it is time to rotate */
2735 /* Get the current time */
2736 if ((t
= time(NULL
)) == (time_t)-1) {
2737 error("dump_and_trunc_packet: can't get current_time: %s",
2738 pcap_strerror(errno
));
2742 /* If the time is greater than the specified window, rotate */
2743 if (t
- Gflag_time
>= Gflag
) {
2744 #ifdef HAVE_CAPSICUM
2749 /* Update the Gflag_time */
2751 /* Update Gflag_count */
2754 * Close the current file and open a new one.
2756 pcap_dump_close(dump_info
->pdd
);
2759 * Compress the file we just closed, if the user asked for it
2762 compress_savefile(dump_info
->CurrentFileName
);
2765 * Check to see if we've exceeded the Wflag (when
2768 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2769 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2772 exit_tcpdump(S_SUCCESS
);
2775 if (dump_info
->CurrentFileName
!= NULL
)
2776 free(dump_info
->CurrentFileName
);
2777 /* Allocate space for max filename + \0. */
2778 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2779 if (dump_info
->CurrentFileName
== NULL
)
2780 error("dump_packet_and_trunc: malloc");
2782 * Gflag was set otherwise we wouldn't be here. Reset the count
2783 * so multiple files would end with 1,2,3 in the filename.
2784 * The counting is handled with the -C flow after this.
2789 * This is always the first file in the Cflag
2791 * We also don't need numbering if Cflag is not set.
2794 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2797 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2799 #ifdef HAVE_LIBCAP_NG
2800 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2801 capng_apply(CAPNG_SELECT_BOTH
);
2802 #endif /* HAVE_LIBCAP_NG */
2803 #ifdef HAVE_CAPSICUM
2804 fd
= openat(dump_info
->dirfd
,
2805 dump_info
->CurrentFileName
,
2806 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2808 error("unable to open file %s",
2809 dump_info
->CurrentFileName
);
2811 fp
= fdopen(fd
, "w");
2813 error("unable to fdopen file %s",
2814 dump_info
->CurrentFileName
);
2816 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2817 #else /* !HAVE_CAPSICUM */
2818 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2820 #ifdef HAVE_LIBCAP_NG
2821 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2822 capng_apply(CAPNG_SELECT_BOTH
);
2823 #endif /* HAVE_LIBCAP_NG */
2824 if (dump_info
->pdd
== NULL
)
2825 error("%s", pcap_geterr(pd
));
2826 #ifdef HAVE_CAPSICUM
2827 set_dumper_capsicum_rights(dump_info
->pdd
);
2833 * XXX - this won't prevent capture files from getting
2834 * larger than Cflag - the last packet written to the
2835 * file could put it over Cflag.
2838 #ifdef HAVE_PCAP_DUMP_FTELL64
2839 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
2842 * XXX - this only handles a Cflag value > 2^31-1 on
2843 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2844 * Windows) or LLP64 (64-bit Windows) would require
2845 * a version of libpcap with pcap_dump_ftell64().
2847 long size
= pcap_dump_ftell(dump_info
->pdd
);
2851 error("ftell fails on output file");
2853 #ifdef HAVE_CAPSICUM
2859 * Close the current file and open a new one.
2861 pcap_dump_close(dump_info
->pdd
);
2864 * Compress the file we just closed, if the user
2868 compress_savefile(dump_info
->CurrentFileName
);
2872 if (Cflag_count
>= Wflag
)
2875 if (dump_info
->CurrentFileName
!= NULL
)
2876 free(dump_info
->CurrentFileName
);
2877 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2878 if (dump_info
->CurrentFileName
== NULL
)
2879 error("dump_packet_and_trunc: malloc");
2880 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2881 #ifdef HAVE_LIBCAP_NG
2882 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2883 capng_apply(CAPNG_SELECT_BOTH
);
2884 #endif /* HAVE_LIBCAP_NG */
2885 #ifdef HAVE_CAPSICUM
2886 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2887 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2889 error("unable to open file %s",
2890 dump_info
->CurrentFileName
);
2892 fp
= fdopen(fd
, "w");
2894 error("unable to fdopen file %s",
2895 dump_info
->CurrentFileName
);
2897 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2898 #else /* !HAVE_CAPSICUM */
2899 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2901 #ifdef HAVE_LIBCAP_NG
2902 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2903 capng_apply(CAPNG_SELECT_BOTH
);
2904 #endif /* HAVE_LIBCAP_NG */
2905 if (dump_info
->pdd
== NULL
)
2906 error("%s", pcap_geterr(pd
));
2907 #ifdef HAVE_CAPSICUM
2908 set_dumper_capsicum_rights(dump_info
->pdd
);
2913 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2914 #ifdef HAVE_PCAP_DUMP_FLUSH
2916 pcap_dump_flush(dump_info
->pdd
);
2919 if (dump_info
->ndo
!= NULL
)
2920 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2928 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2930 struct dump_info
*dump_info
;
2936 dump_info
= (struct dump_info
*)user
;
2938 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2939 #ifdef HAVE_PCAP_DUMP_FLUSH
2941 pcap_dump_flush(dump_info
->pdd
);
2944 if (dump_info
->ndo
!= NULL
)
2945 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2953 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2959 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2966 #ifdef SIGNAL_REQ_INFO
2968 requestinfo(int signo _U_
)
2977 #ifdef SIGNAL_FLUSH_PCAP
2979 flushpcap(int signo _U_
)
2982 pcap_dump_flush(pdd
);
2987 print_packets_captured (void)
2989 static u_int prev_packets_captured
, first
= 1;
2991 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2992 fprintf(stderr
, "Got %u\r", packets_captured
);
2994 prev_packets_captured
= packets_captured
;
2999 * Called once each second in verbose mode while dumping to file
3002 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
3003 BOOLEAN timer_fired _U_
)
3005 print_packets_captured();
3008 static void verbose_stats_dump(int sig _U_
)
3010 print_packets_captured();
3014 USES_APPLE_DEPRECATED_API
3018 #ifndef HAVE_PCAP_LIB_VERSION
3019 #ifdef HAVE_PCAP_VERSION
3020 extern char pcap_version
[];
3021 #else /* HAVE_PCAP_VERSION */
3022 static char pcap_version
[] = "unknown";
3023 #endif /* HAVE_PCAP_VERSION */
3024 #endif /* HAVE_PCAP_LIB_VERSION */
3025 const char *smi_version_string
;
3027 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3028 #ifdef HAVE_PCAP_LIB_VERSION
3029 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
3030 #else /* HAVE_PCAP_LIB_VERSION */
3031 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
3032 #endif /* HAVE_PCAP_LIB_VERSION */
3034 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3035 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3038 smi_version_string
= nd_smi_version_string();
3039 if (smi_version_string
!= NULL
)
3040 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
3041 #ifdef HAVE_DNET_HTOA
3042 (void)fprintf(stderr
, "libdnet unknown version\n");
3045 #if defined(__SANITIZE_ADDRESS__)
3046 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
3047 #elif defined(__has_feature)
3048 # if __has_feature(address_sanitizer)
3049 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
3051 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3059 (void)fprintf(stderr
,
3060 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
3061 (void)fprintf(stderr
,
3062 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3063 (void)fprintf(stderr
,
3064 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3065 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3066 (void)fprintf(stderr
,
3067 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
3070 (void)fprintf(stderr
,
3071 "\t\t" m_FLAG_USAGE
"\n");
3073 (void)fprintf(stderr
,
3074 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
3075 (void)fprintf(stderr
,
3076 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
3077 (void)fprintf(stderr
,
3078 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
3079 (void)fprintf(stderr
,
3080 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
3081 (void)fprintf(stderr
,
3082 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");