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 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
156 static int Bflag
; /* buffer size */
158 #ifdef HAVE_PCAP_DUMP_FTELL64
159 static int64_t Cflag
; /* rotate dump files after this many bytes */
161 static long Cflag
; /* rotate dump files after this many bytes */
163 static int Cflag_count
; /* Keep track of which file number we're writing */
164 #ifdef HAVE_PCAP_FINDALLDEVS
165 static int Dflag
; /* list available devices and exit */
167 #ifdef HAVE_PCAP_FINDALLDEVS_EX
168 static char *remote_interfaces_source
; /* list available devices from this source and exit */
172 * This is exported because, in some versions of libpcap, if libpcap
173 * is built with optimizer debugging code (which is *NOT* the default
174 * configuration!), the library *imports*(!) a variable named dflag,
175 * under the expectation that tcpdump is exporting it, to govern
176 * how much debugging information to print when optimizing
177 * the generated BPF code.
179 * This is a horrible hack; newer versions of libpcap don't import
180 * dflag but, instead, *if* built with optimizer debugging code,
181 * *export* a routine to set that flag.
183 int dflag
; /* print filter code */
184 static int Gflag
; /* rotate dump files after this many seconds */
185 static int Gflag_count
; /* number of files created with Gflag rotation */
186 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
187 static int Lflag
; /* list available data link types and exit */
188 static int Iflag
; /* rfmon (monitor) mode */
189 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
190 static int Jflag
; /* list available time stamp types */
191 static int jflag
= -1; /* packet time stamp source */
193 static int pflag
; /* don't go promiscuous */
194 #ifdef HAVE_PCAP_SETDIRECTION
195 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
197 #ifdef HAVE_PCAP_DUMP_FLUSH
198 static int Uflag
; /* "unbuffered" output of dump files */
200 static int Wflag
; /* recycle output files after this number of files */
201 static int WflagChars
;
202 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
203 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
204 static int immediate_mode
;
207 static int infodelay
;
208 static int infoprint
;
213 cap_channel_t
*capdns
;
217 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
218 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
219 static NORETURN
void exit_tcpdump(int);
220 static void (*setsignal (int sig
, void (*func
)(int)))(int);
221 static void cleanup(int);
222 static void child_cleanup(int);
223 static void print_version(void);
224 static void print_usage(void);
225 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
226 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
228 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
229 #ifdef HAVE_PCAP_FINDALLDEVS
230 static NORETURN
void show_devices_and_exit(void);
232 #ifdef HAVE_PCAP_FINDALLDEVS_EX
233 static NORETURN
void show_remote_devices_and_exit(void);
236 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
237 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
238 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
239 static void droproot(const char *, const char *);
241 #ifdef SIGNAL_REQ_INFO
242 static void requestinfo(int);
245 #ifdef SIGNAL_FLUSH_PCAP
246 static void flushpcap(int);
250 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
251 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
253 static void verbose_stats_dump(int sig
);
256 static void info(int);
257 static u_int packets_captured
;
259 #ifdef HAVE_PCAP_FINDALLDEVS
260 static const struct tok status_flags
[] = {
262 { PCAP_IF_UP
, "Up" },
264 #ifdef PCAP_IF_RUNNING
265 { PCAP_IF_RUNNING
, "Running" },
267 { PCAP_IF_LOOPBACK
, "Loopback" },
268 #ifdef PCAP_IF_WIRELESS
269 { PCAP_IF_WIRELESS
, "Wireless" },
276 static pcap_dumper_t
*pdd
= NULL
;
278 static int supports_monitor_mode
;
286 char *CurrentFileName
;
289 netdissect_options
*ndo
;
295 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
297 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
298 * by any libpcap header, because it's a special hack, only available if
299 * libpcap was configured to include it, and only intended for use by
300 * libpcap developers trying to debug the parser for filter expressions).
303 __declspec(dllimport
)
307 void pcap_set_parser_debug(int);
308 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
310 * We don't have pcap_set_parser_debug() in libpcap, but we do have
311 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
312 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
315 pcap_set_parser_debug(int value
)
317 #ifdef HAVE_PCAP_DEBUG
318 extern int pcap_debug
;
321 #else /* HAVE_PCAP_DEBUG */
325 #endif /* HAVE_PCAP_DEBUG */
328 #define HAVE_PCAP_SET_PARSER_DEBUG
331 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
333 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
334 * by any libpcap header, because it's a special hack, only available if
335 * libpcap was configured to include it, and only intended for use by
336 * libpcap developers trying to debug the optimizer for filter expressions).
339 __declspec(dllimport
)
343 void pcap_set_optimizer_debug(int);
348 error(const char *fmt
, ...)
352 (void)fprintf(stderr
, "%s: ", program_name
);
354 (void)vfprintf(stderr
, fmt
, ap
);
359 (void)fputc('\n', stderr
);
361 exit_tcpdump(S_ERR_HOST_PROGRAM
);
367 warning(const char *fmt
, ...)
371 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
373 (void)vfprintf(stderr
, fmt
, ap
);
378 (void)fputc('\n', stderr
);
383 exit_tcpdump(int status
)
389 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
391 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
394 int *tstamp_types
= 0;
395 const char *tstamp_type_name
;
398 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
399 if (n_tstamp_types
< 0)
400 error("%s", pcap_geterr(pc
));
402 if (n_tstamp_types
== 0) {
403 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
405 exit_tcpdump(S_SUCCESS
);
407 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
409 for (i
= 0; i
< n_tstamp_types
; i
++) {
410 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
411 if (tstamp_type_name
!= NULL
) {
412 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
413 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
415 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
418 pcap_free_tstamp_types(tstamp_types
);
419 exit_tcpdump(S_SUCCESS
);
424 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
428 const char *dlt_name
;
430 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
432 error("%s", pcap_geterr(pc
));
433 else if (n_dlts
== 0 || !dlts
)
434 error("No data link types.");
437 * If the interface is known to support monitor mode, indicate
438 * whether these are the data link types available when not in
439 * monitor mode, if -I wasn't specified, or when in monitor mode,
440 * when -I was specified (the link-layer types available in
441 * monitor mode might be different from the ones available when
442 * not in monitor mode).
444 if (supports_monitor_mode
)
445 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
447 Iflag
? "when in monitor mode" : "when not in monitor mode");
449 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
452 for (i
= 0; i
< n_dlts
; i
++) {
453 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
454 if (dlt_name
!= NULL
) {
455 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
456 pcap_datalink_val_to_description(dlts
[i
]));
459 * OK, does tcpdump handle that type?
461 if (!has_printer(dlts
[i
]))
462 (void) fprintf(stderr
, " (printing not supported)");
463 fprintf(stderr
, "\n");
465 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
469 #ifdef HAVE_PCAP_FREE_DATALINKS
470 pcap_free_datalinks(dlts
);
472 exit_tcpdump(S_SUCCESS
);
475 #ifdef HAVE_PCAP_FINDALLDEVS
477 show_devices_and_exit(void)
479 pcap_if_t
*dev
, *devlist
;
480 char ebuf
[PCAP_ERRBUF_SIZE
];
483 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
485 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
486 printf("%d.%s", i
+1, dev
->name
);
487 if (dev
->description
!= NULL
)
488 printf(" (%s)", dev
->description
);
489 if (dev
->flags
!= 0) {
491 printf("%s", bittok2str(status_flags
, "none", dev
->flags
));
492 #ifdef PCAP_IF_WIRELESS
493 if (dev
->flags
& PCAP_IF_WIRELESS
) {
494 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
496 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
497 printf(", Association status unknown");
500 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
501 printf(", Associated");
504 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
505 printf(", Not associated");
508 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
512 switch (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) {
514 case PCAP_IF_CONNECTION_STATUS_UNKNOWN
:
515 printf(", Connection status unknown");
518 case PCAP_IF_CONNECTION_STATUS_CONNECTED
:
519 printf(", Connected");
522 case PCAP_IF_CONNECTION_STATUS_DISCONNECTED
:
523 printf(", Disconnected");
526 case PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
:
535 pcap_freealldevs(devlist
);
536 exit_tcpdump(S_SUCCESS
);
538 #endif /* HAVE_PCAP_FINDALLDEVS */
540 #ifdef HAVE_PCAP_FINDALLDEVS_EX
542 show_remote_devices_and_exit(void)
544 pcap_if_t
*dev
, *devlist
;
545 char ebuf
[PCAP_ERRBUF_SIZE
];
548 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
551 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
552 printf("%d.%s", i
+1, dev
->name
);
553 if (dev
->description
!= NULL
)
554 printf(" (%s)", dev
->description
);
556 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
559 pcap_freealldevs(devlist
);
560 exit_tcpdump(S_SUCCESS
);
562 #endif /* HAVE_PCAP_FINDALLDEVS */
567 * Note that there we use all letters for short options except for g, k,
568 * o, and P, and those are used by other versions of tcpdump, and we should
569 * only use them for the same purposes that the other versions of tcpdump
572 * macOS tcpdump uses -g to force non--v output for IP to be on one
573 * line, making it more "g"repable;
575 * macOS tcpdump uses -k to specify that packet comments in pcapng files
578 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
579 * for hosts sending TCP SYN packets;
581 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
584 * macOS tcpdump also uses -Q to specify expressions that match packet
585 * metadata, including but not limited to the packet direction.
586 * The expression syntax is different from a simple "in|out|inout",
587 * and those expressions aren't accepted by macOS tcpdump, but the
588 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
589 * "inout" = "dir=in or dir=out", and the parser could conceivably
590 * special-case "in", "out", and "inout" as expressions for backwards
591 * compatibility, so all is not (yet) lost.
595 * Set up flags that might or might not be supported depending on the
596 * version of libpcap we're using.
598 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
600 #define B_FLAG_USAGE " [ -B size ]"
601 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
604 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
606 #ifdef HAVE_PCAP_FINDALLDEVS
612 #ifdef HAVE_PCAP_CREATE
614 #else /* HAVE_PCAP_CREATE */
616 #endif /* HAVE_PCAP_CREATE */
618 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
620 #define j_FLAG_USAGE " [ -j tstamptype ]"
622 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
626 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
628 #ifdef HAVE_PCAP_SETDIRECTION
630 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
636 #ifdef HAVE_PCAP_DUMP_FLUSH
642 #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:#"
647 * We do not currently have long options corresponding to all short
648 * options; we should probably pick appropriate option names for them.
650 * However, the short options where the number of times the option is
651 * specified matters, such as -v and -d and -t, should probably not
652 * just map to a long option, as saying
654 * tcpdump --verbose --verbose
656 * doesn't make sense; it should be --verbosity={N} or something such
659 * For long options with no corresponding short options, we define values
660 * outside the range of ASCII graphic characters, make that the last
661 * component of the entry for the long option, and have a case for that
662 * option in the switch statement.
664 #define OPTION_VERSION 128
665 #define OPTION_TSTAMP_PRECISION 129
666 #define OPTION_IMMEDIATE_MODE 130
667 #define OPTION_PRINT 131
668 #define OPTION_LIST_REMOTE_INTERFACES 132
670 static const struct option longopts
[] = {
671 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
672 { "buffer-size", required_argument
, NULL
, 'B' },
674 { "list-interfaces", no_argument
, NULL
, 'D' },
675 #ifdef HAVE_PCAP_FINDALLDEVS_EX
676 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
678 { "help", no_argument
, NULL
, 'h' },
679 { "interface", required_argument
, NULL
, 'i' },
680 #ifdef HAVE_PCAP_CREATE
681 { "monitor-mode", no_argument
, NULL
, 'I' },
683 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
684 { "time-stamp-type", required_argument
, NULL
, 'j' },
685 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
687 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
688 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
690 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
691 { "list-data-link-types", no_argument
, NULL
, 'L' },
692 { "no-optimize", no_argument
, NULL
, 'O' },
693 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
694 #ifdef HAVE_PCAP_SETDIRECTION
695 { "direction", required_argument
, NULL
, 'Q' },
697 { "snapshot-length", required_argument
, NULL
, 's' },
698 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
699 #ifdef HAVE_PCAP_DUMP_FLUSH
700 { "packet-buffered", no_argument
, NULL
, 'U' },
702 { "linktype", required_argument
, NULL
, 'y' },
703 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
704 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
706 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
707 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
709 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
710 { "number", no_argument
, NULL
, '#' },
711 { "print", no_argument
, NULL
, OPTION_PRINT
},
712 { "version", no_argument
, NULL
, OPTION_VERSION
},
716 #ifdef HAVE_PCAP_FINDALLDEVS_EX
717 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
719 #define LIST_REMOTE_INTERFACES_USAGE
722 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
723 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
725 #define IMMEDIATE_MODE_USAGE ""
728 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
729 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
731 #define TIME_STAMP_PRECISION_USAGE
735 /* Drop root privileges and chroot if necessary */
737 droproot(const char *username
, const char *chroot_dir
)
739 struct passwd
*pw
= NULL
;
741 if (chroot_dir
&& !username
)
742 error("Chroot without dropping root is insecure");
744 pw
= getpwnam(username
);
747 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
748 error("Couldn't chroot/chdir to '%.64s': %s",
749 chroot_dir
, pcap_strerror(errno
));
751 #ifdef HAVE_LIBCAP_NG
753 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
755 error("capng_change_id(): return %d\n", ret
);
757 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 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
764 (unsigned long)pw
->pw_uid
,
765 (unsigned long)pw
->pw_gid
,
766 pcap_strerror(errno
));
768 fprintf(stderr
, "dropped privs to %s\n", username
);
770 #endif /* HAVE_LIBCAP_NG */
772 error("Couldn't find user '%.32s'", username
);
773 #ifdef HAVE_LIBCAP_NG
774 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
775 DIAG_OFF_CLANG(assign
-enum)
778 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
783 DIAG_ON_CLANG(assign
-enum)
784 capng_apply(CAPNG_SELECT_BOTH
);
785 #endif /* HAVE_LIBCAP_NG */
806 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
808 char *filename
= malloc(PATH_MAX
+ 1);
809 if (filename
== NULL
)
810 error("Makefilename: malloc");
812 /* Process with strftime if Gflag is set. */
816 /* Convert Gflag_time to a usable format */
817 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
818 error("MakeTimedFilename: localtime");
821 /* There's no good way to detect an error in strftime since a return
822 * value of 0 isn't necessarily failure.
824 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
826 strncpy(filename
, orig_name
, PATH_MAX
);
829 if (cnt
== 0 && max_chars
== 0)
830 strncpy(buffer
, filename
, PATH_MAX
+ 1);
832 if (nd_snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
833 /* Report an error if the filename is too large */
834 error("too many output files or filename is too long (> %d)", PATH_MAX
);
839 get_next_file(FILE *VFile
, char *ptr
)
843 ret
= fgets(ptr
, PATH_MAX
, VFile
);
847 if (ptr
[strlen(ptr
) - 1] == '\n')
848 ptr
[strlen(ptr
) - 1] = '\0';
854 static cap_channel_t
*
857 cap_channel_t
*capcas
, *capdnsloc
;
858 const char *types
[1];
863 error("unable to create casper process");
864 capdnsloc
= cap_service_open(capcas
, "system.dns");
865 /* Casper capability no longer needed. */
867 if (capdnsloc
== NULL
)
868 error("unable to open system.dns service");
869 /* Limit system.dns to reverse DNS lookups. */
871 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
872 error("unable to limit access to system.dns service");
873 families
[0] = AF_INET
;
874 families
[1] = AF_INET6
;
875 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
876 error("unable to limit access to system.dns service");
880 #endif /* HAVE_CASPER */
882 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
884 tstamp_precision_from_string(const char *precision
)
886 if (strncmp(precision
, "nano", strlen("nano")) == 0)
887 return PCAP_TSTAMP_PRECISION_NANO
;
889 if (strncmp(precision
, "micro", strlen("micro")) == 0)
890 return PCAP_TSTAMP_PRECISION_MICRO
;
896 tstamp_precision_to_string(int precision
)
900 case PCAP_TSTAMP_PRECISION_MICRO
:
903 case PCAP_TSTAMP_PRECISION_NANO
:
914 * Ensure that, on a dump file's descriptor, we have all the rights
915 * necessary to make the standard I/O library work with an fdopen()ed
916 * FILE * from that descriptor.
918 * A long time ago, in a galaxy far far away, AT&T decided that, instead
919 * of providing separate APIs for getting and setting the FD_ flags on a
920 * descriptor, getting and setting the O_ flags on a descriptor, and
921 * locking files, they'd throw them all into a kitchen-sink fcntl() call
922 * along the lines of ioctl(), the fact that ioctl() operations are
923 * largely specific to particular character devices but fcntl() operations
924 * are either generic to all descriptors or generic to all descriptors for
925 * regular files nonwithstanding.
927 * The Capsicum people decided that fine-grained control of descriptor
928 * operations was required, so that you need to grant permission for
929 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
930 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
931 * collection of things, so there are *individual* fcntls for which
932 * permission needs to be granted.
934 * The FreeBSD standard I/O people implemented some optimizations that
935 * requires that the standard I/O routines be able to determine whether
936 * the descriptor for the FILE * is open append-only or not; as that
937 * descriptor could have come from an open() rather than an fopen(),
938 * that requires that it be able to do an F_GETFL fcntl() to read
941 * Tcpdump uses ftell() to determine how much data has been written
942 * to a file in order to, when used with -C, determine when it's time
943 * to rotate capture files. ftell() therefore needs to do an lseek()
944 * to find out the file offset and must, thanks to the aforementioned
945 * optimization, also know whether the descriptor is open append-only
948 * The net result of all the above is that we need to grant CAP_SEEK,
949 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
951 * Perhaps this is the universe's way of saying that either
953 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
954 * using it, so that Capsicum-capable tcpdump wouldn't need to do
959 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
960 * I/O library that knows what rights are needed by the standard
961 * I/O library, based on the open mode, and assigns them, perhaps
962 * with an additional argument indicating, for example, whether
963 * seeking should be allowed, so that tcpdump doesn't need to know
964 * what the standard I/O library happens to require this week.
967 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
969 int fd
= fileno(pcap_dump_file(p
));
972 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
973 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
974 error("unable to limit dump descriptor");
976 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
977 error("unable to limit dump descriptor fcntls");
983 * Copy arg vector into a new buffer, concatenating arguments with spaces.
986 copy_argv(char **argv
)
998 len
+= strlen(*p
++) + 1;
1000 buf
= (char *)malloc(len
);
1002 error("copy_argv: malloc");
1006 while ((src
= *p
++) != NULL
) {
1007 while ((*dst
++ = *src
++) != '\0')
1017 * On Windows, we need to open the file in binary mode, so that
1018 * we get all the bytes specified by the size we get from "fstat()".
1019 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1020 * we define it as 0 if it's not defined, so it does nothing.
1027 read_infile(char *fname
)
1033 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1035 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1037 if (fstat(fd
, &buf
) < 0)
1038 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1040 cp
= malloc((u_int
)buf
.st_size
+ 1);
1042 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1043 fname
, pcap_strerror(errno
));
1044 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1046 error("read %s: %s", fname
, pcap_strerror(errno
));
1047 if (cc
!= buf
.st_size
)
1048 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
1051 /* replace "# comment" with spaces */
1052 for (i
= 0; i
< cc
; i
++) {
1054 while (i
< cc
&& cp
[i
] != '\n')
1061 #ifdef HAVE_PCAP_FINDALLDEVS
1063 parse_interface_number(const char *device
)
1070 * Search for a colon, terminating any scheme at the beginning
1073 p
= strchr(device
, ':');
1076 * We found it. Is it followed by "//"?
1078 p
++; /* skip the : */
1079 if (strncmp(p
, "//", 2) == 0) {
1081 * Yes. Search for the next /, at the end of the
1082 * authority part of the URL.
1084 p
+= 2; /* skip the // */
1088 * OK, past the / is the path.
1094 devnum
= strtol(device
, &end
, 10);
1095 if (device
!= end
&& *end
== '\0') {
1097 * It's all-numeric, but is it a valid number?
1101 * No, it's not an ordinal.
1103 error("Invalid adapter index");
1108 * It's not all-numeric; return -1, so our caller
1116 find_interface_by_number(const char *url
1117 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1122 pcap_if_t
*dev
, *devlist
;
1124 char ebuf
[PCAP_ERRBUF_SIZE
];
1126 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1132 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1134 * Search for a colon, terminating any scheme at the beginning
1137 endp
= strchr(url
, ':');
1140 * We found it. Is it followed by "//"?
1142 endp
++; /* skip the : */
1143 if (strncmp(endp
, "//", 2) == 0) {
1145 * Yes. Search for the next /, at the end of the
1146 * authority part of the URL.
1148 endp
+= 2; /* skip the // */
1149 endp
= strchr(endp
, '/');
1155 * OK, everything from device to endp is a URL to hand
1156 * to pcap_findalldevs_ex().
1158 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1159 host_url
= malloc(endp
- url
+ 1);
1160 memcpy(host_url
, url
, endp
- url
);
1161 host_url
[endp
- url
] = '\0';
1162 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1166 status
= pcap_findalldevs(&devlist
, ebuf
);
1170 * Look for the devnum-th entry in the list of devices (1-based).
1172 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1173 i
++, dev
= dev
->next
)
1176 error("Invalid adapter index");
1177 device
= strdup(dev
->name
);
1178 pcap_freealldevs(devlist
);
1183 #ifdef HAVE_PCAP_OPEN
1185 * Prefix for rpcap URLs.
1187 static char rpcap_prefix
[] = "rpcap://";
1191 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1194 #ifdef HAVE_PCAP_CREATE
1199 #ifdef HAVE_PCAP_OPEN
1201 * Is this an rpcap URL?
1203 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1205 * Yes. Open it with pcap_open().
1208 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1209 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1213 * If this failed with "No such device" or "The system
1214 * cannot find the device specified", that means
1215 * the interface doesn't exist; return NULL, so that
1216 * the caller can see whether the device name is
1217 * actually an interface index.
1219 if (strstr(ebuf
, "No such device") != NULL
||
1220 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1225 warning("%s", ebuf
);
1228 #endif /* HAVE_PCAP_OPEN */
1230 #ifdef HAVE_PCAP_CREATE
1231 pc
= pcap_create(device
, ebuf
);
1234 * If this failed with "No such device", that means
1235 * the interface doesn't exist; return NULL, so that
1236 * the caller can see whether the device name is
1237 * actually an interface index.
1239 if (strstr(ebuf
, "No such device") != NULL
)
1243 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1245 show_tstamp_types_and_exit(pc
, device
);
1247 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1248 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1250 error("%s: Can't set %ssecond time stamp precision: %s",
1252 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1253 pcap_statustostr(status
));
1256 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1257 if (immediate_mode
) {
1258 status
= pcap_set_immediate_mode(pc
, 1);
1260 error("%s: Can't set immediate mode: %s",
1262 pcap_statustostr(status
));
1266 * Is this an interface that supports monitor mode?
1268 if (pcap_can_set_rfmon(pc
) == 1)
1269 supports_monitor_mode
= 1;
1271 supports_monitor_mode
= 0;
1272 if (ndo
->ndo_snaplen
!= 0) {
1274 * A snapshot length was explicitly specified;
1277 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1279 error("%s: Can't set snapshot length: %s",
1280 device
, pcap_statustostr(status
));
1282 status
= pcap_set_promisc(pc
, !pflag
);
1284 error("%s: Can't set promiscuous mode: %s",
1285 device
, pcap_statustostr(status
));
1287 status
= pcap_set_rfmon(pc
, 1);
1289 error("%s: Can't set monitor mode: %s",
1290 device
, pcap_statustostr(status
));
1292 status
= pcap_set_timeout(pc
, 1000);
1294 error("%s: pcap_set_timeout failed: %s",
1295 device
, pcap_statustostr(status
));
1297 status
= pcap_set_buffer_size(pc
, Bflag
);
1299 error("%s: Can't set buffer size: %s",
1300 device
, pcap_statustostr(status
));
1302 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1304 status
= pcap_set_tstamp_type(pc
, jflag
);
1306 error("%s: Can't set time stamp type: %s",
1307 device
, pcap_statustostr(status
));
1310 status
= pcap_activate(pc
);
1313 * pcap_activate() failed.
1315 cp
= pcap_geterr(pc
);
1316 if (status
== PCAP_ERROR
)
1318 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1320 * Return an error for our caller to handle.
1322 nd_snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1323 device
, pcap_statustostr(status
), cp
);
1326 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1327 error("%s: %s\n(%s)", device
,
1328 pcap_statustostr(status
), cp
);
1330 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1331 strncmp(device
, "wlan", 4) == 0) {
1332 char parent
[8], newdev
[8];
1334 size_t s
= sizeof(parent
);
1336 nd_snprintf(sysctl
, sizeof(sysctl
),
1337 "net.wlan.%d.%%parent", atoi(device
+ 4));
1338 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1339 strlcpy(newdev
, device
, sizeof(newdev
));
1340 /* Suggest a new wlan device. */
1341 /* FIXME: incrementing the index this way is not going to work well
1342 * when the index is 9 or greater but the only consequence in this
1343 * specific case would be an error message that looks a bit odd.
1345 newdev
[strlen(newdev
)-1]++;
1346 error("%s is not a monitor mode VAP\n"
1347 "To create a new monitor mode VAP use:\n"
1348 " ifconfig %s create wlandev %s wlanmode monitor\n"
1349 "and use %s as the tcpdump interface",
1350 device
, newdev
, parent
, newdev
);
1354 error("%s: %s", device
,
1355 pcap_statustostr(status
));
1356 } else if (status
> 0) {
1358 * pcap_activate() succeeded, but it's warning us
1359 * of a problem it had.
1361 cp
= pcap_geterr(pc
);
1362 if (status
== PCAP_WARNING
)
1364 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1366 warning("%s: %s\n(%s)", device
,
1367 pcap_statustostr(status
), cp
);
1369 warning("%s: %s", device
,
1370 pcap_statustostr(status
));
1372 #ifdef HAVE_PCAP_SETDIRECTION
1374 status
= pcap_setdirection(pc
, Qflag
);
1376 error("%s: pcap_setdirection() failed: %s",
1377 device
, pcap_geterr(pc
));
1379 #endif /* HAVE_PCAP_SETDIRECTION */
1380 #else /* HAVE_PCAP_CREATE */
1383 * If no snapshot length was specified, or a length of 0 was
1384 * specified, default to 256KB.
1386 if (ndo
->ndo_snaplen
== 0)
1387 ndo
->ndo_snaplen
= 262144;
1388 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1391 * If this failed with "No such device", that means
1392 * the interface doesn't exist; return NULL, so that
1393 * the caller can see whether the device name is
1394 * actually an interface index.
1396 if (strstr(ebuf
, "No such device") != NULL
)
1401 warning("%s", ebuf
);
1402 #endif /* HAVE_PCAP_CREATE */
1408 main(int argc
, char **argv
)
1411 bpf_u_int32 localnet
= 0, netmask
= 0;
1412 int timezone_offset
= 0;
1413 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1415 pcap_handler callback
;
1417 const char *dlt_name
;
1418 struct bpf_program fcode
;
1420 void (*oldhandler
)(int);
1422 struct dump_info dumpinfo
;
1423 u_char
*pcap_userdata
;
1424 char ebuf
[PCAP_ERRBUF_SIZE
];
1425 char VFileLine
[PATH_MAX
+ 1];
1426 char *username
= NULL
;
1427 char *chroot_dir
= NULL
;
1430 #ifdef HAVE_PCAP_FINDALLDEVS
1436 #ifdef HAVE_CAPSICUM
1437 cap_rights_t rights
;
1439 #endif /* HAVE_CAPSICUM */
1440 int Oflag
= 1; /* run filter code optimizer */
1442 const char *yflag_dlt_name
= NULL
;
1445 netdissect_options Ndo
;
1446 netdissect_options
*ndo
= &Ndo
;
1449 * Initialize the netdissect code.
1451 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1454 memset(ndo
, 0, sizeof(*ndo
));
1455 ndo_set_function_pointers(ndo
);
1465 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1466 ndo
->program_name
= program_name
= cp
+ 1;
1468 ndo
->program_name
= program_name
= argv
[0];
1470 #if defined(HAVE_PCAP_WSOCKINIT)
1471 if (pcap_wsockinit() != 0)
1472 error("Attempting to initialize Winsock failed");
1473 #elif defined(HAVE_WSOCKINIT)
1474 if (wsockinit() != 0)
1475 error("Attempting to initialize Winsock failed");
1479 * On platforms where the CPU doesn't support unaligned loads,
1480 * force unaligned accesses to abort with SIGBUS, rather than
1481 * being fixed up (slowly) by the OS kernel; on those platforms,
1482 * misaligned accesses are bugs, and we want tcpdump to crash so
1483 * that the bugs are reported.
1485 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1489 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1493 /* compatibility for old -a */
1504 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1506 Bflag
= atoi(optarg
)*1024;
1508 error("invalid packet buffer size %s", optarg
);
1510 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1515 error("invalid packet count %s", optarg
);
1520 #ifdef HAVE_PCAP_DUMP_FTELL64
1521 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1523 Cflag
= strtol(optarg
, &endp
, 10);
1525 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1527 error("invalid file size %s", optarg
);
1529 * Will multiplying it by 1000000 overflow?
1531 #ifdef HAVE_PCAP_DUMP_FTELL64
1532 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1534 if (Cflag
> LONG_MAX
/ 1000000)
1536 error("file size %s is too large", optarg
);
1544 #ifdef HAVE_PCAP_FINDALLDEVS
1550 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1551 case OPTION_LIST_REMOTE_INTERFACES
:
1552 remote_interfaces_source
= optarg
;
1565 #ifndef HAVE_LIBCRYPTO
1566 warning("crypto code not compiled in");
1568 ndo
->ndo_espsecret
= optarg
;
1580 Gflag
= atoi(optarg
);
1582 error("invalid number of seconds %s", optarg
);
1584 /* We will create one file initially. */
1587 /* Grab the current time for rotation use. */
1588 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1589 error("main: can't get current time: %s",
1590 pcap_strerror(errno
));
1596 exit_tcpdump(S_SUCCESS
);
1607 #ifdef HAVE_PCAP_CREATE
1611 #endif /* HAVE_PCAP_CREATE */
1613 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1615 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1617 error("invalid time stamp type %s", optarg
);
1628 * _IOLBF is the same as _IOFBF in Microsoft's C
1629 * libraries; the only alternative they offer
1632 * XXX - this should really be checking for MSVC++,
1633 * not _WIN32, if, for example, MinGW has its own
1634 * C library that is more UNIX-compatible.
1636 setvbuf(stdout
, NULL
, _IONBF
, 0);
1638 #ifdef HAVE_SETLINEBUF
1641 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1651 if (nd_have_smi_support()) {
1652 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1655 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1656 program_name
, optarg
);
1657 (void)fprintf(stderr
, "(no libsmi support)\n");
1662 /* TCP-MD5 shared secret */
1663 #ifndef HAVE_LIBCRYPTO
1664 warning("crypto code not compiled in");
1666 ndo
->ndo_sigsecret
= optarg
;
1687 ++ndo
->ndo_suppress_default_print
;
1690 #ifdef HAVE_PCAP_SETDIRECTION
1692 if (ascii_strcasecmp(optarg
, "in") == 0)
1694 else if (ascii_strcasecmp(optarg
, "out") == 0)
1696 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1697 Qflag
= PCAP_D_INOUT
;
1699 error("unknown capture direction `%s'", optarg
);
1701 #endif /* HAVE_PCAP_SETDIRECTION */
1708 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1709 if (optarg
== end
|| *end
!= '\0'
1710 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1711 error("invalid snaplen %s", optarg
);
1723 if (ascii_strcasecmp(optarg
, "vat") == 0)
1724 ndo
->ndo_packettype
= PT_VAT
;
1725 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1726 ndo
->ndo_packettype
= PT_WB
;
1727 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1728 ndo
->ndo_packettype
= PT_RPC
;
1729 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1730 ndo
->ndo_packettype
= PT_RTP
;
1731 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1732 ndo
->ndo_packettype
= PT_RTCP
;
1733 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1734 ndo
->ndo_packettype
= PT_SNMP
;
1735 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1736 ndo
->ndo_packettype
= PT_CNFP
;
1737 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1738 ndo
->ndo_packettype
= PT_TFTP
;
1739 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1740 ndo
->ndo_packettype
= PT_AODV
;
1741 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1742 ndo
->ndo_packettype
= PT_CARP
;
1743 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1744 ndo
->ndo_packettype
= PT_RADIUS
;
1745 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1746 ndo
->ndo_packettype
= PT_ZMTP1
;
1747 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1748 ndo
->ndo_packettype
= PT_VXLAN
;
1749 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1750 ndo
->ndo_packettype
= PT_PGM
;
1751 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1752 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1753 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1754 ndo
->ndo_packettype
= PT_LMP
;
1755 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1756 ndo
->ndo_packettype
= PT_RESP
;
1758 error("unknown packet type `%s'", optarg
);
1765 #ifdef HAVE_PCAP_DUMP_FLUSH
1784 Wflag
= atoi(optarg
);
1786 error("invalid number of output files %s", optarg
);
1787 WflagChars
= getWflagChars(Wflag
);
1792 ++ndo
->ndo_suppress_default_print
;
1797 ++ndo
->ndo_suppress_default_print
;
1801 yflag_dlt_name
= optarg
;
1803 pcap_datalink_name_to_val(yflag_dlt_name
);
1805 error("invalid data link type %s", yflag_dlt_name
);
1808 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1811 /* Undocumented flag */
1812 pcap_set_parser_debug(1);
1825 ndo
->ndo_packet_number
= 1;
1828 case OPTION_VERSION
:
1830 exit_tcpdump(S_SUCCESS
);
1833 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1834 case OPTION_TSTAMP_PRECISION
:
1835 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1836 if (ndo
->ndo_tstamp_precision
< 0)
1837 error("unsupported time stamp precision");
1841 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1842 case OPTION_IMMEDIATE_MODE
:
1853 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1857 #ifdef HAVE_PCAP_FINDALLDEVS
1859 show_devices_and_exit();
1861 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1862 if (remote_interfaces_source
!= NULL
)
1863 show_remote_devices_and_exit();
1866 switch (ndo
->ndo_tflag
) {
1868 case 0: /* Default */
1869 case 4: /* Default + Date*/
1870 timezone_offset
= gmt2local(0);
1873 case 1: /* No time stamp */
1874 case 2: /* Unix timeval style */
1875 case 3: /* Microseconds since previous packet */
1876 case 5: /* Microseconds since first packet */
1879 default: /* Not supported */
1880 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1884 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1885 error("-f can not be used with -V or -r");
1887 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1888 error("-V and -r are mutually exclusive.");
1890 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1892 * If we're printing dissected packets to the standard output
1893 * and the standard output is a terminal, use immediate mode,
1894 * as the user's probably expecting to see packets pop up
1897 * XXX - set the timeout to a lower value, instead? If so,
1898 * what value would be appropriate?
1900 if ((WFileName
== NULL
|| print
) && isatty(1))
1905 /* if run as root, prepare for chrooting */
1906 if (getuid() == 0 || geteuid() == 0) {
1907 /* future extensibility for cmd-line arguments */
1909 chroot_dir
= WITH_CHROOT
;
1914 /* if run as root, prepare for dropping root privileges */
1915 if (getuid() == 0 || geteuid() == 0) {
1916 /* Run with '-Z root' to restore old behaviour */
1918 username
= WITH_USER
;
1922 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1924 * If RFileName is non-null, it's the pathname of a
1925 * savefile to read. If VFileName is non-null, it's
1926 * the pathname of a file containing a list of pathnames
1927 * (one per line) of savefiles to read.
1929 * In either case, we're reading a savefile, not doing
1934 * We don't need network access, so relinquish any set-UID
1935 * or set-GID privileges we have (if any).
1937 * We do *not* want set-UID privileges when opening a
1938 * trace file, as that might let the user read other
1939 * people's trace files (especially if we're set-UID
1942 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1943 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1945 if (VFileName
!= NULL
) {
1946 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1949 VFile
= fopen(VFileName
, "r");
1952 error("Unable to open file: %s\n", pcap_strerror(errno
));
1954 ret
= get_next_file(VFile
, VFileLine
);
1956 error("Nothing in %s\n", VFileName
);
1957 RFileName
= VFileLine
;
1960 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1961 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1962 ndo
->ndo_tstamp_precision
, ebuf
);
1964 pd
= pcap_open_offline(RFileName
, ebuf
);
1969 #ifdef HAVE_CAPSICUM
1970 cap_rights_init(&rights
, CAP_READ
);
1971 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1973 error("unable to limit pcap descriptor");
1976 dlt
= pcap_datalink(pd
);
1977 dlt_name
= pcap_datalink_val_to_name(dlt
);
1978 if (dlt_name
== NULL
) {
1979 fprintf(stderr
, "reading from file %s, link-type %u\n",
1983 "reading from file %s, link-type %s (%s)\n",
1984 RFileName
, dlt_name
,
1985 pcap_datalink_val_to_description(dlt
));
1987 #ifdef DLT_LINUX_SLL2
1988 if (dlt
== DLT_LINUX_SLL2
)
1989 fprintf(stderr
, "Warning: interface names might be incorrect\n");
1993 * We're doing a live capture.
1995 if (device
== NULL
) {
1997 * No interface was specified. Pick one.
1999 #ifdef HAVE_PCAP_FINDALLDEVS
2001 * Find the list of interfaces, and pick
2002 * the first interface.
2004 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2006 if (devlist
== NULL
)
2007 error("no interfaces available for capture");
2008 device
= strdup(devlist
->name
);
2009 pcap_freealldevs(devlist
);
2010 #else /* HAVE_PCAP_FINDALLDEVS */
2012 * Use whatever interface pcap_lookupdev()
2015 device
= pcap_lookupdev(ebuf
);
2022 * Try to open the interface with the specified name.
2024 pd
= open_interface(device
, ndo
, ebuf
);
2027 * That failed. If we can get a list of
2028 * interfaces, and the interface name
2029 * is purely numeric, try to use it as
2030 * a 1-based index in the list of
2033 #ifdef HAVE_PCAP_FINDALLDEVS
2034 devnum
= parse_interface_number(device
);
2037 * It's not a number; just report
2038 * the open error and fail.
2044 * OK, it's a number; try to find the
2045 * interface with that index, and try
2048 * find_interface_by_number() exits if it
2049 * couldn't be found.
2051 device
= find_interface_by_number(device
, devnum
);
2052 pd
= open_interface(device
, ndo
, ebuf
);
2055 #else /* HAVE_PCAP_FINDALLDEVS */
2057 * We can't get a list of interfaces; just
2061 #endif /* HAVE_PCAP_FINDALLDEVS */
2065 * Let user own process after capture device has
2069 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2070 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2072 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2074 if(pcap_setbuff(pd
, Bflag
)==-1){
2075 error("%s", pcap_geterr(pd
));
2077 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2079 show_dlts_and_exit(pd
, device
);
2080 if (yflag_dlt
>= 0) {
2081 #ifdef HAVE_PCAP_SET_DATALINK
2082 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2083 error("%s", pcap_geterr(pd
));
2086 * We don't actually support changing the
2087 * data link type, so we only let them
2088 * set it to what it already is.
2090 if (yflag_dlt
!= pcap_datalink(pd
)) {
2091 error("%s is not one of the DLTs supported by this device\n",
2095 (void)fprintf(stderr
, "%s: data link type %s\n",
2096 program_name
, yflag_dlt_name
);
2097 (void)fflush(stderr
);
2099 i
= pcap_snapshot(pd
);
2100 if (ndo
->ndo_snaplen
< i
) {
2101 if (ndo
->ndo_snaplen
!= 0)
2102 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2103 ndo
->ndo_snaplen
= i
;
2104 } else if (ndo
->ndo_snaplen
> i
) {
2105 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2106 ndo
->ndo_snaplen
= i
;
2108 if(ndo
->ndo_fflag
!= 0) {
2109 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2110 warning("foreign (-f) flag used but: %s", ebuf
);
2116 cmdbuf
= read_infile(infile
);
2118 cmdbuf
= copy_argv(&argv
[optind
]);
2120 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2121 pcap_set_optimizer_debug(dflag
);
2123 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2124 error("%s", pcap_geterr(pd
));
2126 bpf_dump(&fcode
, dflag
);
2129 pcap_freecode(&fcode
);
2130 exit_tcpdump(S_SUCCESS
);
2134 if (!ndo
->ndo_nflag
)
2135 capdns
= capdns_setup();
2136 #endif /* HAVE_CASPER */
2138 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2141 (void)setsignal(SIGPIPE
, cleanup
);
2142 (void)setsignal(SIGTERM
, cleanup
);
2144 (void)setsignal(SIGINT
, cleanup
);
2145 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2146 (void)setsignal(SIGCHLD
, child_cleanup
);
2148 /* Cooperate with nohup(1) */
2150 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2151 (void)setsignal(SIGHUP
, oldhandler
);
2156 * If a user name was specified with "-Z", attempt to switch to
2157 * that user's UID. This would probably be used with sudo,
2158 * to allow tcpdump to be run in a special restricted
2159 * account (if you just want to allow users to open capture
2160 * devices, and can't just give users that permission,
2161 * you'd make tcpdump set-UID or set-GID).
2163 * Tcpdump doesn't necessarily write only to one savefile;
2164 * the general only way to allow a -Z instance to write to
2165 * savefiles as the user under whose UID it's run, rather
2166 * than as the user specified with -Z, would thus be to switch
2167 * to the original user ID before opening a capture file and
2168 * then switch back to the -Z user ID after opening the savefile.
2169 * Switching to the -Z user ID only after opening the first
2170 * savefile doesn't handle the general case.
2173 if (getuid() == 0 || geteuid() == 0) {
2174 #ifdef HAVE_LIBCAP_NG
2175 /* Initialize capng */
2176 capng_clear(CAPNG_SELECT_BOTH
);
2178 DIAG_OFF_CLANG(assign
-enum)
2181 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2185 DIAG_ON_CLANG(assign
-enum)
2188 DIAG_OFF_CLANG(assign
-enum)
2191 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2194 DIAG_ON_CLANG(assign
-enum)
2198 DIAG_OFF_CLANG(assign
-enum)
2201 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2204 DIAG_ON_CLANG(assign
-enum)
2206 capng_apply(CAPNG_SELECT_BOTH
);
2207 #endif /* HAVE_LIBCAP_NG */
2208 if (username
|| chroot_dir
)
2209 droproot(username
, chroot_dir
);
2214 if (pcap_setfilter(pd
, &fcode
) < 0)
2215 error("%s", pcap_geterr(pd
));
2216 #ifdef HAVE_CAPSICUM
2217 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2218 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2221 * The various libpcap devices use a combination of
2222 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2223 * so we add the relevant access rights.
2225 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2226 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2228 error("unable to limit pcap descriptor");
2230 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2231 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2232 error("unable to limit ioctls on pcap descriptor");
2237 /* Do not exceed the default PATH_MAX for files. */
2238 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2240 if (dumpinfo
.CurrentFileName
== NULL
)
2241 error("malloc of dumpinfo.CurrentFileName");
2243 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2245 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2247 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2249 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2250 #ifdef HAVE_LIBCAP_NG
2251 /* Give up CAP_DAC_OVERRIDE capability.
2252 * Only allow it to be restored if the -C or -G flag have been
2253 * set since we may need to create more files later on.
2257 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2261 capng_apply(CAPNG_SELECT_BOTH
);
2262 #endif /* HAVE_LIBCAP_NG */
2264 error("%s", pcap_geterr(pd
));
2265 #ifdef HAVE_CAPSICUM
2266 set_dumper_capsicum_rights(p
);
2268 if (Cflag
!= 0 || Gflag
!= 0) {
2269 #ifdef HAVE_CAPSICUM
2270 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2271 if (dumpinfo
.WFileName
== NULL
) {
2272 error("Unable to allocate memory for file %s",
2275 dumpinfo
.dirfd
= open(dirname(WFileName
),
2276 O_DIRECTORY
| O_RDONLY
);
2277 if (dumpinfo
.dirfd
< 0) {
2278 error("unable to open directory %s",
2279 dirname(WFileName
));
2281 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2282 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2283 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2285 error("unable to limit directory rights");
2287 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2289 error("unable to limit dump descriptor fcntls");
2291 #else /* !HAVE_CAPSICUM */
2292 dumpinfo
.WFileName
= WFileName
;
2294 callback
= dump_packet_and_trunc
;
2297 pcap_userdata
= (u_char
*)&dumpinfo
;
2299 callback
= dump_packet
;
2300 dumpinfo
.WFileName
= WFileName
;
2303 pcap_userdata
= (u_char
*)&dumpinfo
;
2306 dlt
= pcap_datalink(pd
);
2307 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2310 dumpinfo
.ndo
= NULL
;
2312 #ifdef HAVE_PCAP_DUMP_FLUSH
2314 pcap_dump_flush(pdd
);
2317 dlt
= pcap_datalink(pd
);
2318 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2319 callback
= print_packet
;
2320 pcap_userdata
= (u_char
*)ndo
;
2323 #ifdef SIGNAL_REQ_INFO
2325 * We can't get statistics when reading from a file rather
2326 * than capturing from a device.
2328 if (RFileName
== NULL
)
2329 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2331 #ifdef SIGNAL_FLUSH_PCAP
2332 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2335 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2337 * When capturing to a file, if "--print" wasn't specified,
2338 *"-v" means tcpdump should, once per second,
2339 * "v"erbosely report the number of packets captured.
2343 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2345 * suggests that this dates back to W2K.
2347 * I don't know what a "long wait" is, but we'll assume
2348 * that printing the stats could be a "long wait".
2350 CreateTimerQueueTimer(&timer_handle
, NULL
,
2351 verbose_stats_dump
, NULL
, 1000, 1000,
2352 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2353 setvbuf(stderr
, NULL
, _IONBF
, 0);
2356 * Assume this is UN*X, and that it has setitimer(); that
2357 * dates back to UNIX 95.
2359 struct itimerval timer
;
2360 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2361 timer
.it_interval
.tv_sec
= 1;
2362 timer
.it_interval
.tv_usec
= 0;
2363 timer
.it_value
.tv_sec
= 1;
2364 timer
.it_value
.tv_usec
= 1;
2365 setitimer(ITIMER_REAL
, &timer
, NULL
);
2369 if (RFileName
== NULL
) {
2371 * Live capture (if -V was specified, we set RFileName
2372 * to a file from the -V file). Print a message to
2373 * the standard error on UN*X.
2375 if (!ndo
->ndo_vflag
&& !WFileName
) {
2376 (void)fprintf(stderr
,
2377 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2380 (void)fprintf(stderr
, "%s: ", program_name
);
2381 dlt
= pcap_datalink(pd
);
2382 dlt_name
= pcap_datalink_val_to_name(dlt
);
2383 if (dlt_name
== NULL
) {
2384 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2385 device
, dlt
, ndo
->ndo_snaplen
);
2387 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2389 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2391 (void)fflush(stderr
);
2394 #ifdef HAVE_CAPSICUM
2395 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2397 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2399 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2400 #endif /* HAVE_CASPER */
2401 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2402 error("unable to enter the capability mode");
2403 #endif /* HAVE_CAPSICUM */
2406 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2407 if (WFileName
== NULL
) {
2409 * We're printing packets. Flush the printed output,
2410 * so it doesn't get intermingled with error output.
2414 * We got interrupted, so perhaps we didn't
2415 * manage to finish a line we were printing.
2416 * Print an extra newline, just in case.
2420 (void)fflush(stdout
);
2424 * We got interrupted. If we are reading multiple
2425 * files (via -V) set these so that we stop.
2434 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2435 program_name
, pcap_geterr(pd
));
2437 if (RFileName
== NULL
) {
2439 * We're doing a live capture. Report the capture
2445 if (VFileName
!= NULL
) {
2446 ret
= get_next_file(VFile
, VFileLine
);
2450 RFileName
= VFileLine
;
2451 pd
= pcap_open_offline(RFileName
, ebuf
);
2454 #ifdef HAVE_CAPSICUM
2455 cap_rights_init(&rights
, CAP_READ
);
2456 if (cap_rights_limit(fileno(pcap_file(pd
)),
2457 &rights
) < 0 && errno
!= ENOSYS
) {
2458 error("unable to limit pcap descriptor");
2461 new_dlt
= pcap_datalink(pd
);
2462 if (new_dlt
!= dlt
) {
2464 * The new file has a different
2465 * link-layer header type from the
2468 if (WFileName
!= NULL
) {
2470 * We're writing raw packets
2471 * that match the filter to
2472 * a pcap file. pcap files
2473 * don't support multiple
2474 * different link-layer
2475 * header types, so we fail
2478 error("%s: new dlt does not match original", RFileName
);
2482 * We're printing the decoded packets;
2483 * switch to the new DLT.
2485 * To do that, we need to change
2486 * the printer, change the DLT name,
2487 * and recompile the filter with
2491 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2492 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2493 error("%s", pcap_geterr(pd
));
2497 * Set the filter on the new file.
2499 if (pcap_setfilter(pd
, &fcode
) < 0)
2500 error("%s", pcap_geterr(pd
));
2503 * Report the new file.
2505 dlt_name
= pcap_datalink_val_to_name(dlt
);
2506 if (dlt_name
== NULL
) {
2507 fprintf(stderr
, "reading from file %s, link-type %u\n",
2511 "reading from file %s, link-type %s (%s)\n",
2512 RFileName
, dlt_name
,
2513 pcap_datalink_val_to_description(dlt
));
2518 while (ret
!= NULL
);
2521 pcap_freecode(&fcode
);
2522 exit_tcpdump(status
== -1 ? 1 : 0);
2529 (*setsignal (int sig
, void (*func
)(int)))(int)
2532 return (signal(sig
, func
));
2534 struct sigaction old
, new;
2536 memset(&new, 0, sizeof(new));
2537 new.sa_handler
= func
;
2539 new.sa_flags
= SA_RESTART
;
2540 if (sigaction(sig
, &new, &old
) < 0)
2542 return (old
.sa_handler
);
2546 /* make a clean exit on interrupts */
2548 cleanup(int signo _U_
)
2551 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2552 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2553 CloseHandle(timer_handle
);
2554 timer_handle
= INVALID_HANDLE_VALUE
;
2557 struct itimerval timer
;
2559 timer
.it_interval
.tv_sec
= 0;
2560 timer
.it_interval
.tv_usec
= 0;
2561 timer
.it_value
.tv_sec
= 0;
2562 timer
.it_value
.tv_usec
= 0;
2563 setitimer(ITIMER_REAL
, &timer
, NULL
);
2566 #ifdef HAVE_PCAP_BREAKLOOP
2568 * We have "pcap_breakloop()"; use it, so that we do as little
2569 * as possible in the signal handler (it's probably not safe
2570 * to do anything with standard I/O streams in a signal handler -
2571 * the ANSI C standard doesn't say it is).
2576 * We don't have "pcap_breakloop()"; this isn't safe, but
2577 * it's the best we can do. Print the summary if we're
2578 * not reading from a savefile - i.e., if we're doing a
2579 * live capture - and exit.
2581 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2583 * We got interrupted, so perhaps we didn't
2584 * manage to finish a line we were printing.
2585 * Print an extra newline, just in case.
2588 (void)fflush(stdout
);
2591 exit_tcpdump(S_SUCCESS
);
2596 On windows, we do not use a fork, so we do not care less about
2597 waiting a child processes to die
2599 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2601 child_cleanup(int signo _U_
)
2605 #endif /* HAVE_FORK && HAVE_VFORK */
2610 struct pcap_stat stats
;
2613 * Older versions of libpcap didn't set ps_ifdrop on some
2614 * platforms; initialize it to 0 to handle that.
2616 stats
.ps_ifdrop
= 0;
2617 if (pcap_stats(pd
, &stats
) < 0) {
2618 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2624 fprintf(stderr
, "%s: ", program_name
);
2626 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2627 PLURAL_SUFFIX(packets_captured
));
2629 fputs(", ", stderr
);
2632 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2633 PLURAL_SUFFIX(stats
.ps_recv
));
2635 fputs(", ", stderr
);
2638 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2639 PLURAL_SUFFIX(stats
.ps_drop
));
2640 if (stats
.ps_ifdrop
!= 0) {
2642 fputs(", ", stderr
);
2645 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2646 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2652 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2654 #define fork_subprocess() fork()
2656 #define fork_subprocess() vfork()
2659 compress_savefile(const char *filename
)
2663 child
= fork_subprocess();
2666 "compress_savefile: fork failed: %s\n",
2667 pcap_strerror(errno
));
2671 /* Parent process. */
2677 * Set to lowest priority so that this doesn't disturb the capture.
2680 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2682 setpriority(PRIO_PROCESS
, 0, 19);
2684 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2686 "compress_savefile: execlp(%s, %s) failed: %s\n",
2689 pcap_strerror(errno
));
2691 exit(S_ERR_HOST_PROGRAM
);
2693 _exit(S_ERR_HOST_PROGRAM
);
2696 #else /* HAVE_FORK && HAVE_VFORK */
2698 compress_savefile(const char *filename
)
2701 "compress_savefile failed. Functionality not implemented under your system\n");
2703 #endif /* HAVE_FORK && HAVE_VFORK */
2706 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2708 struct dump_info
*dump_info
;
2714 dump_info
= (struct dump_info
*)user
;
2717 * XXX - this won't force the file to rotate on the specified time
2718 * boundary, but it will rotate on the first packet received after the
2719 * specified Gflag number of seconds. Note: if a Gflag time boundary
2720 * and a Cflag size boundary coincide, the time rotation will occur
2721 * first thereby cancelling the Cflag boundary (since the file should
2725 /* Check if it is time to rotate */
2728 /* Get the current time */
2729 if ((t
= time(NULL
)) == (time_t)-1) {
2730 error("dump_and_trunc_packet: can't get current_time: %s",
2731 pcap_strerror(errno
));
2735 /* If the time is greater than the specified window, rotate */
2736 if (t
- Gflag_time
>= Gflag
) {
2737 #ifdef HAVE_CAPSICUM
2742 /* Update the Gflag_time */
2744 /* Update Gflag_count */
2747 * Close the current file and open a new one.
2749 pcap_dump_close(dump_info
->pdd
);
2752 * Compress the file we just closed, if the user asked for it
2755 compress_savefile(dump_info
->CurrentFileName
);
2758 * Check to see if we've exceeded the Wflag (when
2761 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2762 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2765 exit_tcpdump(S_SUCCESS
);
2768 if (dump_info
->CurrentFileName
!= NULL
)
2769 free(dump_info
->CurrentFileName
);
2770 /* Allocate space for max filename + \0. */
2771 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2772 if (dump_info
->CurrentFileName
== NULL
)
2773 error("dump_packet_and_trunc: malloc");
2775 * Gflag was set otherwise we wouldn't be here. Reset the count
2776 * so multiple files would end with 1,2,3 in the filename.
2777 * The counting is handled with the -C flow after this.
2782 * This is always the first file in the Cflag
2784 * We also don't need numbering if Cflag is not set.
2787 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2790 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2792 #ifdef HAVE_LIBCAP_NG
2793 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2794 capng_apply(CAPNG_SELECT_BOTH
);
2795 #endif /* HAVE_LIBCAP_NG */
2796 #ifdef HAVE_CAPSICUM
2797 fd
= openat(dump_info
->dirfd
,
2798 dump_info
->CurrentFileName
,
2799 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2801 error("unable to open file %s",
2802 dump_info
->CurrentFileName
);
2804 fp
= fdopen(fd
, "w");
2806 error("unable to fdopen file %s",
2807 dump_info
->CurrentFileName
);
2809 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2810 #else /* !HAVE_CAPSICUM */
2811 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2813 #ifdef HAVE_LIBCAP_NG
2814 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2815 capng_apply(CAPNG_SELECT_BOTH
);
2816 #endif /* HAVE_LIBCAP_NG */
2817 if (dump_info
->pdd
== NULL
)
2818 error("%s", pcap_geterr(pd
));
2819 #ifdef HAVE_CAPSICUM
2820 set_dumper_capsicum_rights(dump_info
->pdd
);
2826 * XXX - this won't prevent capture files from getting
2827 * larger than Cflag - the last packet written to the
2828 * file could put it over Cflag.
2831 #ifdef HAVE_PCAP_DUMP_FTELL64
2832 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
2835 * XXX - this only handles a Cflag value > 2^31-1 on
2836 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2837 * Windows) or LLP64 (64-bit Windows) would require
2838 * a version of libpcap with pcap_dump_ftell64().
2840 long size
= pcap_dump_ftell(dump_info
->pdd
);
2844 error("ftell fails on output file");
2846 #ifdef HAVE_CAPSICUM
2852 * Close the current file and open a new one.
2854 pcap_dump_close(dump_info
->pdd
);
2857 * Compress the file we just closed, if the user
2861 compress_savefile(dump_info
->CurrentFileName
);
2865 if (Cflag_count
>= Wflag
)
2868 if (dump_info
->CurrentFileName
!= NULL
)
2869 free(dump_info
->CurrentFileName
);
2870 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2871 if (dump_info
->CurrentFileName
== NULL
)
2872 error("dump_packet_and_trunc: malloc");
2873 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2874 #ifdef HAVE_LIBCAP_NG
2875 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2876 capng_apply(CAPNG_SELECT_BOTH
);
2877 #endif /* HAVE_LIBCAP_NG */
2878 #ifdef HAVE_CAPSICUM
2879 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2880 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2882 error("unable to open file %s",
2883 dump_info
->CurrentFileName
);
2885 fp
= fdopen(fd
, "w");
2887 error("unable to fdopen file %s",
2888 dump_info
->CurrentFileName
);
2890 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2891 #else /* !HAVE_CAPSICUM */
2892 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2894 #ifdef HAVE_LIBCAP_NG
2895 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2896 capng_apply(CAPNG_SELECT_BOTH
);
2897 #endif /* HAVE_LIBCAP_NG */
2898 if (dump_info
->pdd
== NULL
)
2899 error("%s", pcap_geterr(pd
));
2900 #ifdef HAVE_CAPSICUM
2901 set_dumper_capsicum_rights(dump_info
->pdd
);
2906 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2907 #ifdef HAVE_PCAP_DUMP_FLUSH
2909 pcap_dump_flush(dump_info
->pdd
);
2912 if (dump_info
->ndo
!= NULL
)
2913 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2921 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2923 struct dump_info
*dump_info
;
2929 dump_info
= (struct dump_info
*)user
;
2931 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2932 #ifdef HAVE_PCAP_DUMP_FLUSH
2934 pcap_dump_flush(dump_info
->pdd
);
2937 if (dump_info
->ndo
!= NULL
)
2938 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2946 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2952 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2959 #ifdef SIGNAL_REQ_INFO
2961 requestinfo(int signo _U_
)
2970 #ifdef SIGNAL_FLUSH_PCAP
2972 flushpcap(int signo _U_
)
2975 pcap_dump_flush(pdd
);
2980 print_packets_captured (void)
2982 static u_int prev_packets_captured
, first
= 1;
2984 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2985 fprintf(stderr
, "Got %u\r", packets_captured
);
2987 prev_packets_captured
= packets_captured
;
2992 * Called once each second in verbose mode while dumping to file
2995 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
2996 BOOLEAN timer_fired _U_
)
2998 print_packets_captured();
3001 static void verbose_stats_dump(int sig _U_
)
3003 print_packets_captured();
3007 USES_APPLE_DEPRECATED_API
3011 #ifndef HAVE_PCAP_LIB_VERSION
3012 #ifdef HAVE_PCAP_VERSION
3013 extern char pcap_version
[];
3014 #else /* HAVE_PCAP_VERSION */
3015 static char pcap_version
[] = "unknown";
3016 #endif /* HAVE_PCAP_VERSION */
3017 #endif /* HAVE_PCAP_LIB_VERSION */
3018 const char *smi_version_string
;
3020 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3021 #ifdef HAVE_PCAP_LIB_VERSION
3022 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
3023 #else /* HAVE_PCAP_LIB_VERSION */
3024 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
3025 #endif /* HAVE_PCAP_LIB_VERSION */
3027 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3028 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3031 smi_version_string
= nd_smi_version_string();
3032 if (smi_version_string
!= NULL
)
3033 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
3034 #ifdef HAVE_DNET_HTOA
3035 (void)fprintf(stderr
, "libdnet unknown version\n");
3038 #if defined(__SANITIZE_ADDRESS__)
3039 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
3040 #elif defined(__has_feature)
3041 # if __has_feature(address_sanitizer)
3042 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
3044 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3052 (void)fprintf(stderr
,
3053 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
3054 (void)fprintf(stderr
,
3055 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3056 (void)fprintf(stderr
,
3057 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3058 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3059 (void)fprintf(stderr
,
3060 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
3062 (void)fprintf(stderr
,
3063 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
3064 (void)fprintf(stderr
,
3065 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
3066 (void)fprintf(stderr
,
3067 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
3068 (void)fprintf(stderr
,
3069 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
3070 (void)fprintf(stderr
,
3071 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");