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 "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/capability.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 "gmt2local.h"
136 #include "pcap-missing.h"
137 #include "ascii_strcasecmp.h"
142 #define PATH_MAX 1024
146 #define SIGNAL_REQ_INFO SIGINFO
147 #elif defined(SIGUSR1)
148 #define SIGNAL_REQ_INFO SIGUSR1
151 #if defined(HAVE_PCAP_DUMP_FLUSH) && defined(SIGUSR2)
152 #define SIGNAL_FLUSH_PCAP SIGUSR2
155 static int Bflag
; /* buffer size */
156 #ifdef HAVE_PCAP_DUMP_FTELL64
157 static int64_t Cflag
; /* rotate dump files after this many bytes */
159 static long Cflag
; /* rotate dump files after this many bytes */
161 static int Cflag_count
; /* Keep track of which file number we're writing */
162 #ifdef HAVE_PCAP_FINDALLDEVS
163 static int Dflag
; /* list available devices and exit */
165 #ifdef HAVE_PCAP_FINDALLDEVS_EX
166 static char *remote_interfaces_source
; /* list available devices from this source and exit */
170 * This is exported because, in some versions of libpcap, if libpcap
171 * is built with optimizer debugging code (which is *NOT* the default
172 * configuration!), the library *imports*(!) a variable named dflag,
173 * under the expectation that tcpdump is exporting it, to govern
174 * how much debugging information to print when optimizing
175 * the generated BPF code.
177 * This is a horrible hack; newer versions of libpcap don't import
178 * dflag but, instead, *if* built with optimizer debugging code,
179 * *export* a routine to set that flag.
181 int dflag
; /* print filter code */
182 static int Gflag
; /* rotate dump files after this many seconds */
183 static int Gflag_count
; /* number of files created with Gflag rotation */
184 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
185 static int Lflag
; /* list available data link types and exit */
186 static int Iflag
; /* rfmon (monitor) mode */
187 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
188 static int Jflag
; /* list available time stamp types */
190 static int jflag
= -1; /* packet time stamp source */
191 static int pflag
; /* don't go promiscuous */
192 #ifdef HAVE_PCAP_SETDIRECTION
193 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
195 static int Uflag
; /* "unbuffered" output of dump files */
196 static int Wflag
; /* recycle output files after this number of files */
197 static int WflagChars
;
198 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
199 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
200 static int immediate_mode
;
203 static int infodelay
;
204 static int infoprint
;
209 cap_channel_t
*capdns
;
213 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
214 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
215 static NORETURN
void exit_tcpdump(int);
216 static void (*setsignal (int sig
, void (*func
)(int)))(int);
217 static void cleanup(int);
218 static void child_cleanup(int);
219 static void print_version(void);
220 static void print_usage(void);
221 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
222 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
223 #ifdef HAVE_PCAP_FINDALLDEVS
224 static NORETURN
void show_devices_and_exit(void);
226 #ifdef HAVE_PCAP_FINDALLDEVS_EX
227 static NORETURN
void show_remote_devices_and_exit(void);
230 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
231 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
232 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
233 static void droproot(const char *, const char *);
235 #ifdef SIGNAL_REQ_INFO
236 static void requestinfo(int);
239 #ifdef SIGNAL_FLUSH_PCAP
240 static void flushpcap(int);
244 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
245 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
247 static void verbose_stats_dump(int sig
);
250 static void info(int);
251 static u_int packets_captured
;
253 #ifdef HAVE_PCAP_FINDALLDEVS
254 static const struct tok status_flags
[] = {
256 { PCAP_IF_UP
, "Up" },
258 #ifdef PCAP_IF_RUNNING
259 { PCAP_IF_RUNNING
, "Running" },
261 { PCAP_IF_LOOPBACK
, "Loopback" },
262 #ifdef PCAP_IF_WIRELESS
263 { PCAP_IF_WIRELESS
, "Wireless" },
270 static pcap_dumper_t
*pdd
= NULL
;
272 static int supports_monitor_mode
;
280 char *CurrentFileName
;
283 netdissect_options
*ndo
;
289 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
291 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
292 * by any libpcap header, because it's a special hack, only available if
293 * libpcap was configured to include it, and only intended for use by
294 * libpcap developers trying to debug the parser for filter expressions).
297 __declspec(dllimport
)
301 void pcap_set_parser_debug(int);
302 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
304 * We don't have pcap_set_parser_debug() in libpcap, but we do have
305 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
306 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
309 pcap_set_parser_debug(int value
)
311 #ifdef HAVE_PCAP_DEBUG
312 extern int pcap_debug
;
315 #else /* HAVE_PCAP_DEBUG */
319 #endif /* HAVE_PCAP_DEBUG */
322 #define HAVE_PCAP_SET_PARSER_DEBUG
325 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
327 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
328 * by any libpcap header, because it's a special hack, only available if
329 * libpcap was configured to include it, and only intended for use by
330 * libpcap developers trying to debug the optimizer for filter expressions).
333 __declspec(dllimport
)
337 void pcap_set_optimizer_debug(int);
342 error(const char *fmt
, ...)
346 (void)fprintf(stderr
, "%s: ", program_name
);
348 (void)vfprintf(stderr
, fmt
, ap
);
353 (void)fputc('\n', stderr
);
355 exit_tcpdump(S_ERR_HOST_PROGRAM
);
361 warning(const char *fmt
, ...)
365 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
367 (void)vfprintf(stderr
, fmt
, ap
);
372 (void)fputc('\n', stderr
);
377 exit_tcpdump(int status
)
383 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
385 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
388 int *tstamp_types
= 0;
389 const char *tstamp_type_name
;
392 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
393 if (n_tstamp_types
< 0)
394 error("%s", pcap_geterr(pc
));
396 if (n_tstamp_types
== 0) {
397 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
399 exit_tcpdump(S_SUCCESS
);
401 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
403 for (i
= 0; i
< n_tstamp_types
; i
++) {
404 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
405 if (tstamp_type_name
!= NULL
) {
406 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
407 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
409 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
412 pcap_free_tstamp_types(tstamp_types
);
413 exit_tcpdump(S_SUCCESS
);
418 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
422 const char *dlt_name
;
424 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
426 error("%s", pcap_geterr(pc
));
427 else if (n_dlts
== 0 || !dlts
)
428 error("No data link types.");
431 * If the interface is known to support monitor mode, indicate
432 * whether these are the data link types available when not in
433 * monitor mode, if -I wasn't specified, or when in monitor mode,
434 * when -I was specified (the link-layer types available in
435 * monitor mode might be different from the ones available when
436 * not in monitor mode).
438 if (supports_monitor_mode
)
439 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
441 Iflag
? "when in monitor mode" : "when not in monitor mode");
443 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
446 for (i
= 0; i
< n_dlts
; i
++) {
447 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
448 if (dlt_name
!= NULL
) {
449 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
450 pcap_datalink_val_to_description(dlts
[i
]));
453 * OK, does tcpdump handle that type?
455 if (!has_printer(dlts
[i
]))
456 (void) fprintf(stderr
, " (printing not supported)");
457 fprintf(stderr
, "\n");
459 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
463 #ifdef HAVE_PCAP_FREE_DATALINKS
464 pcap_free_datalinks(dlts
);
466 exit_tcpdump(S_SUCCESS
);
469 #ifdef HAVE_PCAP_FINDALLDEVS
471 show_devices_and_exit(void)
473 pcap_if_t
*dev
, *devlist
;
474 char ebuf
[PCAP_ERRBUF_SIZE
];
477 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
479 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
480 printf("%d.%s", i
+1, dev
->name
);
481 if (dev
->description
!= NULL
)
482 printf(" (%s)", dev
->description
);
483 if (dev
->flags
!= 0) {
485 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
486 #ifdef PCAP_IF_WIRELESS
487 if (dev
->flags
& PCAP_IF_WIRELESS
) {
488 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
490 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
491 printf(", Association status unknown");
494 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
495 printf(", Associated");
498 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
499 printf(", Not associated");
502 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
506 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
508 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
509 printf(", Connection status unknown");
512 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
513 printf(", Connected");
516 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
517 printf(", Disconnected");
520 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
529 pcap_freealldevs(devlist
);
530 exit_tcpdump(S_SUCCESS
);
532 #endif /* HAVE_PCAP_FINDALLDEVS */
534 #ifdef HAVE_PCAP_FINDALLDEVS_EX
536 show_remote_devices_and_exit(void)
538 pcap_if_t
*dev
, *devlist
;
539 char ebuf
[PCAP_ERRBUF_SIZE
];
542 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
545 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
546 printf("%d.%s", i
+1, dev
->name
);
547 if (dev
->description
!= NULL
)
548 printf(" (%s)", dev
->description
);
550 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
553 pcap_freealldevs(devlist
);
554 exit_tcpdump(S_SUCCESS
);
556 #endif /* HAVE_PCAP_FINDALLDEVS */
561 * Note that there we use all letters for short options except for g, k,
562 * o, and P, and those are used by other versions of tcpdump, and we should
563 * only use them for the same purposes that the other versions of tcpdump
566 * macOS tcpdump uses -g to force non--v output for IP to be on one
567 * line, making it more "g"repable;
569 * macOS tcpdump uses -k to specify that packet comments in pcapng files
572 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
573 * for hosts sending TCP SYN packets;
575 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
578 * macOS tcpdump also uses -Q to specify expressions that match packet
579 * metadata, including but not limited to the packet direction.
580 * The expression syntax is different from a simple "in|out|inout",
581 * and those expressions aren't accepted by macOS tcpdump, but the
582 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
583 * "inout" = "dir=in or dir=out", and the parser could conceivably
584 * special-case "in", "out", and "inout" as expressions for backwards
585 * compatibility, so all is not (yet) lost.
589 * Set up flags that might or might not be supported depending on the
590 * version of libpcap we're using.
592 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
594 #define B_FLAG_USAGE " [ -B size ]"
595 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
598 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
600 #ifdef HAVE_PCAP_FINDALLDEVS
606 #ifdef HAVE_PCAP_CREATE
608 #else /* HAVE_PCAP_CREATE */
610 #endif /* HAVE_PCAP_CREATE */
612 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
614 #define j_FLAG_USAGE " [ -j tstamptype ]"
616 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
620 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
622 #ifdef HAVE_PCAP_SETDIRECTION
624 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
630 #ifdef HAVE_PCAP_DUMP_FLUSH
636 #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:#"
641 * We do not currently have long options corresponding to all short
642 * options; we should probably pick appropriate option names for them.
644 * However, the short options where the number of times the option is
645 * specified matters, such as -v and -d and -t, should probably not
646 * just map to a long option, as saying
648 * tcpdump --verbose --verbose
650 * doesn't make sense; it should be --verbosity={N} or something such
653 * For long options with no corresponding short options, we define values
654 * outside the range of ASCII graphic characters, make that the last
655 * component of the entry for the long option, and have a case for that
656 * option in the switch statement.
658 #define OPTION_VERSION 128
659 #define OPTION_TSTAMP_PRECISION 129
660 #define OPTION_IMMEDIATE_MODE 130
661 #define OPTION_PRINT 131
662 #define OPTION_LIST_REMOTE_INTERFACES 132
664 static const struct option longopts
[] = {
665 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
666 { "buffer-size", required_argument
, NULL
, 'B' },
668 { "list-interfaces", no_argument
, NULL
, 'D' },
669 #ifdef HAVE_PCAP_FINDALLDEVS_EX
670 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
672 { "help", no_argument
, NULL
, 'h' },
673 { "interface", required_argument
, NULL
, 'i' },
674 #ifdef HAVE_PCAP_CREATE
675 { "monitor-mode", no_argument
, NULL
, 'I' },
677 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
678 { "time-stamp-type", required_argument
, NULL
, 'j' },
679 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
681 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
682 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
684 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
685 { "list-data-link-types", no_argument
, NULL
, 'L' },
686 { "no-optimize", no_argument
, NULL
, 'O' },
687 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
688 #ifdef HAVE_PCAP_SETDIRECTION
689 { "direction", required_argument
, NULL
, 'Q' },
691 { "snapshot-length", required_argument
, NULL
, 's' },
692 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
693 #ifdef HAVE_PCAP_DUMP_FLUSH
694 { "packet-buffered", no_argument
, NULL
, 'U' },
696 { "linktype", required_argument
, NULL
, 'y' },
697 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
698 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
700 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
701 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
703 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
704 { "number", no_argument
, NULL
, '#' },
705 { "print", no_argument
, NULL
, OPTION_PRINT
},
706 { "version", no_argument
, NULL
, OPTION_VERSION
},
710 #ifdef HAVE_PCAP_FINDALLDEVS_EX
711 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
713 #define LIST_REMOTE_INTERFACES_USAGE
716 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
717 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
719 #define IMMEDIATE_MODE_USAGE ""
722 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
723 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
725 #define TIME_STAMP_PRECISION_USAGE
729 /* Drop root privileges and chroot if necessary */
731 droproot(const char *username
, const char *chroot_dir
)
733 struct passwd
*pw
= NULL
;
735 if (chroot_dir
&& !username
) {
736 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
738 exit_tcpdump(S_ERR_HOST_PROGRAM
);
741 pw
= getpwnam(username
);
744 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
745 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
746 program_name
, chroot_dir
, pcap_strerror(errno
));
747 exit_tcpdump(S_ERR_HOST_PROGRAM
);
750 #ifdef HAVE_LIBCAP_NG
752 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
754 fprintf(stderr
, "error : ret %d\n", ret
);
756 fprintf(stderr
, "dropped privs to %s\n", username
);
760 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
761 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
762 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
763 program_name
, username
,
764 (unsigned long)pw
->pw_uid
,
765 (unsigned long)pw
->pw_gid
,
766 pcap_strerror(errno
));
767 exit_tcpdump(S_ERR_HOST_PROGRAM
);
770 fprintf(stderr
, "dropped privs to %s\n", username
);
772 #endif /* HAVE_LIBCAP_NG */
775 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
776 program_name
, username
);
777 exit_tcpdump(S_ERR_HOST_PROGRAM
);
779 #ifdef HAVE_LIBCAP_NG
780 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
781 DIAG_OFF_CLANG(assign
-enum)
784 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
789 DIAG_ON_CLANG(assign
-enum)
790 capng_apply(CAPNG_SELECT_BOTH
);
791 #endif /* HAVE_LIBCAP_NG */
812 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
814 char *filename
= malloc(PATH_MAX
+ 1);
815 if (filename
== NULL
)
816 error("Makefilename: malloc");
818 /* Process with strftime if Gflag is set. */
822 /* Convert Gflag_time to a usable format */
823 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
824 error("MakeTimedFilename: localtime");
827 /* There's no good way to detect an error in strftime since a return
828 * value of 0 isn't necessarily failure.
830 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
832 strncpy(filename
, orig_name
, PATH_MAX
);
835 if (cnt
== 0 && max_chars
== 0)
836 strncpy(buffer
, filename
, PATH_MAX
+ 1);
838 if (nd_snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
839 /* Report an error if the filename is too large */
840 error("too many output files or filename is too long (> %d)", PATH_MAX
);
845 get_next_file(FILE *VFile
, char *ptr
)
849 ret
= fgets(ptr
, PATH_MAX
, VFile
);
853 if (ptr
[strlen(ptr
) - 1] == '\n')
854 ptr
[strlen(ptr
) - 1] = '\0';
860 static cap_channel_t
*
863 cap_channel_t
*capcas
, *capdnsloc
;
864 const char *types
[1];
869 error("unable to create casper process");
870 capdnsloc
= cap_service_open(capcas
, "system.dns");
871 /* Casper capability no longer needed. */
873 if (capdnsloc
== NULL
)
874 error("unable to open system.dns service");
875 /* Limit system.dns to reverse DNS lookups. */
877 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
878 error("unable to limit access to system.dns service");
879 families
[0] = AF_INET
;
880 families
[1] = AF_INET6
;
881 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
882 error("unable to limit access to system.dns service");
886 #endif /* HAVE_CASPER */
888 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
890 tstamp_precision_from_string(const char *precision
)
892 if (strncmp(precision
, "nano", strlen("nano")) == 0)
893 return PCAP_TSTAMP_PRECISION_NANO
;
895 if (strncmp(precision
, "micro", strlen("micro")) == 0)
896 return PCAP_TSTAMP_PRECISION_MICRO
;
902 tstamp_precision_to_string(int precision
)
906 case PCAP_TSTAMP_PRECISION_MICRO
:
909 case PCAP_TSTAMP_PRECISION_NANO
:
920 * Ensure that, on a dump file's descriptor, we have all the rights
921 * necessary to make the standard I/O library work with an fdopen()ed
922 * FILE * from that descriptor.
924 * A long time ago, in a galaxy far far away, AT&T decided that, instead
925 * of providing separate APIs for getting and setting the FD_ flags on a
926 * descriptor, getting and setting the O_ flags on a descriptor, and
927 * locking files, they'd throw them all into a kitchen-sink fcntl() call
928 * along the lines of ioctl(), the fact that ioctl() operations are
929 * largely specific to particular character devices but fcntl() operations
930 * are either generic to all descriptors or generic to all descriptors for
931 * regular files nonwithstanding.
933 * The Capsicum people decided that fine-grained control of descriptor
934 * operations was required, so that you need to grant permission for
935 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
936 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
937 * collection of things, so there are *individual* fcntls for which
938 * permission needs to be granted.
940 * The FreeBSD standard I/O people implemented some optimizations that
941 * requires that the standard I/O routines be able to determine whether
942 * the descriptor for the FILE * is open append-only or not; as that
943 * descriptor could have come from an open() rather than an fopen(),
944 * that requires that it be able to do an F_GETFL fcntl() to read
947 * Tcpdump uses ftell() to determine how much data has been written
948 * to a file in order to, when used with -C, determine when it's time
949 * to rotate capture files. ftell() therefore needs to do an lseek()
950 * to find out the file offset and must, thanks to the aforementioned
951 * optimization, also know whether the descriptor is open append-only
954 * The net result of all the above is that we need to grant CAP_SEEK,
955 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
957 * Perhaps this is the universe's way of saying that either
959 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
960 * using it, so that Capsicum-capable tcpdump wouldn't need to do
965 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
966 * I/O library that knows what rights are needed by the standard
967 * I/O library, based on the open mode, and assigns them, perhaps
968 * with an additional argument indicating, for example, whether
969 * seeking should be allowed, so that tcpdump doesn't need to know
970 * what the standard I/O library happens to require this week.
973 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
975 int fd
= fileno(pcap_dump_file(p
));
978 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
979 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
980 error("unable to limit dump descriptor");
982 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
983 error("unable to limit dump descriptor fcntls");
989 * Copy arg vector into a new buffer, concatenating arguments with spaces.
992 copy_argv(char **argv
)
1004 len
+= strlen(*p
++) + 1;
1006 buf
= (char *)malloc(len
);
1008 error("copy_argv: malloc");
1012 while ((src
= *p
++) != NULL
) {
1013 while ((*dst
++ = *src
++) != '\0')
1023 * On Windows, we need to open the file in binary mode, so that
1024 * we get all the bytes specified by the size we get from "fstat()".
1025 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1026 * we define it as 0 if it's not defined, so it does nothing.
1033 read_infile(char *fname
)
1039 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1041 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1043 if (fstat(fd
, &buf
) < 0)
1044 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1046 cp
= malloc((u_int
)buf
.st_size
+ 1);
1048 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1049 fname
, pcap_strerror(errno
));
1050 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1052 error("read %s: %s", fname
, pcap_strerror(errno
));
1053 if (cc
!= buf
.st_size
)
1054 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
1057 /* replace "# comment" with spaces */
1058 for (i
= 0; i
< cc
; i
++) {
1060 while (i
< cc
&& cp
[i
] != '\n')
1067 #ifdef HAVE_PCAP_FINDALLDEVS
1069 parse_interface_number(const char *device
)
1076 * Search for a colon, terminating any scheme at the beginning
1079 p
= strchr(device
, ':');
1082 * We found it. Is it followed by "//"?
1084 p
++; /* skip the : */
1085 if (strncmp(p
, "//", 2) == 0) {
1087 * Yes. Search for the next /, at the end of the
1088 * authority part of the URL.
1090 p
+= 2; /* skip the // */
1094 * OK, past the / is the path.
1100 devnum
= strtol(device
, &end
, 10);
1101 if (device
!= end
&& *end
== '\0') {
1103 * It's all-numeric, but is it a valid number?
1107 * No, it's not an ordinal.
1109 error("Invalid adapter index");
1114 * It's not all-numeric; return -1, so our caller
1122 find_interface_by_number(const char *url
, long devnum
)
1124 pcap_if_t
*dev
, *devlist
;
1126 char ebuf
[PCAP_ERRBUF_SIZE
];
1128 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1134 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1136 * Search for a colon, terminating any scheme at the beginning
1139 endp
= strchr(url
, ':');
1142 * We found it. Is it followed by "//"?
1144 endp
++; /* skip the : */
1145 if (strncmp(endp
, "//", 2) == 0) {
1147 * Yes. Search for the next /, at the end of the
1148 * authority part of the URL.
1150 endp
+= 2; /* skip the // */
1151 endp
= strchr(endp
, '/');
1157 * OK, everything from device to endp is a URL to hand
1158 * to pcap_findalldevs_ex().
1160 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1161 host_url
= malloc(endp
- url
+ 1);
1162 memcpy(host_url
, url
, endp
- url
);
1163 host_url
[endp
- url
] = '\0';
1164 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1168 status
= pcap_findalldevs(&devlist
, ebuf
);
1172 * Look for the devnum-th entry in the list of devices (1-based).
1174 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1175 i
++, dev
= dev
->next
)
1178 error("Invalid adapter index");
1179 device
= strdup(dev
->name
);
1180 pcap_freealldevs(devlist
);
1185 #ifdef HAVE_PCAP_OPEN
1187 * Prefix for rpcap URLs.
1189 static char rpcap_prefix
[] = "rpcap://";
1193 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1196 #ifdef HAVE_PCAP_CREATE
1201 #ifdef HAVE_PCAP_OPEN
1203 * Is this an rpcap URL?
1205 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1207 * Yes. Open it with pcap_open().
1210 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1211 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1215 * If this failed with "No such device" or "The system
1216 * cannot find the device specified", that means
1217 * the interface doesn't exist; return NULL, so that
1218 * the caller can see whether the device name is
1219 * actually an interface index.
1221 if (strstr(ebuf
, "No such device") != NULL
||
1222 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1227 warning("%s", ebuf
);
1230 #endif /* HAVE_PCAP_OPEN */
1232 #ifdef HAVE_PCAP_CREATE
1233 pc
= pcap_create(device
, ebuf
);
1236 * If this failed with "No such device", that means
1237 * the interface doesn't exist; return NULL, so that
1238 * the caller can see whether the device name is
1239 * actually an interface index.
1241 if (strstr(ebuf
, "No such device") != NULL
)
1245 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1247 show_tstamp_types_and_exit(pc
, device
);
1249 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1250 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1252 error("%s: Can't set %ssecond time stamp precision: %s",
1254 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1255 pcap_statustostr(status
));
1258 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1259 if (immediate_mode
) {
1260 status
= pcap_set_immediate_mode(pc
, 1);
1262 error("%s: Can't set immediate mode: %s",
1264 pcap_statustostr(status
));
1268 * Is this an interface that supports monitor mode?
1270 if (pcap_can_set_rfmon(pc
) == 1)
1271 supports_monitor_mode
= 1;
1273 supports_monitor_mode
= 0;
1274 if (ndo
->ndo_snaplen
!= 0) {
1276 * A snapshot length was explicitly specified;
1279 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1281 error("%s: Can't set snapshot length: %s",
1282 device
, pcap_statustostr(status
));
1284 status
= pcap_set_promisc(pc
, !pflag
);
1286 error("%s: Can't set promiscuous mode: %s",
1287 device
, pcap_statustostr(status
));
1289 status
= pcap_set_rfmon(pc
, 1);
1291 error("%s: Can't set monitor mode: %s",
1292 device
, pcap_statustostr(status
));
1294 status
= pcap_set_timeout(pc
, 1000);
1296 error("%s: pcap_set_timeout failed: %s",
1297 device
, pcap_statustostr(status
));
1299 status
= pcap_set_buffer_size(pc
, Bflag
);
1301 error("%s: Can't set buffer size: %s",
1302 device
, pcap_statustostr(status
));
1304 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1306 status
= pcap_set_tstamp_type(pc
, jflag
);
1308 error("%s: Can't set time stamp type: %s",
1309 device
, pcap_statustostr(status
));
1312 status
= pcap_activate(pc
);
1315 * pcap_activate() failed.
1317 cp
= pcap_geterr(pc
);
1318 if (status
== PCAP_ERROR
)
1320 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1322 * Return an error for our caller to handle.
1324 nd_snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1325 device
, pcap_statustostr(status
), cp
);
1328 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1329 error("%s: %s\n(%s)", device
,
1330 pcap_statustostr(status
), cp
);
1332 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1333 strncmp(device
, "wlan", 4) == 0) {
1334 char parent
[8], newdev
[8];
1336 size_t s
= sizeof(parent
);
1338 nd_snprintf(sysctl
, sizeof(sysctl
),
1339 "net.wlan.%d.%%parent", atoi(device
+ 4));
1340 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1341 strlcpy(newdev
, device
, sizeof(newdev
));
1342 /* Suggest a new wlan device. */
1343 /* FIXME: incrementing the index this way is not going to work well
1344 * when the index is 9 or greater but the only consequence in this
1345 * specific case would be an error message that looks a bit odd.
1347 newdev
[strlen(newdev
)-1]++;
1348 error("%s is not a monitor mode VAP\n"
1349 "To create a new monitor mode VAP use:\n"
1350 " ifconfig %s create wlandev %s wlanmode monitor\n"
1351 "and use %s as the tcpdump interface",
1352 device
, newdev
, parent
, newdev
);
1356 error("%s: %s", device
,
1357 pcap_statustostr(status
));
1358 } else if (status
> 0) {
1360 * pcap_activate() succeeded, but it's warning us
1361 * of a problem it had.
1363 cp
= pcap_geterr(pc
);
1364 if (status
== PCAP_WARNING
)
1366 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1368 warning("%s: %s\n(%s)", device
,
1369 pcap_statustostr(status
), cp
);
1371 warning("%s: %s", device
,
1372 pcap_statustostr(status
));
1374 #ifdef HAVE_PCAP_SETDIRECTION
1376 status
= pcap_setdirection(pc
, Qflag
);
1378 error("%s: pcap_setdirection() failed: %s",
1379 device
, pcap_geterr(pc
));
1381 #endif /* HAVE_PCAP_SETDIRECTION */
1382 #else /* HAVE_PCAP_CREATE */
1385 * If no snapshot length was specified, or a length of 0 was
1386 * specified, default to 256KB.
1388 if (ndo
->ndo_snaplen
== 0)
1389 ndo
->ndo_snaplen
= 262144;
1390 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1393 * If this failed with "No such device", that means
1394 * the interface doesn't exist; return NULL, so that
1395 * the caller can see whether the device name is
1396 * actually an interface index.
1398 if (strstr(ebuf
, "No such device") != NULL
)
1403 warning("%s", ebuf
);
1404 #endif /* HAVE_PCAP_CREATE */
1410 main(int argc
, char **argv
)
1413 bpf_u_int32 localnet
= 0, netmask
= 0;
1414 int timezone_offset
= 0;
1415 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1417 pcap_handler callback
;
1419 const char *dlt_name
;
1420 struct bpf_program fcode
;
1422 void (*oldhandler
)(int);
1424 struct dump_info dumpinfo
;
1425 u_char
*pcap_userdata
;
1426 char ebuf
[PCAP_ERRBUF_SIZE
];
1427 char VFileLine
[PATH_MAX
+ 1];
1428 char *username
= NULL
;
1429 char *chroot_dir
= NULL
;
1432 #ifdef HAVE_PCAP_FINDALLDEVS
1438 #ifdef HAVE_CAPSICUM
1439 cap_rights_t rights
;
1441 #endif /* HAVE_CAPSICUM */
1442 int Oflag
= 1; /* run filter code optimizer */
1444 const char *yflag_dlt_name
= NULL
;
1447 netdissect_options Ndo
;
1448 netdissect_options
*ndo
= &Ndo
;
1451 * Initialize the netdissect code.
1453 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1456 memset(ndo
, 0, sizeof(*ndo
));
1457 ndo_set_function_pointers(ndo
);
1467 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1468 ndo
->program_name
= program_name
= cp
+ 1;
1470 ndo
->program_name
= program_name
= argv
[0];
1472 #if defined(HAVE_PCAP_WSOCKINIT)
1473 if (pcap_wsockinit() != 0)
1474 error("Attempting to initialize Winsock failed");
1475 #elif defined(HAVE_WSOCKINIT)
1476 if (wsockinit() != 0)
1477 error("Attempting to initialize Winsock failed");
1481 * On platforms where the CPU doesn't support unaligned loads,
1482 * force unaligned accesses to abort with SIGBUS, rather than
1483 * being fixed up (slowly) by the OS kernel; on those platforms,
1484 * misaligned accesses are bugs, and we want tcpdump to crash so
1485 * that the bugs are reported.
1487 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1491 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1495 /* compatibility for old -a */
1506 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1508 Bflag
= atoi(optarg
)*1024;
1510 error("invalid packet buffer size %s", optarg
);
1512 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1517 error("invalid packet count %s", optarg
);
1522 #ifdef HAVE_PCAP_DUMP_FTELL64
1523 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1525 Cflag
= strtol(optarg
, &endp
, 10);
1527 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1529 error("invalid file size %s", optarg
);
1531 * Will multiplying it by 1000000 overflow?
1533 #ifdef HAVE_PCAP_DUMP_FTELL64
1534 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1536 if (Cflag
> LONG_MAX
/ 1000000)
1538 error("file size %s is too large", optarg
);
1546 #ifdef HAVE_PCAP_FINDALLDEVS
1552 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1553 case OPTION_LIST_REMOTE_INTERFACES
:
1554 remote_interfaces_source
= optarg
;
1567 #ifndef HAVE_LIBCRYPTO
1568 warning("crypto code not compiled in");
1570 ndo
->ndo_espsecret
= optarg
;
1582 Gflag
= atoi(optarg
);
1584 error("invalid number of seconds %s", optarg
);
1586 /* We will create one file initially. */
1589 /* Grab the current time for rotation use. */
1590 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1591 error("main: can't get current time: %s",
1592 pcap_strerror(errno
));
1598 exit_tcpdump(S_SUCCESS
);
1609 #ifdef HAVE_PCAP_CREATE
1613 #endif /* HAVE_PCAP_CREATE */
1615 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1617 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1619 error("invalid time stamp type %s", optarg
);
1630 * _IOLBF is the same as _IOFBF in Microsoft's C
1631 * libraries; the only alternative they offer
1634 * XXX - this should really be checking for MSVC++,
1635 * not _WIN32, if, for example, MinGW has its own
1636 * C library that is more UNIX-compatible.
1638 setvbuf(stdout
, NULL
, _IONBF
, 0);
1640 #ifdef HAVE_SETLINEBUF
1643 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1653 if (nd_have_smi_support()) {
1654 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1657 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1658 program_name
, optarg
);
1659 (void)fprintf(stderr
, "(no libsmi support)\n");
1664 /* TCP-MD5 shared secret */
1665 #ifndef HAVE_LIBCRYPTO
1666 warning("crypto code not compiled in");
1668 ndo
->ndo_sigsecret
= optarg
;
1689 ++ndo
->ndo_suppress_default_print
;
1692 #ifdef HAVE_PCAP_SETDIRECTION
1694 if (ascii_strcasecmp(optarg
, "in") == 0)
1696 else if (ascii_strcasecmp(optarg
, "out") == 0)
1698 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1699 Qflag
= PCAP_D_INOUT
;
1701 error("unknown capture direction `%s'", optarg
);
1703 #endif /* HAVE_PCAP_SETDIRECTION */
1710 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1711 if (optarg
== end
|| *end
!= '\0'
1712 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1713 error("invalid snaplen %s", optarg
);
1725 if (ascii_strcasecmp(optarg
, "vat") == 0)
1726 ndo
->ndo_packettype
= PT_VAT
;
1727 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1728 ndo
->ndo_packettype
= PT_WB
;
1729 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1730 ndo
->ndo_packettype
= PT_RPC
;
1731 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1732 ndo
->ndo_packettype
= PT_RTP
;
1733 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1734 ndo
->ndo_packettype
= PT_RTCP
;
1735 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1736 ndo
->ndo_packettype
= PT_SNMP
;
1737 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1738 ndo
->ndo_packettype
= PT_CNFP
;
1739 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1740 ndo
->ndo_packettype
= PT_TFTP
;
1741 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1742 ndo
->ndo_packettype
= PT_AODV
;
1743 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1744 ndo
->ndo_packettype
= PT_CARP
;
1745 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1746 ndo
->ndo_packettype
= PT_RADIUS
;
1747 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1748 ndo
->ndo_packettype
= PT_ZMTP1
;
1749 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1750 ndo
->ndo_packettype
= PT_VXLAN
;
1751 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1752 ndo
->ndo_packettype
= PT_PGM
;
1753 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1754 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1755 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1756 ndo
->ndo_packettype
= PT_LMP
;
1757 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1758 ndo
->ndo_packettype
= PT_RESP
;
1760 error("unknown packet type `%s'", optarg
);
1767 #ifdef HAVE_PCAP_DUMP_FLUSH
1786 Wflag
= atoi(optarg
);
1788 error("invalid number of output files %s", optarg
);
1789 WflagChars
= getWflagChars(Wflag
);
1794 ++ndo
->ndo_suppress_default_print
;
1799 ++ndo
->ndo_suppress_default_print
;
1803 yflag_dlt_name
= optarg
;
1805 pcap_datalink_name_to_val(yflag_dlt_name
);
1807 error("invalid data link type %s", yflag_dlt_name
);
1810 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1813 /* Undocumented flag */
1814 pcap_set_parser_debug(1);
1827 ndo
->ndo_packet_number
= 1;
1830 case OPTION_VERSION
:
1832 exit_tcpdump(S_SUCCESS
);
1835 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1836 case OPTION_TSTAMP_PRECISION
:
1837 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1838 if (ndo
->ndo_tstamp_precision
< 0)
1839 error("unsupported time stamp precision");
1843 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1844 case OPTION_IMMEDIATE_MODE
:
1855 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1859 #ifdef HAVE_PCAP_FINDALLDEVS
1861 show_devices_and_exit();
1863 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1864 if (remote_interfaces_source
!= NULL
)
1865 show_remote_devices_and_exit();
1868 switch (ndo
->ndo_tflag
) {
1870 case 0: /* Default */
1871 case 4: /* Default + Date*/
1872 timezone_offset
= gmt2local(0);
1875 case 1: /* No time stamp */
1876 case 2: /* Unix timeval style */
1877 case 3: /* Microseconds since previous packet */
1878 case 5: /* Microseconds since first packet */
1881 default: /* Not supported */
1882 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1886 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1887 error("-f can not be used with -V or -r");
1889 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1890 error("-V and -r are mutually exclusive.");
1892 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1894 * If we're printing dissected packets to the standard output
1895 * and the standard output is a terminal, use immediate mode,
1896 * as the user's probably expecting to see packets pop up
1899 * XXX - set the timeout to a lower value, instead? If so,
1900 * what value would be appropriate?
1902 if ((WFileName
== NULL
|| print
) && isatty(1))
1907 /* if run as root, prepare for chrooting */
1908 if (getuid() == 0 || geteuid() == 0) {
1909 /* future extensibility for cmd-line arguments */
1911 chroot_dir
= WITH_CHROOT
;
1916 /* if run as root, prepare for dropping root privileges */
1917 if (getuid() == 0 || geteuid() == 0) {
1918 /* Run with '-Z root' to restore old behaviour */
1920 username
= WITH_USER
;
1924 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1926 * If RFileName is non-null, it's the pathname of a
1927 * savefile to read. If VFileName is non-null, it's
1928 * the pathname of a file containing a list of pathnames
1929 * (one per line) of savefiles to read.
1931 * In either case, we're reading a savefile, not doing
1936 * We don't need network access, so relinquish any set-UID
1937 * or set-GID privileges we have (if any).
1939 * We do *not* want set-UID privileges when opening a
1940 * trace file, as that might let the user read other
1941 * people's trace files (especially if we're set-UID
1944 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1945 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1947 if (VFileName
!= NULL
) {
1948 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1951 VFile
= fopen(VFileName
, "r");
1954 error("Unable to open file: %s\n", pcap_strerror(errno
));
1956 ret
= get_next_file(VFile
, VFileLine
);
1958 error("Nothing in %s\n", VFileName
);
1959 RFileName
= VFileLine
;
1962 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1963 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1964 ndo
->ndo_tstamp_precision
, ebuf
);
1966 pd
= pcap_open_offline(RFileName
, ebuf
);
1971 #ifdef HAVE_CAPSICUM
1972 cap_rights_init(&rights
, CAP_READ
);
1973 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1975 error("unable to limit pcap descriptor");
1978 dlt
= pcap_datalink(pd
);
1979 dlt_name
= pcap_datalink_val_to_name(dlt
);
1980 if (dlt_name
== NULL
) {
1981 fprintf(stderr
, "reading from file %s, link-type %u\n",
1985 "reading from file %s, link-type %s (%s)\n",
1986 RFileName
, dlt_name
,
1987 pcap_datalink_val_to_description(dlt
));
1991 * We're doing a live capture.
1993 if (device
== NULL
) {
1995 * No interface was specified. Pick one.
1997 #ifdef HAVE_PCAP_FINDALLDEVS
1999 * Find the list of interfaces, and pick
2000 * the first interface.
2002 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2004 if (devlist
== NULL
)
2005 error("no interfaces available for capture");
2006 device
= strdup(devlist
->name
);
2007 pcap_freealldevs(devlist
);
2008 #else /* HAVE_PCAP_FINDALLDEVS */
2010 * Use whatever interface pcap_lookupdev()
2013 device
= pcap_lookupdev(ebuf
);
2020 * Try to open the interface with the specified name.
2022 pd
= open_interface(device
, ndo
, ebuf
);
2025 * That failed. If we can get a list of
2026 * interfaces, and the interface name
2027 * is purely numeric, try to use it as
2028 * a 1-based index in the list of
2031 #ifdef HAVE_PCAP_FINDALLDEVS
2032 devnum
= parse_interface_number(device
);
2035 * It's not a number; just report
2036 * the open error and fail.
2042 * OK, it's a number; try to find the
2043 * interface with that index, and try
2046 * find_interface_by_number() exits if it
2047 * couldn't be found.
2049 device
= find_interface_by_number(device
, devnum
);
2050 pd
= open_interface(device
, ndo
, ebuf
);
2053 #else /* HAVE_PCAP_FINDALLDEVS */
2055 * We can't get a list of interfaces; just
2059 #endif /* HAVE_PCAP_FINDALLDEVS */
2063 * Let user own process after capture device has
2067 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2068 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2070 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2072 if(pcap_setbuff(pd
, Bflag
)==-1){
2073 error("%s", pcap_geterr(pd
));
2075 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2077 show_dlts_and_exit(pd
, device
);
2078 if (yflag_dlt
>= 0) {
2079 #ifdef HAVE_PCAP_SET_DATALINK
2080 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2081 error("%s", pcap_geterr(pd
));
2084 * We don't actually support changing the
2085 * data link type, so we only let them
2086 * set it to what it already is.
2088 if (yflag_dlt
!= pcap_datalink(pd
)) {
2089 error("%s is not one of the DLTs supported by this device\n",
2093 (void)fprintf(stderr
, "%s: data link type %s\n",
2094 program_name
, yflag_dlt_name
);
2095 (void)fflush(stderr
);
2097 i
= pcap_snapshot(pd
);
2098 if (ndo
->ndo_snaplen
< i
) {
2099 if (ndo
->ndo_snaplen
!= 0)
2100 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2101 ndo
->ndo_snaplen
= i
;
2102 } else if (ndo
->ndo_snaplen
> i
) {
2103 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2104 ndo
->ndo_snaplen
= i
;
2106 if(ndo
->ndo_fflag
!= 0) {
2107 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2108 warning("foreign (-f) flag used but: %s", ebuf
);
2114 cmdbuf
= read_infile(infile
);
2116 cmdbuf
= copy_argv(&argv
[optind
]);
2118 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2119 pcap_set_optimizer_debug(dflag
);
2121 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2122 error("%s", pcap_geterr(pd
));
2124 bpf_dump(&fcode
, dflag
);
2127 pcap_freecode(&fcode
);
2128 exit_tcpdump(S_SUCCESS
);
2132 if (!ndo
->ndo_nflag
)
2133 capdns
= capdns_setup();
2134 #endif /* HAVE_CASPER */
2136 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2139 (void)setsignal(SIGPIPE
, cleanup
);
2140 (void)setsignal(SIGTERM
, cleanup
);
2142 (void)setsignal(SIGINT
, cleanup
);
2143 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2144 (void)setsignal(SIGCHLD
, child_cleanup
);
2146 /* Cooperate with nohup(1) */
2148 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2149 (void)setsignal(SIGHUP
, oldhandler
);
2154 * If a user name was specified with "-Z", attempt to switch to
2155 * that user's UID. This would probably be used with sudo,
2156 * to allow tcpdump to be run in a special restricted
2157 * account (if you just want to allow users to open capture
2158 * devices, and can't just give users that permission,
2159 * you'd make tcpdump set-UID or set-GID).
2161 * Tcpdump doesn't necessarily write only to one savefile;
2162 * the general only way to allow a -Z instance to write to
2163 * savefiles as the user under whose UID it's run, rather
2164 * than as the user specified with -Z, would thus be to switch
2165 * to the original user ID before opening a capture file and
2166 * then switch back to the -Z user ID after opening the savefile.
2167 * Switching to the -Z user ID only after opening the first
2168 * savefile doesn't handle the general case.
2171 if (getuid() == 0 || geteuid() == 0) {
2172 #ifdef HAVE_LIBCAP_NG
2173 /* Initialize capng */
2174 capng_clear(CAPNG_SELECT_BOTH
);
2176 DIAG_OFF_CLANG(assign
-enum)
2179 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2183 DIAG_ON_CLANG(assign
-enum)
2186 DIAG_OFF_CLANG(assign
-enum)
2189 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2192 DIAG_ON_CLANG(assign
-enum)
2196 DIAG_OFF_CLANG(assign
-enum)
2199 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2202 DIAG_ON_CLANG(assign
-enum)
2204 capng_apply(CAPNG_SELECT_BOTH
);
2205 #endif /* HAVE_LIBCAP_NG */
2206 if (username
|| chroot_dir
)
2207 droproot(username
, chroot_dir
);
2212 if (pcap_setfilter(pd
, &fcode
) < 0)
2213 error("%s", pcap_geterr(pd
));
2214 #ifdef HAVE_CAPSICUM
2215 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2216 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2219 * The various libpcap devices use a combination of
2220 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2221 * so we add the relevant access rights.
2223 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2224 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2226 error("unable to limit pcap descriptor");
2228 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2229 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2230 error("unable to limit ioctls on pcap descriptor");
2235 /* Do not exceed the default PATH_MAX for files. */
2236 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2238 if (dumpinfo
.CurrentFileName
== NULL
)
2239 error("malloc of dumpinfo.CurrentFileName");
2241 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2243 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2245 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2247 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2248 #ifdef HAVE_LIBCAP_NG
2249 /* Give up CAP_DAC_OVERRIDE capability.
2250 * Only allow it to be restored if the -C or -G flag have been
2251 * set since we may need to create more files later on.
2255 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2259 capng_apply(CAPNG_SELECT_BOTH
);
2260 #endif /* HAVE_LIBCAP_NG */
2262 error("%s", pcap_geterr(pd
));
2263 #ifdef HAVE_CAPSICUM
2264 set_dumper_capsicum_rights(p
);
2266 if (Cflag
!= 0 || Gflag
!= 0) {
2267 #ifdef HAVE_CAPSICUM
2268 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2269 if (dumpinfo
.WFileName
== NULL
) {
2270 error("Unable to allocate memory for file %s",
2273 dumpinfo
.dirfd
= open(dirname(WFileName
),
2274 O_DIRECTORY
| O_RDONLY
);
2275 if (dumpinfo
.dirfd
< 0) {
2276 error("unable to open directory %s",
2277 dirname(WFileName
));
2279 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2280 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2281 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2283 error("unable to limit directory rights");
2285 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2287 error("unable to limit dump descriptor fcntls");
2289 #else /* !HAVE_CAPSICUM */
2290 dumpinfo
.WFileName
= WFileName
;
2292 callback
= dump_packet_and_trunc
;
2295 pcap_userdata
= (u_char
*)&dumpinfo
;
2297 callback
= dump_packet
;
2298 dumpinfo
.WFileName
= WFileName
;
2301 pcap_userdata
= (u_char
*)&dumpinfo
;
2304 dlt
= pcap_datalink(pd
);
2305 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2308 dumpinfo
.ndo
= NULL
;
2310 #ifdef HAVE_PCAP_DUMP_FLUSH
2312 pcap_dump_flush(pdd
);
2315 dlt
= pcap_datalink(pd
);
2316 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2317 callback
= print_packet
;
2318 pcap_userdata
= (u_char
*)ndo
;
2321 #ifdef SIGNAL_REQ_INFO
2323 * We can't get statistics when reading from a file rather
2324 * than capturing from a device.
2326 if (RFileName
== NULL
)
2327 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2329 #ifdef SIGNAL_FLUSH_PCAP
2330 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2333 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2335 * When capturing to a file, if "--print" wasn't specified,
2336 *"-v" means tcpdump should, once per second,
2337 * "v"erbosely report the number of packets captured.
2341 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2343 * suggests that this dates back to W2K.
2345 * I don't know what a "long wait" is, but we'll assume
2346 * that printing the stats could be a "long wait".
2348 CreateTimerQueueTimer(&timer_handle
, NULL
,
2349 verbose_stats_dump
, NULL
, 1000, 1000,
2350 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2351 setvbuf(stderr
, NULL
, _IONBF
, 0);
2354 * Assume this is UN*X, and that it has setitimer(); that
2355 * dates back to UNIX 95.
2357 struct itimerval timer
;
2358 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2359 timer
.it_interval
.tv_sec
= 1;
2360 timer
.it_interval
.tv_usec
= 0;
2361 timer
.it_value
.tv_sec
= 1;
2362 timer
.it_value
.tv_usec
= 1;
2363 setitimer(ITIMER_REAL
, &timer
, NULL
);
2367 if (RFileName
== NULL
) {
2369 * Live capture (if -V was specified, we set RFileName
2370 * to a file from the -V file). Print a message to
2371 * the standard error on UN*X.
2373 if (!ndo
->ndo_vflag
&& !WFileName
) {
2374 (void)fprintf(stderr
,
2375 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2378 (void)fprintf(stderr
, "%s: ", program_name
);
2379 dlt
= pcap_datalink(pd
);
2380 dlt_name
= pcap_datalink_val_to_name(dlt
);
2381 if (dlt_name
== NULL
) {
2382 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2383 device
, dlt
, ndo
->ndo_snaplen
);
2385 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2387 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2389 (void)fflush(stderr
);
2392 #ifdef HAVE_CAPSICUM
2393 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2395 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2397 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2398 #endif /* HAVE_CASPER */
2399 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2400 error("unable to enter the capability mode");
2401 #endif /* HAVE_CAPSICUM */
2404 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2405 if (WFileName
== NULL
) {
2407 * We're printing packets. Flush the printed output,
2408 * so it doesn't get intermingled with error output.
2412 * We got interrupted, so perhaps we didn't
2413 * manage to finish a line we were printing.
2414 * Print an extra newline, just in case.
2418 (void)fflush(stdout
);
2422 * We got interrupted. If we are reading multiple
2423 * files (via -V) set these so that we stop.
2432 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2433 program_name
, pcap_geterr(pd
));
2435 if (RFileName
== NULL
) {
2437 * We're doing a live capture. Report the capture
2443 if (VFileName
!= NULL
) {
2444 ret
= get_next_file(VFile
, VFileLine
);
2448 RFileName
= VFileLine
;
2449 pd
= pcap_open_offline(RFileName
, ebuf
);
2452 #ifdef HAVE_CAPSICUM
2453 cap_rights_init(&rights
, CAP_READ
);
2454 if (cap_rights_limit(fileno(pcap_file(pd
)),
2455 &rights
) < 0 && errno
!= ENOSYS
) {
2456 error("unable to limit pcap descriptor");
2459 new_dlt
= pcap_datalink(pd
);
2460 if (new_dlt
!= dlt
) {
2462 * The new file has a different
2463 * link-layer header type from the
2466 if (WFileName
!= NULL
) {
2468 * We're writing raw packets
2469 * that match the filter to
2470 * a pcap file. pcap files
2471 * don't support multiple
2472 * different link-layer
2473 * header types, so we fail
2476 error("%s: new dlt does not match original", RFileName
);
2480 * We're printing the decoded packets;
2481 * switch to the new DLT.
2483 * To do that, we need to change
2484 * the printer, change the DLT name,
2485 * and recompile the filter with
2489 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2490 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2491 error("%s", pcap_geterr(pd
));
2495 * Set the filter on the new file.
2497 if (pcap_setfilter(pd
, &fcode
) < 0)
2498 error("%s", pcap_geterr(pd
));
2501 * Report the new file.
2503 dlt_name
= pcap_datalink_val_to_name(dlt
);
2504 if (dlt_name
== NULL
) {
2505 fprintf(stderr
, "reading from file %s, link-type %u\n",
2509 "reading from file %s, link-type %s (%s)\n",
2510 RFileName
, dlt_name
,
2511 pcap_datalink_val_to_description(dlt
));
2516 while (ret
!= NULL
);
2519 pcap_freecode(&fcode
);
2520 exit_tcpdump(status
== -1 ? 1 : 0);
2527 (*setsignal (int sig
, void (*func
)(int)))(int)
2530 return (signal(sig
, func
));
2532 struct sigaction old
, new;
2534 memset(&new, 0, sizeof(new));
2535 new.sa_handler
= func
;
2537 new.sa_flags
= SA_RESTART
;
2538 if (sigaction(sig
, &new, &old
) < 0)
2540 return (old
.sa_handler
);
2544 /* make a clean exit on interrupts */
2546 cleanup(int signo _U_
)
2549 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2550 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2551 CloseHandle(timer_handle
);
2552 timer_handle
= INVALID_HANDLE_VALUE
;
2555 struct itimerval timer
;
2557 timer
.it_interval
.tv_sec
= 0;
2558 timer
.it_interval
.tv_usec
= 0;
2559 timer
.it_value
.tv_sec
= 0;
2560 timer
.it_value
.tv_usec
= 0;
2561 setitimer(ITIMER_REAL
, &timer
, NULL
);
2564 #ifdef HAVE_PCAP_BREAKLOOP
2566 * We have "pcap_breakloop()"; use it, so that we do as little
2567 * as possible in the signal handler (it's probably not safe
2568 * to do anything with standard I/O streams in a signal handler -
2569 * the ANSI C standard doesn't say it is).
2574 * We don't have "pcap_breakloop()"; this isn't safe, but
2575 * it's the best we can do. Print the summary if we're
2576 * not reading from a savefile - i.e., if we're doing a
2577 * live capture - and exit.
2579 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2581 * We got interrupted, so perhaps we didn't
2582 * manage to finish a line we were printing.
2583 * Print an extra newline, just in case.
2586 (void)fflush(stdout
);
2589 exit_tcpdump(S_SUCCESS
);
2594 On windows, we do not use a fork, so we do not care less about
2595 waiting a child processes to die
2597 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2599 child_cleanup(int signo _U_
)
2603 #endif /* HAVE_FORK && HAVE_VFORK */
2608 struct pcap_stat stats
;
2611 * Older versions of libpcap didn't set ps_ifdrop on some
2612 * platforms; initialize it to 0 to handle that.
2614 stats
.ps_ifdrop
= 0;
2615 if (pcap_stats(pd
, &stats
) < 0) {
2616 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2622 fprintf(stderr
, "%s: ", program_name
);
2624 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2625 PLURAL_SUFFIX(packets_captured
));
2627 fputs(", ", stderr
);
2630 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2631 PLURAL_SUFFIX(stats
.ps_recv
));
2633 fputs(", ", stderr
);
2636 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2637 PLURAL_SUFFIX(stats
.ps_drop
));
2638 if (stats
.ps_ifdrop
!= 0) {
2640 fputs(", ", stderr
);
2643 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2644 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2650 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2652 #define fork_subprocess() fork()
2654 #define fork_subprocess() vfork()
2657 compress_savefile(const char *filename
)
2661 child
= fork_subprocess();
2664 "compress_savefile: fork failed: %s\n",
2665 pcap_strerror(errno
));
2669 /* Parent process. */
2675 * Set to lowest priority so that this doesn't disturb the capture.
2678 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2680 setpriority(PRIO_PROCESS
, 0, 19);
2682 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2684 "compress_savefile: execlp(%s, %s) failed: %s\n",
2687 pcap_strerror(errno
));
2689 exit(S_ERR_HOST_PROGRAM
);
2691 _exit(S_ERR_HOST_PROGRAM
);
2694 #else /* HAVE_FORK && HAVE_VFORK */
2696 compress_savefile(const char *filename
)
2699 "compress_savefile failed. Functionality not implemented under your system\n");
2701 #endif /* HAVE_FORK && HAVE_VFORK */
2704 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2706 struct dump_info
*dump_info
;
2712 dump_info
= (struct dump_info
*)user
;
2715 * XXX - this won't force the file to rotate on the specified time
2716 * boundary, but it will rotate on the first packet received after the
2717 * specified Gflag number of seconds. Note: if a Gflag time boundary
2718 * and a Cflag size boundary coincide, the time rotation will occur
2719 * first thereby cancelling the Cflag boundary (since the file should
2723 /* Check if it is time to rotate */
2726 /* Get the current time */
2727 if ((t
= time(NULL
)) == (time_t)-1) {
2728 error("dump_and_trunc_packet: can't get current_time: %s",
2729 pcap_strerror(errno
));
2733 /* If the time is greater than the specified window, rotate */
2734 if (t
- Gflag_time
>= Gflag
) {
2735 #ifdef HAVE_CAPSICUM
2740 /* Update the Gflag_time */
2742 /* Update Gflag_count */
2745 * Close the current file and open a new one.
2747 pcap_dump_close(dump_info
->pdd
);
2750 * Compress the file we just closed, if the user asked for it
2753 compress_savefile(dump_info
->CurrentFileName
);
2756 * Check to see if we've exceeded the Wflag (when
2759 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2760 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2763 exit_tcpdump(S_SUCCESS
);
2766 if (dump_info
->CurrentFileName
!= NULL
)
2767 free(dump_info
->CurrentFileName
);
2768 /* Allocate space for max filename + \0. */
2769 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2770 if (dump_info
->CurrentFileName
== NULL
)
2771 error("dump_packet_and_trunc: malloc");
2773 * Gflag was set otherwise we wouldn't be here. Reset the count
2774 * so multiple files would end with 1,2,3 in the filename.
2775 * The counting is handled with the -C flow after this.
2780 * This is always the first file in the Cflag
2782 * We also don't need numbering if Cflag is not set.
2785 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2788 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2790 #ifdef HAVE_LIBCAP_NG
2791 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2792 capng_apply(CAPNG_SELECT_BOTH
);
2793 #endif /* HAVE_LIBCAP_NG */
2794 #ifdef HAVE_CAPSICUM
2795 fd
= openat(dump_info
->dirfd
,
2796 dump_info
->CurrentFileName
,
2797 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2799 error("unable to open file %s",
2800 dump_info
->CurrentFileName
);
2802 fp
= fdopen(fd
, "w");
2804 error("unable to fdopen file %s",
2805 dump_info
->CurrentFileName
);
2807 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2808 #else /* !HAVE_CAPSICUM */
2809 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2811 #ifdef HAVE_LIBCAP_NG
2812 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2813 capng_apply(CAPNG_SELECT_BOTH
);
2814 #endif /* HAVE_LIBCAP_NG */
2815 if (dump_info
->pdd
== NULL
)
2816 error("%s", pcap_geterr(pd
));
2817 #ifdef HAVE_CAPSICUM
2818 set_dumper_capsicum_rights(dump_info
->pdd
);
2824 * XXX - this won't prevent capture files from getting
2825 * larger than Cflag - the last packet written to the
2826 * file could put it over Cflag.
2829 #ifdef HAVE_PCAP_DUMP_FTELL64
2830 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
2833 * XXX - this only handles a Cflag value > 2^31-1 on
2834 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2835 * Windows) or LLP64 (64-bit Windows) would require
2836 * a version of libpcap with pcap_dump_ftell64().
2838 long size
= pcap_dump_ftell(dump_info
->pdd
);
2842 error("ftell fails on output file");
2844 #ifdef HAVE_CAPSICUM
2850 * Close the current file and open a new one.
2852 pcap_dump_close(dump_info
->pdd
);
2855 * Compress the file we just closed, if the user
2859 compress_savefile(dump_info
->CurrentFileName
);
2863 if (Cflag_count
>= Wflag
)
2866 if (dump_info
->CurrentFileName
!= NULL
)
2867 free(dump_info
->CurrentFileName
);
2868 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2869 if (dump_info
->CurrentFileName
== NULL
)
2870 error("dump_packet_and_trunc: malloc");
2871 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2872 #ifdef HAVE_LIBCAP_NG
2873 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2874 capng_apply(CAPNG_SELECT_BOTH
);
2875 #endif /* HAVE_LIBCAP_NG */
2876 #ifdef HAVE_CAPSICUM
2877 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2878 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2880 error("unable to open file %s",
2881 dump_info
->CurrentFileName
);
2883 fp
= fdopen(fd
, "w");
2885 error("unable to fdopen file %s",
2886 dump_info
->CurrentFileName
);
2888 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2889 #else /* !HAVE_CAPSICUM */
2890 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2892 #ifdef HAVE_LIBCAP_NG
2893 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2894 capng_apply(CAPNG_SELECT_BOTH
);
2895 #endif /* HAVE_LIBCAP_NG */
2896 if (dump_info
->pdd
== NULL
)
2897 error("%s", pcap_geterr(pd
));
2898 #ifdef HAVE_CAPSICUM
2899 set_dumper_capsicum_rights(dump_info
->pdd
);
2904 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2905 #ifdef HAVE_PCAP_DUMP_FLUSH
2907 pcap_dump_flush(dump_info
->pdd
);
2910 if (dump_info
->ndo
!= NULL
)
2911 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2919 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2921 struct dump_info
*dump_info
;
2927 dump_info
= (struct dump_info
*)user
;
2929 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2930 #ifdef HAVE_PCAP_DUMP_FLUSH
2932 pcap_dump_flush(dump_info
->pdd
);
2935 if (dump_info
->ndo
!= NULL
)
2936 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2944 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2950 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2957 #ifdef SIGNAL_REQ_INFO
2959 requestinfo(int signo _U_
)
2968 #ifdef SIGNAL_FLUSH_PCAP
2970 flushpcap(int signo _U_
)
2973 pcap_dump_flush(pdd
);
2978 print_packets_captured (void)
2980 static u_int prev_packets_captured
, first
= 1;
2982 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2983 fprintf(stderr
, "Got %u\r", packets_captured
);
2985 prev_packets_captured
= packets_captured
;
2990 * Called once each second in verbose mode while dumping to file
2993 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
2994 BOOLEAN timer_fired _U_
)
2996 print_packets_captured();
2999 static void verbose_stats_dump(int sig _U_
)
3001 print_packets_captured();
3005 USES_APPLE_DEPRECATED_API
3009 #ifndef HAVE_PCAP_LIB_VERSION
3010 #ifdef HAVE_PCAP_VERSION
3011 extern char pcap_version
[];
3012 #else /* HAVE_PCAP_VERSION */
3013 static char pcap_version
[] = "unknown";
3014 #endif /* HAVE_PCAP_VERSION */
3015 #endif /* HAVE_PCAP_LIB_VERSION */
3016 const char *smi_version_string
;
3018 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3019 #ifdef HAVE_PCAP_LIB_VERSION
3020 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
3021 #else /* HAVE_PCAP_LIB_VERSION */
3022 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
3023 #endif /* HAVE_PCAP_LIB_VERSION */
3025 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3026 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3029 smi_version_string
= nd_smi_version_string();
3030 if (smi_version_string
!= NULL
)
3031 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
3032 #ifdef HAVE_DNET_HTOA
3033 (void)fprintf(stderr
, "libdnet unknown version\n");
3036 #if defined(__SANITIZE_ADDRESS__)
3037 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
3038 #elif defined(__has_feature)
3039 # if __has_feature(address_sanitizer)
3040 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
3042 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3050 (void)fprintf(stderr
,
3051 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
3052 (void)fprintf(stderr
,
3053 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3054 (void)fprintf(stderr
,
3055 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3056 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3057 (void)fprintf(stderr
,
3058 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
3060 (void)fprintf(stderr
,
3061 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
3062 (void)fprintf(stderr
,
3063 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
3064 (void)fprintf(stderr
,
3065 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
3066 (void)fprintf(stderr
,
3067 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
3068 (void)fprintf(stderr
,
3069 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");