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 */
101 #include <sys/wait.h>
102 #include <sys/resource.h>
107 /* capabilities convenience library */
108 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
109 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
110 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
112 #ifdef HAVE_LIBCAP_NG
116 #undef HAVE_LIBCAP_NG
117 #endif /* HAVE_CAP_NG_H */
118 #endif /* HAVE_LIBCAP_NG */
121 #include <sys/sysctl.h>
122 #endif /* __FreeBSD__ */
124 #include "netdissect.h"
125 #include "interface.h"
126 #include "addrtoname.h"
128 #include "gmt2local.h"
129 #include "pcap-missing.h"
130 #include "ascii_strcasecmp.h"
135 #define PATH_MAX 1024
139 #define SIGNAL_REQ_INFO SIGINFO
141 #define SIGNAL_REQ_INFO SIGUSR1
144 static int Bflag
; /* buffer size */
145 #ifdef HAVE_PCAP_DUMP_FTELL64
146 static int64_t Cflag
; /* rotate dump files after this many bytes */
148 static long Cflag
; /* rotate dump files after this many bytes */
150 static int Cflag_count
; /* Keep track of which file number we're writing */
151 #ifdef HAVE_PCAP_FINDALLDEVS
152 static int Dflag
; /* list available devices and exit */
154 #ifdef HAVE_PCAP_FINDALLDEVS_EX
155 static char *remote_interfaces_source
; /* list available devices from this source and exit */
159 * This is exported because, in some versions of libpcap, if libpcap
160 * is built with optimizer debugging code (which is *NOT* the default
161 * configuration!), the library *imports*(!) a variable named dflag,
162 * under the expectation that tcpdump is exporting it, to govern
163 * how much debugging information to print when optimizing
164 * the generated BPF code.
166 * This is a horrible hack; newer versions of libpcap don't import
167 * dflag but, instead, *if* built with optimizer debugging code,
168 * *export* a routine to set that flag.
170 int dflag
; /* print filter code */
171 static int Gflag
; /* rotate dump files after this many seconds */
172 static int Gflag_count
; /* number of files created with Gflag rotation */
173 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
174 static int Lflag
; /* list available data link types and exit */
175 static int Iflag
; /* rfmon (monitor) mode */
176 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
177 static int Jflag
; /* list available time stamp types */
179 static int jflag
= -1; /* packet time stamp source */
180 static int pflag
; /* don't go promiscuous */
181 #ifdef HAVE_PCAP_SETDIRECTION
182 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
184 static int Uflag
; /* "unbuffered" output of dump files */
185 static int Wflag
; /* recycle output files after this number of files */
186 static int WflagChars
;
187 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
188 static int immediate_mode
;
190 static int infodelay
;
191 static int infoprint
;
196 cap_channel_t
*capdns
;
200 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
201 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
202 static NORETURN
void exit_tcpdump(int);
203 static void (*setsignal (int sig
, void (*func
)(int)))(int);
204 static void cleanup(int);
205 static void child_cleanup(int);
206 static void print_version(void);
207 static void print_usage(void);
208 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
209 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
210 #ifdef HAVE_PCAP_FINDALLDEVS
211 static NORETURN
void show_devices_and_exit(void);
213 #ifdef HAVE_PCAP_FINDALLDEVS_EX
214 static NORETURN
void show_remote_devices_and_exit(void);
217 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
218 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
219 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
220 static void droproot(const char *, const char *);
222 #ifdef SIGNAL_REQ_INFO
223 void requestinfo(int);
226 #if defined(USE_WIN32_MM_TIMER)
227 #include <MMsystem.h>
228 static UINT timer_id
;
229 static void CALLBACK
verbose_stats_dump(UINT
, UINT
, DWORD_PTR
, DWORD_PTR
, DWORD_PTR
);
230 #elif defined(HAVE_ALARM)
231 static void verbose_stats_dump(int sig
);
234 static void info(int);
235 static u_int packets_captured
;
237 #ifdef HAVE_PCAP_FINDALLDEVS
238 static const struct tok status_flags
[] = {
240 { PCAP_IF_UP
, "Up" },
242 #ifdef PCAP_IF_RUNNING
243 { PCAP_IF_RUNNING
, "Running" },
245 { PCAP_IF_LOOPBACK
, "Loopback" },
252 static int supports_monitor_mode
;
260 char *CurrentFileName
;
263 netdissect_options
*ndo
;
269 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
271 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
272 * by any libpcap header, because it's a special hack, only available if
273 * libpcap was configured to include it, and only intended for use by
274 * libpcap developers trying to debug the parser for filter expressions).
277 __declspec(dllimport
)
281 void pcap_set_parser_debug(int);
282 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
284 * We don't have pcap_set_parser_debug() in libpcap, but we do have
285 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
286 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
289 pcap_set_parser_debug(int value
)
291 #ifdef HAVE_PCAP_DEBUG
292 extern int pcap_debug
;
295 #else /* HAVE_PCAP_DEBUG */
299 #endif /* HAVE_PCAP_DEBUG */
302 #define HAVE_PCAP_SET_PARSER_DEBUG
305 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
307 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
308 * by any libpcap header, because it's a special hack, only available if
309 * libpcap was configured to include it, and only intended for use by
310 * libpcap developers trying to debug the optimizer for filter expressions).
313 __declspec(dllimport
)
317 void pcap_set_optimizer_debug(int);
322 error(const char *fmt
, ...)
326 (void)fprintf(stderr
, "%s: ", program_name
);
328 (void)vfprintf(stderr
, fmt
, ap
);
333 (void)fputc('\n', stderr
);
341 warning(const char *fmt
, ...)
345 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
347 (void)vfprintf(stderr
, fmt
, ap
);
352 (void)fputc('\n', stderr
);
357 exit_tcpdump(int status
)
363 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
365 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
368 int *tstamp_types
= 0;
369 const char *tstamp_type_name
;
372 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
373 if (n_tstamp_types
< 0)
374 error("%s", pcap_geterr(pc
));
376 if (n_tstamp_types
== 0) {
377 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
381 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
383 for (i
= 0; i
< n_tstamp_types
; i
++) {
384 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
385 if (tstamp_type_name
!= NULL
) {
386 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
387 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
389 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
392 pcap_free_tstamp_types(tstamp_types
);
398 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
402 const char *dlt_name
;
404 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
406 error("%s", pcap_geterr(pc
));
407 else if (n_dlts
== 0 || !dlts
)
408 error("No data link types.");
411 * If the interface is known to support monitor mode, indicate
412 * whether these are the data link types available when not in
413 * monitor mode, if -I wasn't specified, or when in monitor mode,
414 * when -I was specified (the link-layer types available in
415 * monitor mode might be different from the ones available when
416 * not in monitor mode).
418 if (supports_monitor_mode
)
419 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
421 Iflag
? "when in monitor mode" : "when not in monitor mode");
423 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
426 for (i
= 0; i
< n_dlts
; i
++) {
427 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
428 if (dlt_name
!= NULL
) {
429 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
430 pcap_datalink_val_to_description(dlts
[i
]));
433 * OK, does tcpdump handle that type?
435 if (!has_printer(dlts
[i
]))
436 (void) fprintf(stderr
, " (printing not supported)");
437 fprintf(stderr
, "\n");
439 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
443 #ifdef HAVE_PCAP_FREE_DATALINKS
444 pcap_free_datalinks(dlts
);
449 #ifdef HAVE_PCAP_FINDALLDEVS
451 show_devices_and_exit(void)
453 pcap_if_t
*dev
, *devlist
;
454 char ebuf
[PCAP_ERRBUF_SIZE
];
457 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
459 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
460 printf("%d.%s", i
+1, dev
->name
);
461 if (dev
->description
!= NULL
)
462 printf(" (%s)", dev
->description
);
464 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
467 pcap_freealldevs(devlist
);
470 #endif /* HAVE_PCAP_FINDALLDEVS */
472 #ifdef HAVE_PCAP_FINDALLDEVS_EX
474 show_remote_devices_and_exit(void)
476 pcap_if_t
*dev
, *devlist
;
477 char ebuf
[PCAP_ERRBUF_SIZE
];
480 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
483 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
484 printf("%d.%s", i
+1, dev
->name
);
485 if (dev
->description
!= NULL
)
486 printf(" (%s)", dev
->description
);
488 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
491 pcap_freealldevs(devlist
);
494 #endif /* HAVE_PCAP_FINDALLDEVS */
499 * Note that there we use all letters for short options except for g, k,
500 * o, and P, and those are used by other versions of tcpdump, and we should
501 * only use them for the same purposes that the other versions of tcpdump
504 * OS X tcpdump uses -g to force non--v output for IP to be on one
505 * line, making it more "g"repable;
507 * OS X tcpdump uses -k to specify that packet comments in pcap-ng files
510 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
511 * for hosts sending TCP SYN packets;
513 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
516 * OS X tcpdump also uses -Q to specify expressions that match packet
517 * metadata, including but not limited to the packet direction.
518 * The expression syntax is different from a simple "in|out|inout",
519 * and those expressions aren't accepted by OS X tcpdump, but the
520 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
521 * "inout" = "dir=in or dir=out", and the parser could conceivably
522 * special-case "in", "out", and "inout" as expressions for backwards
523 * compatibility, so all is not (yet) lost.
527 * Set up flags that might or might not be supported depending on the
528 * version of libpcap we're using.
530 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
532 #define B_FLAG_USAGE " [ -B size ]"
533 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
536 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
538 #ifdef HAVE_PCAP_FINDALLDEVS
544 #ifdef HAVE_PCAP_CREATE
546 #else /* HAVE_PCAP_CREATE */
548 #endif /* HAVE_PCAP_CREATE */
550 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
552 #define j_FLAG_USAGE " [ -j tstamptype ]"
554 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
558 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
560 #ifdef HAVE_PCAP_SETDIRECTION
562 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
568 #ifdef HAVE_PCAP_DUMP_FLUSH
574 #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:#"
579 * We do not currently have long options corresponding to all short
580 * options; we should probably pick appropriate option names for them.
582 * However, the short options where the number of times the option is
583 * specified matters, such as -v and -d and -t, should probably not
584 * just map to a long option, as saying
586 * tcpdump --verbose --verbose
588 * doesn't make sense; it should be --verbosity={N} or something such
591 * For long options with no corresponding short options, we define values
592 * outside the range of ASCII graphic characters, make that the last
593 * component of the entry for the long option, and have a case for that
594 * option in the switch statement.
596 #define OPTION_VERSION 128
597 #define OPTION_TSTAMP_PRECISION 129
598 #define OPTION_IMMEDIATE_MODE 130
599 #define OPTION_PRINT 131
600 #define OPTION_LIST_REMOTE_INTERFACES 132
602 static const struct option longopts
[] = {
603 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
604 { "buffer-size", required_argument
, NULL
, 'B' },
606 { "list-interfaces", no_argument
, NULL
, 'D' },
607 #ifdef HAVE_PCAP_FINDALLDEVS_EX
608 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
610 { "help", no_argument
, NULL
, 'h' },
611 { "interface", required_argument
, NULL
, 'i' },
612 #ifdef HAVE_PCAP_CREATE
613 { "monitor-mode", no_argument
, NULL
, 'I' },
615 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
616 { "time-stamp-type", required_argument
, NULL
, 'j' },
617 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
619 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
620 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
622 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
623 { "list-data-link-types", no_argument
, NULL
, 'L' },
624 { "no-optimize", no_argument
, NULL
, 'O' },
625 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
626 #ifdef HAVE_PCAP_SETDIRECTION
627 { "direction", required_argument
, NULL
, 'Q' },
629 { "snapshot-length", required_argument
, NULL
, 's' },
630 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
631 #ifdef HAVE_PCAP_DUMP_FLUSH
632 { "packet-buffered", no_argument
, NULL
, 'U' },
634 { "linktype", required_argument
, NULL
, 'y' },
635 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
636 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
638 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
639 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
641 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
642 { "number", no_argument
, NULL
, '#' },
643 { "print", no_argument
, NULL
, OPTION_PRINT
},
644 { "version", no_argument
, NULL
, OPTION_VERSION
},
648 #ifdef HAVE_PCAP_FINDALLDEVS_EX
649 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
651 #define LIST_REMOTE_INTERFACES_USAGE
654 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
655 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
657 #define IMMEDIATE_MODE_USAGE ""
660 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
661 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
663 #define TIME_STAMP_PRECISION_USAGE
667 /* Drop root privileges and chroot if necessary */
669 droproot(const char *username
, const char *chroot_dir
)
671 struct passwd
*pw
= NULL
;
673 if (chroot_dir
&& !username
) {
674 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
679 pw
= getpwnam(username
);
682 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
683 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
684 program_name
, chroot_dir
, pcap_strerror(errno
));
688 #ifdef HAVE_LIBCAP_NG
690 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
692 fprintf(stderr
, "error : ret %d\n", ret
);
694 fprintf(stderr
, "dropped privs to %s\n", username
);
698 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
699 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
700 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
701 program_name
, username
,
702 (unsigned long)pw
->pw_uid
,
703 (unsigned long)pw
->pw_gid
,
704 pcap_strerror(errno
));
708 fprintf(stderr
, "dropped privs to %s\n", username
);
710 #endif /* HAVE_LIBCAP_NG */
713 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
714 program_name
, username
);
717 #ifdef HAVE_LIBCAP_NG
718 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
719 DIAG_OFF_CLANG(assign
-enum)
722 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
727 DIAG_ON_CLANG(assign
-enum)
728 capng_apply(CAPNG_SELECT_BOTH
);
729 #endif /* HAVE_LIBCAP_NG */
750 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
752 char *filename
= malloc(PATH_MAX
+ 1);
753 if (filename
== NULL
)
754 error("Makefilename: malloc");
756 /* Process with strftime if Gflag is set. */
760 /* Convert Gflag_time to a usable format */
761 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
762 error("MakeTimedFilename: localtime");
765 /* There's no good way to detect an error in strftime since a return
766 * value of 0 isn't necessarily failure.
768 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
770 strncpy(filename
, orig_name
, PATH_MAX
);
773 if (cnt
== 0 && max_chars
== 0)
774 strncpy(buffer
, filename
, PATH_MAX
+ 1);
776 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
777 /* Report an error if the filename is too large */
778 error("too many output files or filename is too long (> %d)", PATH_MAX
);
783 get_next_file(FILE *VFile
, char *ptr
)
787 ret
= fgets(ptr
, PATH_MAX
, VFile
);
791 if (ptr
[strlen(ptr
) - 1] == '\n')
792 ptr
[strlen(ptr
) - 1] = '\0';
798 static cap_channel_t
*
801 cap_channel_t
*capcas
, *capdnsloc
;
802 const char *types
[1];
807 error("unable to create casper process");
808 capdnsloc
= cap_service_open(capcas
, "system.dns");
809 /* Casper capability no longer needed. */
811 if (capdnsloc
== NULL
)
812 error("unable to open system.dns service");
813 /* Limit system.dns to reverse DNS lookups. */
815 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
816 error("unable to limit access to system.dns service");
817 families
[0] = AF_INET
;
818 families
[1] = AF_INET6
;
819 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
820 error("unable to limit access to system.dns service");
824 #endif /* HAVE_CASPER */
826 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
828 tstamp_precision_from_string(const char *precision
)
830 if (strncmp(precision
, "nano", strlen("nano")) == 0)
831 return PCAP_TSTAMP_PRECISION_NANO
;
833 if (strncmp(precision
, "micro", strlen("micro")) == 0)
834 return PCAP_TSTAMP_PRECISION_MICRO
;
840 tstamp_precision_to_string(int precision
)
844 case PCAP_TSTAMP_PRECISION_MICRO
:
847 case PCAP_TSTAMP_PRECISION_NANO
:
858 * Ensure that, on a dump file's descriptor, we have all the rights
859 * necessary to make the standard I/O library work with an fdopen()ed
860 * FILE * from that descriptor.
862 * A long time ago, in a galaxy far far away, AT&T decided that, instead
863 * of providing separate APIs for getting and setting the FD_ flags on a
864 * descriptor, getting and setting the O_ flags on a descriptor, and
865 * locking files, they'd throw them all into a kitchen-sink fcntl() call
866 * along the lines of ioctl(), the fact that ioctl() operations are
867 * largely specific to particular character devices but fcntl() operations
868 * are either generic to all descriptors or generic to all descriptors for
869 * regular files nonwithstanding.
871 * The Capsicum people decided that fine-grained control of descriptor
872 * operations was required, so that you need to grant permission for
873 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
874 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
875 * collection of things, so there are *individual* fcntls for which
876 * permission needs to be granted.
878 * The FreeBSD standard I/O people implemented some optimizations that
879 * requires that the standard I/O routines be able to determine whether
880 * the descriptor for the FILE * is open append-only or not; as that
881 * descriptor could have come from an open() rather than an fopen(),
882 * that requires that it be able to do an F_GETFL fcntl() to read
885 * Tcpdump uses ftell() to determine how much data has been written
886 * to a file in order to, when used with -C, determine when it's time
887 * to rotate capture files. ftell() therefore needs to do an lseek()
888 * to find out the file offset and must, thanks to the aforementioned
889 * optimization, also know whether the descriptor is open append-only
892 * The net result of all the above is that we need to grant CAP_SEEK,
893 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
895 * Perhaps this is the universe's way of saying that either
897 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
898 * using it, so that Capsicum-capable tcpdump wouldn't need to do
903 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
904 * I/O library that knows what rights are needed by the standard
905 * I/O library, based on the open mode, and assigns them, perhaps
906 * with an additional argument indicating, for example, whether
907 * seeking should be allowed, so that tcpdump doesn't need to know
908 * what the standard I/O library happens to require this week.
911 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
913 int fd
= fileno(pcap_dump_file(p
));
916 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
917 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
918 error("unable to limit dump descriptor");
920 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
921 error("unable to limit dump descriptor fcntls");
927 * Copy arg vector into a new buffer, concatenating arguments with spaces.
930 copy_argv(register char **argv
)
933 register u_int len
= 0;
942 len
+= strlen(*p
++) + 1;
944 buf
= (char *)malloc(len
);
946 error("copy_argv: malloc");
950 while ((src
= *p
++) != NULL
) {
951 while ((*dst
++ = *src
++) != '\0')
961 * On Windows, we need to open the file in binary mode, so that
962 * we get all the bytes specified by the size we get from "fstat()".
963 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
964 * we define it as 0 if it's not defined, so it does nothing.
971 read_infile(char *fname
)
973 register int i
, fd
, cc
;
977 fd
= open(fname
, O_RDONLY
|O_BINARY
);
979 error("can't open %s: %s", fname
, pcap_strerror(errno
));
981 if (fstat(fd
, &buf
) < 0)
982 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
984 cp
= malloc((u_int
)buf
.st_size
+ 1);
986 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
987 fname
, pcap_strerror(errno
));
988 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
990 error("read %s: %s", fname
, pcap_strerror(errno
));
991 if (cc
!= buf
.st_size
)
992 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
995 /* replace "# comment" with spaces */
996 for (i
= 0; i
< cc
; i
++) {
998 while (i
< cc
&& cp
[i
] != '\n')
1005 #ifdef HAVE_PCAP_FINDALLDEVS
1007 parse_interface_number(const char *device
)
1012 devnum
= strtol(device
, &end
, 10);
1013 if (device
!= end
&& *end
== '\0') {
1015 * It's all-numeric, but is it a valid number?
1019 * No, it's not an ordinal.
1021 error("Invalid adapter index");
1026 * It's not all-numeric; return -1, so our caller
1034 find_interface_by_number(long devnum
)
1036 pcap_if_t
*dev
, *devlist
;
1038 char ebuf
[PCAP_ERRBUF_SIZE
];
1041 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
1044 * Look for the devnum-th entry in the list of devices (1-based).
1046 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1047 i
++, dev
= dev
->next
)
1050 error("Invalid adapter index");
1051 device
= strdup(dev
->name
);
1052 pcap_freealldevs(devlist
);
1057 #ifdef HAVE_PCAP_OPEN
1059 * Prefix for rpcap URLs.
1061 static char rpcap_prefix
[] = "rpcap://";
1065 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1068 #ifdef HAVE_PCAP_CREATE
1073 #ifdef HAVE_PCAP_OPEN
1075 * Is this an rpcap URL?
1077 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1079 * Yes. Open it with pcap_open().
1082 fprintf(stderr
, "Opening %s\n", device
);
1083 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1084 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1088 * If this failed with "No such device", that means
1089 * the interface doesn't exist; return NULL, so that
1090 * the caller can see whether the device name is
1091 * actually an interface index.
1093 if (strstr(ebuf
, "No such device") != NULL
)
1098 warning("%s", ebuf
);
1101 #endif /* HAVE_PCAP_OPEN */
1103 #ifdef HAVE_PCAP_CREATE
1104 pc
= pcap_create(device
, ebuf
);
1107 * If this failed with "No such device", that means
1108 * the interface doesn't exist; return NULL, so that
1109 * the caller can see whether the device name is
1110 * actually an interface index.
1112 if (strstr(ebuf
, "No such device") != NULL
)
1116 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1118 show_tstamp_types_and_exit(pc
, device
);
1120 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1121 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1123 error("%s: Can't set %ssecond time stamp precision: %s",
1125 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1126 pcap_statustostr(status
));
1129 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1130 if (immediate_mode
) {
1131 status
= pcap_set_immediate_mode(pc
, 1);
1133 error("%s: Can't set immediate mode: %s",
1135 pcap_statustostr(status
));
1139 * Is this an interface that supports monitor mode?
1141 if (pcap_can_set_rfmon(pc
) == 1)
1142 supports_monitor_mode
= 1;
1144 supports_monitor_mode
= 0;
1145 if (ndo
->ndo_snaplen
!= 0) {
1147 * A snapshot length was explicitly specified;
1150 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1152 error("%s: Can't set snapshot length: %s",
1153 device
, pcap_statustostr(status
));
1155 status
= pcap_set_promisc(pc
, !pflag
);
1157 error("%s: Can't set promiscuous mode: %s",
1158 device
, pcap_statustostr(status
));
1160 status
= pcap_set_rfmon(pc
, 1);
1162 error("%s: Can't set monitor mode: %s",
1163 device
, pcap_statustostr(status
));
1165 status
= pcap_set_timeout(pc
, 1000);
1167 error("%s: pcap_set_timeout failed: %s",
1168 device
, pcap_statustostr(status
));
1170 status
= pcap_set_buffer_size(pc
, Bflag
);
1172 error("%s: Can't set buffer size: %s",
1173 device
, pcap_statustostr(status
));
1175 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1177 status
= pcap_set_tstamp_type(pc
, jflag
);
1179 error("%s: Can't set time stamp type: %s",
1180 device
, pcap_statustostr(status
));
1183 status
= pcap_activate(pc
);
1186 * pcap_activate() failed.
1188 cp
= pcap_geterr(pc
);
1189 if (status
== PCAP_ERROR
)
1191 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1193 * Return an error for our caller to handle.
1195 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1196 device
, pcap_statustostr(status
), cp
);
1199 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1200 error("%s: %s\n(%s)", device
,
1201 pcap_statustostr(status
), cp
);
1203 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1204 strncmp(device
, "wlan", 4) == 0) {
1205 char parent
[8], newdev
[8];
1207 size_t s
= sizeof(parent
);
1209 snprintf(sysctl
, sizeof(sysctl
),
1210 "net.wlan.%d.%%parent", atoi(device
+ 4));
1211 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1212 strlcpy(newdev
, device
, sizeof(newdev
));
1213 /* Suggest a new wlan device. */
1214 /* FIXME: incrementing the index this way is not going to work well
1215 * when the index is 9 or greater but the only consequence in this
1216 * specific case would be an error message that looks a bit odd.
1218 newdev
[strlen(newdev
)-1]++;
1219 error("%s is not a monitor mode VAP\n"
1220 "To create a new monitor mode VAP use:\n"
1221 " ifconfig %s create wlandev %s wlanmode monitor\n"
1222 "and use %s as the tcpdump interface",
1223 device
, newdev
, parent
, newdev
);
1227 error("%s: %s", device
,
1228 pcap_statustostr(status
));
1229 } else if (status
> 0) {
1231 * pcap_activate() succeeded, but it's warning us
1232 * of a problem it had.
1234 cp
= pcap_geterr(pc
);
1235 if (status
== PCAP_WARNING
)
1237 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1239 warning("%s: %s\n(%s)", device
,
1240 pcap_statustostr(status
), cp
);
1242 warning("%s: %s", device
,
1243 pcap_statustostr(status
));
1245 #ifdef HAVE_PCAP_SETDIRECTION
1247 status
= pcap_setdirection(pc
, Qflag
);
1249 error("%s: pcap_setdirection() failed: %s",
1250 device
, pcap_geterr(pc
));
1252 #endif /* HAVE_PCAP_SETDIRECTION */
1253 #else /* HAVE_PCAP_CREATE */
1256 * If no snapshot length was specified, or a length of 0 was
1257 * specified, default to 256KB.
1259 if (ndo
->ndo_snaplen
== 0)
1260 ndo
->ndo_snaplen
= 262144;
1261 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1264 * If this failed with "No such device", that means
1265 * the interface doesn't exist; return NULL, so that
1266 * the caller can see whether the device name is
1267 * actually an interface index.
1269 if (strstr(ebuf
, "No such device") != NULL
)
1274 warning("%s", ebuf
);
1275 #endif /* HAVE_PCAP_CREATE */
1281 main(int argc
, char **argv
)
1283 register int cnt
, op
, i
;
1284 bpf_u_int32 localnet
= 0, netmask
= 0;
1285 int timezone_offset
= 0;
1286 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1288 pcap_handler callback
;
1290 const char *dlt_name
;
1291 struct bpf_program fcode
;
1293 void (*oldhandler
)(int);
1295 struct dump_info dumpinfo
;
1296 u_char
*pcap_userdata
;
1297 char ebuf
[PCAP_ERRBUF_SIZE
];
1298 char VFileLine
[PATH_MAX
+ 1];
1299 char *username
= NULL
;
1300 char *chroot_dir
= NULL
;
1303 #ifdef HAVE_PCAP_FINDALLDEVS
1309 #ifdef HAVE_CAPSICUM
1310 cap_rights_t rights
;
1312 #endif /* HAVE_CAPSICUM */
1313 int Oflag
= 1; /* run filter code optimizer */
1315 const char *yflag_dlt_name
= NULL
;
1318 netdissect_options Ndo
;
1319 netdissect_options
*ndo
= &Ndo
;
1322 * Initialize the netdissect code.
1324 if (nd_init(ebuf
, sizeof ebuf
) == -1)
1327 memset(ndo
, 0, sizeof(*ndo
));
1328 ndo_set_function_pointers(ndo
);
1338 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1339 ndo
->program_name
= program_name
= cp
+ 1;
1341 ndo
->program_name
= program_name
= argv
[0];
1344 if (pcap_wsockinit() != 0)
1345 error("Attempting to initialize Winsock failed");
1349 * On platforms where the CPU doesn't support unaligned loads,
1350 * force unaligned accesses to abort with SIGBUS, rather than
1351 * being fixed up (slowly) by the OS kernel; on those platforms,
1352 * misaligned accesses are bugs, and we want tcpdump to crash so
1353 * that the bugs are reported.
1355 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1359 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1363 /* compatibility for old -a */
1374 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1376 Bflag
= atoi(optarg
)*1024;
1378 error("invalid packet buffer size %s", optarg
);
1380 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1385 error("invalid packet count %s", optarg
);
1390 #ifdef HAVE_PCAP_DUMP_FTELL64
1391 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1393 Cflag
= strtol(optarg
, &endp
, 10);
1395 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1397 error("invalid file size %s", optarg
);
1399 * Will multiplying it by 1000000 overflow?
1401 #ifdef HAVE_PCAP_DUMP_FTELL64
1402 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1404 if (Cflag
> LONG_MAX
/ 1000000)
1406 error("file size %s is too large", optarg
);
1414 #ifdef HAVE_PCAP_FINDALLDEVS
1420 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1421 case OPTION_LIST_REMOTE_INTERFACES
:
1422 remote_interfaces_source
= optarg
;
1435 #ifndef HAVE_LIBCRYPTO
1436 warning("crypto code not compiled in");
1438 ndo
->ndo_espsecret
= optarg
;
1450 Gflag
= atoi(optarg
);
1452 error("invalid number of seconds %s", optarg
);
1454 /* We will create one file initially. */
1457 /* Grab the current time for rotation use. */
1458 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1459 error("main: can't get current time: %s",
1460 pcap_strerror(errno
));
1477 #ifdef HAVE_PCAP_CREATE
1481 #endif /* HAVE_PCAP_CREATE */
1483 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1485 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1487 error("invalid time stamp type %s", optarg
);
1498 * _IOLBF is the same as _IOFBF in Microsoft's C
1499 * libraries; the only alternative they offer
1502 * XXX - this should really be checking for MSVC++,
1503 * not _WIN32, if, for example, MinGW has its own
1504 * C library that is more UNIX-compatible.
1506 setvbuf(stdout
, NULL
, _IONBF
, 0);
1508 #ifdef HAVE_SETLINEBUF
1511 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1521 if (nd_have_smi_support()) {
1522 if (nd_load_smi_module(optarg
, ebuf
, sizeof ebuf
) == -1)
1525 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1526 program_name
, optarg
);
1527 (void)fprintf(stderr
, "(no libsmi support)\n");
1532 /* TCP-MD5 shared secret */
1533 #ifndef HAVE_LIBCRYPTO
1534 warning("crypto code not compiled in");
1536 ndo
->ndo_sigsecret
= optarg
;
1557 ++ndo
->ndo_suppress_default_print
;
1560 #ifdef HAVE_PCAP_SETDIRECTION
1562 if (ascii_strcasecmp(optarg
, "in") == 0)
1564 else if (ascii_strcasecmp(optarg
, "out") == 0)
1566 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1567 Qflag
= PCAP_D_INOUT
;
1569 error("unknown capture direction `%s'", optarg
);
1571 #endif /* HAVE_PCAP_SETDIRECTION */
1578 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1579 if (optarg
== end
|| *end
!= '\0'
1580 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1581 error("invalid snaplen %s", optarg
);
1593 if (ascii_strcasecmp(optarg
, "vat") == 0)
1594 ndo
->ndo_packettype
= PT_VAT
;
1595 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1596 ndo
->ndo_packettype
= PT_WB
;
1597 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1598 ndo
->ndo_packettype
= PT_RPC
;
1599 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1600 ndo
->ndo_packettype
= PT_RTP
;
1601 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1602 ndo
->ndo_packettype
= PT_RTCP
;
1603 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1604 ndo
->ndo_packettype
= PT_SNMP
;
1605 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1606 ndo
->ndo_packettype
= PT_CNFP
;
1607 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1608 ndo
->ndo_packettype
= PT_TFTP
;
1609 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1610 ndo
->ndo_packettype
= PT_AODV
;
1611 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1612 ndo
->ndo_packettype
= PT_CARP
;
1613 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1614 ndo
->ndo_packettype
= PT_RADIUS
;
1615 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1616 ndo
->ndo_packettype
= PT_ZMTP1
;
1617 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1618 ndo
->ndo_packettype
= PT_VXLAN
;
1619 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1620 ndo
->ndo_packettype
= PT_PGM
;
1621 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1622 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1623 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1624 ndo
->ndo_packettype
= PT_LMP
;
1625 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1626 ndo
->ndo_packettype
= PT_RESP
;
1628 error("unknown packet type `%s'", optarg
);
1635 #ifdef HAVE_PCAP_DUMP_FLUSH
1654 Wflag
= atoi(optarg
);
1656 error("invalid number of output files %s", optarg
);
1657 WflagChars
= getWflagChars(Wflag
);
1662 ++ndo
->ndo_suppress_default_print
;
1667 ++ndo
->ndo_suppress_default_print
;
1671 yflag_dlt_name
= optarg
;
1673 pcap_datalink_name_to_val(yflag_dlt_name
);
1675 error("invalid data link type %s", yflag_dlt_name
);
1678 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1681 /* Undocumented flag */
1682 pcap_set_parser_debug(1);
1695 ndo
->ndo_packet_number
= 1;
1698 case OPTION_VERSION
:
1703 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1704 case OPTION_TSTAMP_PRECISION
:
1705 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1706 if (ndo
->ndo_tstamp_precision
< 0)
1707 error("unsupported time stamp precision");
1711 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1712 case OPTION_IMMEDIATE_MODE
:
1727 #ifdef HAVE_PCAP_FINDALLDEVS
1729 show_devices_and_exit();
1731 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1732 if (remote_interfaces_source
!= NULL
)
1733 show_remote_devices_and_exit();
1736 switch (ndo
->ndo_tflag
) {
1738 case 0: /* Default */
1739 case 4: /* Default + Date*/
1740 timezone_offset
= gmt2local(0);
1743 case 1: /* No time stamp */
1744 case 2: /* Unix timeval style */
1745 case 3: /* Microseconds since previous packet */
1746 case 5: /* Microseconds since first packet */
1749 default: /* Not supported */
1750 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1754 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1755 error("-f can not be used with -V or -r");
1757 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1758 error("-V and -r are mutually exclusive.");
1760 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1762 * If we're printing dissected packets to the standard output
1763 * and the standard output is a terminal, use immediate mode,
1764 * as the user's probably expecting to see packets pop up
1767 * XXX - set the timeout to a lower value, instead? If so,
1768 * what value would be appropriate?
1770 if ((WFileName
== NULL
|| print
) && isatty(1))
1775 /* if run as root, prepare for chrooting */
1776 if (getuid() == 0 || geteuid() == 0) {
1777 /* future extensibility for cmd-line arguments */
1779 chroot_dir
= WITH_CHROOT
;
1784 /* if run as root, prepare for dropping root privileges */
1785 if (getuid() == 0 || geteuid() == 0) {
1786 /* Run with '-Z root' to restore old behaviour */
1788 username
= WITH_USER
;
1792 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1794 * If RFileName is non-null, it's the pathname of a
1795 * savefile to read. If VFileName is non-null, it's
1796 * the pathname of a file containing a list of pathnames
1797 * (one per line) of savefiles to read.
1799 * In either case, we're reading a savefile, not doing
1804 * We don't need network access, so relinquish any set-UID
1805 * or set-GID privileges we have (if any).
1807 * We do *not* want set-UID privileges when opening a
1808 * trace file, as that might let the user read other
1809 * people's trace files (especially if we're set-UID
1812 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1813 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1815 if (VFileName
!= NULL
) {
1816 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1819 VFile
= fopen(VFileName
, "r");
1822 error("Unable to open file: %s\n", pcap_strerror(errno
));
1824 ret
= get_next_file(VFile
, VFileLine
);
1826 error("Nothing in %s\n", VFileName
);
1827 RFileName
= VFileLine
;
1830 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1831 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1832 ndo
->ndo_tstamp_precision
, ebuf
);
1834 pd
= pcap_open_offline(RFileName
, ebuf
);
1839 #ifdef HAVE_CAPSICUM
1840 cap_rights_init(&rights
, CAP_READ
);
1841 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1843 error("unable to limit pcap descriptor");
1846 dlt
= pcap_datalink(pd
);
1847 dlt_name
= pcap_datalink_val_to_name(dlt
);
1848 if (dlt_name
== NULL
) {
1849 fprintf(stderr
, "reading from file %s, link-type %u\n",
1853 "reading from file %s, link-type %s (%s)\n",
1854 RFileName
, dlt_name
,
1855 pcap_datalink_val_to_description(dlt
));
1859 * We're doing a live capture.
1861 if (device
== NULL
) {
1863 * No interface was specified. Pick one.
1865 #ifdef HAVE_PCAP_FINDALLDEVS
1867 * Find the list of interfaces, and pick
1868 * the first interface.
1870 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
1872 if (devlist
== NULL
)
1873 error("no interfaces available for capture");
1874 device
= strdup(devlist
->name
);
1875 pcap_freealldevs(devlist
);
1876 #else /* HAVE_PCAP_FINDALLDEVS */
1878 * Use whatever interface pcap_lookupdev()
1881 device
= pcap_lookupdev(ebuf
);
1888 * Try to open the interface with the specified name.
1890 pd
= open_interface(device
, ndo
, ebuf
);
1893 * That failed. If we can get a list of
1894 * interfaces, and the interface name
1895 * is purely numeric, try to use it as
1896 * a 1-based index in the list of
1899 #ifdef HAVE_PCAP_FINDALLDEVS
1900 devnum
= parse_interface_number(device
);
1903 * It's not a number; just report
1904 * the open error and fail.
1910 * OK, it's a number; try to find the
1911 * interface with that index, and try
1914 * find_interface_by_number() exits if it
1915 * couldn't be found.
1917 device
= find_interface_by_number(devnum
);
1918 pd
= open_interface(device
, ndo
, ebuf
);
1921 #else /* HAVE_PCAP_FINDALLDEVS */
1923 * We can't get a list of interfaces; just
1927 #endif /* HAVE_PCAP_FINDALLDEVS */
1931 * Let user own process after capture device has
1935 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1936 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1938 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1940 if(pcap_setbuff(pd
, Bflag
)==-1){
1941 error("%s", pcap_geterr(pd
));
1943 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1945 show_dlts_and_exit(pd
, device
);
1946 if (yflag_dlt
>= 0) {
1947 #ifdef HAVE_PCAP_SET_DATALINK
1948 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1949 error("%s", pcap_geterr(pd
));
1952 * We don't actually support changing the
1953 * data link type, so we only let them
1954 * set it to what it already is.
1956 if (yflag_dlt
!= pcap_datalink(pd
)) {
1957 error("%s is not one of the DLTs supported by this device\n",
1961 (void)fprintf(stderr
, "%s: data link type %s\n",
1962 program_name
, yflag_dlt_name
);
1963 (void)fflush(stderr
);
1965 i
= pcap_snapshot(pd
);
1966 if (ndo
->ndo_snaplen
< i
) {
1967 if (ndo
->ndo_snaplen
!= 0)
1968 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1969 ndo
->ndo_snaplen
= i
;
1970 } else if (ndo
->ndo_snaplen
> i
) {
1971 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
1972 ndo
->ndo_snaplen
= i
;
1974 if(ndo
->ndo_fflag
!= 0) {
1975 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1976 warning("foreign (-f) flag used but: %s", ebuf
);
1982 cmdbuf
= read_infile(infile
);
1984 cmdbuf
= copy_argv(&argv
[optind
]);
1986 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1987 pcap_set_optimizer_debug(dflag
);
1989 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1990 error("%s", pcap_geterr(pd
));
1992 bpf_dump(&fcode
, dflag
);
1995 pcap_freecode(&fcode
);
2000 if (!ndo
->ndo_nflag
)
2001 capdns
= capdns_setup();
2002 #endif /* HAVE_CASPER */
2004 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2007 (void)setsignal(SIGPIPE
, cleanup
);
2008 (void)setsignal(SIGTERM
, cleanup
);
2010 (void)setsignal(SIGINT
, cleanup
);
2011 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2012 (void)setsignal(SIGCHLD
, child_cleanup
);
2014 /* Cooperate with nohup(1) */
2016 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2017 (void)setsignal(SIGHUP
, oldhandler
);
2022 * If a user name was specified with "-Z", attempt to switch to
2023 * that user's UID. This would probably be used with sudo,
2024 * to allow tcpdump to be run in a special restricted
2025 * account (if you just want to allow users to open capture
2026 * devices, and can't just give users that permission,
2027 * you'd make tcpdump set-UID or set-GID).
2029 * Tcpdump doesn't necessarily write only to one savefile;
2030 * the general only way to allow a -Z instance to write to
2031 * savefiles as the user under whose UID it's run, rather
2032 * than as the user specified with -Z, would thus be to switch
2033 * to the original user ID before opening a capture file and
2034 * then switch back to the -Z user ID after opening the savefile.
2035 * Switching to the -Z user ID only after opening the first
2036 * savefile doesn't handle the general case.
2039 if (getuid() == 0 || geteuid() == 0) {
2040 #ifdef HAVE_LIBCAP_NG
2041 /* Initialize capng */
2042 capng_clear(CAPNG_SELECT_BOTH
);
2044 DIAG_OFF_CLANG(assign
-enum)
2047 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2051 DIAG_ON_CLANG(assign
-enum)
2054 DIAG_OFF_CLANG(assign
-enum)
2057 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2060 DIAG_ON_CLANG(assign
-enum)
2064 DIAG_OFF_CLANG(assign
-enum)
2067 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2070 DIAG_ON_CLANG(assign
-enum)
2072 capng_apply(CAPNG_SELECT_BOTH
);
2073 #endif /* HAVE_LIBCAP_NG */
2074 if (username
|| chroot_dir
)
2075 droproot(username
, chroot_dir
);
2080 if (pcap_setfilter(pd
, &fcode
) < 0)
2081 error("%s", pcap_geterr(pd
));
2082 #ifdef HAVE_CAPSICUM
2083 if (RFileName
== NULL
&& VFileName
== NULL
) {
2084 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2087 * The various libpcap devices use a combination of
2088 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2089 * so we add the relevant access rights.
2091 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2092 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2094 error("unable to limit pcap descriptor");
2096 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2097 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2098 error("unable to limit ioctls on pcap descriptor");
2104 /* Do not exceed the default PATH_MAX for files. */
2105 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2107 if (dumpinfo
.CurrentFileName
== NULL
)
2108 error("malloc of dumpinfo.CurrentFileName");
2110 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2112 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2114 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2116 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2117 #ifdef HAVE_LIBCAP_NG
2118 /* Give up CAP_DAC_OVERRIDE capability.
2119 * Only allow it to be restored if the -C or -G flag have been
2120 * set since we may need to create more files later on.
2124 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2128 capng_apply(CAPNG_SELECT_BOTH
);
2129 #endif /* HAVE_LIBCAP_NG */
2131 error("%s", pcap_geterr(pd
));
2132 #ifdef HAVE_CAPSICUM
2133 set_dumper_capsicum_rights(p
);
2135 if (Cflag
!= 0 || Gflag
!= 0) {
2136 #ifdef HAVE_CAPSICUM
2137 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2138 if (dumpinfo
.WFileName
== NULL
) {
2139 error("Unable to allocate memory for file %s",
2142 dumpinfo
.dirfd
= open(dirname(WFileName
),
2143 O_DIRECTORY
| O_RDONLY
);
2144 if (dumpinfo
.dirfd
< 0) {
2145 error("unable to open directory %s",
2146 dirname(WFileName
));
2148 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2149 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2150 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2152 error("unable to limit directory rights");
2154 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2156 error("unable to limit dump descriptor fcntls");
2158 #else /* !HAVE_CAPSICUM */
2159 dumpinfo
.WFileName
= WFileName
;
2161 callback
= dump_packet_and_trunc
;
2164 pcap_userdata
= (u_char
*)&dumpinfo
;
2166 callback
= dump_packet
;
2167 dumpinfo
.WFileName
= WFileName
;
2170 pcap_userdata
= (u_char
*)&dumpinfo
;
2173 dlt
= pcap_datalink(pd
);
2174 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2177 dumpinfo
.ndo
= NULL
;
2179 #ifdef HAVE_PCAP_DUMP_FLUSH
2184 dlt
= pcap_datalink(pd
);
2185 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2186 callback
= print_packet
;
2187 pcap_userdata
= (u_char
*)ndo
;
2190 #ifdef SIGNAL_REQ_INFO
2192 * We can't get statistics when reading from a file rather
2193 * than capturing from a device.
2195 if (RFileName
== NULL
)
2196 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2199 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2201 * When capturing to a file, if "--print" wasn't specified,
2202 *"-v" means tcpdump should, once per second,
2203 * "v"erbosely report the number of packets captured.
2205 #ifdef USE_WIN32_MM_TIMER
2206 /* call verbose_stats_dump() each 1000 +/-100msec */
2207 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
2208 setvbuf(stderr
, NULL
, _IONBF
, 0);
2209 #elif defined(HAVE_ALARM)
2210 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2215 if (RFileName
== NULL
) {
2217 * Live capture (if -V was specified, we set RFileName
2218 * to a file from the -V file). Print a message to
2219 * the standard error on UN*X.
2221 if (!ndo
->ndo_vflag
&& !WFileName
) {
2222 (void)fprintf(stderr
,
2223 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2226 (void)fprintf(stderr
, "%s: ", program_name
);
2227 dlt
= pcap_datalink(pd
);
2228 dlt_name
= pcap_datalink_val_to_name(dlt
);
2229 if (dlt_name
== NULL
) {
2230 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2231 device
, dlt
, ndo
->ndo_snaplen
);
2233 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2235 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2237 (void)fflush(stderr
);
2240 #ifdef HAVE_CAPSICUM
2241 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2243 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2245 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2246 #endif /* HAVE_CASPER */
2247 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2248 error("unable to enter the capability mode");
2249 #endif /* HAVE_CAPSICUM */
2252 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2253 if (WFileName
== NULL
) {
2255 * We're printing packets. Flush the printed output,
2256 * so it doesn't get intermingled with error output.
2260 * We got interrupted, so perhaps we didn't
2261 * manage to finish a line we were printing.
2262 * Print an extra newline, just in case.
2266 (void)fflush(stdout
);
2270 * We got interrupted. If we are reading multiple
2271 * files (via -V) set these so that we stop.
2280 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2281 program_name
, pcap_geterr(pd
));
2283 if (RFileName
== NULL
) {
2285 * We're doing a live capture. Report the capture
2291 if (VFileName
!= NULL
) {
2292 ret
= get_next_file(VFile
, VFileLine
);
2296 RFileName
= VFileLine
;
2297 pd
= pcap_open_offline(RFileName
, ebuf
);
2300 #ifdef HAVE_CAPSICUM
2301 cap_rights_init(&rights
, CAP_READ
);
2302 if (cap_rights_limit(fileno(pcap_file(pd
)),
2303 &rights
) < 0 && errno
!= ENOSYS
) {
2304 error("unable to limit pcap descriptor");
2307 new_dlt
= pcap_datalink(pd
);
2308 if (new_dlt
!= dlt
) {
2310 * The new file has a different
2311 * link-layer header type from the
2314 if (WFileName
!= NULL
) {
2316 * We're writing raw packets
2317 * that match the filter to
2318 * a pcap file. pcap files
2319 * don't support multiple
2320 * different link-layer
2321 * header types, so we fail
2324 error("%s: new dlt does not match original", RFileName
);
2328 * We're printing the decoded packets;
2329 * switch to the new DLT.
2331 * To do that, we need to change
2332 * the printer, change the DLT name,
2333 * and recompile the filter with
2337 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2338 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2339 error("%s", pcap_geterr(pd
));
2343 * Set the filter on the new file.
2345 if (pcap_setfilter(pd
, &fcode
) < 0)
2346 error("%s", pcap_geterr(pd
));
2349 * Report the new file.
2351 dlt_name
= pcap_datalink_val_to_name(dlt
);
2352 if (dlt_name
== NULL
) {
2353 fprintf(stderr
, "reading from file %s, link-type %u\n",
2357 "reading from file %s, link-type %s (%s)\n",
2358 RFileName
, dlt_name
,
2359 pcap_datalink_val_to_description(dlt
));
2364 while (ret
!= NULL
);
2367 pcap_freecode(&fcode
);
2368 exit_tcpdump(status
== -1 ? 1 : 0);
2375 (*setsignal (int sig
, void (*func
)(int)))(int)
2378 return (signal(sig
, func
));
2380 struct sigaction old
, new;
2382 memset(&new, 0, sizeof(new));
2383 new.sa_handler
= func
;
2385 new.sa_flags
= SA_RESTART
;
2386 if (sigaction(sig
, &new, &old
) < 0)
2388 return (old
.sa_handler
);
2392 /* make a clean exit on interrupts */
2394 cleanup(int signo _U_
)
2396 #ifdef USE_WIN32_MM_TIMER
2398 timeKillEvent(timer_id
);
2400 #elif defined(HAVE_ALARM)
2404 #ifdef HAVE_PCAP_BREAKLOOP
2406 * We have "pcap_breakloop()"; use it, so that we do as little
2407 * as possible in the signal handler (it's probably not safe
2408 * to do anything with standard I/O streams in a signal handler -
2409 * the ANSI C standard doesn't say it is).
2414 * We don't have "pcap_breakloop()"; this isn't safe, but
2415 * it's the best we can do. Print the summary if we're
2416 * not reading from a savefile - i.e., if we're doing a
2417 * live capture - and exit.
2419 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2421 * We got interrupted, so perhaps we didn't
2422 * manage to finish a line we were printing.
2423 * Print an extra newline, just in case.
2426 (void)fflush(stdout
);
2434 On windows, we do not use a fork, so we do not care less about
2435 waiting a child processes to die
2437 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2439 child_cleanup(int signo _U_
)
2443 #endif /* HAVE_FORK && HAVE_VFORK */
2446 info(register int verbose
)
2448 struct pcap_stat stats
;
2451 * Older versions of libpcap didn't set ps_ifdrop on some
2452 * platforms; initialize it to 0 to handle that.
2454 stats
.ps_ifdrop
= 0;
2455 if (pcap_stats(pd
, &stats
) < 0) {
2456 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2462 fprintf(stderr
, "%s: ", program_name
);
2464 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2465 PLURAL_SUFFIX(packets_captured
));
2467 fputs(", ", stderr
);
2470 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2471 PLURAL_SUFFIX(stats
.ps_recv
));
2473 fputs(", ", stderr
);
2476 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2477 PLURAL_SUFFIX(stats
.ps_drop
));
2478 if (stats
.ps_ifdrop
!= 0) {
2480 fputs(", ", stderr
);
2483 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2484 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2490 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2492 #define fork_subprocess() fork()
2494 #define fork_subprocess() vfork()
2497 compress_savefile(const char *filename
)
2501 child
= fork_subprocess();
2504 "compress_savefile: fork failed: %s\n",
2505 pcap_strerror(errno
));
2509 /* Parent process. */
2515 * Set to lowest priority so that this doesn't disturb the capture.
2518 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2520 setpriority(PRIO_PROCESS
, 0, 19);
2522 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2524 "compress_savefile: execlp(%s, %s) failed: %s\n",
2527 pcap_strerror(errno
));
2534 #else /* HAVE_FORK && HAVE_VFORK */
2536 compress_savefile(const char *filename
)
2539 "compress_savefile failed. Functionality not implemented under your system\n");
2541 #endif /* HAVE_FORK && HAVE_VFORK */
2544 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2546 struct dump_info
*dump_info
;
2552 dump_info
= (struct dump_info
*)user
;
2555 * XXX - this won't force the file to rotate on the specified time
2556 * boundary, but it will rotate on the first packet received after the
2557 * specified Gflag number of seconds. Note: if a Gflag time boundary
2558 * and a Cflag size boundary coincide, the time rotation will occur
2559 * first thereby cancelling the Cflag boundary (since the file should
2563 /* Check if it is time to rotate */
2566 /* Get the current time */
2567 if ((t
= time(NULL
)) == (time_t)-1) {
2568 error("dump_and_trunc_packet: can't get current_time: %s",
2569 pcap_strerror(errno
));
2573 /* If the time is greater than the specified window, rotate */
2574 if (t
- Gflag_time
>= Gflag
) {
2575 #ifdef HAVE_CAPSICUM
2580 /* Update the Gflag_time */
2582 /* Update Gflag_count */
2585 * Close the current file and open a new one.
2587 pcap_dump_close(dump_info
->p
);
2590 * Compress the file we just closed, if the user asked for it
2593 compress_savefile(dump_info
->CurrentFileName
);
2596 * Check to see if we've exceeded the Wflag (when
2599 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2600 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2606 if (dump_info
->CurrentFileName
!= NULL
)
2607 free(dump_info
->CurrentFileName
);
2608 /* Allocate space for max filename + \0. */
2609 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2610 if (dump_info
->CurrentFileName
== NULL
)
2611 error("dump_packet_and_trunc: malloc");
2613 * Gflag was set otherwise we wouldn't be here. Reset the count
2614 * so multiple files would end with 1,2,3 in the filename.
2615 * The counting is handled with the -C flow after this.
2620 * This is always the first file in the Cflag
2622 * We also don't need numbering if Cflag is not set.
2625 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2628 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2630 #ifdef HAVE_LIBCAP_NG
2631 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2632 capng_apply(CAPNG_SELECT_BOTH
);
2633 #endif /* HAVE_LIBCAP_NG */
2634 #ifdef HAVE_CAPSICUM
2635 fd
= openat(dump_info
->dirfd
,
2636 dump_info
->CurrentFileName
,
2637 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2639 error("unable to open file %s",
2640 dump_info
->CurrentFileName
);
2642 fp
= fdopen(fd
, "w");
2644 error("unable to fdopen file %s",
2645 dump_info
->CurrentFileName
);
2647 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2648 #else /* !HAVE_CAPSICUM */
2649 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2651 #ifdef HAVE_LIBCAP_NG
2652 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2653 capng_apply(CAPNG_SELECT_BOTH
);
2654 #endif /* HAVE_LIBCAP_NG */
2655 if (dump_info
->p
== NULL
)
2656 error("%s", pcap_geterr(pd
));
2657 #ifdef HAVE_CAPSICUM
2658 set_dumper_capsicum_rights(dump_info
->p
);
2664 * XXX - this won't prevent capture files from getting
2665 * larger than Cflag - the last packet written to the
2666 * file could put it over Cflag.
2669 #ifdef HAVE_PCAP_DUMP_FTELL64
2670 int64_t size
= pcap_dump_ftell64(dump_info
->p
);
2673 * XXX - this only handles a Cflag value > 2^31-1 on
2674 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2675 * Windows) or LLP64 (64-bit Windows) would require
2676 * a version of libpcap with pcap_dump_ftell64().
2678 long size
= pcap_dump_ftell(dump_info
->p
);
2682 error("ftell fails on output file");
2684 #ifdef HAVE_CAPSICUM
2690 * Close the current file and open a new one.
2692 pcap_dump_close(dump_info
->p
);
2695 * Compress the file we just closed, if the user
2699 compress_savefile(dump_info
->CurrentFileName
);
2703 if (Cflag_count
>= Wflag
)
2706 if (dump_info
->CurrentFileName
!= NULL
)
2707 free(dump_info
->CurrentFileName
);
2708 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2709 if (dump_info
->CurrentFileName
== NULL
)
2710 error("dump_packet_and_trunc: malloc");
2711 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2712 #ifdef HAVE_LIBCAP_NG
2713 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2714 capng_apply(CAPNG_SELECT_BOTH
);
2715 #endif /* HAVE_LIBCAP_NG */
2716 #ifdef HAVE_CAPSICUM
2717 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2718 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2720 error("unable to open file %s",
2721 dump_info
->CurrentFileName
);
2723 fp
= fdopen(fd
, "w");
2725 error("unable to fdopen file %s",
2726 dump_info
->CurrentFileName
);
2728 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2729 #else /* !HAVE_CAPSICUM */
2730 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2732 #ifdef HAVE_LIBCAP_NG
2733 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2734 capng_apply(CAPNG_SELECT_BOTH
);
2735 #endif /* HAVE_LIBCAP_NG */
2736 if (dump_info
->p
== NULL
)
2737 error("%s", pcap_geterr(pd
));
2738 #ifdef HAVE_CAPSICUM
2739 set_dumper_capsicum_rights(dump_info
->p
);
2744 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2745 #ifdef HAVE_PCAP_DUMP_FLUSH
2747 pcap_dump_flush(dump_info
->p
);
2750 if (dump_info
->ndo
!= NULL
)
2751 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2759 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2761 struct dump_info
*dump_info
;
2767 dump_info
= (struct dump_info
*)user
;
2769 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2770 #ifdef HAVE_PCAP_DUMP_FLUSH
2772 pcap_dump_flush(dump_info
->p
);
2775 if (dump_info
->ndo
!= NULL
)
2776 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2784 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2790 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2799 * XXX - there should really be libpcap calls to get the version
2800 * number as a string (the string would be generated from #defines
2801 * at run time, so that it's not generated from string constants
2802 * in the library, as, on many UNIX systems, those constants would
2803 * be statically linked into the application executable image, and
2804 * would thus reflect the version of libpcap on the system on
2805 * which the application was *linked*, not the system on which it's
2808 * That routine should be documented, unlike the "version[]"
2809 * string, so that UNIX vendors providing their own libpcaps
2810 * don't omit it (as a couple of vendors have...).
2812 * Packet.dll should perhaps also export a routine to return the
2813 * version number of the Packet.dll code, to supply the
2814 * "Wpcap_version" information on Windows.
2816 char WDversion
[]="current-git.tcpdump.org";
2817 #if !defined(HAVE_GENERATED_VERSION)
2818 char version
[]="current-git.tcpdump.org";
2820 char pcap_version
[]="current-git.tcpdump.org";
2821 char Wpcap_version
[]="3.1";
2824 #ifdef SIGNAL_REQ_INFO
2825 void requestinfo(int signo _U_
)
2835 print_packets_captured (void)
2837 static u_int prev_packets_captured
, first
= 1;
2839 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2840 fprintf(stderr
, "Got %u\r", packets_captured
);
2842 prev_packets_captured
= packets_captured
;
2847 * Called once each second in verbose mode while dumping to file
2849 #ifdef USE_WIN32_MM_TIMER
2850 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2851 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2853 print_packets_captured();
2855 #elif defined(HAVE_ALARM)
2856 static void verbose_stats_dump(int sig _U_
)
2858 print_packets_captured();
2863 USES_APPLE_DEPRECATED_API
2867 #ifndef HAVE_PCAP_LIB_VERSION
2868 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2869 extern char pcap_version
[];
2870 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2871 static char pcap_version
[] = "unknown";
2872 #endif /* defined(_WIN32) || defined(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