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
148 #define SIGNAL_REQ_INFO SIGUSR1
151 static int Bflag
; /* buffer size */
152 #ifdef HAVE_PCAP_DUMP_FTELL64
153 static int64_t Cflag
; /* rotate dump files after this many bytes */
155 static long Cflag
; /* rotate dump files after this many bytes */
157 static int Cflag_count
; /* Keep track of which file number we're writing */
158 #ifdef HAVE_PCAP_FINDALLDEVS
159 static int Dflag
; /* list available devices and exit */
161 #ifdef HAVE_PCAP_FINDALLDEVS_EX
162 static char *remote_interfaces_source
; /* list available devices from this source and exit */
166 * This is exported because, in some versions of libpcap, if libpcap
167 * is built with optimizer debugging code (which is *NOT* the default
168 * configuration!), the library *imports*(!) a variable named dflag,
169 * under the expectation that tcpdump is exporting it, to govern
170 * how much debugging information to print when optimizing
171 * the generated BPF code.
173 * This is a horrible hack; newer versions of libpcap don't import
174 * dflag but, instead, *if* built with optimizer debugging code,
175 * *export* a routine to set that flag.
177 int dflag
; /* print filter code */
178 static int Gflag
; /* rotate dump files after this many seconds */
179 static int Gflag_count
; /* number of files created with Gflag rotation */
180 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
181 static int Lflag
; /* list available data link types and exit */
182 static int Iflag
; /* rfmon (monitor) mode */
183 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
184 static int Jflag
; /* list available time stamp types */
186 static int jflag
= -1; /* packet time stamp source */
187 static int pflag
; /* don't go promiscuous */
188 #ifdef HAVE_PCAP_SETDIRECTION
189 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
191 static int Uflag
; /* "unbuffered" output of dump files */
192 static int Wflag
; /* recycle output files after this number of files */
193 static int WflagChars
;
194 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
195 static int immediate_mode
;
197 static int infodelay
;
198 static int infoprint
;
203 cap_channel_t
*capdns
;
207 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
208 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
209 static NORETURN
void exit_tcpdump(int);
210 static void (*setsignal (int sig
, void (*func
)(int)))(int);
211 static void cleanup(int);
212 static void child_cleanup(int);
213 static void print_version(void);
214 static void print_usage(void);
215 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
216 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
217 #ifdef HAVE_PCAP_FINDALLDEVS
218 static NORETURN
void show_devices_and_exit(void);
220 #ifdef HAVE_PCAP_FINDALLDEVS_EX
221 static NORETURN
void show_remote_devices_and_exit(void);
224 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
225 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
226 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
227 static void droproot(const char *, const char *);
229 #ifdef SIGNAL_REQ_INFO
230 void requestinfo(int);
234 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
235 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
237 static void verbose_stats_dump(int sig
);
240 static void info(int);
241 static u_int packets_captured
;
243 #ifdef HAVE_PCAP_FINDALLDEVS
244 static const struct tok status_flags
[] = {
246 { PCAP_IF_UP
, "Up" },
248 #ifdef PCAP_IF_RUNNING
249 { PCAP_IF_RUNNING
, "Running" },
251 { PCAP_IF_LOOPBACK
, "Loopback" },
258 static int supports_monitor_mode
;
266 char *CurrentFileName
;
269 netdissect_options
*ndo
;
275 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
277 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
278 * by any libpcap header, because it's a special hack, only available if
279 * libpcap was configured to include it, and only intended for use by
280 * libpcap developers trying to debug the parser for filter expressions).
283 __declspec(dllimport
)
287 void pcap_set_parser_debug(int);
288 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
290 * We don't have pcap_set_parser_debug() in libpcap, but we do have
291 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
292 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
295 pcap_set_parser_debug(int value
)
297 #ifdef HAVE_PCAP_DEBUG
298 extern int pcap_debug
;
301 #else /* HAVE_PCAP_DEBUG */
305 #endif /* HAVE_PCAP_DEBUG */
308 #define HAVE_PCAP_SET_PARSER_DEBUG
311 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
313 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
314 * by any libpcap header, because it's a special hack, only available if
315 * libpcap was configured to include it, and only intended for use by
316 * libpcap developers trying to debug the optimizer for filter expressions).
319 __declspec(dllimport
)
323 void pcap_set_optimizer_debug(int);
328 error(const char *fmt
, ...)
332 (void)fprintf(stderr
, "%s: ", program_name
);
334 (void)vfprintf(stderr
, fmt
, ap
);
339 (void)fputc('\n', stderr
);
341 exit_tcpdump(S_ERR_HOST_PROGRAM
);
347 warning(const char *fmt
, ...)
351 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
353 (void)vfprintf(stderr
, fmt
, ap
);
358 (void)fputc('\n', stderr
);
363 exit_tcpdump(int status
)
369 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
371 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
374 int *tstamp_types
= 0;
375 const char *tstamp_type_name
;
378 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
379 if (n_tstamp_types
< 0)
380 error("%s", pcap_geterr(pc
));
382 if (n_tstamp_types
== 0) {
383 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
385 exit_tcpdump(S_SUCCESS
);
387 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
389 for (i
= 0; i
< n_tstamp_types
; i
++) {
390 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
391 if (tstamp_type_name
!= NULL
) {
392 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
393 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
395 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
398 pcap_free_tstamp_types(tstamp_types
);
399 exit_tcpdump(S_SUCCESS
);
404 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
408 const char *dlt_name
;
410 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
412 error("%s", pcap_geterr(pc
));
413 else if (n_dlts
== 0 || !dlts
)
414 error("No data link types.");
417 * If the interface is known to support monitor mode, indicate
418 * whether these are the data link types available when not in
419 * monitor mode, if -I wasn't specified, or when in monitor mode,
420 * when -I was specified (the link-layer types available in
421 * monitor mode might be different from the ones available when
422 * not in monitor mode).
424 if (supports_monitor_mode
)
425 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
427 Iflag
? "when in monitor mode" : "when not in monitor mode");
429 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
432 for (i
= 0; i
< n_dlts
; i
++) {
433 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
434 if (dlt_name
!= NULL
) {
435 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
436 pcap_datalink_val_to_description(dlts
[i
]));
439 * OK, does tcpdump handle that type?
441 if (!has_printer(dlts
[i
]))
442 (void) fprintf(stderr
, " (printing not supported)");
443 fprintf(stderr
, "\n");
445 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
449 #ifdef HAVE_PCAP_FREE_DATALINKS
450 pcap_free_datalinks(dlts
);
452 exit_tcpdump(S_SUCCESS
);
455 #ifdef HAVE_PCAP_FINDALLDEVS
457 show_devices_and_exit(void)
459 pcap_if_t
*dev
, *devlist
;
460 char ebuf
[PCAP_ERRBUF_SIZE
];
463 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
465 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
466 printf("%d.%s", i
+1, dev
->name
);
467 if (dev
->description
!= NULL
)
468 printf(" (%s)", dev
->description
);
470 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
473 pcap_freealldevs(devlist
);
474 exit_tcpdump(S_SUCCESS
);
476 #endif /* HAVE_PCAP_FINDALLDEVS */
478 #ifdef HAVE_PCAP_FINDALLDEVS_EX
480 show_remote_devices_and_exit(void)
482 pcap_if_t
*dev
, *devlist
;
483 char ebuf
[PCAP_ERRBUF_SIZE
];
486 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
489 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
490 printf("%d.%s", i
+1, dev
->name
);
491 if (dev
->description
!= NULL
)
492 printf(" (%s)", dev
->description
);
494 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
497 pcap_freealldevs(devlist
);
498 exit_tcpdump(S_SUCCESS
);
500 #endif /* HAVE_PCAP_FINDALLDEVS */
505 * Note that there we use all letters for short options except for g, k,
506 * o, and P, and those are used by other versions of tcpdump, and we should
507 * only use them for the same purposes that the other versions of tcpdump
510 * macOS tcpdump uses -g to force non--v output for IP to be on one
511 * line, making it more "g"repable;
513 * macOS tcpdump uses -k to specify that packet comments in pcapng files
516 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
517 * for hosts sending TCP SYN packets;
519 * macOS tcpdump uses -P to indicate that -w should write pcapng rather
522 * macOS tcpdump also uses -Q to specify expressions that match packet
523 * metadata, including but not limited to the packet direction.
524 * The expression syntax is different from a simple "in|out|inout",
525 * and those expressions aren't accepted by macOS tcpdump, but the
526 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
527 * "inout" = "dir=in or dir=out", and the parser could conceivably
528 * special-case "in", "out", and "inout" as expressions for backwards
529 * compatibility, so all is not (yet) lost.
533 * Set up flags that might or might not be supported depending on the
534 * version of libpcap we're using.
536 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
538 #define B_FLAG_USAGE " [ -B size ]"
539 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
542 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
544 #ifdef HAVE_PCAP_FINDALLDEVS
550 #ifdef HAVE_PCAP_CREATE
552 #else /* HAVE_PCAP_CREATE */
554 #endif /* HAVE_PCAP_CREATE */
556 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
558 #define j_FLAG_USAGE " [ -j tstamptype ]"
560 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
564 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
566 #ifdef HAVE_PCAP_SETDIRECTION
568 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
574 #ifdef HAVE_PCAP_DUMP_FLUSH
580 #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:#"
585 * We do not currently have long options corresponding to all short
586 * options; we should probably pick appropriate option names for them.
588 * However, the short options where the number of times the option is
589 * specified matters, such as -v and -d and -t, should probably not
590 * just map to a long option, as saying
592 * tcpdump --verbose --verbose
594 * doesn't make sense; it should be --verbosity={N} or something such
597 * For long options with no corresponding short options, we define values
598 * outside the range of ASCII graphic characters, make that the last
599 * component of the entry for the long option, and have a case for that
600 * option in the switch statement.
602 #define OPTION_VERSION 128
603 #define OPTION_TSTAMP_PRECISION 129
604 #define OPTION_IMMEDIATE_MODE 130
605 #define OPTION_PRINT 131
606 #define OPTION_LIST_REMOTE_INTERFACES 132
608 static const struct option longopts
[] = {
609 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
610 { "buffer-size", required_argument
, NULL
, 'B' },
612 { "list-interfaces", no_argument
, NULL
, 'D' },
613 #ifdef HAVE_PCAP_FINDALLDEVS_EX
614 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
616 { "help", no_argument
, NULL
, 'h' },
617 { "interface", required_argument
, NULL
, 'i' },
618 #ifdef HAVE_PCAP_CREATE
619 { "monitor-mode", no_argument
, NULL
, 'I' },
621 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
622 { "time-stamp-type", required_argument
, NULL
, 'j' },
623 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
625 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
626 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
628 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
629 { "list-data-link-types", no_argument
, NULL
, 'L' },
630 { "no-optimize", no_argument
, NULL
, 'O' },
631 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
632 #ifdef HAVE_PCAP_SETDIRECTION
633 { "direction", required_argument
, NULL
, 'Q' },
635 { "snapshot-length", required_argument
, NULL
, 's' },
636 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
637 #ifdef HAVE_PCAP_DUMP_FLUSH
638 { "packet-buffered", no_argument
, NULL
, 'U' },
640 { "linktype", required_argument
, NULL
, 'y' },
641 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
642 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
644 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
645 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
647 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
648 { "number", no_argument
, NULL
, '#' },
649 { "print", no_argument
, NULL
, OPTION_PRINT
},
650 { "version", no_argument
, NULL
, OPTION_VERSION
},
654 #ifdef HAVE_PCAP_FINDALLDEVS_EX
655 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
657 #define LIST_REMOTE_INTERFACES_USAGE
660 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
661 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
663 #define IMMEDIATE_MODE_USAGE ""
666 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
667 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
669 #define TIME_STAMP_PRECISION_USAGE
673 /* Drop root privileges and chroot if necessary */
675 droproot(const char *username
, const char *chroot_dir
)
677 struct passwd
*pw
= NULL
;
679 if (chroot_dir
&& !username
) {
680 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
682 exit_tcpdump(S_ERR_HOST_PROGRAM
);
685 pw
= getpwnam(username
);
688 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
689 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
690 program_name
, chroot_dir
, pcap_strerror(errno
));
691 exit_tcpdump(S_ERR_HOST_PROGRAM
);
694 #ifdef HAVE_LIBCAP_NG
696 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
698 fprintf(stderr
, "error : ret %d\n", ret
);
700 fprintf(stderr
, "dropped privs to %s\n", username
);
704 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
705 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
706 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
707 program_name
, username
,
708 (unsigned long)pw
->pw_uid
,
709 (unsigned long)pw
->pw_gid
,
710 pcap_strerror(errno
));
711 exit_tcpdump(S_ERR_HOST_PROGRAM
);
714 fprintf(stderr
, "dropped privs to %s\n", username
);
716 #endif /* HAVE_LIBCAP_NG */
719 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
720 program_name
, username
);
721 exit_tcpdump(S_ERR_HOST_PROGRAM
);
723 #ifdef HAVE_LIBCAP_NG
724 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
725 DIAG_OFF_CLANG(assign
-enum)
728 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
733 DIAG_ON_CLANG(assign
-enum)
734 capng_apply(CAPNG_SELECT_BOTH
);
735 #endif /* HAVE_LIBCAP_NG */
756 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
758 char *filename
= malloc(PATH_MAX
+ 1);
759 if (filename
== NULL
)
760 error("Makefilename: malloc");
762 /* Process with strftime if Gflag is set. */
766 /* Convert Gflag_time to a usable format */
767 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
768 error("MakeTimedFilename: localtime");
771 /* There's no good way to detect an error in strftime since a return
772 * value of 0 isn't necessarily failure.
774 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
776 strncpy(filename
, orig_name
, PATH_MAX
);
779 if (cnt
== 0 && max_chars
== 0)
780 strncpy(buffer
, filename
, PATH_MAX
+ 1);
782 if (nd_snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
783 /* Report an error if the filename is too large */
784 error("too many output files or filename is too long (> %d)", PATH_MAX
);
789 get_next_file(FILE *VFile
, char *ptr
)
793 ret
= fgets(ptr
, PATH_MAX
, VFile
);
797 if (ptr
[strlen(ptr
) - 1] == '\n')
798 ptr
[strlen(ptr
) - 1] = '\0';
804 static cap_channel_t
*
807 cap_channel_t
*capcas
, *capdnsloc
;
808 const char *types
[1];
813 error("unable to create casper process");
814 capdnsloc
= cap_service_open(capcas
, "system.dns");
815 /* Casper capability no longer needed. */
817 if (capdnsloc
== NULL
)
818 error("unable to open system.dns service");
819 /* Limit system.dns to reverse DNS lookups. */
821 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
822 error("unable to limit access to system.dns service");
823 families
[0] = AF_INET
;
824 families
[1] = AF_INET6
;
825 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
826 error("unable to limit access to system.dns service");
830 #endif /* HAVE_CASPER */
832 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
834 tstamp_precision_from_string(const char *precision
)
836 if (strncmp(precision
, "nano", strlen("nano")) == 0)
837 return PCAP_TSTAMP_PRECISION_NANO
;
839 if (strncmp(precision
, "micro", strlen("micro")) == 0)
840 return PCAP_TSTAMP_PRECISION_MICRO
;
846 tstamp_precision_to_string(int precision
)
850 case PCAP_TSTAMP_PRECISION_MICRO
:
853 case PCAP_TSTAMP_PRECISION_NANO
:
864 * Ensure that, on a dump file's descriptor, we have all the rights
865 * necessary to make the standard I/O library work with an fdopen()ed
866 * FILE * from that descriptor.
868 * A long time ago, in a galaxy far far away, AT&T decided that, instead
869 * of providing separate APIs for getting and setting the FD_ flags on a
870 * descriptor, getting and setting the O_ flags on a descriptor, and
871 * locking files, they'd throw them all into a kitchen-sink fcntl() call
872 * along the lines of ioctl(), the fact that ioctl() operations are
873 * largely specific to particular character devices but fcntl() operations
874 * are either generic to all descriptors or generic to all descriptors for
875 * regular files nonwithstanding.
877 * The Capsicum people decided that fine-grained control of descriptor
878 * operations was required, so that you need to grant permission for
879 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
880 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
881 * collection of things, so there are *individual* fcntls for which
882 * permission needs to be granted.
884 * The FreeBSD standard I/O people implemented some optimizations that
885 * requires that the standard I/O routines be able to determine whether
886 * the descriptor for the FILE * is open append-only or not; as that
887 * descriptor could have come from an open() rather than an fopen(),
888 * that requires that it be able to do an F_GETFL fcntl() to read
891 * Tcpdump uses ftell() to determine how much data has been written
892 * to a file in order to, when used with -C, determine when it's time
893 * to rotate capture files. ftell() therefore needs to do an lseek()
894 * to find out the file offset and must, thanks to the aforementioned
895 * optimization, also know whether the descriptor is open append-only
898 * The net result of all the above is that we need to grant CAP_SEEK,
899 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
901 * Perhaps this is the universe's way of saying that either
903 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
904 * using it, so that Capsicum-capable tcpdump wouldn't need to do
909 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
910 * I/O library that knows what rights are needed by the standard
911 * I/O library, based on the open mode, and assigns them, perhaps
912 * with an additional argument indicating, for example, whether
913 * seeking should be allowed, so that tcpdump doesn't need to know
914 * what the standard I/O library happens to require this week.
917 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
919 int fd
= fileno(pcap_dump_file(p
));
922 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
923 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
924 error("unable to limit dump descriptor");
926 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
927 error("unable to limit dump descriptor fcntls");
933 * Copy arg vector into a new buffer, concatenating arguments with spaces.
936 copy_argv(char **argv
)
948 len
+= strlen(*p
++) + 1;
950 buf
= (char *)malloc(len
);
952 error("copy_argv: malloc");
956 while ((src
= *p
++) != NULL
) {
957 while ((*dst
++ = *src
++) != '\0')
967 * On Windows, we need to open the file in binary mode, so that
968 * we get all the bytes specified by the size we get from "fstat()".
969 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
970 * we define it as 0 if it's not defined, so it does nothing.
977 read_infile(char *fname
)
983 fd
= open(fname
, O_RDONLY
|O_BINARY
);
985 error("can't open %s: %s", fname
, pcap_strerror(errno
));
987 if (fstat(fd
, &buf
) < 0)
988 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
990 cp
= malloc((u_int
)buf
.st_size
+ 1);
992 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
993 fname
, pcap_strerror(errno
));
994 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
996 error("read %s: %s", fname
, pcap_strerror(errno
));
997 if (cc
!= buf
.st_size
)
998 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
1001 /* replace "# comment" with spaces */
1002 for (i
= 0; i
< cc
; i
++) {
1004 while (i
< cc
&& cp
[i
] != '\n')
1011 #ifdef HAVE_PCAP_FINDALLDEVS
1013 parse_interface_number(const char *device
)
1018 devnum
= strtol(device
, &end
, 10);
1019 if (device
!= end
&& *end
== '\0') {
1021 * It's all-numeric, but is it a valid number?
1025 * No, it's not an ordinal.
1027 error("Invalid adapter index");
1032 * It's not all-numeric; return -1, so our caller
1040 find_interface_by_number(long devnum
)
1042 pcap_if_t
*dev
, *devlist
;
1044 char ebuf
[PCAP_ERRBUF_SIZE
];
1047 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
1050 * Look for the devnum-th entry in the list of devices (1-based).
1052 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1053 i
++, dev
= dev
->next
)
1056 error("Invalid adapter index");
1057 device
= strdup(dev
->name
);
1058 pcap_freealldevs(devlist
);
1063 #ifdef HAVE_PCAP_OPEN
1065 * Prefix for rpcap URLs.
1067 static char rpcap_prefix
[] = "rpcap://";
1071 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1074 #ifdef HAVE_PCAP_CREATE
1079 #ifdef HAVE_PCAP_OPEN
1081 * Is this an rpcap URL?
1083 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1085 * Yes. Open it with pcap_open().
1088 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1089 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1093 * If this failed with "No such device", that means
1094 * the interface doesn't exist; return NULL, so that
1095 * the caller can see whether the device name is
1096 * actually an interface index.
1098 if (strstr(ebuf
, "No such device") != NULL
)
1103 warning("%s", ebuf
);
1106 #endif /* HAVE_PCAP_OPEN */
1108 #ifdef HAVE_PCAP_CREATE
1109 pc
= pcap_create(device
, ebuf
);
1112 * If this failed with "No such device", that means
1113 * the interface doesn't exist; return NULL, so that
1114 * the caller can see whether the device name is
1115 * actually an interface index.
1117 if (strstr(ebuf
, "No such device") != NULL
)
1121 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1123 show_tstamp_types_and_exit(pc
, device
);
1125 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1126 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1128 error("%s: Can't set %ssecond time stamp precision: %s",
1130 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1131 pcap_statustostr(status
));
1134 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1135 if (immediate_mode
) {
1136 status
= pcap_set_immediate_mode(pc
, 1);
1138 error("%s: Can't set immediate mode: %s",
1140 pcap_statustostr(status
));
1144 * Is this an interface that supports monitor mode?
1146 if (pcap_can_set_rfmon(pc
) == 1)
1147 supports_monitor_mode
= 1;
1149 supports_monitor_mode
= 0;
1150 if (ndo
->ndo_snaplen
!= 0) {
1152 * A snapshot length was explicitly specified;
1155 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1157 error("%s: Can't set snapshot length: %s",
1158 device
, pcap_statustostr(status
));
1160 status
= pcap_set_promisc(pc
, !pflag
);
1162 error("%s: Can't set promiscuous mode: %s",
1163 device
, pcap_statustostr(status
));
1165 status
= pcap_set_rfmon(pc
, 1);
1167 error("%s: Can't set monitor mode: %s",
1168 device
, pcap_statustostr(status
));
1170 status
= pcap_set_timeout(pc
, 1000);
1172 error("%s: pcap_set_timeout failed: %s",
1173 device
, pcap_statustostr(status
));
1175 status
= pcap_set_buffer_size(pc
, Bflag
);
1177 error("%s: Can't set buffer size: %s",
1178 device
, pcap_statustostr(status
));
1180 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1182 status
= pcap_set_tstamp_type(pc
, jflag
);
1184 error("%s: Can't set time stamp type: %s",
1185 device
, pcap_statustostr(status
));
1188 status
= pcap_activate(pc
);
1191 * pcap_activate() failed.
1193 cp
= pcap_geterr(pc
);
1194 if (status
== PCAP_ERROR
)
1196 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1198 * Return an error for our caller to handle.
1200 nd_snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1201 device
, pcap_statustostr(status
), cp
);
1204 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1205 error("%s: %s\n(%s)", device
,
1206 pcap_statustostr(status
), cp
);
1208 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1209 strncmp(device
, "wlan", 4) == 0) {
1210 char parent
[8], newdev
[8];
1212 size_t s
= sizeof(parent
);
1214 nd_snprintf(sysctl
, sizeof(sysctl
),
1215 "net.wlan.%d.%%parent", atoi(device
+ 4));
1216 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1217 strlcpy(newdev
, device
, sizeof(newdev
));
1218 /* Suggest a new wlan device. */
1219 /* FIXME: incrementing the index this way is not going to work well
1220 * when the index is 9 or greater but the only consequence in this
1221 * specific case would be an error message that looks a bit odd.
1223 newdev
[strlen(newdev
)-1]++;
1224 error("%s is not a monitor mode VAP\n"
1225 "To create a new monitor mode VAP use:\n"
1226 " ifconfig %s create wlandev %s wlanmode monitor\n"
1227 "and use %s as the tcpdump interface",
1228 device
, newdev
, parent
, newdev
);
1232 error("%s: %s", device
,
1233 pcap_statustostr(status
));
1234 } else if (status
> 0) {
1236 * pcap_activate() succeeded, but it's warning us
1237 * of a problem it had.
1239 cp
= pcap_geterr(pc
);
1240 if (status
== PCAP_WARNING
)
1242 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1244 warning("%s: %s\n(%s)", device
,
1245 pcap_statustostr(status
), cp
);
1247 warning("%s: %s", device
,
1248 pcap_statustostr(status
));
1250 #ifdef HAVE_PCAP_SETDIRECTION
1252 status
= pcap_setdirection(pc
, Qflag
);
1254 error("%s: pcap_setdirection() failed: %s",
1255 device
, pcap_geterr(pc
));
1257 #endif /* HAVE_PCAP_SETDIRECTION */
1258 #else /* HAVE_PCAP_CREATE */
1261 * If no snapshot length was specified, or a length of 0 was
1262 * specified, default to 256KB.
1264 if (ndo
->ndo_snaplen
== 0)
1265 ndo
->ndo_snaplen
= 262144;
1266 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1269 * If this failed with "No such device", that means
1270 * the interface doesn't exist; return NULL, so that
1271 * the caller can see whether the device name is
1272 * actually an interface index.
1274 if (strstr(ebuf
, "No such device") != NULL
)
1279 warning("%s", ebuf
);
1280 #endif /* HAVE_PCAP_CREATE */
1286 main(int argc
, char **argv
)
1289 bpf_u_int32 localnet
= 0, netmask
= 0;
1290 int timezone_offset
= 0;
1291 char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1293 pcap_handler callback
;
1295 const char *dlt_name
;
1296 struct bpf_program fcode
;
1298 void (*oldhandler
)(int);
1300 struct dump_info dumpinfo
;
1301 u_char
*pcap_userdata
;
1302 char ebuf
[PCAP_ERRBUF_SIZE
];
1303 char VFileLine
[PATH_MAX
+ 1];
1304 char *username
= NULL
;
1305 char *chroot_dir
= NULL
;
1308 #ifdef HAVE_PCAP_FINDALLDEVS
1314 #ifdef HAVE_CAPSICUM
1315 cap_rights_t rights
;
1317 #endif /* HAVE_CAPSICUM */
1318 int Oflag
= 1; /* run filter code optimizer */
1320 const char *yflag_dlt_name
= NULL
;
1323 netdissect_options Ndo
;
1324 netdissect_options
*ndo
= &Ndo
;
1327 * Initialize the netdissect code.
1329 if (nd_init(ebuf
, sizeof(ebuf
)) == -1)
1332 memset(ndo
, 0, sizeof(*ndo
));
1333 ndo_set_function_pointers(ndo
);
1343 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1344 ndo
->program_name
= program_name
= cp
+ 1;
1346 ndo
->program_name
= program_name
= argv
[0];
1348 #if defined(HAVE_PCAP_WSOCKINIT)
1349 if (pcap_wsockinit() != 0)
1350 error("Attempting to initialize Winsock failed");
1351 #elif defined(HAVE_WSOCKINIT)
1352 if (wsockinit() != 0)
1353 error("Attempting to initialize Winsock failed");
1357 * On platforms where the CPU doesn't support unaligned loads,
1358 * force unaligned accesses to abort with SIGBUS, rather than
1359 * being fixed up (slowly) by the OS kernel; on those platforms,
1360 * misaligned accesses are bugs, and we want tcpdump to crash so
1361 * that the bugs are reported.
1363 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1367 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1371 /* compatibility for old -a */
1382 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1384 Bflag
= atoi(optarg
)*1024;
1386 error("invalid packet buffer size %s", optarg
);
1388 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1393 error("invalid packet count %s", optarg
);
1398 #ifdef HAVE_PCAP_DUMP_FTELL64
1399 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1401 Cflag
= strtol(optarg
, &endp
, 10);
1403 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1405 error("invalid file size %s", optarg
);
1407 * Will multiplying it by 1000000 overflow?
1409 #ifdef HAVE_PCAP_DUMP_FTELL64
1410 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1412 if (Cflag
> LONG_MAX
/ 1000000)
1414 error("file size %s is too large", optarg
);
1422 #ifdef HAVE_PCAP_FINDALLDEVS
1428 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1429 case OPTION_LIST_REMOTE_INTERFACES
:
1430 remote_interfaces_source
= optarg
;
1443 #ifndef HAVE_LIBCRYPTO
1444 warning("crypto code not compiled in");
1446 ndo
->ndo_espsecret
= optarg
;
1458 Gflag
= atoi(optarg
);
1460 error("invalid number of seconds %s", optarg
);
1462 /* We will create one file initially. */
1465 /* Grab the current time for rotation use. */
1466 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1467 error("main: can't get current time: %s",
1468 pcap_strerror(errno
));
1474 exit_tcpdump(S_SUCCESS
);
1485 #ifdef HAVE_PCAP_CREATE
1489 #endif /* HAVE_PCAP_CREATE */
1491 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1493 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1495 error("invalid time stamp type %s", optarg
);
1506 * _IOLBF is the same as _IOFBF in Microsoft's C
1507 * libraries; the only alternative they offer
1510 * XXX - this should really be checking for MSVC++,
1511 * not _WIN32, if, for example, MinGW has its own
1512 * C library that is more UNIX-compatible.
1514 setvbuf(stdout
, NULL
, _IONBF
, 0);
1516 #ifdef HAVE_SETLINEBUF
1519 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1529 if (nd_have_smi_support()) {
1530 if (nd_load_smi_module(optarg
, ebuf
, sizeof(ebuf
)) == -1)
1533 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1534 program_name
, optarg
);
1535 (void)fprintf(stderr
, "(no libsmi support)\n");
1540 /* TCP-MD5 shared secret */
1541 #ifndef HAVE_LIBCRYPTO
1542 warning("crypto code not compiled in");
1544 ndo
->ndo_sigsecret
= optarg
;
1565 ++ndo
->ndo_suppress_default_print
;
1568 #ifdef HAVE_PCAP_SETDIRECTION
1570 if (ascii_strcasecmp(optarg
, "in") == 0)
1572 else if (ascii_strcasecmp(optarg
, "out") == 0)
1574 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1575 Qflag
= PCAP_D_INOUT
;
1577 error("unknown capture direction `%s'", optarg
);
1579 #endif /* HAVE_PCAP_SETDIRECTION */
1586 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1587 if (optarg
== end
|| *end
!= '\0'
1588 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1589 error("invalid snaplen %s", optarg
);
1601 if (ascii_strcasecmp(optarg
, "vat") == 0)
1602 ndo
->ndo_packettype
= PT_VAT
;
1603 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1604 ndo
->ndo_packettype
= PT_WB
;
1605 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1606 ndo
->ndo_packettype
= PT_RPC
;
1607 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1608 ndo
->ndo_packettype
= PT_RTP
;
1609 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1610 ndo
->ndo_packettype
= PT_RTCP
;
1611 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1612 ndo
->ndo_packettype
= PT_SNMP
;
1613 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1614 ndo
->ndo_packettype
= PT_CNFP
;
1615 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1616 ndo
->ndo_packettype
= PT_TFTP
;
1617 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1618 ndo
->ndo_packettype
= PT_AODV
;
1619 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1620 ndo
->ndo_packettype
= PT_CARP
;
1621 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1622 ndo
->ndo_packettype
= PT_RADIUS
;
1623 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1624 ndo
->ndo_packettype
= PT_ZMTP1
;
1625 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1626 ndo
->ndo_packettype
= PT_VXLAN
;
1627 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1628 ndo
->ndo_packettype
= PT_PGM
;
1629 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1630 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1631 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1632 ndo
->ndo_packettype
= PT_LMP
;
1633 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1634 ndo
->ndo_packettype
= PT_RESP
;
1636 error("unknown packet type `%s'", optarg
);
1643 #ifdef HAVE_PCAP_DUMP_FLUSH
1662 Wflag
= atoi(optarg
);
1664 error("invalid number of output files %s", optarg
);
1665 WflagChars
= getWflagChars(Wflag
);
1670 ++ndo
->ndo_suppress_default_print
;
1675 ++ndo
->ndo_suppress_default_print
;
1679 yflag_dlt_name
= optarg
;
1681 pcap_datalink_name_to_val(yflag_dlt_name
);
1683 error("invalid data link type %s", yflag_dlt_name
);
1686 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1689 /* Undocumented flag */
1690 pcap_set_parser_debug(1);
1703 ndo
->ndo_packet_number
= 1;
1706 case OPTION_VERSION
:
1708 exit_tcpdump(S_SUCCESS
);
1711 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1712 case OPTION_TSTAMP_PRECISION
:
1713 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1714 if (ndo
->ndo_tstamp_precision
< 0)
1715 error("unsupported time stamp precision");
1719 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1720 case OPTION_IMMEDIATE_MODE
:
1731 exit_tcpdump(S_ERR_HOST_PROGRAM
);
1735 #ifdef HAVE_PCAP_FINDALLDEVS
1737 show_devices_and_exit();
1739 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1740 if (remote_interfaces_source
!= NULL
)
1741 show_remote_devices_and_exit();
1744 switch (ndo
->ndo_tflag
) {
1746 case 0: /* Default */
1747 case 4: /* Default + Date*/
1748 timezone_offset
= gmt2local(0);
1751 case 1: /* No time stamp */
1752 case 2: /* Unix timeval style */
1753 case 3: /* Microseconds since previous packet */
1754 case 5: /* Microseconds since first packet */
1757 default: /* Not supported */
1758 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1762 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1763 error("-f can not be used with -V or -r");
1765 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1766 error("-V and -r are mutually exclusive.");
1768 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1770 * If we're printing dissected packets to the standard output
1771 * and the standard output is a terminal, use immediate mode,
1772 * as the user's probably expecting to see packets pop up
1775 * XXX - set the timeout to a lower value, instead? If so,
1776 * what value would be appropriate?
1778 if ((WFileName
== NULL
|| print
) && isatty(1))
1783 /* if run as root, prepare for chrooting */
1784 if (getuid() == 0 || geteuid() == 0) {
1785 /* future extensibility for cmd-line arguments */
1787 chroot_dir
= WITH_CHROOT
;
1792 /* if run as root, prepare for dropping root privileges */
1793 if (getuid() == 0 || geteuid() == 0) {
1794 /* Run with '-Z root' to restore old behaviour */
1796 username
= WITH_USER
;
1800 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1802 * If RFileName is non-null, it's the pathname of a
1803 * savefile to read. If VFileName is non-null, it's
1804 * the pathname of a file containing a list of pathnames
1805 * (one per line) of savefiles to read.
1807 * In either case, we're reading a savefile, not doing
1812 * We don't need network access, so relinquish any set-UID
1813 * or set-GID privileges we have (if any).
1815 * We do *not* want set-UID privileges when opening a
1816 * trace file, as that might let the user read other
1817 * people's trace files (especially if we're set-UID
1820 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1821 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1823 if (VFileName
!= NULL
) {
1824 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1827 VFile
= fopen(VFileName
, "r");
1830 error("Unable to open file: %s\n", pcap_strerror(errno
));
1832 ret
= get_next_file(VFile
, VFileLine
);
1834 error("Nothing in %s\n", VFileName
);
1835 RFileName
= VFileLine
;
1838 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1839 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1840 ndo
->ndo_tstamp_precision
, ebuf
);
1842 pd
= pcap_open_offline(RFileName
, ebuf
);
1847 #ifdef HAVE_CAPSICUM
1848 cap_rights_init(&rights
, CAP_READ
);
1849 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1851 error("unable to limit pcap descriptor");
1854 dlt
= pcap_datalink(pd
);
1855 dlt_name
= pcap_datalink_val_to_name(dlt
);
1856 if (dlt_name
== NULL
) {
1857 fprintf(stderr
, "reading from file %s, link-type %u\n",
1861 "reading from file %s, link-type %s (%s)\n",
1862 RFileName
, dlt_name
,
1863 pcap_datalink_val_to_description(dlt
));
1867 * We're doing a live capture.
1869 if (device
== NULL
) {
1871 * No interface was specified. Pick one.
1873 #ifdef HAVE_PCAP_FINDALLDEVS
1875 * Find the list of interfaces, and pick
1876 * the first interface.
1878 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
1880 if (devlist
== NULL
)
1881 error("no interfaces available for capture");
1882 device
= strdup(devlist
->name
);
1883 pcap_freealldevs(devlist
);
1884 #else /* HAVE_PCAP_FINDALLDEVS */
1886 * Use whatever interface pcap_lookupdev()
1889 device
= pcap_lookupdev(ebuf
);
1896 * Try to open the interface with the specified name.
1898 pd
= open_interface(device
, ndo
, ebuf
);
1901 * That failed. If we can get a list of
1902 * interfaces, and the interface name
1903 * is purely numeric, try to use it as
1904 * a 1-based index in the list of
1907 #ifdef HAVE_PCAP_FINDALLDEVS
1908 devnum
= parse_interface_number(device
);
1911 * It's not a number; just report
1912 * the open error and fail.
1918 * OK, it's a number; try to find the
1919 * interface with that index, and try
1922 * find_interface_by_number() exits if it
1923 * couldn't be found.
1925 device
= find_interface_by_number(devnum
);
1926 pd
= open_interface(device
, ndo
, ebuf
);
1929 #else /* HAVE_PCAP_FINDALLDEVS */
1931 * We can't get a list of interfaces; just
1935 #endif /* HAVE_PCAP_FINDALLDEVS */
1939 * Let user own process after capture device has
1943 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1944 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1946 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1948 if(pcap_setbuff(pd
, Bflag
)==-1){
1949 error("%s", pcap_geterr(pd
));
1951 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1953 show_dlts_and_exit(pd
, device
);
1954 if (yflag_dlt
>= 0) {
1955 #ifdef HAVE_PCAP_SET_DATALINK
1956 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1957 error("%s", pcap_geterr(pd
));
1960 * We don't actually support changing the
1961 * data link type, so we only let them
1962 * set it to what it already is.
1964 if (yflag_dlt
!= pcap_datalink(pd
)) {
1965 error("%s is not one of the DLTs supported by this device\n",
1969 (void)fprintf(stderr
, "%s: data link type %s\n",
1970 program_name
, yflag_dlt_name
);
1971 (void)fflush(stderr
);
1973 i
= pcap_snapshot(pd
);
1974 if (ndo
->ndo_snaplen
< i
) {
1975 if (ndo
->ndo_snaplen
!= 0)
1976 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1977 ndo
->ndo_snaplen
= i
;
1978 } else if (ndo
->ndo_snaplen
> i
) {
1979 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
1980 ndo
->ndo_snaplen
= i
;
1982 if(ndo
->ndo_fflag
!= 0) {
1983 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1984 warning("foreign (-f) flag used but: %s", ebuf
);
1990 cmdbuf
= read_infile(infile
);
1992 cmdbuf
= copy_argv(&argv
[optind
]);
1994 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1995 pcap_set_optimizer_debug(dflag
);
1997 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1998 error("%s", pcap_geterr(pd
));
2000 bpf_dump(&fcode
, dflag
);
2003 pcap_freecode(&fcode
);
2004 exit_tcpdump(S_SUCCESS
);
2008 if (!ndo
->ndo_nflag
)
2009 capdns
= capdns_setup();
2010 #endif /* HAVE_CASPER */
2012 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2015 (void)setsignal(SIGPIPE
, cleanup
);
2016 (void)setsignal(SIGTERM
, cleanup
);
2018 (void)setsignal(SIGINT
, cleanup
);
2019 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2020 (void)setsignal(SIGCHLD
, child_cleanup
);
2022 /* Cooperate with nohup(1) */
2024 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2025 (void)setsignal(SIGHUP
, oldhandler
);
2030 * If a user name was specified with "-Z", attempt to switch to
2031 * that user's UID. This would probably be used with sudo,
2032 * to allow tcpdump to be run in a special restricted
2033 * account (if you just want to allow users to open capture
2034 * devices, and can't just give users that permission,
2035 * you'd make tcpdump set-UID or set-GID).
2037 * Tcpdump doesn't necessarily write only to one savefile;
2038 * the general only way to allow a -Z instance to write to
2039 * savefiles as the user under whose UID it's run, rather
2040 * than as the user specified with -Z, would thus be to switch
2041 * to the original user ID before opening a capture file and
2042 * then switch back to the -Z user ID after opening the savefile.
2043 * Switching to the -Z user ID only after opening the first
2044 * savefile doesn't handle the general case.
2047 if (getuid() == 0 || geteuid() == 0) {
2048 #ifdef HAVE_LIBCAP_NG
2049 /* Initialize capng */
2050 capng_clear(CAPNG_SELECT_BOTH
);
2052 DIAG_OFF_CLANG(assign
-enum)
2055 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2059 DIAG_ON_CLANG(assign
-enum)
2062 DIAG_OFF_CLANG(assign
-enum)
2065 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2068 DIAG_ON_CLANG(assign
-enum)
2072 DIAG_OFF_CLANG(assign
-enum)
2075 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2078 DIAG_ON_CLANG(assign
-enum)
2080 capng_apply(CAPNG_SELECT_BOTH
);
2081 #endif /* HAVE_LIBCAP_NG */
2082 if (username
|| chroot_dir
)
2083 droproot(username
, chroot_dir
);
2088 if (pcap_setfilter(pd
, &fcode
) < 0)
2089 error("%s", pcap_geterr(pd
));
2090 #ifdef HAVE_CAPSICUM
2091 if (RFileName
== NULL
&& VFileName
== NULL
) {
2092 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2095 * The various libpcap devices use a combination of
2096 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2097 * so we add the relevant access rights.
2099 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2100 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2102 error("unable to limit pcap descriptor");
2104 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2105 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2106 error("unable to limit ioctls on pcap descriptor");
2112 /* Do not exceed the default PATH_MAX for files. */
2113 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2115 if (dumpinfo
.CurrentFileName
== NULL
)
2116 error("malloc of dumpinfo.CurrentFileName");
2118 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2120 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2122 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2124 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2125 #ifdef HAVE_LIBCAP_NG
2126 /* Give up CAP_DAC_OVERRIDE capability.
2127 * Only allow it to be restored if the -C or -G flag have been
2128 * set since we may need to create more files later on.
2132 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2136 capng_apply(CAPNG_SELECT_BOTH
);
2137 #endif /* HAVE_LIBCAP_NG */
2139 error("%s", pcap_geterr(pd
));
2140 #ifdef HAVE_CAPSICUM
2141 set_dumper_capsicum_rights(p
);
2143 if (Cflag
!= 0 || Gflag
!= 0) {
2144 #ifdef HAVE_CAPSICUM
2145 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2146 if (dumpinfo
.WFileName
== NULL
) {
2147 error("Unable to allocate memory for file %s",
2150 dumpinfo
.dirfd
= open(dirname(WFileName
),
2151 O_DIRECTORY
| O_RDONLY
);
2152 if (dumpinfo
.dirfd
< 0) {
2153 error("unable to open directory %s",
2154 dirname(WFileName
));
2156 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2157 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2158 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2160 error("unable to limit directory rights");
2162 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2164 error("unable to limit dump descriptor fcntls");
2166 #else /* !HAVE_CAPSICUM */
2167 dumpinfo
.WFileName
= WFileName
;
2169 callback
= dump_packet_and_trunc
;
2172 pcap_userdata
= (u_char
*)&dumpinfo
;
2174 callback
= dump_packet
;
2175 dumpinfo
.WFileName
= WFileName
;
2178 pcap_userdata
= (u_char
*)&dumpinfo
;
2181 dlt
= pcap_datalink(pd
);
2182 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2185 dumpinfo
.ndo
= NULL
;
2187 #ifdef HAVE_PCAP_DUMP_FLUSH
2192 dlt
= pcap_datalink(pd
);
2193 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2194 callback
= print_packet
;
2195 pcap_userdata
= (u_char
*)ndo
;
2198 #ifdef SIGNAL_REQ_INFO
2200 * We can't get statistics when reading from a file rather
2201 * than capturing from a device.
2203 if (RFileName
== NULL
)
2204 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2207 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2209 * When capturing to a file, if "--print" wasn't specified,
2210 *"-v" means tcpdump should, once per second,
2211 * "v"erbosely report the number of packets captured.
2215 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2217 * suggests that this dates back to W2K.
2219 * I don't know what a "long wait" is, but we'll assume
2220 * that printing the stats could be a "long wait".
2222 CreateTimerQueueTimer(&timer_handle
, NULL
,
2223 verbose_stats_dump
, NULL
, 1000, 1000,
2224 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2225 setvbuf(stderr
, NULL
, _IONBF
, 0);
2228 * Assume this is UN*X, and that it has setitimer(); that
2229 * dates back to UNIX 95.
2231 struct itimerval timer
;
2232 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2233 timer
.it_interval
.tv_sec
= 1;
2234 timer
.it_interval
.tv_usec
= 0;
2235 timer
.it_value
.tv_sec
= 1;
2236 timer
.it_value
.tv_usec
= 1;
2237 setitimer(ITIMER_REAL
, &timer
, NULL
);
2241 if (RFileName
== NULL
) {
2243 * Live capture (if -V was specified, we set RFileName
2244 * to a file from the -V file). Print a message to
2245 * the standard error on UN*X.
2247 if (!ndo
->ndo_vflag
&& !WFileName
) {
2248 (void)fprintf(stderr
,
2249 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2252 (void)fprintf(stderr
, "%s: ", program_name
);
2253 dlt
= pcap_datalink(pd
);
2254 dlt_name
= pcap_datalink_val_to_name(dlt
);
2255 if (dlt_name
== NULL
) {
2256 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2257 device
, dlt
, ndo
->ndo_snaplen
);
2259 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2261 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2263 (void)fflush(stderr
);
2266 #ifdef HAVE_CAPSICUM
2267 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2269 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2271 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2272 #endif /* HAVE_CASPER */
2273 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2274 error("unable to enter the capability mode");
2275 #endif /* HAVE_CAPSICUM */
2278 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2279 if (WFileName
== NULL
) {
2281 * We're printing packets. Flush the printed output,
2282 * so it doesn't get intermingled with error output.
2286 * We got interrupted, so perhaps we didn't
2287 * manage to finish a line we were printing.
2288 * Print an extra newline, just in case.
2292 (void)fflush(stdout
);
2296 * We got interrupted. If we are reading multiple
2297 * files (via -V) set these so that we stop.
2306 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2307 program_name
, pcap_geterr(pd
));
2309 if (RFileName
== NULL
) {
2311 * We're doing a live capture. Report the capture
2317 if (VFileName
!= NULL
) {
2318 ret
= get_next_file(VFile
, VFileLine
);
2322 RFileName
= VFileLine
;
2323 pd
= pcap_open_offline(RFileName
, ebuf
);
2326 #ifdef HAVE_CAPSICUM
2327 cap_rights_init(&rights
, CAP_READ
);
2328 if (cap_rights_limit(fileno(pcap_file(pd
)),
2329 &rights
) < 0 && errno
!= ENOSYS
) {
2330 error("unable to limit pcap descriptor");
2333 new_dlt
= pcap_datalink(pd
);
2334 if (new_dlt
!= dlt
) {
2336 * The new file has a different
2337 * link-layer header type from the
2340 if (WFileName
!= NULL
) {
2342 * We're writing raw packets
2343 * that match the filter to
2344 * a pcap file. pcap files
2345 * don't support multiple
2346 * different link-layer
2347 * header types, so we fail
2350 error("%s: new dlt does not match original", RFileName
);
2354 * We're printing the decoded packets;
2355 * switch to the new DLT.
2357 * To do that, we need to change
2358 * the printer, change the DLT name,
2359 * and recompile the filter with
2363 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2364 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2365 error("%s", pcap_geterr(pd
));
2369 * Set the filter on the new file.
2371 if (pcap_setfilter(pd
, &fcode
) < 0)
2372 error("%s", pcap_geterr(pd
));
2375 * Report the new file.
2377 dlt_name
= pcap_datalink_val_to_name(dlt
);
2378 if (dlt_name
== NULL
) {
2379 fprintf(stderr
, "reading from file %s, link-type %u\n",
2383 "reading from file %s, link-type %s (%s)\n",
2384 RFileName
, dlt_name
,
2385 pcap_datalink_val_to_description(dlt
));
2390 while (ret
!= NULL
);
2393 pcap_freecode(&fcode
);
2394 exit_tcpdump(status
== -1 ? 1 : 0);
2401 (*setsignal (int sig
, void (*func
)(int)))(int)
2404 return (signal(sig
, func
));
2406 struct sigaction old
, new;
2408 memset(&new, 0, sizeof(new));
2409 new.sa_handler
= func
;
2411 new.sa_flags
= SA_RESTART
;
2412 if (sigaction(sig
, &new, &old
) < 0)
2414 return (old
.sa_handler
);
2418 /* make a clean exit on interrupts */
2420 cleanup(int signo _U_
)
2423 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2424 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2425 CloseHandle(timer_handle
);
2426 timer_handle
= INVALID_HANDLE_VALUE
;
2429 struct itimerval timer
;
2431 timer
.it_interval
.tv_sec
= 0;
2432 timer
.it_interval
.tv_usec
= 0;
2433 timer
.it_value
.tv_sec
= 0;
2434 timer
.it_value
.tv_usec
= 0;
2435 setitimer(ITIMER_REAL
, &timer
, NULL
);
2438 #ifdef HAVE_PCAP_BREAKLOOP
2440 * We have "pcap_breakloop()"; use it, so that we do as little
2441 * as possible in the signal handler (it's probably not safe
2442 * to do anything with standard I/O streams in a signal handler -
2443 * the ANSI C standard doesn't say it is).
2448 * We don't have "pcap_breakloop()"; this isn't safe, but
2449 * it's the best we can do. Print the summary if we're
2450 * not reading from a savefile - i.e., if we're doing a
2451 * live capture - and exit.
2453 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2455 * We got interrupted, so perhaps we didn't
2456 * manage to finish a line we were printing.
2457 * Print an extra newline, just in case.
2460 (void)fflush(stdout
);
2463 exit_tcpdump(S_SUCCESS
);
2468 On windows, we do not use a fork, so we do not care less about
2469 waiting a child processes to die
2471 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2473 child_cleanup(int signo _U_
)
2477 #endif /* HAVE_FORK && HAVE_VFORK */
2482 struct pcap_stat stats
;
2485 * Older versions of libpcap didn't set ps_ifdrop on some
2486 * platforms; initialize it to 0 to handle that.
2488 stats
.ps_ifdrop
= 0;
2489 if (pcap_stats(pd
, &stats
) < 0) {
2490 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2496 fprintf(stderr
, "%s: ", program_name
);
2498 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2499 PLURAL_SUFFIX(packets_captured
));
2501 fputs(", ", stderr
);
2504 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2505 PLURAL_SUFFIX(stats
.ps_recv
));
2507 fputs(", ", stderr
);
2510 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2511 PLURAL_SUFFIX(stats
.ps_drop
));
2512 if (stats
.ps_ifdrop
!= 0) {
2514 fputs(", ", stderr
);
2517 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2518 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2524 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2526 #define fork_subprocess() fork()
2528 #define fork_subprocess() vfork()
2531 compress_savefile(const char *filename
)
2535 child
= fork_subprocess();
2538 "compress_savefile: fork failed: %s\n",
2539 pcap_strerror(errno
));
2543 /* Parent process. */
2549 * Set to lowest priority so that this doesn't disturb the capture.
2552 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2554 setpriority(PRIO_PROCESS
, 0, 19);
2556 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2558 "compress_savefile: execlp(%s, %s) failed: %s\n",
2561 pcap_strerror(errno
));
2563 exit(S_ERR_HOST_PROGRAM
);
2565 _exit(S_ERR_HOST_PROGRAM
);
2568 #else /* HAVE_FORK && HAVE_VFORK */
2570 compress_savefile(const char *filename
)
2573 "compress_savefile failed. Functionality not implemented under your system\n");
2575 #endif /* HAVE_FORK && HAVE_VFORK */
2578 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2580 struct dump_info
*dump_info
;
2586 dump_info
= (struct dump_info
*)user
;
2589 * XXX - this won't force the file to rotate on the specified time
2590 * boundary, but it will rotate on the first packet received after the
2591 * specified Gflag number of seconds. Note: if a Gflag time boundary
2592 * and a Cflag size boundary coincide, the time rotation will occur
2593 * first thereby cancelling the Cflag boundary (since the file should
2597 /* Check if it is time to rotate */
2600 /* Get the current time */
2601 if ((t
= time(NULL
)) == (time_t)-1) {
2602 error("dump_and_trunc_packet: can't get current_time: %s",
2603 pcap_strerror(errno
));
2607 /* If the time is greater than the specified window, rotate */
2608 if (t
- Gflag_time
>= Gflag
) {
2609 #ifdef HAVE_CAPSICUM
2614 /* Update the Gflag_time */
2616 /* Update Gflag_count */
2619 * Close the current file and open a new one.
2621 pcap_dump_close(dump_info
->p
);
2624 * Compress the file we just closed, if the user asked for it
2627 compress_savefile(dump_info
->CurrentFileName
);
2630 * Check to see if we've exceeded the Wflag (when
2633 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2634 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2637 exit_tcpdump(S_SUCCESS
);
2640 if (dump_info
->CurrentFileName
!= NULL
)
2641 free(dump_info
->CurrentFileName
);
2642 /* Allocate space for max filename + \0. */
2643 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2644 if (dump_info
->CurrentFileName
== NULL
)
2645 error("dump_packet_and_trunc: malloc");
2647 * Gflag was set otherwise we wouldn't be here. Reset the count
2648 * so multiple files would end with 1,2,3 in the filename.
2649 * The counting is handled with the -C flow after this.
2654 * This is always the first file in the Cflag
2656 * We also don't need numbering if Cflag is not set.
2659 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2662 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2664 #ifdef HAVE_LIBCAP_NG
2665 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2666 capng_apply(CAPNG_SELECT_BOTH
);
2667 #endif /* HAVE_LIBCAP_NG */
2668 #ifdef HAVE_CAPSICUM
2669 fd
= openat(dump_info
->dirfd
,
2670 dump_info
->CurrentFileName
,
2671 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2673 error("unable to open file %s",
2674 dump_info
->CurrentFileName
);
2676 fp
= fdopen(fd
, "w");
2678 error("unable to fdopen file %s",
2679 dump_info
->CurrentFileName
);
2681 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2682 #else /* !HAVE_CAPSICUM */
2683 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2685 #ifdef HAVE_LIBCAP_NG
2686 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2687 capng_apply(CAPNG_SELECT_BOTH
);
2688 #endif /* HAVE_LIBCAP_NG */
2689 if (dump_info
->p
== NULL
)
2690 error("%s", pcap_geterr(pd
));
2691 #ifdef HAVE_CAPSICUM
2692 set_dumper_capsicum_rights(dump_info
->p
);
2698 * XXX - this won't prevent capture files from getting
2699 * larger than Cflag - the last packet written to the
2700 * file could put it over Cflag.
2703 #ifdef HAVE_PCAP_DUMP_FTELL64
2704 int64_t size
= pcap_dump_ftell64(dump_info
->p
);
2707 * XXX - this only handles a Cflag value > 2^31-1 on
2708 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2709 * Windows) or LLP64 (64-bit Windows) would require
2710 * a version of libpcap with pcap_dump_ftell64().
2712 long size
= pcap_dump_ftell(dump_info
->p
);
2716 error("ftell fails on output file");
2718 #ifdef HAVE_CAPSICUM
2724 * Close the current file and open a new one.
2726 pcap_dump_close(dump_info
->p
);
2729 * Compress the file we just closed, if the user
2733 compress_savefile(dump_info
->CurrentFileName
);
2737 if (Cflag_count
>= Wflag
)
2740 if (dump_info
->CurrentFileName
!= NULL
)
2741 free(dump_info
->CurrentFileName
);
2742 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2743 if (dump_info
->CurrentFileName
== NULL
)
2744 error("dump_packet_and_trunc: malloc");
2745 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2746 #ifdef HAVE_LIBCAP_NG
2747 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2748 capng_apply(CAPNG_SELECT_BOTH
);
2749 #endif /* HAVE_LIBCAP_NG */
2750 #ifdef HAVE_CAPSICUM
2751 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2752 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2754 error("unable to open file %s",
2755 dump_info
->CurrentFileName
);
2757 fp
= fdopen(fd
, "w");
2759 error("unable to fdopen file %s",
2760 dump_info
->CurrentFileName
);
2762 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2763 #else /* !HAVE_CAPSICUM */
2764 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2766 #ifdef HAVE_LIBCAP_NG
2767 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2768 capng_apply(CAPNG_SELECT_BOTH
);
2769 #endif /* HAVE_LIBCAP_NG */
2770 if (dump_info
->p
== NULL
)
2771 error("%s", pcap_geterr(pd
));
2772 #ifdef HAVE_CAPSICUM
2773 set_dumper_capsicum_rights(dump_info
->p
);
2778 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2779 #ifdef HAVE_PCAP_DUMP_FLUSH
2781 pcap_dump_flush(dump_info
->p
);
2784 if (dump_info
->ndo
!= NULL
)
2785 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2793 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2795 struct dump_info
*dump_info
;
2801 dump_info
= (struct dump_info
*)user
;
2803 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2804 #ifdef HAVE_PCAP_DUMP_FLUSH
2806 pcap_dump_flush(dump_info
->p
);
2809 if (dump_info
->ndo
!= NULL
)
2810 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2818 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2824 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2831 #ifdef SIGNAL_REQ_INFO
2832 void requestinfo(int signo _U_
)
2842 print_packets_captured (void)
2844 static u_int prev_packets_captured
, first
= 1;
2846 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2847 fprintf(stderr
, "Got %u\r", packets_captured
);
2849 prev_packets_captured
= packets_captured
;
2854 * Called once each second in verbose mode while dumping to file
2857 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
2858 BOOLEAN timer_fired _U_
)
2860 print_packets_captured();
2863 static void verbose_stats_dump(int sig _U_
)
2865 print_packets_captured();
2869 USES_APPLE_DEPRECATED_API
2873 #ifndef HAVE_PCAP_LIB_VERSION
2874 #ifdef HAVE_PCAP_VERSION
2875 extern char pcap_version
[];
2876 #else /* HAVE_PCAP_VERSION */
2877 static char pcap_version
[] = "unknown";
2878 #endif /* HAVE_PCAP_VERSION */
2879 #endif /* HAVE_PCAP_LIB_VERSION */
2880 const char *smi_version_string
;
2882 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
2883 #ifdef HAVE_PCAP_LIB_VERSION
2884 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
2885 #else /* HAVE_PCAP_LIB_VERSION */
2886 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2887 #endif /* HAVE_PCAP_LIB_VERSION */
2889 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2890 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2893 smi_version_string
= nd_smi_version_string();
2894 if (smi_version_string
!= NULL
)
2895 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2896 #ifdef HAVE_DNET_HTOA
2897 (void)fprintf(stderr
, "libdnet unknown version\n");
2900 #if defined(__SANITIZE_ADDRESS__)
2901 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
2902 #elif defined(__has_feature)
2903 # if __has_feature(address_sanitizer)
2904 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
2906 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2914 (void)fprintf(stderr
,
2915 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2916 (void)fprintf(stderr
,
2917 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2918 (void)fprintf(stderr
,
2919 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
2920 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2921 (void)fprintf(stderr
,
2922 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
2924 (void)fprintf(stderr
,
2925 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
2926 (void)fprintf(stderr
,
2927 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
2928 (void)fprintf(stderr
,
2929 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
2930 (void)fprintf(stderr
,
2931 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
2932 (void)fprintf(stderr
,
2933 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");