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 error("Chroot without dropping root is insecure");
738 pw
= getpwnam(username
);
741 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0)
742 error("Couldn't chroot/chdir to '%.64s': %s",
743 chroot_dir
, pcap_strerror(errno
));
745 #ifdef HAVE_LIBCAP_NG
747 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
749 error("capng_change_id(): return %d\n", ret
);
751 fprintf(stderr
, "dropped privs to %s\n", username
);
754 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
755 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0)
756 error("Couldn't change to '%.32s' uid=%lu gid=%lu: %s",
758 (unsigned long)pw
->pw_uid
,
759 (unsigned long)pw
->pw_gid
,
760 pcap_strerror(errno
));
762 fprintf(stderr
, "dropped privs to %s\n", username
);
764 #endif /* HAVE_LIBCAP_NG */
766 error("Couldn't find user '%.32s'", username
);
767 #ifdef HAVE_LIBCAP_NG
768 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
769 DIAG_OFF_CLANG(assign
-enum)
772 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
777 DIAG_ON_CLANG(assign
-enum)
778 capng_apply(CAPNG_SELECT_BOTH
);
779 #endif /* HAVE_LIBCAP_NG */
800 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
802 char *filename
= malloc(PATH_MAX
+ 1);
803 if (filename
== NULL
)
804 error("Makefilename: malloc");
806 /* Process with strftime if Gflag is set. */
810 /* Convert Gflag_time to a usable format */
811 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
812 error("MakeTimedFilename: localtime");
815 /* There's no good way to detect an error in strftime since a return
816 * value of 0 isn't necessarily failure.
818 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
820 strncpy(filename
, orig_name
, PATH_MAX
);
823 if (cnt
== 0 && max_chars
== 0)
824 strncpy(buffer
, filename
, PATH_MAX
+ 1);
826 if (nd_snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
827 /* Report an error if the filename is too large */
828 error("too many output files or filename is too long (> %d)", PATH_MAX
);
833 get_next_file(FILE *VFile
, char *ptr
)
837 ret
= fgets(ptr
, PATH_MAX
, VFile
);
841 if (ptr
[strlen(ptr
) - 1] == '\n')
842 ptr
[strlen(ptr
) - 1] = '\0';
848 static cap_channel_t
*
851 cap_channel_t
*capcas
, *capdnsloc
;
852 const char *types
[1];
857 error("unable to create casper process");
858 capdnsloc
= cap_service_open(capcas
, "system.dns");
859 /* Casper capability no longer needed. */
861 if (capdnsloc
== NULL
)
862 error("unable to open system.dns service");
863 /* Limit system.dns to reverse DNS lookups. */
865 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
866 error("unable to limit access to system.dns service");
867 families
[0] = AF_INET
;
868 families
[1] = AF_INET6
;
869 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
870 error("unable to limit access to system.dns service");
874 #endif /* HAVE_CASPER */
876 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
878 tstamp_precision_from_string(const char *precision
)
880 if (strncmp(precision
, "nano", strlen("nano")) == 0)
881 return PCAP_TSTAMP_PRECISION_NANO
;
883 if (strncmp(precision
, "micro", strlen("micro")) == 0)
884 return PCAP_TSTAMP_PRECISION_MICRO
;
890 tstamp_precision_to_string(int precision
)
894 case PCAP_TSTAMP_PRECISION_MICRO
:
897 case PCAP_TSTAMP_PRECISION_NANO
:
908 * Ensure that, on a dump file's descriptor, we have all the rights
909 * necessary to make the standard I/O library work with an fdopen()ed
910 * FILE * from that descriptor.
912 * A long time ago, in a galaxy far far away, AT&T decided that, instead
913 * of providing separate APIs for getting and setting the FD_ flags on a
914 * descriptor, getting and setting the O_ flags on a descriptor, and
915 * locking files, they'd throw them all into a kitchen-sink fcntl() call
916 * along the lines of ioctl(), the fact that ioctl() operations are
917 * largely specific to particular character devices but fcntl() operations
918 * are either generic to all descriptors or generic to all descriptors for
919 * regular files nonwithstanding.
921 * The Capsicum people decided that fine-grained control of descriptor
922 * operations was required, so that you need to grant permission for
923 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
924 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
925 * collection of things, so there are *individual* fcntls for which
926 * permission needs to be granted.
928 * The FreeBSD standard I/O people implemented some optimizations that
929 * requires that the standard I/O routines be able to determine whether
930 * the descriptor for the FILE * is open append-only or not; as that
931 * descriptor could have come from an open() rather than an fopen(),
932 * that requires that it be able to do an F_GETFL fcntl() to read
935 * Tcpdump uses ftell() to determine how much data has been written
936 * to a file in order to, when used with -C, determine when it's time
937 * to rotate capture files. ftell() therefore needs to do an lseek()
938 * to find out the file offset and must, thanks to the aforementioned
939 * optimization, also know whether the descriptor is open append-only
942 * The net result of all the above is that we need to grant CAP_SEEK,
943 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
945 * Perhaps this is the universe's way of saying that either
947 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
948 * using it, so that Capsicum-capable tcpdump wouldn't need to do
953 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
954 * I/O library that knows what rights are needed by the standard
955 * I/O library, based on the open mode, and assigns them, perhaps
956 * with an additional argument indicating, for example, whether
957 * seeking should be allowed, so that tcpdump doesn't need to know
958 * what the standard I/O library happens to require this week.
961 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
963 int fd
= fileno(pcap_dump_file(p
));
966 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
967 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
968 error("unable to limit dump descriptor");
970 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
971 error("unable to limit dump descriptor fcntls");
977 * Copy arg vector into a new buffer, concatenating arguments with spaces.
980 copy_argv(char **argv
)
992 len
+= strlen(*p
++) + 1;
994 buf
= (char *)malloc(len
);
996 error("copy_argv: malloc");
1000 while ((src
= *p
++) != NULL
) {
1001 while ((*dst
++ = *src
++) != '\0')
1011 * On Windows, we need to open the file in binary mode, so that
1012 * we get all the bytes specified by the size we get from "fstat()".
1013 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
1014 * we define it as 0 if it's not defined, so it does nothing.
1021 read_infile(char *fname
)
1027 fd
= open(fname
, O_RDONLY
|O_BINARY
);
1029 error("can't open %s: %s", fname
, pcap_strerror(errno
));
1031 if (fstat(fd
, &buf
) < 0)
1032 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
1034 cp
= malloc((u_int
)buf
.st_size
+ 1);
1036 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
1037 fname
, pcap_strerror(errno
));
1038 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
1040 error("read %s: %s", fname
, pcap_strerror(errno
));
1041 if (cc
!= buf
.st_size
)
1042 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
1045 /* replace "# comment" with spaces */
1046 for (i
= 0; i
< cc
; i
++) {
1048 while (i
< cc
&& cp
[i
] != '\n')
1055 #ifdef HAVE_PCAP_FINDALLDEVS
1057 parse_interface_number(const char *device
)
1064 * Search for a colon, terminating any scheme at the beginning
1067 p
= strchr(device
, ':');
1070 * We found it. Is it followed by "//"?
1072 p
++; /* skip the : */
1073 if (strncmp(p
, "//", 2) == 0) {
1075 * Yes. Search for the next /, at the end of the
1076 * authority part of the URL.
1078 p
+= 2; /* skip the // */
1082 * OK, past the / is the path.
1088 devnum
= strtol(device
, &end
, 10);
1089 if (device
!= end
&& *end
== '\0') {
1091 * It's all-numeric, but is it a valid number?
1095 * No, it's not an ordinal.
1097 error("Invalid adapter index");
1102 * It's not all-numeric; return -1, so our caller
1110 find_interface_by_number(const char *url
1111 #ifndef HAVE_PCAP_FINDALLDEVS_EX
1116 pcap_if_t
*dev
, *devlist
;
1118 char ebuf
[PCAP_ERRBUF_SIZE
];
1120 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1126 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1128 * Search for a colon, terminating any scheme at the beginning
1131 endp
= strchr(url
, ':');
1134 * We found it. Is it followed by "//"?
1136 endp
++; /* skip the : */
1137 if (strncmp(endp
, "//", 2) == 0) {
1139 * Yes. Search for the next /, at the end of the
1140 * authority part of the URL.
1142 endp
+= 2; /* skip the // */
1143 endp
= strchr(endp
, '/');
1149 * OK, everything from device to endp is a URL to hand
1150 * to pcap_findalldevs_ex().
1152 endp
++; /* Include the trailing / in the URL; pcap_findalldevs_ex() requires it */
1153 host_url
= malloc(endp
- url
+ 1);
1154 memcpy(host_url
, url
, endp
- url
);
1155 host_url
[endp
- url
] = '\0';
1156 status
= pcap_findalldevs_ex(host_url
, NULL
, &devlist
, ebuf
);
1160 status
= pcap_findalldevs(&devlist
, ebuf
);
1164 * Look for the devnum-th entry in the list of devices (1-based).
1166 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1167 i
++, dev
= dev
->next
)
1170 error("Invalid adapter index");
1171 device
= strdup(dev
->name
);
1172 pcap_freealldevs(devlist
);
1177 #ifdef HAVE_PCAP_OPEN
1179 * Prefix for rpcap URLs.
1181 static char rpcap_prefix
[] = "rpcap://";
1185 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1188 #ifdef HAVE_PCAP_CREATE
1193 #ifdef HAVE_PCAP_OPEN
1195 * Is this an rpcap URL?
1197 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1199 * Yes. Open it with pcap_open().
1202 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1203 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1207 * If this failed with "No such device" or "The system
1208 * cannot find the device specified", that means
1209 * the interface doesn't exist; return NULL, so that
1210 * the caller can see whether the device name is
1211 * actually an interface index.
1213 if (strstr(ebuf
, "No such device") != NULL
||
1214 strstr(ebuf
, "The system cannot find the device specified") != NULL
)
1219 warning("%s", ebuf
);
1222 #endif /* HAVE_PCAP_OPEN */
1224 #ifdef HAVE_PCAP_CREATE
1225 pc
= pcap_create(device
, ebuf
);
1228 * If this failed with "No such device", that means
1229 * the interface doesn't exist; return NULL, so that
1230 * the caller can see whether the device name is
1231 * actually an interface index.
1233 if (strstr(ebuf
, "No such device") != NULL
)
1237 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1239 show_tstamp_types_and_exit(pc
, device
);
1241 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1242 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1244 error("%s: Can't set %ssecond time stamp precision: %s",
1246 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1247 pcap_statustostr(status
));
1250 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1251 if (immediate_mode
) {
1252 status
= pcap_set_immediate_mode(pc
, 1);
1254 error("%s: Can't set immediate mode: %s",
1256 pcap_statustostr(status
));
1260 * Is this an interface that supports monitor mode?
1262 if (pcap_can_set_rfmon(pc
) == 1)
1263 supports_monitor_mode
= 1;
1265 supports_monitor_mode
= 0;
1266 if (ndo
->ndo_snaplen
!= 0) {
1268 * A snapshot length was explicitly specified;
1271 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1273 error("%s: Can't set snapshot length: %s",
1274 device
, pcap_statustostr(status
));
1276 status
= pcap_set_promisc(pc
, !pflag
);
1278 error("%s: Can't set promiscuous mode: %s",
1279 device
, pcap_statustostr(status
));
1281 status
= pcap_set_rfmon(pc
, 1);
1283 error("%s: Can't set monitor mode: %s",
1284 device
, pcap_statustostr(status
));
1286 status
= pcap_set_timeout(pc
, 1000);
1288 error("%s: pcap_set_timeout failed: %s",
1289 device
, pcap_statustostr(status
));
1291 status
= pcap_set_buffer_size(pc
, Bflag
);
1293 error("%s: Can't set buffer size: %s",
1294 device
, pcap_statustostr(status
));
1296 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1298 status
= pcap_set_tstamp_type(pc
, jflag
);
1300 error("%s: Can't set time stamp type: %s",
1301 device
, pcap_statustostr(status
));
1304 status
= pcap_activate(pc
);
1307 * pcap_activate() failed.
1309 cp
= pcap_geterr(pc
);
1310 if (status
== PCAP_ERROR
)
1312 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1314 * Return an error for our caller to handle.
1316 nd_snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1317 device
, pcap_statustostr(status
), cp
);
1320 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1321 error("%s: %s\n(%s)", device
,
1322 pcap_statustostr(status
), cp
);
1324 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1325 strncmp(device
, "wlan", 4) == 0) {
1326 char parent
[8], newdev
[8];
1328 size_t s
= sizeof(parent
);
1330 nd_snprintf(sysctl
, sizeof(sysctl
),
1331 "net.wlan.%d.%%parent", atoi(device
+ 4));
1332 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1333 strlcpy(newdev
, device
, sizeof(newdev
));
1334 /* Suggest a new wlan device. */
1335 /* FIXME: incrementing the index this way is not going to work well
1336 * when the index is 9 or greater but the only consequence in this
1337 * specific case would be an error message that looks a bit odd.
1339 newdev
[strlen(newdev
)-1]++;
1340 error("%s is not a monitor mode VAP\n"
1341 "To create a new monitor mode VAP use:\n"
1342 " ifconfig %s create wlandev %s wlanmode monitor\n"
1343 "and use %s as the tcpdump interface",
1344 device
, newdev
, parent
, newdev
);
1348 error("%s: %s", device
,
1349 pcap_statustostr(status
));
1350 } else if (status
> 0) {
1352 * pcap_activate() succeeded, but it's warning us
1353 * of a problem it had.
1355 cp
= pcap_geterr(pc
);
1356 if (status
== PCAP_WARNING
)
1358 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1360 warning("%s: %s\n(%s)", device
,
1361 pcap_statustostr(status
), cp
);
1363 warning("%s: %s", device
,
1364 pcap_statustostr(status
));
1366 #ifdef HAVE_PCAP_SETDIRECTION
1368 status
= pcap_setdirection(pc
, Qflag
);
1370 error("%s: pcap_setdirection() failed: %s",
1371 device
, pcap_geterr(pc
));
1373 #endif /* HAVE_PCAP_SETDIRECTION */
1374 #else /* HAVE_PCAP_CREATE */
1377 * If no snapshot length was specified, or a length of 0 was
1378 * specified, default to 256KB.
1380 if (ndo
->ndo_snaplen
== 0)
1381 ndo
->ndo_snaplen
= 262144;
1382 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1385 * If this failed with "No such device", that means
1386 * the interface doesn't exist; return NULL, so that
1387 * the caller can see whether the device name is
1388 * actually an interface index.
1390 if (strstr(ebuf
, "No such device") != NULL
)
1395 warning("%s", ebuf
);
1396 #endif /* HAVE_PCAP_CREATE */
1402 main(int argc
, char **argv
)
1405 bpf_u_int32 localnet
= 0, netmask
= 0;
1406 int timezone_offset
= 0;
1407 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1409 pcap_handler callback
;
1411 const char *dlt_name
;
1412 struct bpf_program fcode
;
1414 void (*oldhandler
)(int);
1416 struct dump_info dumpinfo
;
1417 u_char
*pcap_userdata
;
1418 char ebuf
[PCAP_ERRBUF_SIZE
];
1419 char VFileLine
[PATH_MAX
+ 1];
1420 char *username
= NULL
;
1421 char *chroot_dir
= NULL
;
1424 #ifdef HAVE_PCAP_FINDALLDEVS
1430 #ifdef HAVE_CAPSICUM
1431 cap_rights_t rights
;
1433 #endif /* HAVE_CAPSICUM */
1434 int Oflag
= 1; /* run filter code optimizer */
1436 const char *yflag_dlt_name
= NULL
;
1439 netdissect_options Ndo
;
1440 netdissect_options
*ndo
= &Ndo
;
1443 * Initialize the netdissect code.
1445 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1448 memset(ndo
, 0, sizeof(*ndo
));
1449 ndo_set_function_pointers(ndo
);
1459 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1460 ndo
->program_name
= program_name
= cp
+ 1;
1462 ndo
->program_name
= program_name
= argv
[0];
1464 #if defined(HAVE_PCAP_WSOCKINIT)
1465 if (pcap_wsockinit() != 0)
1466 error("Attempting to initialize Winsock failed");
1467 #elif defined(HAVE_WSOCKINIT)
1468 if (wsockinit() != 0)
1469 error("Attempting to initialize Winsock failed");
1473 * On platforms where the CPU doesn't support unaligned loads,
1474 * force unaligned accesses to abort with SIGBUS, rather than
1475 * being fixed up (slowly) by the OS kernel; on those platforms,
1476 * misaligned accesses are bugs, and we want tcpdump to crash so
1477 * that the bugs are reported.
1479 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1483 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1487 /* compatibility for old -a */
1498 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1500 Bflag
= atoi(optarg
)*1024;
1502 error("invalid packet buffer size %s", optarg
);
1504 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1509 error("invalid packet count %s", optarg
);
1514 #ifdef HAVE_PCAP_DUMP_FTELL64
1515 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1517 Cflag
= strtol(optarg
, &endp
, 10);
1519 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1521 error("invalid file size %s", optarg
);
1523 * Will multiplying it by 1000000 overflow?
1525 #ifdef HAVE_PCAP_DUMP_FTELL64
1526 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1528 if (Cflag
> LONG_MAX
/ 1000000)
1530 error("file size %s is too large", optarg
);
1538 #ifdef HAVE_PCAP_FINDALLDEVS
1544 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1545 case OPTION_LIST_REMOTE_INTERFACES
:
1546 remote_interfaces_source
= optarg
;
1559 #ifndef HAVE_LIBCRYPTO
1560 warning("crypto code not compiled in");
1562 ndo
->ndo_espsecret
= optarg
;
1574 Gflag
= atoi(optarg
);
1576 error("invalid number of seconds %s", optarg
);
1578 /* We will create one file initially. */
1581 /* Grab the current time for rotation use. */
1582 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1583 error("main: can't get current time: %s",
1584 pcap_strerror(errno
));
1590 exit_tcpdump(S_SUCCESS
);
1601 #ifdef HAVE_PCAP_CREATE
1605 #endif /* HAVE_PCAP_CREATE */
1607 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1609 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1611 error("invalid time stamp type %s", optarg
);
1622 * _IOLBF is the same as _IOFBF in Microsoft's C
1623 * libraries; the only alternative they offer
1626 * XXX - this should really be checking for MSVC++,
1627 * not _WIN32, if, for example, MinGW has its own
1628 * C library that is more UNIX-compatible.
1630 setvbuf(stdout
, NULL
, _IONBF
, 0);
1632 #ifdef HAVE_SETLINEBUF
1635 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1645 if (nd_have_smi_support()) {
1646 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1649 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1650 program_name
, optarg
);
1651 (void)fprintf(stderr
, "(no libsmi support)\n");
1656 /* TCP-MD5 shared secret */
1657 #ifndef HAVE_LIBCRYPTO
1658 warning("crypto code not compiled in");
1660 ndo
->ndo_sigsecret
= optarg
;
1681 ++ndo
->ndo_suppress_default_print
;
1684 #ifdef HAVE_PCAP_SETDIRECTION
1686 if (ascii_strcasecmp(optarg
, "in") == 0)
1688 else if (ascii_strcasecmp(optarg
, "out") == 0)
1690 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1691 Qflag
= PCAP_D_INOUT
;
1693 error("unknown capture direction `%s'", optarg
);
1695 #endif /* HAVE_PCAP_SETDIRECTION */
1702 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1703 if (optarg
== end
|| *end
!= '\0'
1704 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1705 error("invalid snaplen %s", optarg
);
1717 if (ascii_strcasecmp(optarg
, "vat") == 0)
1718 ndo
->ndo_packettype
= PT_VAT
;
1719 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1720 ndo
->ndo_packettype
= PT_WB
;
1721 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1722 ndo
->ndo_packettype
= PT_RPC
;
1723 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1724 ndo
->ndo_packettype
= PT_RTP
;
1725 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1726 ndo
->ndo_packettype
= PT_RTCP
;
1727 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1728 ndo
->ndo_packettype
= PT_SNMP
;
1729 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1730 ndo
->ndo_packettype
= PT_CNFP
;
1731 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1732 ndo
->ndo_packettype
= PT_TFTP
;
1733 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1734 ndo
->ndo_packettype
= PT_AODV
;
1735 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1736 ndo
->ndo_packettype
= PT_CARP
;
1737 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1738 ndo
->ndo_packettype
= PT_RADIUS
;
1739 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1740 ndo
->ndo_packettype
= PT_ZMTP1
;
1741 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1742 ndo
->ndo_packettype
= PT_VXLAN
;
1743 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1744 ndo
->ndo_packettype
= PT_PGM
;
1745 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1746 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1747 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1748 ndo
->ndo_packettype
= PT_LMP
;
1749 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1750 ndo
->ndo_packettype
= PT_RESP
;
1752 error("unknown packet type `%s'", optarg
);
1759 #ifdef HAVE_PCAP_DUMP_FLUSH
1778 Wflag
= atoi(optarg
);
1780 error("invalid number of output files %s", optarg
);
1781 WflagChars
= getWflagChars(Wflag
);
1786 ++ndo
->ndo_suppress_default_print
;
1791 ++ndo
->ndo_suppress_default_print
;
1795 yflag_dlt_name
= optarg
;
1797 pcap_datalink_name_to_val(yflag_dlt_name
);
1799 error("invalid data link type %s", yflag_dlt_name
);
1802 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1805 /* Undocumented flag */
1806 pcap_set_parser_debug(1);
1819 ndo
->ndo_packet_number
= 1;
1822 case OPTION_VERSION
:
1824 exit_tcpdump(S_SUCCESS
);
1827 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1828 case OPTION_TSTAMP_PRECISION
:
1829 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1830 if (ndo
->ndo_tstamp_precision
< 0)
1831 error("unsupported time stamp precision");
1835 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1836 case OPTION_IMMEDIATE_MODE
:
1847 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1851 #ifdef HAVE_PCAP_FINDALLDEVS
1853 show_devices_and_exit();
1855 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1856 if (remote_interfaces_source
!= NULL
)
1857 show_remote_devices_and_exit();
1860 switch (ndo
->ndo_tflag
) {
1862 case 0: /* Default */
1863 case 4: /* Default + Date*/
1864 timezone_offset
= gmt2local(0);
1867 case 1: /* No time stamp */
1868 case 2: /* Unix timeval style */
1869 case 3: /* Microseconds since previous packet */
1870 case 5: /* Microseconds since first packet */
1873 default: /* Not supported */
1874 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1878 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1879 error("-f can not be used with -V or -r");
1881 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1882 error("-V and -r are mutually exclusive.");
1884 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1886 * If we're printing dissected packets to the standard output
1887 * and the standard output is a terminal, use immediate mode,
1888 * as the user's probably expecting to see packets pop up
1891 * XXX - set the timeout to a lower value, instead? If so,
1892 * what value would be appropriate?
1894 if ((WFileName
== NULL
|| print
) && isatty(1))
1899 /* if run as root, prepare for chrooting */
1900 if (getuid() == 0 || geteuid() == 0) {
1901 /* future extensibility for cmd-line arguments */
1903 chroot_dir
= WITH_CHROOT
;
1908 /* if run as root, prepare for dropping root privileges */
1909 if (getuid() == 0 || geteuid() == 0) {
1910 /* Run with '-Z root' to restore old behaviour */
1912 username
= WITH_USER
;
1916 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1918 * If RFileName is non-null, it's the pathname of a
1919 * savefile to read. If VFileName is non-null, it's
1920 * the pathname of a file containing a list of pathnames
1921 * (one per line) of savefiles to read.
1923 * In either case, we're reading a savefile, not doing
1928 * We don't need network access, so relinquish any set-UID
1929 * or set-GID privileges we have (if any).
1931 * We do *not* want set-UID privileges when opening a
1932 * trace file, as that might let the user read other
1933 * people's trace files (especially if we're set-UID
1936 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1937 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1939 if (VFileName
!= NULL
) {
1940 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1943 VFile
= fopen(VFileName
, "r");
1946 error("Unable to open file: %s\n", pcap_strerror(errno
));
1948 ret
= get_next_file(VFile
, VFileLine
);
1950 error("Nothing in %s\n", VFileName
);
1951 RFileName
= VFileLine
;
1954 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1955 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1956 ndo
->ndo_tstamp_precision
, ebuf
);
1958 pd
= pcap_open_offline(RFileName
, ebuf
);
1963 #ifdef HAVE_CAPSICUM
1964 cap_rights_init(&rights
, CAP_READ
);
1965 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1967 error("unable to limit pcap descriptor");
1970 dlt
= pcap_datalink(pd
);
1971 dlt_name
= pcap_datalink_val_to_name(dlt
);
1972 if (dlt_name
== NULL
) {
1973 fprintf(stderr
, "reading from file %s, link-type %u\n",
1977 "reading from file %s, link-type %s (%s)\n",
1978 RFileName
, dlt_name
,
1979 pcap_datalink_val_to_description(dlt
));
1981 #ifdef DLT_LINUX_SLL2
1982 if (dlt
== DLT_LINUX_SLL2
)
1983 fprintf(stderr
, "Warning: interface names might be incorrect\n");
1987 * We're doing a live capture.
1989 if (device
== NULL
) {
1991 * No interface was specified. Pick one.
1993 #ifdef HAVE_PCAP_FINDALLDEVS
1995 * Find the list of interfaces, and pick
1996 * the first interface.
1998 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
2000 if (devlist
== NULL
)
2001 error("no interfaces available for capture");
2002 device
= strdup(devlist
->name
);
2003 pcap_freealldevs(devlist
);
2004 #else /* HAVE_PCAP_FINDALLDEVS */
2006 * Use whatever interface pcap_lookupdev()
2009 device
= pcap_lookupdev(ebuf
);
2016 * Try to open the interface with the specified name.
2018 pd
= open_interface(device
, ndo
, ebuf
);
2021 * That failed. If we can get a list of
2022 * interfaces, and the interface name
2023 * is purely numeric, try to use it as
2024 * a 1-based index in the list of
2027 #ifdef HAVE_PCAP_FINDALLDEVS
2028 devnum
= parse_interface_number(device
);
2031 * It's not a number; just report
2032 * the open error and fail.
2038 * OK, it's a number; try to find the
2039 * interface with that index, and try
2042 * find_interface_by_number() exits if it
2043 * couldn't be found.
2045 device
= find_interface_by_number(device
, devnum
);
2046 pd
= open_interface(device
, ndo
, ebuf
);
2049 #else /* HAVE_PCAP_FINDALLDEVS */
2051 * We can't get a list of interfaces; just
2055 #endif /* HAVE_PCAP_FINDALLDEVS */
2059 * Let user own process after capture device has
2063 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
2064 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
2066 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
2068 if(pcap_setbuff(pd
, Bflag
)==-1){
2069 error("%s", pcap_geterr(pd
));
2071 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
2073 show_dlts_and_exit(pd
, device
);
2074 if (yflag_dlt
>= 0) {
2075 #ifdef HAVE_PCAP_SET_DATALINK
2076 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
2077 error("%s", pcap_geterr(pd
));
2080 * We don't actually support changing the
2081 * data link type, so we only let them
2082 * set it to what it already is.
2084 if (yflag_dlt
!= pcap_datalink(pd
)) {
2085 error("%s is not one of the DLTs supported by this device\n",
2089 (void)fprintf(stderr
, "%s: data link type %s\n",
2090 program_name
, yflag_dlt_name
);
2091 (void)fflush(stderr
);
2093 i
= pcap_snapshot(pd
);
2094 if (ndo
->ndo_snaplen
< i
) {
2095 if (ndo
->ndo_snaplen
!= 0)
2096 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
2097 ndo
->ndo_snaplen
= i
;
2098 } else if (ndo
->ndo_snaplen
> i
) {
2099 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
2100 ndo
->ndo_snaplen
= i
;
2102 if(ndo
->ndo_fflag
!= 0) {
2103 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
2104 warning("foreign (-f) flag used but: %s", ebuf
);
2110 cmdbuf
= read_infile(infile
);
2112 cmdbuf
= copy_argv(&argv
[optind
]);
2114 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
2115 pcap_set_optimizer_debug(dflag
);
2117 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2118 error("%s", pcap_geterr(pd
));
2120 bpf_dump(&fcode
, dflag
);
2123 pcap_freecode(&fcode
);
2124 exit_tcpdump(S_SUCCESS
);
2128 if (!ndo
->ndo_nflag
)
2129 capdns
= capdns_setup();
2130 #endif /* HAVE_CASPER */
2132 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2135 (void)setsignal(SIGPIPE
, cleanup
);
2136 (void)setsignal(SIGTERM
, cleanup
);
2138 (void)setsignal(SIGINT
, cleanup
);
2139 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2140 (void)setsignal(SIGCHLD
, child_cleanup
);
2142 /* Cooperate with nohup(1) */
2144 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2145 (void)setsignal(SIGHUP
, oldhandler
);
2150 * If a user name was specified with "-Z", attempt to switch to
2151 * that user's UID. This would probably be used with sudo,
2152 * to allow tcpdump to be run in a special restricted
2153 * account (if you just want to allow users to open capture
2154 * devices, and can't just give users that permission,
2155 * you'd make tcpdump set-UID or set-GID).
2157 * Tcpdump doesn't necessarily write only to one savefile;
2158 * the general only way to allow a -Z instance to write to
2159 * savefiles as the user under whose UID it's run, rather
2160 * than as the user specified with -Z, would thus be to switch
2161 * to the original user ID before opening a capture file and
2162 * then switch back to the -Z user ID after opening the savefile.
2163 * Switching to the -Z user ID only after opening the first
2164 * savefile doesn't handle the general case.
2167 if (getuid() == 0 || geteuid() == 0) {
2168 #ifdef HAVE_LIBCAP_NG
2169 /* Initialize capng */
2170 capng_clear(CAPNG_SELECT_BOTH
);
2172 DIAG_OFF_CLANG(assign
-enum)
2175 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2179 DIAG_ON_CLANG(assign
-enum)
2182 DIAG_OFF_CLANG(assign
-enum)
2185 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2188 DIAG_ON_CLANG(assign
-enum)
2192 DIAG_OFF_CLANG(assign
-enum)
2195 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2198 DIAG_ON_CLANG(assign
-enum)
2200 capng_apply(CAPNG_SELECT_BOTH
);
2201 #endif /* HAVE_LIBCAP_NG */
2202 if (username
|| chroot_dir
)
2203 droproot(username
, chroot_dir
);
2208 if (pcap_setfilter(pd
, &fcode
) < 0)
2209 error("%s", pcap_geterr(pd
));
2210 #ifdef HAVE_CAPSICUM
2211 if (RFileName
== NULL
&& VFileName
== NULL
&& pcap_fileno(pd
) != -1) {
2212 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2215 * The various libpcap devices use a combination of
2216 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2217 * so we add the relevant access rights.
2219 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2220 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2222 error("unable to limit pcap descriptor");
2224 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2225 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2226 error("unable to limit ioctls on pcap descriptor");
2231 /* Do not exceed the default PATH_MAX for files. */
2232 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2234 if (dumpinfo
.CurrentFileName
== NULL
)
2235 error("malloc of dumpinfo.CurrentFileName");
2237 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2239 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2241 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2243 pdd
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2244 #ifdef HAVE_LIBCAP_NG
2245 /* Give up CAP_DAC_OVERRIDE capability.
2246 * Only allow it to be restored if the -C or -G flag have been
2247 * set since we may need to create more files later on.
2251 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2255 capng_apply(CAPNG_SELECT_BOTH
);
2256 #endif /* HAVE_LIBCAP_NG */
2258 error("%s", pcap_geterr(pd
));
2259 #ifdef HAVE_CAPSICUM
2260 set_dumper_capsicum_rights(p
);
2262 if (Cflag
!= 0 || Gflag
!= 0) {
2263 #ifdef HAVE_CAPSICUM
2264 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2265 if (dumpinfo
.WFileName
== NULL
) {
2266 error("Unable to allocate memory for file %s",
2269 dumpinfo
.dirfd
= open(dirname(WFileName
),
2270 O_DIRECTORY
| O_RDONLY
);
2271 if (dumpinfo
.dirfd
< 0) {
2272 error("unable to open directory %s",
2273 dirname(WFileName
));
2275 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2276 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2277 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2279 error("unable to limit directory rights");
2281 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2283 error("unable to limit dump descriptor fcntls");
2285 #else /* !HAVE_CAPSICUM */
2286 dumpinfo
.WFileName
= WFileName
;
2288 callback
= dump_packet_and_trunc
;
2291 pcap_userdata
= (u_char
*)&dumpinfo
;
2293 callback
= dump_packet
;
2294 dumpinfo
.WFileName
= WFileName
;
2297 pcap_userdata
= (u_char
*)&dumpinfo
;
2300 dlt
= pcap_datalink(pd
);
2301 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2304 dumpinfo
.ndo
= NULL
;
2306 #ifdef HAVE_PCAP_DUMP_FLUSH
2308 pcap_dump_flush(pdd
);
2311 dlt
= pcap_datalink(pd
);
2312 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2313 callback
= print_packet
;
2314 pcap_userdata
= (u_char
*)ndo
;
2317 #ifdef SIGNAL_REQ_INFO
2319 * We can't get statistics when reading from a file rather
2320 * than capturing from a device.
2322 if (RFileName
== NULL
)
2323 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2325 #ifdef SIGNAL_FLUSH_PCAP
2326 (void)setsignal(SIGNAL_FLUSH_PCAP
, flushpcap
);
2329 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2331 * When capturing to a file, if "--print" wasn't specified,
2332 *"-v" means tcpdump should, once per second,
2333 * "v"erbosely report the number of packets captured.
2337 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2339 * suggests that this dates back to W2K.
2341 * I don't know what a "long wait" is, but we'll assume
2342 * that printing the stats could be a "long wait".
2344 CreateTimerQueueTimer(&timer_handle
, NULL
,
2345 verbose_stats_dump
, NULL
, 1000, 1000,
2346 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2347 setvbuf(stderr
, NULL
, _IONBF
, 0);
2350 * Assume this is UN*X, and that it has setitimer(); that
2351 * dates back to UNIX 95.
2353 struct itimerval timer
;
2354 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2355 timer
.it_interval
.tv_sec
= 1;
2356 timer
.it_interval
.tv_usec
= 0;
2357 timer
.it_value
.tv_sec
= 1;
2358 timer
.it_value
.tv_usec
= 1;
2359 setitimer(ITIMER_REAL
, &timer
, NULL
);
2363 if (RFileName
== NULL
) {
2365 * Live capture (if -V was specified, we set RFileName
2366 * to a file from the -V file). Print a message to
2367 * the standard error on UN*X.
2369 if (!ndo
->ndo_vflag
&& !WFileName
) {
2370 (void)fprintf(stderr
,
2371 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2374 (void)fprintf(stderr
, "%s: ", program_name
);
2375 dlt
= pcap_datalink(pd
);
2376 dlt_name
= pcap_datalink_val_to_name(dlt
);
2377 if (dlt_name
== NULL
) {
2378 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2379 device
, dlt
, ndo
->ndo_snaplen
);
2381 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2383 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2385 (void)fflush(stderr
);
2388 #ifdef HAVE_CAPSICUM
2389 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2391 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2393 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2394 #endif /* HAVE_CASPER */
2395 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2396 error("unable to enter the capability mode");
2397 #endif /* HAVE_CAPSICUM */
2400 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2401 if (WFileName
== NULL
) {
2403 * We're printing packets. Flush the printed output,
2404 * so it doesn't get intermingled with error output.
2408 * We got interrupted, so perhaps we didn't
2409 * manage to finish a line we were printing.
2410 * Print an extra newline, just in case.
2414 (void)fflush(stdout
);
2418 * We got interrupted. If we are reading multiple
2419 * files (via -V) set these so that we stop.
2428 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2429 program_name
, pcap_geterr(pd
));
2431 if (RFileName
== NULL
) {
2433 * We're doing a live capture. Report the capture
2439 if (VFileName
!= NULL
) {
2440 ret
= get_next_file(VFile
, VFileLine
);
2444 RFileName
= VFileLine
;
2445 pd
= pcap_open_offline(RFileName
, ebuf
);
2448 #ifdef HAVE_CAPSICUM
2449 cap_rights_init(&rights
, CAP_READ
);
2450 if (cap_rights_limit(fileno(pcap_file(pd
)),
2451 &rights
) < 0 && errno
!= ENOSYS
) {
2452 error("unable to limit pcap descriptor");
2455 new_dlt
= pcap_datalink(pd
);
2456 if (new_dlt
!= dlt
) {
2458 * The new file has a different
2459 * link-layer header type from the
2462 if (WFileName
!= NULL
) {
2464 * We're writing raw packets
2465 * that match the filter to
2466 * a pcap file. pcap files
2467 * don't support multiple
2468 * different link-layer
2469 * header types, so we fail
2472 error("%s: new dlt does not match original", RFileName
);
2476 * We're printing the decoded packets;
2477 * switch to the new DLT.
2479 * To do that, we need to change
2480 * the printer, change the DLT name,
2481 * and recompile the filter with
2485 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2486 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2487 error("%s", pcap_geterr(pd
));
2491 * Set the filter on the new file.
2493 if (pcap_setfilter(pd
, &fcode
) < 0)
2494 error("%s", pcap_geterr(pd
));
2497 * Report the new file.
2499 dlt_name
= pcap_datalink_val_to_name(dlt
);
2500 if (dlt_name
== NULL
) {
2501 fprintf(stderr
, "reading from file %s, link-type %u\n",
2505 "reading from file %s, link-type %s (%s)\n",
2506 RFileName
, dlt_name
,
2507 pcap_datalink_val_to_description(dlt
));
2512 while (ret
!= NULL
);
2515 pcap_freecode(&fcode
);
2516 exit_tcpdump(status
== -1 ? 1 : 0);
2523 (*setsignal (int sig
, void (*func
)(int)))(int)
2526 return (signal(sig
, func
));
2528 struct sigaction old
, new;
2530 memset(&new, 0, sizeof(new));
2531 new.sa_handler
= func
;
2533 new.sa_flags
= SA_RESTART
;
2534 if (sigaction(sig
, &new, &old
) < 0)
2536 return (old
.sa_handler
);
2540 /* make a clean exit on interrupts */
2542 cleanup(int signo _U_
)
2545 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2546 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2547 CloseHandle(timer_handle
);
2548 timer_handle
= INVALID_HANDLE_VALUE
;
2551 struct itimerval timer
;
2553 timer
.it_interval
.tv_sec
= 0;
2554 timer
.it_interval
.tv_usec
= 0;
2555 timer
.it_value
.tv_sec
= 0;
2556 timer
.it_value
.tv_usec
= 0;
2557 setitimer(ITIMER_REAL
, &timer
, NULL
);
2560 #ifdef HAVE_PCAP_BREAKLOOP
2562 * We have "pcap_breakloop()"; use it, so that we do as little
2563 * as possible in the signal handler (it's probably not safe
2564 * to do anything with standard I/O streams in a signal handler -
2565 * the ANSI C standard doesn't say it is).
2570 * We don't have "pcap_breakloop()"; this isn't safe, but
2571 * it's the best we can do. Print the summary if we're
2572 * not reading from a savefile - i.e., if we're doing a
2573 * live capture - and exit.
2575 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2577 * We got interrupted, so perhaps we didn't
2578 * manage to finish a line we were printing.
2579 * Print an extra newline, just in case.
2582 (void)fflush(stdout
);
2585 exit_tcpdump(S_SUCCESS
);
2590 On windows, we do not use a fork, so we do not care less about
2591 waiting a child processes to die
2593 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2595 child_cleanup(int signo _U_
)
2599 #endif /* HAVE_FORK && HAVE_VFORK */
2604 struct pcap_stat stats
;
2607 * Older versions of libpcap didn't set ps_ifdrop on some
2608 * platforms; initialize it to 0 to handle that.
2610 stats
.ps_ifdrop
= 0;
2611 if (pcap_stats(pd
, &stats
) < 0) {
2612 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2618 fprintf(stderr
, "%s: ", program_name
);
2620 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2621 PLURAL_SUFFIX(packets_captured
));
2623 fputs(", ", stderr
);
2626 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2627 PLURAL_SUFFIX(stats
.ps_recv
));
2629 fputs(", ", stderr
);
2632 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2633 PLURAL_SUFFIX(stats
.ps_drop
));
2634 if (stats
.ps_ifdrop
!= 0) {
2636 fputs(", ", stderr
);
2639 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2640 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2646 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2648 #define fork_subprocess() fork()
2650 #define fork_subprocess() vfork()
2653 compress_savefile(const char *filename
)
2657 child
= fork_subprocess();
2660 "compress_savefile: fork failed: %s\n",
2661 pcap_strerror(errno
));
2665 /* Parent process. */
2671 * Set to lowest priority so that this doesn't disturb the capture.
2674 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2676 setpriority(PRIO_PROCESS
, 0, 19);
2678 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2680 "compress_savefile: execlp(%s, %s) failed: %s\n",
2683 pcap_strerror(errno
));
2685 exit(S_ERR_HOST_PROGRAM
);
2687 _exit(S_ERR_HOST_PROGRAM
);
2690 #else /* HAVE_FORK && HAVE_VFORK */
2692 compress_savefile(const char *filename
)
2695 "compress_savefile failed. Functionality not implemented under your system\n");
2697 #endif /* HAVE_FORK && HAVE_VFORK */
2700 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2702 struct dump_info
*dump_info
;
2708 dump_info
= (struct dump_info
*)user
;
2711 * XXX - this won't force the file to rotate on the specified time
2712 * boundary, but it will rotate on the first packet received after the
2713 * specified Gflag number of seconds. Note: if a Gflag time boundary
2714 * and a Cflag size boundary coincide, the time rotation will occur
2715 * first thereby cancelling the Cflag boundary (since the file should
2719 /* Check if it is time to rotate */
2722 /* Get the current time */
2723 if ((t
= time(NULL
)) == (time_t)-1) {
2724 error("dump_and_trunc_packet: can't get current_time: %s",
2725 pcap_strerror(errno
));
2729 /* If the time is greater than the specified window, rotate */
2730 if (t
- Gflag_time
>= Gflag
) {
2731 #ifdef HAVE_CAPSICUM
2736 /* Update the Gflag_time */
2738 /* Update Gflag_count */
2741 * Close the current file and open a new one.
2743 pcap_dump_close(dump_info
->pdd
);
2746 * Compress the file we just closed, if the user asked for it
2749 compress_savefile(dump_info
->CurrentFileName
);
2752 * Check to see if we've exceeded the Wflag (when
2755 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2756 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2759 exit_tcpdump(S_SUCCESS
);
2762 if (dump_info
->CurrentFileName
!= NULL
)
2763 free(dump_info
->CurrentFileName
);
2764 /* Allocate space for max filename + \0. */
2765 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2766 if (dump_info
->CurrentFileName
== NULL
)
2767 error("dump_packet_and_trunc: malloc");
2769 * Gflag was set otherwise we wouldn't be here. Reset the count
2770 * so multiple files would end with 1,2,3 in the filename.
2771 * The counting is handled with the -C flow after this.
2776 * This is always the first file in the Cflag
2778 * We also don't need numbering if Cflag is not set.
2781 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2784 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2786 #ifdef HAVE_LIBCAP_NG
2787 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2788 capng_apply(CAPNG_SELECT_BOTH
);
2789 #endif /* HAVE_LIBCAP_NG */
2790 #ifdef HAVE_CAPSICUM
2791 fd
= openat(dump_info
->dirfd
,
2792 dump_info
->CurrentFileName
,
2793 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2795 error("unable to open file %s",
2796 dump_info
->CurrentFileName
);
2798 fp
= fdopen(fd
, "w");
2800 error("unable to fdopen file %s",
2801 dump_info
->CurrentFileName
);
2803 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2804 #else /* !HAVE_CAPSICUM */
2805 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2807 #ifdef HAVE_LIBCAP_NG
2808 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2809 capng_apply(CAPNG_SELECT_BOTH
);
2810 #endif /* HAVE_LIBCAP_NG */
2811 if (dump_info
->pdd
== NULL
)
2812 error("%s", pcap_geterr(pd
));
2813 #ifdef HAVE_CAPSICUM
2814 set_dumper_capsicum_rights(dump_info
->pdd
);
2820 * XXX - this won't prevent capture files from getting
2821 * larger than Cflag - the last packet written to the
2822 * file could put it over Cflag.
2825 #ifdef HAVE_PCAP_DUMP_FTELL64
2826 int64_t size
= pcap_dump_ftell64(dump_info
->pdd
);
2829 * XXX - this only handles a Cflag value > 2^31-1 on
2830 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2831 * Windows) or LLP64 (64-bit Windows) would require
2832 * a version of libpcap with pcap_dump_ftell64().
2834 long size
= pcap_dump_ftell(dump_info
->pdd
);
2838 error("ftell fails on output file");
2840 #ifdef HAVE_CAPSICUM
2846 * Close the current file and open a new one.
2848 pcap_dump_close(dump_info
->pdd
);
2851 * Compress the file we just closed, if the user
2855 compress_savefile(dump_info
->CurrentFileName
);
2859 if (Cflag_count
>= Wflag
)
2862 if (dump_info
->CurrentFileName
!= NULL
)
2863 free(dump_info
->CurrentFileName
);
2864 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2865 if (dump_info
->CurrentFileName
== NULL
)
2866 error("dump_packet_and_trunc: malloc");
2867 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2868 #ifdef HAVE_LIBCAP_NG
2869 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2870 capng_apply(CAPNG_SELECT_BOTH
);
2871 #endif /* HAVE_LIBCAP_NG */
2872 #ifdef HAVE_CAPSICUM
2873 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2874 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2876 error("unable to open file %s",
2877 dump_info
->CurrentFileName
);
2879 fp
= fdopen(fd
, "w");
2881 error("unable to fdopen file %s",
2882 dump_info
->CurrentFileName
);
2884 dump_info
->pdd
= pcap_dump_fopen(dump_info
->pd
, fp
);
2885 #else /* !HAVE_CAPSICUM */
2886 dump_info
->pdd
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2888 #ifdef HAVE_LIBCAP_NG
2889 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2890 capng_apply(CAPNG_SELECT_BOTH
);
2891 #endif /* HAVE_LIBCAP_NG */
2892 if (dump_info
->pdd
== NULL
)
2893 error("%s", pcap_geterr(pd
));
2894 #ifdef HAVE_CAPSICUM
2895 set_dumper_capsicum_rights(dump_info
->pdd
);
2900 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2901 #ifdef HAVE_PCAP_DUMP_FLUSH
2903 pcap_dump_flush(dump_info
->pdd
);
2906 if (dump_info
->ndo
!= NULL
)
2907 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2915 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2917 struct dump_info
*dump_info
;
2923 dump_info
= (struct dump_info
*)user
;
2925 pcap_dump((u_char
*)dump_info
->pdd
, h
, sp
);
2926 #ifdef HAVE_PCAP_DUMP_FLUSH
2928 pcap_dump_flush(dump_info
->pdd
);
2931 if (dump_info
->ndo
!= NULL
)
2932 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2940 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2946 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2953 #ifdef SIGNAL_REQ_INFO
2955 requestinfo(int signo _U_
)
2964 #ifdef SIGNAL_FLUSH_PCAP
2966 flushpcap(int signo _U_
)
2969 pcap_dump_flush(pdd
);
2974 print_packets_captured (void)
2976 static u_int prev_packets_captured
, first
= 1;
2978 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2979 fprintf(stderr
, "Got %u\r", packets_captured
);
2981 prev_packets_captured
= packets_captured
;
2986 * Called once each second in verbose mode while dumping to file
2989 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
2990 BOOLEAN timer_fired _U_
)
2992 print_packets_captured();
2995 static void verbose_stats_dump(int sig _U_
)
2997 print_packets_captured();
3001 USES_APPLE_DEPRECATED_API
3005 #ifndef HAVE_PCAP_LIB_VERSION
3006 #ifdef HAVE_PCAP_VERSION
3007 extern char pcap_version
[];
3008 #else /* HAVE_PCAP_VERSION */
3009 static char pcap_version
[] = "unknown";
3010 #endif /* HAVE_PCAP_VERSION */
3011 #endif /* HAVE_PCAP_LIB_VERSION */
3012 const char *smi_version_string
;
3014 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
3015 #ifdef HAVE_PCAP_LIB_VERSION
3016 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
3017 #else /* HAVE_PCAP_LIB_VERSION */
3018 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
3019 #endif /* HAVE_PCAP_LIB_VERSION */
3021 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
3022 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
3025 smi_version_string
= nd_smi_version_string();
3026 if (smi_version_string
!= NULL
)
3027 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
3028 #ifdef HAVE_DNET_HTOA
3029 (void)fprintf(stderr
, "libdnet unknown version\n");
3032 #if defined(__SANITIZE_ADDRESS__)
3033 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
3034 #elif defined(__has_feature)
3035 # if __has_feature(address_sanitizer)
3036 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
3038 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
3046 (void)fprintf(stderr
,
3047 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
3048 (void)fprintf(stderr
,
3049 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3050 (void)fprintf(stderr
,
3051 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
3052 #ifdef HAVE_PCAP_FINDALLDEVS_EX
3053 (void)fprintf(stderr
,
3054 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
3056 (void)fprintf(stderr
,
3057 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
3058 (void)fprintf(stderr
,
3059 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
3060 (void)fprintf(stderr
,
3061 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
3062 (void)fprintf(stderr
,
3063 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
3064 (void)fprintf(stderr
,
3065 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");