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 static const char copyright
[] _U_
=
30 "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
31 The Regents of the University of California. All rights reserved.\n";
35 * tcpdump - dump traffic on a network
37 * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
38 * Mercilessly hacked and occasionally improved since then via the
39 * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
47 * Some older versions of Mac OS X may ship pcap.h from libpcap 0.6 with a
48 * libpcap based on 0.8. That means it has pcap_findalldevs() but the
49 * header doesn't define pcap_if_t, meaning that we can't actually *use*
52 #ifdef HAVE_PCAP_FINDALLDEVS
53 #ifndef HAVE_PCAP_IF_T
54 #undef HAVE_PCAP_FINDALLDEVS
58 #include <netdissect-stdinc.h>
67 #include <openssl/crypto.h>
70 #ifdef HAVE_GETOPT_LONG
73 #include "getopt_long.h"
75 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
76 * to compile if <pcap.h> has already been included; including the headers
77 * in the opposite order works fine.
80 #include <sys/capability.h>
81 #include <sys/ioccom.h>
85 #include <libcasper.h>
86 #include <casper/cap_dns.h>
88 #endif /* HAVE_CASPER */
89 #endif /* HAVE_CAPSICUM */
103 #include <sys/time.h>
104 #include <sys/wait.h>
105 #include <sys/resource.h>
110 /* capabilities convenience library */
111 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
112 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
113 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
115 #ifdef HAVE_LIBCAP_NG
119 #undef HAVE_LIBCAP_NG
120 #endif /* HAVE_CAP_NG_H */
121 #endif /* HAVE_LIBCAP_NG */
124 #include <sys/sysctl.h>
125 #endif /* __FreeBSD__ */
127 #include "netdissect.h"
128 #include "interface.h"
129 #include "addrtoname.h"
131 #include "gmt2local.h"
132 #include "pcap-missing.h"
133 #include "ascii_strcasecmp.h"
138 #define PATH_MAX 1024
142 #define SIGNAL_REQ_INFO SIGINFO
144 #define SIGNAL_REQ_INFO SIGUSR1
147 static int Bflag
; /* buffer size */
148 #ifdef HAVE_PCAP_DUMP_FTELL64
149 static int64_t Cflag
; /* rotate dump files after this many bytes */
151 static long Cflag
; /* rotate dump files after this many bytes */
153 static int Cflag_count
; /* Keep track of which file number we're writing */
154 #ifdef HAVE_PCAP_FINDALLDEVS
155 static int Dflag
; /* list available devices and exit */
157 #ifdef HAVE_PCAP_FINDALLDEVS_EX
158 static char *remote_interfaces_source
; /* list available devices from this source and exit */
162 * This is exported because, in some versions of libpcap, if libpcap
163 * is built with optimizer debugging code (which is *NOT* the default
164 * configuration!), the library *imports*(!) a variable named dflag,
165 * under the expectation that tcpdump is exporting it, to govern
166 * how much debugging information to print when optimizing
167 * the generated BPF code.
169 * This is a horrible hack; newer versions of libpcap don't import
170 * dflag but, instead, *if* built with optimizer debugging code,
171 * *export* a routine to set that flag.
173 int dflag
; /* print filter code */
174 static int Gflag
; /* rotate dump files after this many seconds */
175 static int Gflag_count
; /* number of files created with Gflag rotation */
176 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
177 static int Lflag
; /* list available data link types and exit */
178 static int Iflag
; /* rfmon (monitor) mode */
179 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
180 static int Jflag
; /* list available time stamp types */
182 static int jflag
= -1; /* packet time stamp source */
183 static int pflag
; /* don't go promiscuous */
184 #ifdef HAVE_PCAP_SETDIRECTION
185 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
187 static int Uflag
; /* "unbuffered" output of dump files */
188 static int Wflag
; /* recycle output files after this number of files */
189 static int WflagChars
;
190 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
191 static int immediate_mode
;
193 static int infodelay
;
194 static int infoprint
;
199 cap_channel_t
*capdns
;
203 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
204 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
205 static NORETURN
void exit_tcpdump(int);
206 static void (*setsignal (int sig
, void (*func
)(int)))(int);
207 static void cleanup(int);
208 static void child_cleanup(int);
209 static void print_version(void);
210 static void print_usage(void);
211 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
212 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
213 #ifdef HAVE_PCAP_FINDALLDEVS
214 static NORETURN
void show_devices_and_exit(void);
216 #ifdef HAVE_PCAP_FINDALLDEVS_EX
217 static NORETURN
void show_remote_devices_and_exit(void);
220 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
221 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
222 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
223 static void droproot(const char *, const char *);
225 #ifdef SIGNAL_REQ_INFO
226 void requestinfo(int);
230 static HANDLE timer_handle
= INVALID_HANDLE_VALUE
;
231 static void CALLBACK
verbose_stats_dump(PVOID param
, BOOLEAN timer_fired
);
233 static void verbose_stats_dump(int sig
);
236 static void info(int);
237 static u_int packets_captured
;
239 #ifdef HAVE_PCAP_FINDALLDEVS
240 static const struct tok status_flags
[] = {
242 { PCAP_IF_UP
, "Up" },
244 #ifdef PCAP_IF_RUNNING
245 { PCAP_IF_RUNNING
, "Running" },
247 { PCAP_IF_LOOPBACK
, "Loopback" },
254 static int supports_monitor_mode
;
262 char *CurrentFileName
;
265 netdissect_options
*ndo
;
271 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
273 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
274 * by any libpcap header, because it's a special hack, only available if
275 * libpcap was configured to include it, and only intended for use by
276 * libpcap developers trying to debug the parser for filter expressions).
279 __declspec(dllimport
)
283 void pcap_set_parser_debug(int);
284 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
286 * We don't have pcap_set_parser_debug() in libpcap, but we do have
287 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
288 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
291 pcap_set_parser_debug(int value
)
293 #ifdef HAVE_PCAP_DEBUG
294 extern int pcap_debug
;
297 #else /* HAVE_PCAP_DEBUG */
301 #endif /* HAVE_PCAP_DEBUG */
304 #define HAVE_PCAP_SET_PARSER_DEBUG
307 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
309 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
310 * by any libpcap header, because it's a special hack, only available if
311 * libpcap was configured to include it, and only intended for use by
312 * libpcap developers trying to debug the optimizer for filter expressions).
315 __declspec(dllimport
)
319 void pcap_set_optimizer_debug(int);
324 error(const char *fmt
, ...)
328 (void)fprintf(stderr
, "%s: ", program_name
);
330 (void)vfprintf(stderr
, fmt
, ap
);
335 (void)fputc('\n', stderr
);
343 warning(const char *fmt
, ...)
347 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
349 (void)vfprintf(stderr
, fmt
, ap
);
354 (void)fputc('\n', stderr
);
359 exit_tcpdump(int status
)
365 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
367 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
370 int *tstamp_types
= 0;
371 const char *tstamp_type_name
;
374 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
375 if (n_tstamp_types
< 0)
376 error("%s", pcap_geterr(pc
));
378 if (n_tstamp_types
== 0) {
379 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
383 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
385 for (i
= 0; i
< n_tstamp_types
; i
++) {
386 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
387 if (tstamp_type_name
!= NULL
) {
388 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
389 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
391 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
394 pcap_free_tstamp_types(tstamp_types
);
400 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
404 const char *dlt_name
;
406 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
408 error("%s", pcap_geterr(pc
));
409 else if (n_dlts
== 0 || !dlts
)
410 error("No data link types.");
413 * If the interface is known to support monitor mode, indicate
414 * whether these are the data link types available when not in
415 * monitor mode, if -I wasn't specified, or when in monitor mode,
416 * when -I was specified (the link-layer types available in
417 * monitor mode might be different from the ones available when
418 * not in monitor mode).
420 if (supports_monitor_mode
)
421 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
423 Iflag
? "when in monitor mode" : "when not in monitor mode");
425 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
428 for (i
= 0; i
< n_dlts
; i
++) {
429 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
430 if (dlt_name
!= NULL
) {
431 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
432 pcap_datalink_val_to_description(dlts
[i
]));
435 * OK, does tcpdump handle that type?
437 if (!has_printer(dlts
[i
]))
438 (void) fprintf(stderr
, " (printing not supported)");
439 fprintf(stderr
, "\n");
441 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
445 #ifdef HAVE_PCAP_FREE_DATALINKS
446 pcap_free_datalinks(dlts
);
451 #ifdef HAVE_PCAP_FINDALLDEVS
453 show_devices_and_exit(void)
455 pcap_if_t
*dev
, *devlist
;
456 char ebuf
[PCAP_ERRBUF_SIZE
];
459 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
461 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
462 printf("%d.%s", i
+1, dev
->name
);
463 if (dev
->description
!= NULL
)
464 printf(" (%s)", dev
->description
);
466 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
469 pcap_freealldevs(devlist
);
472 #endif /* HAVE_PCAP_FINDALLDEVS */
474 #ifdef HAVE_PCAP_FINDALLDEVS_EX
476 show_remote_devices_and_exit(void)
478 pcap_if_t
*dev
, *devlist
;
479 char ebuf
[PCAP_ERRBUF_SIZE
];
482 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
485 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
486 printf("%d.%s", i
+1, dev
->name
);
487 if (dev
->description
!= NULL
)
488 printf(" (%s)", dev
->description
);
490 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
493 pcap_freealldevs(devlist
);
496 #endif /* HAVE_PCAP_FINDALLDEVS */
501 * Note that there we use all letters for short options except for g, k,
502 * o, and P, and those are used by other versions of tcpdump, and we should
503 * only use them for the same purposes that the other versions of tcpdump
506 * OS X tcpdump uses -g to force non--v output for IP to be on one
507 * line, making it more "g"repable;
509 * OS X tcpdump uses -k to specify that packet comments in pcap-ng files
512 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
513 * for hosts sending TCP SYN packets;
515 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
518 * OS X tcpdump also uses -Q to specify expressions that match packet
519 * metadata, including but not limited to the packet direction.
520 * The expression syntax is different from a simple "in|out|inout",
521 * and those expressions aren't accepted by OS X tcpdump, but the
522 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
523 * "inout" = "dir=in or dir=out", and the parser could conceivably
524 * special-case "in", "out", and "inout" as expressions for backwards
525 * compatibility, so all is not (yet) lost.
529 * Set up flags that might or might not be supported depending on the
530 * version of libpcap we're using.
532 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
534 #define B_FLAG_USAGE " [ -B size ]"
535 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
538 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
540 #ifdef HAVE_PCAP_FINDALLDEVS
546 #ifdef HAVE_PCAP_CREATE
548 #else /* HAVE_PCAP_CREATE */
550 #endif /* HAVE_PCAP_CREATE */
552 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
554 #define j_FLAG_USAGE " [ -j tstamptype ]"
556 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
560 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
562 #ifdef HAVE_PCAP_SETDIRECTION
564 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
570 #ifdef HAVE_PCAP_DUMP_FLUSH
576 #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:#"
581 * We do not currently have long options corresponding to all short
582 * options; we should probably pick appropriate option names for them.
584 * However, the short options where the number of times the option is
585 * specified matters, such as -v and -d and -t, should probably not
586 * just map to a long option, as saying
588 * tcpdump --verbose --verbose
590 * doesn't make sense; it should be --verbosity={N} or something such
593 * For long options with no corresponding short options, we define values
594 * outside the range of ASCII graphic characters, make that the last
595 * component of the entry for the long option, and have a case for that
596 * option in the switch statement.
598 #define OPTION_VERSION 128
599 #define OPTION_TSTAMP_PRECISION 129
600 #define OPTION_IMMEDIATE_MODE 130
601 #define OPTION_PRINT 131
602 #define OPTION_LIST_REMOTE_INTERFACES 132
604 static const struct option longopts
[] = {
605 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
606 { "buffer-size", required_argument
, NULL
, 'B' },
608 { "list-interfaces", no_argument
, NULL
, 'D' },
609 #ifdef HAVE_PCAP_FINDALLDEVS_EX
610 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
612 { "help", no_argument
, NULL
, 'h' },
613 { "interface", required_argument
, NULL
, 'i' },
614 #ifdef HAVE_PCAP_CREATE
615 { "monitor-mode", no_argument
, NULL
, 'I' },
617 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
618 { "time-stamp-type", required_argument
, NULL
, 'j' },
619 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
621 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
622 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
624 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
625 { "list-data-link-types", no_argument
, NULL
, 'L' },
626 { "no-optimize", no_argument
, NULL
, 'O' },
627 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
628 #ifdef HAVE_PCAP_SETDIRECTION
629 { "direction", required_argument
, NULL
, 'Q' },
631 { "snapshot-length", required_argument
, NULL
, 's' },
632 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
633 #ifdef HAVE_PCAP_DUMP_FLUSH
634 { "packet-buffered", no_argument
, NULL
, 'U' },
636 { "linktype", required_argument
, NULL
, 'y' },
637 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
638 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
640 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
641 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
643 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
644 { "number", no_argument
, NULL
, '#' },
645 { "print", no_argument
, NULL
, OPTION_PRINT
},
646 { "version", no_argument
, NULL
, OPTION_VERSION
},
650 #ifdef HAVE_PCAP_FINDALLDEVS_EX
651 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
653 #define LIST_REMOTE_INTERFACES_USAGE
656 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
657 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
659 #define IMMEDIATE_MODE_USAGE ""
662 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
663 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
665 #define TIME_STAMP_PRECISION_USAGE
669 /* Drop root privileges and chroot if necessary */
671 droproot(const char *username
, const char *chroot_dir
)
673 struct passwd
*pw
= NULL
;
675 if (chroot_dir
&& !username
) {
676 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
681 pw
= getpwnam(username
);
684 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
685 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
686 program_name
, chroot_dir
, pcap_strerror(errno
));
690 #ifdef HAVE_LIBCAP_NG
692 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
694 fprintf(stderr
, "error : ret %d\n", ret
);
696 fprintf(stderr
, "dropped privs to %s\n", username
);
700 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
701 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
702 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
703 program_name
, username
,
704 (unsigned long)pw
->pw_uid
,
705 (unsigned long)pw
->pw_gid
,
706 pcap_strerror(errno
));
710 fprintf(stderr
, "dropped privs to %s\n", username
);
712 #endif /* HAVE_LIBCAP_NG */
715 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
716 program_name
, username
);
719 #ifdef HAVE_LIBCAP_NG
720 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
721 DIAG_OFF_CLANG(assign
-enum)
724 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
729 DIAG_ON_CLANG(assign
-enum)
730 capng_apply(CAPNG_SELECT_BOTH
);
731 #endif /* HAVE_LIBCAP_NG */
752 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
754 char *filename
= malloc(PATH_MAX
+ 1);
755 if (filename
== NULL
)
756 error("Makefilename: malloc");
758 /* Process with strftime if Gflag is set. */
762 /* Convert Gflag_time to a usable format */
763 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
764 error("MakeTimedFilename: localtime");
767 /* There's no good way to detect an error in strftime since a return
768 * value of 0 isn't necessarily failure.
770 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
772 strncpy(filename
, orig_name
, PATH_MAX
);
775 if (cnt
== 0 && max_chars
== 0)
776 strncpy(buffer
, filename
, PATH_MAX
+ 1);
778 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
779 /* Report an error if the filename is too large */
780 error("too many output files or filename is too long (> %d)", PATH_MAX
);
785 get_next_file(FILE *VFile
, char *ptr
)
789 ret
= fgets(ptr
, PATH_MAX
, VFile
);
793 if (ptr
[strlen(ptr
) - 1] == '\n')
794 ptr
[strlen(ptr
) - 1] = '\0';
800 static cap_channel_t
*
803 cap_channel_t
*capcas
, *capdnsloc
;
804 const char *types
[1];
809 error("unable to create casper process");
810 capdnsloc
= cap_service_open(capcas
, "system.dns");
811 /* Casper capability no longer needed. */
813 if (capdnsloc
== NULL
)
814 error("unable to open system.dns service");
815 /* Limit system.dns to reverse DNS lookups. */
817 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
818 error("unable to limit access to system.dns service");
819 families
[0] = AF_INET
;
820 families
[1] = AF_INET6
;
821 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
822 error("unable to limit access to system.dns service");
826 #endif /* HAVE_CASPER */
828 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
830 tstamp_precision_from_string(const char *precision
)
832 if (strncmp(precision
, "nano", strlen("nano")) == 0)
833 return PCAP_TSTAMP_PRECISION_NANO
;
835 if (strncmp(precision
, "micro", strlen("micro")) == 0)
836 return PCAP_TSTAMP_PRECISION_MICRO
;
842 tstamp_precision_to_string(int precision
)
846 case PCAP_TSTAMP_PRECISION_MICRO
:
849 case PCAP_TSTAMP_PRECISION_NANO
:
860 * Ensure that, on a dump file's descriptor, we have all the rights
861 * necessary to make the standard I/O library work with an fdopen()ed
862 * FILE * from that descriptor.
864 * A long time ago, in a galaxy far far away, AT&T decided that, instead
865 * of providing separate APIs for getting and setting the FD_ flags on a
866 * descriptor, getting and setting the O_ flags on a descriptor, and
867 * locking files, they'd throw them all into a kitchen-sink fcntl() call
868 * along the lines of ioctl(), the fact that ioctl() operations are
869 * largely specific to particular character devices but fcntl() operations
870 * are either generic to all descriptors or generic to all descriptors for
871 * regular files nonwithstanding.
873 * The Capsicum people decided that fine-grained control of descriptor
874 * operations was required, so that you need to grant permission for
875 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
876 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
877 * collection of things, so there are *individual* fcntls for which
878 * permission needs to be granted.
880 * The FreeBSD standard I/O people implemented some optimizations that
881 * requires that the standard I/O routines be able to determine whether
882 * the descriptor for the FILE * is open append-only or not; as that
883 * descriptor could have come from an open() rather than an fopen(),
884 * that requires that it be able to do an F_GETFL fcntl() to read
887 * Tcpdump uses ftell() to determine how much data has been written
888 * to a file in order to, when used with -C, determine when it's time
889 * to rotate capture files. ftell() therefore needs to do an lseek()
890 * to find out the file offset and must, thanks to the aforementioned
891 * optimization, also know whether the descriptor is open append-only
894 * The net result of all the above is that we need to grant CAP_SEEK,
895 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
897 * Perhaps this is the universe's way of saying that either
899 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
900 * using it, so that Capsicum-capable tcpdump wouldn't need to do
905 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
906 * I/O library that knows what rights are needed by the standard
907 * I/O library, based on the open mode, and assigns them, perhaps
908 * with an additional argument indicating, for example, whether
909 * seeking should be allowed, so that tcpdump doesn't need to know
910 * what the standard I/O library happens to require this week.
913 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
915 int fd
= fileno(pcap_dump_file(p
));
918 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
919 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
920 error("unable to limit dump descriptor");
922 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
923 error("unable to limit dump descriptor fcntls");
929 * Copy arg vector into a new buffer, concatenating arguments with spaces.
932 copy_argv(register char **argv
)
935 register u_int len
= 0;
944 len
+= strlen(*p
++) + 1;
946 buf
= (char *)malloc(len
);
948 error("copy_argv: malloc");
952 while ((src
= *p
++) != NULL
) {
953 while ((*dst
++ = *src
++) != '\0')
963 * On Windows, we need to open the file in binary mode, so that
964 * we get all the bytes specified by the size we get from "fstat()".
965 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
966 * we define it as 0 if it's not defined, so it does nothing.
973 read_infile(char *fname
)
975 register int i
, fd
, cc
;
979 fd
= open(fname
, O_RDONLY
|O_BINARY
);
981 error("can't open %s: %s", fname
, pcap_strerror(errno
));
983 if (fstat(fd
, &buf
) < 0)
984 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
986 cp
= malloc((u_int
)buf
.st_size
+ 1);
988 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
989 fname
, pcap_strerror(errno
));
990 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
992 error("read %s: %s", fname
, pcap_strerror(errno
));
993 if (cc
!= buf
.st_size
)
994 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
997 /* replace "# comment" with spaces */
998 for (i
= 0; i
< cc
; i
++) {
1000 while (i
< cc
&& cp
[i
] != '\n')
1007 #ifdef HAVE_PCAP_FINDALLDEVS
1009 parse_interface_number(const char *device
)
1014 devnum
= strtol(device
, &end
, 10);
1015 if (device
!= end
&& *end
== '\0') {
1017 * It's all-numeric, but is it a valid number?
1021 * No, it's not an ordinal.
1023 error("Invalid adapter index");
1028 * It's not all-numeric; return -1, so our caller
1036 find_interface_by_number(long devnum
)
1038 pcap_if_t
*dev
, *devlist
;
1040 char ebuf
[PCAP_ERRBUF_SIZE
];
1043 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
1046 * Look for the devnum-th entry in the list of devices (1-based).
1048 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1049 i
++, dev
= dev
->next
)
1052 error("Invalid adapter index");
1053 device
= strdup(dev
->name
);
1054 pcap_freealldevs(devlist
);
1059 #ifdef HAVE_PCAP_OPEN
1061 * Prefix for rpcap URLs.
1063 static char rpcap_prefix
[] = "rpcap://";
1067 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1070 #ifdef HAVE_PCAP_CREATE
1075 #ifdef HAVE_PCAP_OPEN
1077 * Is this an rpcap URL?
1079 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1081 * Yes. Open it with pcap_open().
1084 fprintf(stderr
, "Opening %s\n", device
);
1085 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1086 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1090 * If this failed with "No such device", that means
1091 * the interface doesn't exist; return NULL, so that
1092 * the caller can see whether the device name is
1093 * actually an interface index.
1095 if (strstr(ebuf
, "No such device") != NULL
)
1100 warning("%s", ebuf
);
1103 #endif /* HAVE_PCAP_OPEN */
1105 #ifdef HAVE_PCAP_CREATE
1106 pc
= pcap_create(device
, ebuf
);
1109 * If this failed with "No such device", that means
1110 * the interface doesn't exist; return NULL, so that
1111 * the caller can see whether the device name is
1112 * actually an interface index.
1114 if (strstr(ebuf
, "No such device") != NULL
)
1118 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1120 show_tstamp_types_and_exit(pc
, device
);
1122 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1123 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1125 error("%s: Can't set %ssecond time stamp precision: %s",
1127 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1128 pcap_statustostr(status
));
1131 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1132 if (immediate_mode
) {
1133 status
= pcap_set_immediate_mode(pc
, 1);
1135 error("%s: Can't set immediate mode: %s",
1137 pcap_statustostr(status
));
1141 * Is this an interface that supports monitor mode?
1143 if (pcap_can_set_rfmon(pc
) == 1)
1144 supports_monitor_mode
= 1;
1146 supports_monitor_mode
= 0;
1147 if (ndo
->ndo_snaplen
!= 0) {
1149 * A snapshot length was explicitly specified;
1152 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1154 error("%s: Can't set snapshot length: %s",
1155 device
, pcap_statustostr(status
));
1157 status
= pcap_set_promisc(pc
, !pflag
);
1159 error("%s: Can't set promiscuous mode: %s",
1160 device
, pcap_statustostr(status
));
1162 status
= pcap_set_rfmon(pc
, 1);
1164 error("%s: Can't set monitor mode: %s",
1165 device
, pcap_statustostr(status
));
1167 status
= pcap_set_timeout(pc
, 1000);
1169 error("%s: pcap_set_timeout failed: %s",
1170 device
, pcap_statustostr(status
));
1172 status
= pcap_set_buffer_size(pc
, Bflag
);
1174 error("%s: Can't set buffer size: %s",
1175 device
, pcap_statustostr(status
));
1177 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1179 status
= pcap_set_tstamp_type(pc
, jflag
);
1181 error("%s: Can't set time stamp type: %s",
1182 device
, pcap_statustostr(status
));
1185 status
= pcap_activate(pc
);
1188 * pcap_activate() failed.
1190 cp
= pcap_geterr(pc
);
1191 if (status
== PCAP_ERROR
)
1193 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1195 * Return an error for our caller to handle.
1197 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1198 device
, pcap_statustostr(status
), cp
);
1201 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1202 error("%s: %s\n(%s)", device
,
1203 pcap_statustostr(status
), cp
);
1205 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1206 strncmp(device
, "wlan", 4) == 0) {
1207 char parent
[8], newdev
[8];
1209 size_t s
= sizeof(parent
);
1211 snprintf(sysctl
, sizeof(sysctl
),
1212 "net.wlan.%d.%%parent", atoi(device
+ 4));
1213 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1214 strlcpy(newdev
, device
, sizeof(newdev
));
1215 /* Suggest a new wlan device. */
1216 /* FIXME: incrementing the index this way is not going to work well
1217 * when the index is 9 or greater but the only consequence in this
1218 * specific case would be an error message that looks a bit odd.
1220 newdev
[strlen(newdev
)-1]++;
1221 error("%s is not a monitor mode VAP\n"
1222 "To create a new monitor mode VAP use:\n"
1223 " ifconfig %s create wlandev %s wlanmode monitor\n"
1224 "and use %s as the tcpdump interface",
1225 device
, newdev
, parent
, newdev
);
1229 error("%s: %s", device
,
1230 pcap_statustostr(status
));
1231 } else if (status
> 0) {
1233 * pcap_activate() succeeded, but it's warning us
1234 * of a problem it had.
1236 cp
= pcap_geterr(pc
);
1237 if (status
== PCAP_WARNING
)
1239 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1241 warning("%s: %s\n(%s)", device
,
1242 pcap_statustostr(status
), cp
);
1244 warning("%s: %s", device
,
1245 pcap_statustostr(status
));
1247 #ifdef HAVE_PCAP_SETDIRECTION
1249 status
= pcap_setdirection(pc
, Qflag
);
1251 error("%s: pcap_setdirection() failed: %s",
1252 device
, pcap_geterr(pc
));
1254 #endif /* HAVE_PCAP_SETDIRECTION */
1255 #else /* HAVE_PCAP_CREATE */
1258 * If no snapshot length was specified, or a length of 0 was
1259 * specified, default to 256KB.
1261 if (ndo
->ndo_snaplen
== 0)
1262 ndo
->ndo_snaplen
= 262144;
1263 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1266 * If this failed with "No such device", that means
1267 * the interface doesn't exist; return NULL, so that
1268 * the caller can see whether the device name is
1269 * actually an interface index.
1271 if (strstr(ebuf
, "No such device") != NULL
)
1276 warning("%s", ebuf
);
1277 #endif /* HAVE_PCAP_CREATE */
1283 main(int argc
, char **argv
)
1285 register int cnt
, op
, i
;
1286 bpf_u_int32 localnet
= 0, netmask
= 0;
1287 int timezone_offset
= 0;
1288 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1290 pcap_handler callback
;
1292 const char *dlt_name
;
1293 struct bpf_program fcode
;
1295 void (*oldhandler
)(int);
1297 struct dump_info dumpinfo
;
1298 u_char
*pcap_userdata
;
1299 char ebuf
[PCAP_ERRBUF_SIZE
];
1300 char VFileLine
[PATH_MAX
+ 1];
1301 char *username
= NULL
;
1302 char *chroot_dir
= NULL
;
1305 #ifdef HAVE_PCAP_FINDALLDEVS
1311 #ifdef HAVE_CAPSICUM
1312 cap_rights_t rights
;
1314 #endif /* HAVE_CAPSICUM */
1315 int Oflag
= 1; /* run filter code optimizer */
1317 const char *yflag_dlt_name
= NULL
;
1320 netdissect_options Ndo
;
1321 netdissect_options
*ndo
= &Ndo
;
1324 * Initialize the netdissect code.
1326 if (nd_init(ebuf
, sizeof ebuf
) == -1)
1329 memset(ndo
, 0, sizeof(*ndo
));
1330 ndo_set_function_pointers(ndo
);
1340 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1341 ndo
->program_name
= program_name
= cp
+ 1;
1343 ndo
->program_name
= program_name
= argv
[0];
1346 if (pcap_wsockinit() != 0)
1347 error("Attempting to initialize Winsock failed");
1351 * On platforms where the CPU doesn't support unaligned loads,
1352 * force unaligned accesses to abort with SIGBUS, rather than
1353 * being fixed up (slowly) by the OS kernel; on those platforms,
1354 * misaligned accesses are bugs, and we want tcpdump to crash so
1355 * that the bugs are reported.
1357 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1361 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1365 /* compatibility for old -a */
1376 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1378 Bflag
= atoi(optarg
)*1024;
1380 error("invalid packet buffer size %s", optarg
);
1382 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1387 error("invalid packet count %s", optarg
);
1392 #ifdef HAVE_PCAP_DUMP_FTELL64
1393 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1395 Cflag
= strtol(optarg
, &endp
, 10);
1397 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1399 error("invalid file size %s", optarg
);
1401 * Will multiplying it by 1000000 overflow?
1403 #ifdef HAVE_PCAP_DUMP_FTELL64
1404 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1406 if (Cflag
> LONG_MAX
/ 1000000)
1408 error("file size %s is too large", optarg
);
1416 #ifdef HAVE_PCAP_FINDALLDEVS
1422 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1423 case OPTION_LIST_REMOTE_INTERFACES
:
1424 remote_interfaces_source
= optarg
;
1437 #ifndef HAVE_LIBCRYPTO
1438 warning("crypto code not compiled in");
1440 ndo
->ndo_espsecret
= optarg
;
1452 Gflag
= atoi(optarg
);
1454 error("invalid number of seconds %s", optarg
);
1456 /* We will create one file initially. */
1459 /* Grab the current time for rotation use. */
1460 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1461 error("main: can't get current time: %s",
1462 pcap_strerror(errno
));
1479 #ifdef HAVE_PCAP_CREATE
1483 #endif /* HAVE_PCAP_CREATE */
1485 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1487 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1489 error("invalid time stamp type %s", optarg
);
1500 * _IOLBF is the same as _IOFBF in Microsoft's C
1501 * libraries; the only alternative they offer
1504 * XXX - this should really be checking for MSVC++,
1505 * not _WIN32, if, for example, MinGW has its own
1506 * C library that is more UNIX-compatible.
1508 setvbuf(stdout
, NULL
, _IONBF
, 0);
1510 #ifdef HAVE_SETLINEBUF
1513 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1523 if (nd_have_smi_support()) {
1524 if (nd_load_smi_module(optarg
, ebuf
, sizeof ebuf
) == -1)
1527 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1528 program_name
, optarg
);
1529 (void)fprintf(stderr
, "(no libsmi support)\n");
1534 /* TCP-MD5 shared secret */
1535 #ifndef HAVE_LIBCRYPTO
1536 warning("crypto code not compiled in");
1538 ndo
->ndo_sigsecret
= optarg
;
1559 ++ndo
->ndo_suppress_default_print
;
1562 #ifdef HAVE_PCAP_SETDIRECTION
1564 if (ascii_strcasecmp(optarg
, "in") == 0)
1566 else if (ascii_strcasecmp(optarg
, "out") == 0)
1568 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1569 Qflag
= PCAP_D_INOUT
;
1571 error("unknown capture direction `%s'", optarg
);
1573 #endif /* HAVE_PCAP_SETDIRECTION */
1580 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1581 if (optarg
== end
|| *end
!= '\0'
1582 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1583 error("invalid snaplen %s", optarg
);
1595 if (ascii_strcasecmp(optarg
, "vat") == 0)
1596 ndo
->ndo_packettype
= PT_VAT
;
1597 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1598 ndo
->ndo_packettype
= PT_WB
;
1599 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1600 ndo
->ndo_packettype
= PT_RPC
;
1601 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1602 ndo
->ndo_packettype
= PT_RTP
;
1603 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1604 ndo
->ndo_packettype
= PT_RTCP
;
1605 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1606 ndo
->ndo_packettype
= PT_SNMP
;
1607 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1608 ndo
->ndo_packettype
= PT_CNFP
;
1609 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1610 ndo
->ndo_packettype
= PT_TFTP
;
1611 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1612 ndo
->ndo_packettype
= PT_AODV
;
1613 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1614 ndo
->ndo_packettype
= PT_CARP
;
1615 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1616 ndo
->ndo_packettype
= PT_RADIUS
;
1617 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1618 ndo
->ndo_packettype
= PT_ZMTP1
;
1619 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1620 ndo
->ndo_packettype
= PT_VXLAN
;
1621 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1622 ndo
->ndo_packettype
= PT_PGM
;
1623 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1624 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1625 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1626 ndo
->ndo_packettype
= PT_LMP
;
1627 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1628 ndo
->ndo_packettype
= PT_RESP
;
1630 error("unknown packet type `%s'", optarg
);
1637 #ifdef HAVE_PCAP_DUMP_FLUSH
1656 Wflag
= atoi(optarg
);
1658 error("invalid number of output files %s", optarg
);
1659 WflagChars
= getWflagChars(Wflag
);
1664 ++ndo
->ndo_suppress_default_print
;
1669 ++ndo
->ndo_suppress_default_print
;
1673 yflag_dlt_name
= optarg
;
1675 pcap_datalink_name_to_val(yflag_dlt_name
);
1677 error("invalid data link type %s", yflag_dlt_name
);
1680 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1683 /* Undocumented flag */
1684 pcap_set_parser_debug(1);
1697 ndo
->ndo_packet_number
= 1;
1700 case OPTION_VERSION
:
1705 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1706 case OPTION_TSTAMP_PRECISION
:
1707 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1708 if (ndo
->ndo_tstamp_precision
< 0)
1709 error("unsupported time stamp precision");
1713 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1714 case OPTION_IMMEDIATE_MODE
:
1729 #ifdef HAVE_PCAP_FINDALLDEVS
1731 show_devices_and_exit();
1733 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1734 if (remote_interfaces_source
!= NULL
)
1735 show_remote_devices_and_exit();
1738 switch (ndo
->ndo_tflag
) {
1740 case 0: /* Default */
1741 case 4: /* Default + Date*/
1742 timezone_offset
= gmt2local(0);
1745 case 1: /* No time stamp */
1746 case 2: /* Unix timeval style */
1747 case 3: /* Microseconds since previous packet */
1748 case 5: /* Microseconds since first packet */
1751 default: /* Not supported */
1752 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1756 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1757 error("-f can not be used with -V or -r");
1759 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1760 error("-V and -r are mutually exclusive.");
1762 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1764 * If we're printing dissected packets to the standard output
1765 * and the standard output is a terminal, use immediate mode,
1766 * as the user's probably expecting to see packets pop up
1769 * XXX - set the timeout to a lower value, instead? If so,
1770 * what value would be appropriate?
1772 if ((WFileName
== NULL
|| print
) && isatty(1))
1777 /* if run as root, prepare for chrooting */
1778 if (getuid() == 0 || geteuid() == 0) {
1779 /* future extensibility for cmd-line arguments */
1781 chroot_dir
= WITH_CHROOT
;
1786 /* if run as root, prepare for dropping root privileges */
1787 if (getuid() == 0 || geteuid() == 0) {
1788 /* Run with '-Z root' to restore old behaviour */
1790 username
= WITH_USER
;
1794 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1796 * If RFileName is non-null, it's the pathname of a
1797 * savefile to read. If VFileName is non-null, it's
1798 * the pathname of a file containing a list of pathnames
1799 * (one per line) of savefiles to read.
1801 * In either case, we're reading a savefile, not doing
1806 * We don't need network access, so relinquish any set-UID
1807 * or set-GID privileges we have (if any).
1809 * We do *not* want set-UID privileges when opening a
1810 * trace file, as that might let the user read other
1811 * people's trace files (especially if we're set-UID
1814 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1815 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1817 if (VFileName
!= NULL
) {
1818 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1821 VFile
= fopen(VFileName
, "r");
1824 error("Unable to open file: %s\n", pcap_strerror(errno
));
1826 ret
= get_next_file(VFile
, VFileLine
);
1828 error("Nothing in %s\n", VFileName
);
1829 RFileName
= VFileLine
;
1832 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1833 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1834 ndo
->ndo_tstamp_precision
, ebuf
);
1836 pd
= pcap_open_offline(RFileName
, ebuf
);
1841 #ifdef HAVE_CAPSICUM
1842 cap_rights_init(&rights
, CAP_READ
);
1843 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1845 error("unable to limit pcap descriptor");
1848 dlt
= pcap_datalink(pd
);
1849 dlt_name
= pcap_datalink_val_to_name(dlt
);
1850 if (dlt_name
== NULL
) {
1851 fprintf(stderr
, "reading from file %s, link-type %u\n",
1855 "reading from file %s, link-type %s (%s)\n",
1856 RFileName
, dlt_name
,
1857 pcap_datalink_val_to_description(dlt
));
1861 * We're doing a live capture.
1863 if (device
== NULL
) {
1865 * No interface was specified. Pick one.
1867 #ifdef HAVE_PCAP_FINDALLDEVS
1869 * Find the list of interfaces, and pick
1870 * the first interface.
1872 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
1874 if (devlist
== NULL
)
1875 error("no interfaces available for capture");
1876 device
= strdup(devlist
->name
);
1877 pcap_freealldevs(devlist
);
1878 #else /* HAVE_PCAP_FINDALLDEVS */
1880 * Use whatever interface pcap_lookupdev()
1883 device
= pcap_lookupdev(ebuf
);
1890 * Try to open the interface with the specified name.
1892 pd
= open_interface(device
, ndo
, ebuf
);
1895 * That failed. If we can get a list of
1896 * interfaces, and the interface name
1897 * is purely numeric, try to use it as
1898 * a 1-based index in the list of
1901 #ifdef HAVE_PCAP_FINDALLDEVS
1902 devnum
= parse_interface_number(device
);
1905 * It's not a number; just report
1906 * the open error and fail.
1912 * OK, it's a number; try to find the
1913 * interface with that index, and try
1916 * find_interface_by_number() exits if it
1917 * couldn't be found.
1919 device
= find_interface_by_number(devnum
);
1920 pd
= open_interface(device
, ndo
, ebuf
);
1923 #else /* HAVE_PCAP_FINDALLDEVS */
1925 * We can't get a list of interfaces; just
1929 #endif /* HAVE_PCAP_FINDALLDEVS */
1933 * Let user own process after capture device has
1937 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1938 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1940 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1942 if(pcap_setbuff(pd
, Bflag
)==-1){
1943 error("%s", pcap_geterr(pd
));
1945 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1947 show_dlts_and_exit(pd
, device
);
1948 if (yflag_dlt
>= 0) {
1949 #ifdef HAVE_PCAP_SET_DATALINK
1950 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1951 error("%s", pcap_geterr(pd
));
1954 * We don't actually support changing the
1955 * data link type, so we only let them
1956 * set it to what it already is.
1958 if (yflag_dlt
!= pcap_datalink(pd
)) {
1959 error("%s is not one of the DLTs supported by this device\n",
1963 (void)fprintf(stderr
, "%s: data link type %s\n",
1964 program_name
, yflag_dlt_name
);
1965 (void)fflush(stderr
);
1967 i
= pcap_snapshot(pd
);
1968 if (ndo
->ndo_snaplen
< i
) {
1969 if (ndo
->ndo_snaplen
!= 0)
1970 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1971 ndo
->ndo_snaplen
= i
;
1972 } else if (ndo
->ndo_snaplen
> i
) {
1973 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
1974 ndo
->ndo_snaplen
= i
;
1976 if(ndo
->ndo_fflag
!= 0) {
1977 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1978 warning("foreign (-f) flag used but: %s", ebuf
);
1984 cmdbuf
= read_infile(infile
);
1986 cmdbuf
= copy_argv(&argv
[optind
]);
1988 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1989 pcap_set_optimizer_debug(dflag
);
1991 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1992 error("%s", pcap_geterr(pd
));
1994 bpf_dump(&fcode
, dflag
);
1997 pcap_freecode(&fcode
);
2002 if (!ndo
->ndo_nflag
)
2003 capdns
= capdns_setup();
2004 #endif /* HAVE_CASPER */
2006 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2009 (void)setsignal(SIGPIPE
, cleanup
);
2010 (void)setsignal(SIGTERM
, cleanup
);
2012 (void)setsignal(SIGINT
, cleanup
);
2013 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2014 (void)setsignal(SIGCHLD
, child_cleanup
);
2016 /* Cooperate with nohup(1) */
2018 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2019 (void)setsignal(SIGHUP
, oldhandler
);
2024 * If a user name was specified with "-Z", attempt to switch to
2025 * that user's UID. This would probably be used with sudo,
2026 * to allow tcpdump to be run in a special restricted
2027 * account (if you just want to allow users to open capture
2028 * devices, and can't just give users that permission,
2029 * you'd make tcpdump set-UID or set-GID).
2031 * Tcpdump doesn't necessarily write only to one savefile;
2032 * the general only way to allow a -Z instance to write to
2033 * savefiles as the user under whose UID it's run, rather
2034 * than as the user specified with -Z, would thus be to switch
2035 * to the original user ID before opening a capture file and
2036 * then switch back to the -Z user ID after opening the savefile.
2037 * Switching to the -Z user ID only after opening the first
2038 * savefile doesn't handle the general case.
2041 if (getuid() == 0 || geteuid() == 0) {
2042 #ifdef HAVE_LIBCAP_NG
2043 /* Initialize capng */
2044 capng_clear(CAPNG_SELECT_BOTH
);
2046 DIAG_OFF_CLANG(assign
-enum)
2049 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2053 DIAG_ON_CLANG(assign
-enum)
2056 DIAG_OFF_CLANG(assign
-enum)
2059 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2062 DIAG_ON_CLANG(assign
-enum)
2066 DIAG_OFF_CLANG(assign
-enum)
2069 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2072 DIAG_ON_CLANG(assign
-enum)
2074 capng_apply(CAPNG_SELECT_BOTH
);
2075 #endif /* HAVE_LIBCAP_NG */
2076 if (username
|| chroot_dir
)
2077 droproot(username
, chroot_dir
);
2082 if (pcap_setfilter(pd
, &fcode
) < 0)
2083 error("%s", pcap_geterr(pd
));
2084 #ifdef HAVE_CAPSICUM
2085 if (RFileName
== NULL
&& VFileName
== NULL
) {
2086 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2089 * The various libpcap devices use a combination of
2090 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2091 * so we add the relevant access rights.
2093 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2094 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2096 error("unable to limit pcap descriptor");
2098 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2099 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2100 error("unable to limit ioctls on pcap descriptor");
2106 /* Do not exceed the default PATH_MAX for files. */
2107 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2109 if (dumpinfo
.CurrentFileName
== NULL
)
2110 error("malloc of dumpinfo.CurrentFileName");
2112 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2114 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2116 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2118 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2119 #ifdef HAVE_LIBCAP_NG
2120 /* Give up CAP_DAC_OVERRIDE capability.
2121 * Only allow it to be restored if the -C or -G flag have been
2122 * set since we may need to create more files later on.
2126 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2130 capng_apply(CAPNG_SELECT_BOTH
);
2131 #endif /* HAVE_LIBCAP_NG */
2133 error("%s", pcap_geterr(pd
));
2134 #ifdef HAVE_CAPSICUM
2135 set_dumper_capsicum_rights(p
);
2137 if (Cflag
!= 0 || Gflag
!= 0) {
2138 #ifdef HAVE_CAPSICUM
2139 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2140 if (dumpinfo
.WFileName
== NULL
) {
2141 error("Unable to allocate memory for file %s",
2144 dumpinfo
.dirfd
= open(dirname(WFileName
),
2145 O_DIRECTORY
| O_RDONLY
);
2146 if (dumpinfo
.dirfd
< 0) {
2147 error("unable to open directory %s",
2148 dirname(WFileName
));
2150 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2151 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2152 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2154 error("unable to limit directory rights");
2156 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2158 error("unable to limit dump descriptor fcntls");
2160 #else /* !HAVE_CAPSICUM */
2161 dumpinfo
.WFileName
= WFileName
;
2163 callback
= dump_packet_and_trunc
;
2166 pcap_userdata
= (u_char
*)&dumpinfo
;
2168 callback
= dump_packet
;
2169 dumpinfo
.WFileName
= WFileName
;
2172 pcap_userdata
= (u_char
*)&dumpinfo
;
2175 dlt
= pcap_datalink(pd
);
2176 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2179 dumpinfo
.ndo
= NULL
;
2181 #ifdef HAVE_PCAP_DUMP_FLUSH
2186 dlt
= pcap_datalink(pd
);
2187 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2188 callback
= print_packet
;
2189 pcap_userdata
= (u_char
*)ndo
;
2192 #ifdef SIGNAL_REQ_INFO
2194 * We can't get statistics when reading from a file rather
2195 * than capturing from a device.
2197 if (RFileName
== NULL
)
2198 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2201 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2203 * When capturing to a file, if "--print" wasn't specified,
2204 *"-v" means tcpdump should, once per second,
2205 * "v"erbosely report the number of packets captured.
2209 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2211 * suggests that this dates back to W2K.
2213 * I don't know what a "long wait" is, but we'll assume
2214 * that printing the stats could be a "long wait".
2216 CreateTimerQueueTimer(&timer_handle
, NULL
,
2217 verbose_stats_dump
, NULL
, 1000, 1000,
2218 WT_EXECUTEDEFAULT
|WT_EXECUTELONGFUNCTION
);
2219 setvbuf(stderr
, NULL
, _IONBF
, 0);
2222 * Assume this is UN*X, and that it has setitimer(); that
2223 * dates back to UNIX 95.
2225 struct itimerval timer
;
2226 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2227 timer
.it_interval
.tv_sec
= 1;
2228 timer
.it_interval
.tv_usec
= 0;
2229 timer
.it_value
.tv_sec
= 1;
2230 timer
.it_value
.tv_usec
= 1;
2231 setitimer(ITIMER_REAL
, &timer
, NULL
);
2235 if (RFileName
== NULL
) {
2237 * Live capture (if -V was specified, we set RFileName
2238 * to a file from the -V file). Print a message to
2239 * the standard error on UN*X.
2241 if (!ndo
->ndo_vflag
&& !WFileName
) {
2242 (void)fprintf(stderr
,
2243 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2246 (void)fprintf(stderr
, "%s: ", program_name
);
2247 dlt
= pcap_datalink(pd
);
2248 dlt_name
= pcap_datalink_val_to_name(dlt
);
2249 if (dlt_name
== NULL
) {
2250 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2251 device
, dlt
, ndo
->ndo_snaplen
);
2253 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2255 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2257 (void)fflush(stderr
);
2260 #ifdef HAVE_CAPSICUM
2261 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2263 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2265 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2266 #endif /* HAVE_CASPER */
2267 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2268 error("unable to enter the capability mode");
2269 #endif /* HAVE_CAPSICUM */
2272 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2273 if (WFileName
== NULL
) {
2275 * We're printing packets. Flush the printed output,
2276 * so it doesn't get intermingled with error output.
2280 * We got interrupted, so perhaps we didn't
2281 * manage to finish a line we were printing.
2282 * Print an extra newline, just in case.
2286 (void)fflush(stdout
);
2290 * We got interrupted. If we are reading multiple
2291 * files (via -V) set these so that we stop.
2300 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2301 program_name
, pcap_geterr(pd
));
2303 if (RFileName
== NULL
) {
2305 * We're doing a live capture. Report the capture
2311 if (VFileName
!= NULL
) {
2312 ret
= get_next_file(VFile
, VFileLine
);
2316 RFileName
= VFileLine
;
2317 pd
= pcap_open_offline(RFileName
, ebuf
);
2320 #ifdef HAVE_CAPSICUM
2321 cap_rights_init(&rights
, CAP_READ
);
2322 if (cap_rights_limit(fileno(pcap_file(pd
)),
2323 &rights
) < 0 && errno
!= ENOSYS
) {
2324 error("unable to limit pcap descriptor");
2327 new_dlt
= pcap_datalink(pd
);
2328 if (new_dlt
!= dlt
) {
2330 * The new file has a different
2331 * link-layer header type from the
2334 if (WFileName
!= NULL
) {
2336 * We're writing raw packets
2337 * that match the filter to
2338 * a pcap file. pcap files
2339 * don't support multiple
2340 * different link-layer
2341 * header types, so we fail
2344 error("%s: new dlt does not match original", RFileName
);
2348 * We're printing the decoded packets;
2349 * switch to the new DLT.
2351 * To do that, we need to change
2352 * the printer, change the DLT name,
2353 * and recompile the filter with
2357 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2358 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2359 error("%s", pcap_geterr(pd
));
2363 * Set the filter on the new file.
2365 if (pcap_setfilter(pd
, &fcode
) < 0)
2366 error("%s", pcap_geterr(pd
));
2369 * Report the new file.
2371 dlt_name
= pcap_datalink_val_to_name(dlt
);
2372 if (dlt_name
== NULL
) {
2373 fprintf(stderr
, "reading from file %s, link-type %u\n",
2377 "reading from file %s, link-type %s (%s)\n",
2378 RFileName
, dlt_name
,
2379 pcap_datalink_val_to_description(dlt
));
2384 while (ret
!= NULL
);
2387 pcap_freecode(&fcode
);
2388 exit_tcpdump(status
== -1 ? 1 : 0);
2395 (*setsignal (int sig
, void (*func
)(int)))(int)
2398 return (signal(sig
, func
));
2400 struct sigaction old
, new;
2402 memset(&new, 0, sizeof(new));
2403 new.sa_handler
= func
;
2405 new.sa_flags
= SA_RESTART
;
2406 if (sigaction(sig
, &new, &old
) < 0)
2408 return (old
.sa_handler
);
2412 /* make a clean exit on interrupts */
2414 cleanup(int signo _U_
)
2417 if (timer_handle
!= INVALID_HANDLE_VALUE
) {
2418 DeleteTimerQueueTimer(NULL
, timer_handle
, NULL
);
2419 CloseHandle(timer_handle
);
2420 timer_handle
= INVALID_HANDLE_VALUE
;
2423 struct itimerval timer
;
2425 timer
.it_interval
.tv_sec
= 0;
2426 timer
.it_interval
.tv_usec
= 0;
2427 timer
.it_value
.tv_sec
= 0;
2428 timer
.it_value
.tv_usec
= 0;
2429 setitimer(ITIMER_REAL
, &timer
, NULL
);
2432 #ifdef HAVE_PCAP_BREAKLOOP
2434 * We have "pcap_breakloop()"; use it, so that we do as little
2435 * as possible in the signal handler (it's probably not safe
2436 * to do anything with standard I/O streams in a signal handler -
2437 * the ANSI C standard doesn't say it is).
2442 * We don't have "pcap_breakloop()"; this isn't safe, but
2443 * it's the best we can do. Print the summary if we're
2444 * not reading from a savefile - i.e., if we're doing a
2445 * live capture - and exit.
2447 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2449 * We got interrupted, so perhaps we didn't
2450 * manage to finish a line we were printing.
2451 * Print an extra newline, just in case.
2454 (void)fflush(stdout
);
2462 On windows, we do not use a fork, so we do not care less about
2463 waiting a child processes to die
2465 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2467 child_cleanup(int signo _U_
)
2471 #endif /* HAVE_FORK && HAVE_VFORK */
2474 info(register int verbose
)
2476 struct pcap_stat stats
;
2479 * Older versions of libpcap didn't set ps_ifdrop on some
2480 * platforms; initialize it to 0 to handle that.
2482 stats
.ps_ifdrop
= 0;
2483 if (pcap_stats(pd
, &stats
) < 0) {
2484 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2490 fprintf(stderr
, "%s: ", program_name
);
2492 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2493 PLURAL_SUFFIX(packets_captured
));
2495 fputs(", ", stderr
);
2498 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2499 PLURAL_SUFFIX(stats
.ps_recv
));
2501 fputs(", ", stderr
);
2504 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2505 PLURAL_SUFFIX(stats
.ps_drop
));
2506 if (stats
.ps_ifdrop
!= 0) {
2508 fputs(", ", stderr
);
2511 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2512 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2518 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2520 #define fork_subprocess() fork()
2522 #define fork_subprocess() vfork()
2525 compress_savefile(const char *filename
)
2529 child
= fork_subprocess();
2532 "compress_savefile: fork failed: %s\n",
2533 pcap_strerror(errno
));
2537 /* Parent process. */
2543 * Set to lowest priority so that this doesn't disturb the capture.
2546 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2548 setpriority(PRIO_PROCESS
, 0, 19);
2550 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2552 "compress_savefile: execlp(%s, %s) failed: %s\n",
2555 pcap_strerror(errno
));
2562 #else /* HAVE_FORK && HAVE_VFORK */
2564 compress_savefile(const char *filename
)
2567 "compress_savefile failed. Functionality not implemented under your system\n");
2569 #endif /* HAVE_FORK && HAVE_VFORK */
2572 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2574 struct dump_info
*dump_info
;
2580 dump_info
= (struct dump_info
*)user
;
2583 * XXX - this won't force the file to rotate on the specified time
2584 * boundary, but it will rotate on the first packet received after the
2585 * specified Gflag number of seconds. Note: if a Gflag time boundary
2586 * and a Cflag size boundary coincide, the time rotation will occur
2587 * first thereby cancelling the Cflag boundary (since the file should
2591 /* Check if it is time to rotate */
2594 /* Get the current time */
2595 if ((t
= time(NULL
)) == (time_t)-1) {
2596 error("dump_and_trunc_packet: can't get current_time: %s",
2597 pcap_strerror(errno
));
2601 /* If the time is greater than the specified window, rotate */
2602 if (t
- Gflag_time
>= Gflag
) {
2603 #ifdef HAVE_CAPSICUM
2608 /* Update the Gflag_time */
2610 /* Update Gflag_count */
2613 * Close the current file and open a new one.
2615 pcap_dump_close(dump_info
->p
);
2618 * Compress the file we just closed, if the user asked for it
2621 compress_savefile(dump_info
->CurrentFileName
);
2624 * Check to see if we've exceeded the Wflag (when
2627 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2628 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2634 if (dump_info
->CurrentFileName
!= NULL
)
2635 free(dump_info
->CurrentFileName
);
2636 /* Allocate space for max filename + \0. */
2637 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2638 if (dump_info
->CurrentFileName
== NULL
)
2639 error("dump_packet_and_trunc: malloc");
2641 * Gflag was set otherwise we wouldn't be here. Reset the count
2642 * so multiple files would end with 1,2,3 in the filename.
2643 * The counting is handled with the -C flow after this.
2648 * This is always the first file in the Cflag
2650 * We also don't need numbering if Cflag is not set.
2653 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2656 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2658 #ifdef HAVE_LIBCAP_NG
2659 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2660 capng_apply(CAPNG_SELECT_BOTH
);
2661 #endif /* HAVE_LIBCAP_NG */
2662 #ifdef HAVE_CAPSICUM
2663 fd
= openat(dump_info
->dirfd
,
2664 dump_info
->CurrentFileName
,
2665 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2667 error("unable to open file %s",
2668 dump_info
->CurrentFileName
);
2670 fp
= fdopen(fd
, "w");
2672 error("unable to fdopen file %s",
2673 dump_info
->CurrentFileName
);
2675 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2676 #else /* !HAVE_CAPSICUM */
2677 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2679 #ifdef HAVE_LIBCAP_NG
2680 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2681 capng_apply(CAPNG_SELECT_BOTH
);
2682 #endif /* HAVE_LIBCAP_NG */
2683 if (dump_info
->p
== NULL
)
2684 error("%s", pcap_geterr(pd
));
2685 #ifdef HAVE_CAPSICUM
2686 set_dumper_capsicum_rights(dump_info
->p
);
2692 * XXX - this won't prevent capture files from getting
2693 * larger than Cflag - the last packet written to the
2694 * file could put it over Cflag.
2697 #ifdef HAVE_PCAP_DUMP_FTELL64
2698 int64_t size
= pcap_dump_ftell64(dump_info
->p
);
2701 * XXX - this only handles a Cflag value > 2^31-1 on
2702 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2703 * Windows) or LLP64 (64-bit Windows) would require
2704 * a version of libpcap with pcap_dump_ftell64().
2706 long size
= pcap_dump_ftell(dump_info
->p
);
2710 error("ftell fails on output file");
2712 #ifdef HAVE_CAPSICUM
2718 * Close the current file and open a new one.
2720 pcap_dump_close(dump_info
->p
);
2723 * Compress the file we just closed, if the user
2727 compress_savefile(dump_info
->CurrentFileName
);
2731 if (Cflag_count
>= Wflag
)
2734 if (dump_info
->CurrentFileName
!= NULL
)
2735 free(dump_info
->CurrentFileName
);
2736 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2737 if (dump_info
->CurrentFileName
== NULL
)
2738 error("dump_packet_and_trunc: malloc");
2739 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2740 #ifdef HAVE_LIBCAP_NG
2741 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2742 capng_apply(CAPNG_SELECT_BOTH
);
2743 #endif /* HAVE_LIBCAP_NG */
2744 #ifdef HAVE_CAPSICUM
2745 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2746 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2748 error("unable to open file %s",
2749 dump_info
->CurrentFileName
);
2751 fp
= fdopen(fd
, "w");
2753 error("unable to fdopen file %s",
2754 dump_info
->CurrentFileName
);
2756 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2757 #else /* !HAVE_CAPSICUM */
2758 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2760 #ifdef HAVE_LIBCAP_NG
2761 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2762 capng_apply(CAPNG_SELECT_BOTH
);
2763 #endif /* HAVE_LIBCAP_NG */
2764 if (dump_info
->p
== NULL
)
2765 error("%s", pcap_geterr(pd
));
2766 #ifdef HAVE_CAPSICUM
2767 set_dumper_capsicum_rights(dump_info
->p
);
2772 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2773 #ifdef HAVE_PCAP_DUMP_FLUSH
2775 pcap_dump_flush(dump_info
->p
);
2778 if (dump_info
->ndo
!= NULL
)
2779 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2787 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2789 struct dump_info
*dump_info
;
2795 dump_info
= (struct dump_info
*)user
;
2797 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2798 #ifdef HAVE_PCAP_DUMP_FLUSH
2800 pcap_dump_flush(dump_info
->p
);
2803 if (dump_info
->ndo
!= NULL
)
2804 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2812 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2818 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2825 #ifdef SIGNAL_REQ_INFO
2826 void requestinfo(int signo _U_
)
2836 print_packets_captured (void)
2838 static u_int prev_packets_captured
, first
= 1;
2840 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2841 fprintf(stderr
, "Got %u\r", packets_captured
);
2843 prev_packets_captured
= packets_captured
;
2848 * Called once each second in verbose mode while dumping to file
2851 static void CALLBACK
verbose_stats_dump(PVOID param _U_
,
2852 BOOLEAN timer_fired _U_
)
2854 print_packets_captured();
2857 static void verbose_stats_dump(int sig _U_
)
2859 print_packets_captured();
2863 USES_APPLE_DEPRECATED_API
2867 #ifndef HAVE_PCAP_LIB_VERSION
2868 #ifdef HAVE_PCAP_VERSION
2869 extern char pcap_version
[];
2870 #else /* HAVE_PCAP_VERSION */
2871 static char pcap_version
[] = "unknown";
2872 #endif /* HAVE_PCAP_VERSION */
2873 #endif /* HAVE_PCAP_LIB_VERSION */
2874 const char *smi_version_string
;
2876 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
2877 #ifdef HAVE_PCAP_LIB_VERSION
2878 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
2879 #else /* HAVE_PCAP_LIB_VERSION */
2880 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2881 #endif /* HAVE_PCAP_LIB_VERSION */
2883 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2884 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2887 smi_version_string
= nd_smi_version_string();
2888 if (smi_version_string
!= NULL
)
2889 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2890 #ifdef HAVE_DNET_HTOA
2891 (void)fprintf(stderr
, "libdnet unknown version\n");
2894 #if defined(__SANITIZE_ADDRESS__)
2895 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
2896 #elif defined(__has_feature)
2897 # if __has_feature(address_sanitizer)
2898 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
2900 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2908 (void)fprintf(stderr
,
2909 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2910 (void)fprintf(stderr
,
2911 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2912 (void)fprintf(stderr
,
2913 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
2914 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2915 (void)fprintf(stderr
,
2916 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
2918 (void)fprintf(stderr
,
2919 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
2920 (void)fprintf(stderr
,
2921 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
2922 (void)fprintf(stderr
,
2923 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
2924 (void)fprintf(stderr
,
2925 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
2926 (void)fprintf(stderr
,
2927 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");
2931 * c-style: whitesmith