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. */
721 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
726 capng_apply(CAPNG_SELECT_BOTH
);
727 #endif /* HAVE_LIBCAP_NG */
748 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
750 char *filename
= malloc(PATH_MAX
+ 1);
751 if (filename
== NULL
)
752 error("Makefilename: malloc");
754 /* Process with strftime if Gflag is set. */
758 /* Convert Gflag_time to a usable format */
759 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
760 error("MakeTimedFilename: localtime");
763 /* There's no good way to detect an error in strftime since a return
764 * value of 0 isn't necessarily failure.
766 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
768 strncpy(filename
, orig_name
, PATH_MAX
);
771 if (cnt
== 0 && max_chars
== 0)
772 strncpy(buffer
, filename
, PATH_MAX
+ 1);
774 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
775 /* Report an error if the filename is too large */
776 error("too many output files or filename is too long (> %d)", PATH_MAX
);
781 get_next_file(FILE *VFile
, char *ptr
)
785 ret
= fgets(ptr
, PATH_MAX
, VFile
);
789 if (ptr
[strlen(ptr
) - 1] == '\n')
790 ptr
[strlen(ptr
) - 1] = '\0';
796 static cap_channel_t
*
799 cap_channel_t
*capcas
, *capdnsloc
;
800 const char *types
[1];
805 error("unable to create casper process");
806 capdnsloc
= cap_service_open(capcas
, "system.dns");
807 /* Casper capability no longer needed. */
809 if (capdnsloc
== NULL
)
810 error("unable to open system.dns service");
811 /* Limit system.dns to reverse DNS lookups. */
813 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
814 error("unable to limit access to system.dns service");
815 families
[0] = AF_INET
;
816 families
[1] = AF_INET6
;
817 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
818 error("unable to limit access to system.dns service");
822 #endif /* HAVE_CASPER */
824 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
826 tstamp_precision_from_string(const char *precision
)
828 if (strncmp(precision
, "nano", strlen("nano")) == 0)
829 return PCAP_TSTAMP_PRECISION_NANO
;
831 if (strncmp(precision
, "micro", strlen("micro")) == 0)
832 return PCAP_TSTAMP_PRECISION_MICRO
;
838 tstamp_precision_to_string(int precision
)
842 case PCAP_TSTAMP_PRECISION_MICRO
:
845 case PCAP_TSTAMP_PRECISION_NANO
:
856 * Ensure that, on a dump file's descriptor, we have all the rights
857 * necessary to make the standard I/O library work with an fdopen()ed
858 * FILE * from that descriptor.
860 * A long time ago, in a galaxy far far away, AT&T decided that, instead
861 * of providing separate APIs for getting and setting the FD_ flags on a
862 * descriptor, getting and setting the O_ flags on a descriptor, and
863 * locking files, they'd throw them all into a kitchen-sink fcntl() call
864 * along the lines of ioctl(), the fact that ioctl() operations are
865 * largely specific to particular character devices but fcntl() operations
866 * are either generic to all descriptors or generic to all descriptors for
867 * regular files nonwithstanding.
869 * The Capsicum people decided that fine-grained control of descriptor
870 * operations was required, so that you need to grant permission for
871 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
872 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
873 * collection of things, so there are *individual* fcntls for which
874 * permission needs to be granted.
876 * The FreeBSD standard I/O people implemented some optimizations that
877 * requires that the standard I/O routines be able to determine whether
878 * the descriptor for the FILE * is open append-only or not; as that
879 * descriptor could have come from an open() rather than an fopen(),
880 * that requires that it be able to do an F_GETFL fcntl() to read
883 * Tcpdump uses ftell() to determine how much data has been written
884 * to a file in order to, when used with -C, determine when it's time
885 * to rotate capture files. ftell() therefore needs to do an lseek()
886 * to find out the file offset and must, thanks to the aforementioned
887 * optimization, also know whether the descriptor is open append-only
890 * The net result of all the above is that we need to grant CAP_SEEK,
891 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
893 * Perhaps this is the universe's way of saying that either
895 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
896 * using it, so that Capsicum-capable tcpdump wouldn't need to do
901 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
902 * I/O library that knows what rights are needed by the standard
903 * I/O library, based on the open mode, and assigns them, perhaps
904 * with an additional argument indicating, for example, whether
905 * seeking should be allowed, so that tcpdump doesn't need to know
906 * what the standard I/O library happens to require this week.
909 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
911 int fd
= fileno(pcap_dump_file(p
));
914 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
915 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
916 error("unable to limit dump descriptor");
918 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
919 error("unable to limit dump descriptor fcntls");
925 * Copy arg vector into a new buffer, concatenating arguments with spaces.
928 copy_argv(register char **argv
)
931 register u_int len
= 0;
940 len
+= strlen(*p
++) + 1;
942 buf
= (char *)malloc(len
);
944 error("copy_argv: malloc");
948 while ((src
= *p
++) != NULL
) {
949 while ((*dst
++ = *src
++) != '\0')
959 * On Windows, we need to open the file in binary mode, so that
960 * we get all the bytes specified by the size we get from "fstat()".
961 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
962 * we define it as 0 if it's not defined, so it does nothing.
969 read_infile(char *fname
)
971 register int i
, fd
, cc
;
975 fd
= open(fname
, O_RDONLY
|O_BINARY
);
977 error("can't open %s: %s", fname
, pcap_strerror(errno
));
979 if (fstat(fd
, &buf
) < 0)
980 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
982 cp
= malloc((u_int
)buf
.st_size
+ 1);
984 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
985 fname
, pcap_strerror(errno
));
986 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
988 error("read %s: %s", fname
, pcap_strerror(errno
));
989 if (cc
!= buf
.st_size
)
990 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
993 /* replace "# comment" with spaces */
994 for (i
= 0; i
< cc
; i
++) {
996 while (i
< cc
&& cp
[i
] != '\n')
1003 #ifdef HAVE_PCAP_FINDALLDEVS
1005 parse_interface_number(const char *device
)
1010 devnum
= strtol(device
, &end
, 10);
1011 if (device
!= end
&& *end
== '\0') {
1013 * It's all-numeric, but is it a valid number?
1017 * No, it's not an ordinal.
1019 error("Invalid adapter index");
1024 * It's not all-numeric; return -1, so our caller
1032 find_interface_by_number(long devnum
)
1034 pcap_if_t
*dev
, *devlist
;
1036 char ebuf
[PCAP_ERRBUF_SIZE
];
1039 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
1042 * Look for the devnum-th entry in the list of devices (1-based).
1044 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1045 i
++, dev
= dev
->next
)
1048 error("Invalid adapter index");
1049 device
= strdup(dev
->name
);
1050 pcap_freealldevs(devlist
);
1055 #ifdef HAVE_PCAP_OPEN
1057 * Prefix for rpcap URLs.
1059 static char rpcap_prefix
[] = "rpcap://";
1063 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1066 #ifdef HAVE_PCAP_CREATE
1071 #ifdef HAVE_PCAP_OPEN
1073 * Is this an rpcap URL?
1075 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1077 * Yes. Open it with pcap_open().
1080 fprintf(stderr
, "Opening %s\n", device
);
1081 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1082 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1086 * If this failed with "No such device", that means
1087 * the interface doesn't exist; return NULL, so that
1088 * the caller can see whether the device name is
1089 * actually an interface index.
1091 if (strstr(ebuf
, "No such device") != NULL
)
1096 warning("%s", ebuf
);
1099 #endif /* HAVE_PCAP_OPEN */
1101 #ifdef HAVE_PCAP_CREATE
1102 pc
= pcap_create(device
, ebuf
);
1105 * If this failed with "No such device", that means
1106 * the interface doesn't exist; return NULL, so that
1107 * the caller can see whether the device name is
1108 * actually an interface index.
1110 if (strstr(ebuf
, "No such device") != NULL
)
1114 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1116 show_tstamp_types_and_exit(pc
, device
);
1118 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1119 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1121 error("%s: Can't set %ssecond time stamp precision: %s",
1123 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1124 pcap_statustostr(status
));
1127 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1128 if (immediate_mode
) {
1129 status
= pcap_set_immediate_mode(pc
, 1);
1131 error("%s: Can't set immediate mode: %s",
1133 pcap_statustostr(status
));
1137 * Is this an interface that supports monitor mode?
1139 if (pcap_can_set_rfmon(pc
) == 1)
1140 supports_monitor_mode
= 1;
1142 supports_monitor_mode
= 0;
1143 if (ndo
->ndo_snaplen
!= 0) {
1145 * A snapshot length was explicitly specified;
1148 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1150 error("%s: Can't set snapshot length: %s",
1151 device
, pcap_statustostr(status
));
1153 status
= pcap_set_promisc(pc
, !pflag
);
1155 error("%s: Can't set promiscuous mode: %s",
1156 device
, pcap_statustostr(status
));
1158 status
= pcap_set_rfmon(pc
, 1);
1160 error("%s: Can't set monitor mode: %s",
1161 device
, pcap_statustostr(status
));
1163 status
= pcap_set_timeout(pc
, 1000);
1165 error("%s: pcap_set_timeout failed: %s",
1166 device
, pcap_statustostr(status
));
1168 status
= pcap_set_buffer_size(pc
, Bflag
);
1170 error("%s: Can't set buffer size: %s",
1171 device
, pcap_statustostr(status
));
1173 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1175 status
= pcap_set_tstamp_type(pc
, jflag
);
1177 error("%s: Can't set time stamp type: %s",
1178 device
, pcap_statustostr(status
));
1181 status
= pcap_activate(pc
);
1184 * pcap_activate() failed.
1186 cp
= pcap_geterr(pc
);
1187 if (status
== PCAP_ERROR
)
1189 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1191 * Return an error for our caller to handle.
1193 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1194 device
, pcap_statustostr(status
), cp
);
1197 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1198 error("%s: %s\n(%s)", device
,
1199 pcap_statustostr(status
), cp
);
1201 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1202 strncmp(device
, "wlan", 4) == 0) {
1203 char parent
[8], newdev
[8];
1205 size_t s
= sizeof(parent
);
1207 snprintf(sysctl
, sizeof(sysctl
),
1208 "net.wlan.%d.%%parent", atoi(device
+ 4));
1209 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1210 strlcpy(newdev
, device
, sizeof(newdev
));
1211 /* Suggest a new wlan device. */
1212 /* FIXME: incrementing the index this way is not going to work well
1213 * when the index is 9 or greater but the only consequence in this
1214 * specific case would be an error message that looks a bit odd.
1216 newdev
[strlen(newdev
)-1]++;
1217 error("%s is not a monitor mode VAP\n"
1218 "To create a new monitor mode VAP use:\n"
1219 " ifconfig %s create wlandev %s wlanmode monitor\n"
1220 "and use %s as the tcpdump interface",
1221 device
, newdev
, parent
, newdev
);
1225 error("%s: %s", device
,
1226 pcap_statustostr(status
));
1227 } else if (status
> 0) {
1229 * pcap_activate() succeeded, but it's warning us
1230 * of a problem it had.
1232 cp
= pcap_geterr(pc
);
1233 if (status
== PCAP_WARNING
)
1235 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1237 warning("%s: %s\n(%s)", device
,
1238 pcap_statustostr(status
), cp
);
1240 warning("%s: %s", device
,
1241 pcap_statustostr(status
));
1243 #ifdef HAVE_PCAP_SETDIRECTION
1245 status
= pcap_setdirection(pc
, Qflag
);
1247 error("%s: pcap_setdirection() failed: %s",
1248 device
, pcap_geterr(pc
));
1250 #endif /* HAVE_PCAP_SETDIRECTION */
1251 #else /* HAVE_PCAP_CREATE */
1254 * If no snapshot length was specified, or a length of 0 was
1255 * specified, default to 256KB.
1257 if (ndo
->ndo_snaplen
== 0)
1258 ndo
->ndo_snaplen
= 262144;
1259 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1262 * If this failed with "No such device", that means
1263 * the interface doesn't exist; return NULL, so that
1264 * the caller can see whether the device name is
1265 * actually an interface index.
1267 if (strstr(ebuf
, "No such device") != NULL
)
1272 warning("%s", ebuf
);
1273 #endif /* HAVE_PCAP_CREATE */
1279 main(int argc
, char **argv
)
1281 register int cnt
, op
, i
;
1282 bpf_u_int32 localnet
= 0, netmask
= 0;
1283 int timezone_offset
= 0;
1284 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1286 pcap_handler callback
;
1288 const char *dlt_name
;
1289 struct bpf_program fcode
;
1291 void (*oldhandler
)(int);
1293 struct dump_info dumpinfo
;
1294 u_char
*pcap_userdata
;
1295 char ebuf
[PCAP_ERRBUF_SIZE
];
1296 char VFileLine
[PATH_MAX
+ 1];
1297 char *username
= NULL
;
1298 char *chroot_dir
= NULL
;
1301 #ifdef HAVE_PCAP_FINDALLDEVS
1307 #ifdef HAVE_CAPSICUM
1308 cap_rights_t rights
;
1310 #endif /* HAVE_CAPSICUM */
1311 int Oflag
= 1; /* run filter code optimizer */
1313 const char *yflag_dlt_name
= NULL
;
1316 netdissect_options Ndo
;
1317 netdissect_options
*ndo
= &Ndo
;
1320 * Initialize the netdissect code.
1322 if (nd_init(ebuf
, sizeof ebuf
) == -1)
1325 memset(ndo
, 0, sizeof(*ndo
));
1326 ndo_set_function_pointers(ndo
);
1336 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1337 ndo
->program_name
= program_name
= cp
+ 1;
1339 ndo
->program_name
= program_name
= argv
[0];
1342 if (pcap_wsockinit() != 0)
1343 error("Attempting to initialize Winsock failed");
1347 * On platforms where the CPU doesn't support unaligned loads,
1348 * force unaligned accesses to abort with SIGBUS, rather than
1349 * being fixed up (slowly) by the OS kernel; on those platforms,
1350 * misaligned accesses are bugs, and we want tcpdump to crash so
1351 * that the bugs are reported.
1353 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1357 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1361 /* compatibility for old -a */
1372 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1374 Bflag
= atoi(optarg
)*1024;
1376 error("invalid packet buffer size %s", optarg
);
1378 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1383 error("invalid packet count %s", optarg
);
1388 #ifdef HAVE_PCAP_DUMP_FTELL64
1389 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1391 Cflag
= strtol(optarg
, &endp
, 10);
1393 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1395 error("invalid file size %s", optarg
);
1397 * Will multiplying it by 1000000 overflow?
1399 #ifdef HAVE_PCAP_DUMP_FTELL64
1400 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffffU
) / 1000000)
1402 if (Cflag
> LONG_MAX
/ 1000000)
1404 error("file size %s is too large", optarg
);
1412 #ifdef HAVE_PCAP_FINDALLDEVS
1418 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1419 case OPTION_LIST_REMOTE_INTERFACES
:
1420 remote_interfaces_source
= optarg
;
1433 #ifndef HAVE_LIBCRYPTO
1434 warning("crypto code not compiled in");
1436 ndo
->ndo_espsecret
= optarg
;
1448 Gflag
= atoi(optarg
);
1450 error("invalid number of seconds %s", optarg
);
1452 /* We will create one file initially. */
1455 /* Grab the current time for rotation use. */
1456 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1457 error("main: can't get current time: %s",
1458 pcap_strerror(errno
));
1475 #ifdef HAVE_PCAP_CREATE
1479 #endif /* HAVE_PCAP_CREATE */
1481 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1483 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1485 error("invalid time stamp type %s", optarg
);
1496 * _IOLBF is the same as _IOFBF in Microsoft's C
1497 * libraries; the only alternative they offer
1500 * XXX - this should really be checking for MSVC++,
1501 * not _WIN32, if, for example, MinGW has its own
1502 * C library that is more UNIX-compatible.
1504 setvbuf(stdout
, NULL
, _IONBF
, 0);
1506 #ifdef HAVE_SETLINEBUF
1509 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1519 if (nd_have_smi_support()) {
1520 if (nd_load_smi_module(optarg
, ebuf
, sizeof ebuf
) == -1)
1523 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1524 program_name
, optarg
);
1525 (void)fprintf(stderr
, "(no libsmi support)\n");
1530 /* TCP-MD5 shared secret */
1531 #ifndef HAVE_LIBCRYPTO
1532 warning("crypto code not compiled in");
1534 ndo
->ndo_sigsecret
= optarg
;
1555 ++ndo
->ndo_suppress_default_print
;
1558 #ifdef HAVE_PCAP_SETDIRECTION
1560 if (ascii_strcasecmp(optarg
, "in") == 0)
1562 else if (ascii_strcasecmp(optarg
, "out") == 0)
1564 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1565 Qflag
= PCAP_D_INOUT
;
1567 error("unknown capture direction `%s'", optarg
);
1569 #endif /* HAVE_PCAP_SETDIRECTION */
1576 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1577 if (optarg
== end
|| *end
!= '\0'
1578 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1579 error("invalid snaplen %s", optarg
);
1591 if (ascii_strcasecmp(optarg
, "vat") == 0)
1592 ndo
->ndo_packettype
= PT_VAT
;
1593 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1594 ndo
->ndo_packettype
= PT_WB
;
1595 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1596 ndo
->ndo_packettype
= PT_RPC
;
1597 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1598 ndo
->ndo_packettype
= PT_RTP
;
1599 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1600 ndo
->ndo_packettype
= PT_RTCP
;
1601 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1602 ndo
->ndo_packettype
= PT_SNMP
;
1603 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1604 ndo
->ndo_packettype
= PT_CNFP
;
1605 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1606 ndo
->ndo_packettype
= PT_TFTP
;
1607 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1608 ndo
->ndo_packettype
= PT_AODV
;
1609 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1610 ndo
->ndo_packettype
= PT_CARP
;
1611 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1612 ndo
->ndo_packettype
= PT_RADIUS
;
1613 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1614 ndo
->ndo_packettype
= PT_ZMTP1
;
1615 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1616 ndo
->ndo_packettype
= PT_VXLAN
;
1617 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1618 ndo
->ndo_packettype
= PT_PGM
;
1619 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1620 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1621 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1622 ndo
->ndo_packettype
= PT_LMP
;
1623 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1624 ndo
->ndo_packettype
= PT_RESP
;
1626 error("unknown packet type `%s'", optarg
);
1633 #ifdef HAVE_PCAP_DUMP_FLUSH
1652 Wflag
= atoi(optarg
);
1654 error("invalid number of output files %s", optarg
);
1655 WflagChars
= getWflagChars(Wflag
);
1660 ++ndo
->ndo_suppress_default_print
;
1665 ++ndo
->ndo_suppress_default_print
;
1669 yflag_dlt_name
= optarg
;
1671 pcap_datalink_name_to_val(yflag_dlt_name
);
1673 error("invalid data link type %s", yflag_dlt_name
);
1676 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1679 /* Undocumented flag */
1680 pcap_set_parser_debug(1);
1693 ndo
->ndo_packet_number
= 1;
1696 case OPTION_VERSION
:
1701 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1702 case OPTION_TSTAMP_PRECISION
:
1703 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1704 if (ndo
->ndo_tstamp_precision
< 0)
1705 error("unsupported time stamp precision");
1709 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1710 case OPTION_IMMEDIATE_MODE
:
1725 #ifdef HAVE_PCAP_FINDALLDEVS
1727 show_devices_and_exit();
1729 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1730 if (remote_interfaces_source
!= NULL
)
1731 show_remote_devices_and_exit();
1734 switch (ndo
->ndo_tflag
) {
1736 case 0: /* Default */
1737 case 4: /* Default + Date*/
1738 timezone_offset
= gmt2local(0);
1741 case 1: /* No time stamp */
1742 case 2: /* Unix timeval style */
1743 case 3: /* Microseconds since previous packet */
1744 case 5: /* Microseconds since first packet */
1747 default: /* Not supported */
1748 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1752 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1753 error("-f can not be used with -V or -r");
1755 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1756 error("-V and -r are mutually exclusive.");
1758 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1760 * If we're printing dissected packets to the standard output
1761 * and the standard output is a terminal, use immediate mode,
1762 * as the user's probably expecting to see packets pop up
1765 * XXX - set the timeout to a lower value, instead? If so,
1766 * what value would be appropriate?
1768 if ((WFileName
== NULL
|| print
) && isatty(1))
1773 /* if run as root, prepare for chrooting */
1774 if (getuid() == 0 || geteuid() == 0) {
1775 /* future extensibility for cmd-line arguments */
1777 chroot_dir
= WITH_CHROOT
;
1782 /* if run as root, prepare for dropping root privileges */
1783 if (getuid() == 0 || geteuid() == 0) {
1784 /* Run with '-Z root' to restore old behaviour */
1786 username
= WITH_USER
;
1790 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1792 * If RFileName is non-null, it's the pathname of a
1793 * savefile to read. If VFileName is non-null, it's
1794 * the pathname of a file containing a list of pathnames
1795 * (one per line) of savefiles to read.
1797 * In either case, we're reading a savefile, not doing
1802 * We don't need network access, so relinquish any set-UID
1803 * or set-GID privileges we have (if any).
1805 * We do *not* want set-UID privileges when opening a
1806 * trace file, as that might let the user read other
1807 * people's trace files (especially if we're set-UID
1810 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1811 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1813 if (VFileName
!= NULL
) {
1814 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1817 VFile
= fopen(VFileName
, "r");
1820 error("Unable to open file: %s\n", pcap_strerror(errno
));
1822 ret
= get_next_file(VFile
, VFileLine
);
1824 error("Nothing in %s\n", VFileName
);
1825 RFileName
= VFileLine
;
1828 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1829 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1830 ndo
->ndo_tstamp_precision
, ebuf
);
1832 pd
= pcap_open_offline(RFileName
, ebuf
);
1837 #ifdef HAVE_CAPSICUM
1838 cap_rights_init(&rights
, CAP_READ
);
1839 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1841 error("unable to limit pcap descriptor");
1844 dlt
= pcap_datalink(pd
);
1845 dlt_name
= pcap_datalink_val_to_name(dlt
);
1846 if (dlt_name
== NULL
) {
1847 fprintf(stderr
, "reading from file %s, link-type %u\n",
1851 "reading from file %s, link-type %s (%s)\n",
1852 RFileName
, dlt_name
,
1853 pcap_datalink_val_to_description(dlt
));
1857 * We're doing a live capture.
1859 if (device
== NULL
) {
1861 * No interface was specified. Pick one.
1863 #ifdef HAVE_PCAP_FINDALLDEVS
1865 * Find the list of interfaces, and pick
1866 * the first interface.
1868 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
1870 if (devlist
== NULL
)
1871 error("no interfaces available for capture");
1872 device
= strdup(devlist
->name
);
1873 pcap_freealldevs(devlist
);
1874 #else /* HAVE_PCAP_FINDALLDEVS */
1876 * Use whatever interface pcap_lookupdev()
1879 device
= pcap_lookupdev(ebuf
);
1886 * Try to open the interface with the specified name.
1888 pd
= open_interface(device
, ndo
, ebuf
);
1891 * That failed. If we can get a list of
1892 * interfaces, and the interface name
1893 * is purely numeric, try to use it as
1894 * a 1-based index in the list of
1897 #ifdef HAVE_PCAP_FINDALLDEVS
1898 devnum
= parse_interface_number(device
);
1901 * It's not a number; just report
1902 * the open error and fail.
1908 * OK, it's a number; try to find the
1909 * interface with that index, and try
1912 * find_interface_by_number() exits if it
1913 * couldn't be found.
1915 device
= find_interface_by_number(devnum
);
1916 pd
= open_interface(device
, ndo
, ebuf
);
1919 #else /* HAVE_PCAP_FINDALLDEVS */
1921 * We can't get a list of interfaces; just
1925 #endif /* HAVE_PCAP_FINDALLDEVS */
1929 * Let user own process after capture device has
1933 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1934 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1936 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1938 if(pcap_setbuff(pd
, Bflag
)==-1){
1939 error("%s", pcap_geterr(pd
));
1941 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1943 show_dlts_and_exit(pd
, device
);
1944 if (yflag_dlt
>= 0) {
1945 #ifdef HAVE_PCAP_SET_DATALINK
1946 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1947 error("%s", pcap_geterr(pd
));
1950 * We don't actually support changing the
1951 * data link type, so we only let them
1952 * set it to what it already is.
1954 if (yflag_dlt
!= pcap_datalink(pd
)) {
1955 error("%s is not one of the DLTs supported by this device\n",
1959 (void)fprintf(stderr
, "%s: data link type %s\n",
1960 program_name
, yflag_dlt_name
);
1961 (void)fflush(stderr
);
1963 i
= pcap_snapshot(pd
);
1964 if (ndo
->ndo_snaplen
< i
) {
1965 if (ndo
->ndo_snaplen
!= 0)
1966 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1967 ndo
->ndo_snaplen
= i
;
1968 } else if (ndo
->ndo_snaplen
> i
) {
1969 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
1970 ndo
->ndo_snaplen
= i
;
1972 if(ndo
->ndo_fflag
!= 0) {
1973 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1974 warning("foreign (-f) flag used but: %s", ebuf
);
1980 cmdbuf
= read_infile(infile
);
1982 cmdbuf
= copy_argv(&argv
[optind
]);
1984 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1985 pcap_set_optimizer_debug(dflag
);
1987 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1988 error("%s", pcap_geterr(pd
));
1990 bpf_dump(&fcode
, dflag
);
1993 pcap_freecode(&fcode
);
1998 if (!ndo
->ndo_nflag
)
1999 capdns
= capdns_setup();
2000 #endif /* HAVE_CASPER */
2002 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2005 (void)setsignal(SIGPIPE
, cleanup
);
2006 (void)setsignal(SIGTERM
, cleanup
);
2007 (void)setsignal(SIGINT
, cleanup
);
2009 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2010 (void)setsignal(SIGCHLD
, child_cleanup
);
2012 /* Cooperate with nohup(1) */
2014 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2015 (void)setsignal(SIGHUP
, oldhandler
);
2020 * If a user name was specified with "-Z", attempt to switch to
2021 * that user's UID. This would probably be used with sudo,
2022 * to allow tcpdump to be run in a special restricted
2023 * account (if you just want to allow users to open capture
2024 * devices, and can't just give users that permission,
2025 * you'd make tcpdump set-UID or set-GID).
2027 * Tcpdump doesn't necessarily write only to one savefile;
2028 * the general only way to allow a -Z instance to write to
2029 * savefiles as the user under whose UID it's run, rather
2030 * than as the user specified with -Z, would thus be to switch
2031 * to the original user ID before opening a capture file and
2032 * then switch back to the -Z user ID after opening the savefile.
2033 * Switching to the -Z user ID only after opening the first
2034 * savefile doesn't handle the general case.
2037 if (getuid() == 0 || geteuid() == 0) {
2038 #ifdef HAVE_LIBCAP_NG
2039 /* Initialize capng */
2040 capng_clear(CAPNG_SELECT_BOTH
);
2044 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2052 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2060 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2064 capng_apply(CAPNG_SELECT_BOTH
);
2065 #endif /* HAVE_LIBCAP_NG */
2066 if (username
|| chroot_dir
)
2067 droproot(username
, chroot_dir
);
2072 if (pcap_setfilter(pd
, &fcode
) < 0)
2073 error("%s", pcap_geterr(pd
));
2074 #ifdef HAVE_CAPSICUM
2075 if (RFileName
== NULL
&& VFileName
== NULL
) {
2076 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2079 * The various libpcap devices use a combination of
2080 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2081 * so we add the relevant access rights.
2083 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2084 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2086 error("unable to limit pcap descriptor");
2088 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2089 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2090 error("unable to limit ioctls on pcap descriptor");
2096 /* Do not exceed the default PATH_MAX for files. */
2097 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2099 if (dumpinfo
.CurrentFileName
== NULL
)
2100 error("malloc of dumpinfo.CurrentFileName");
2102 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2104 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2106 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2108 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2109 #ifdef HAVE_LIBCAP_NG
2110 /* Give up CAP_DAC_OVERRIDE capability.
2111 * Only allow it to be restored if the -C or -G flag have been
2112 * set since we may need to create more files later on.
2116 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2120 capng_apply(CAPNG_SELECT_BOTH
);
2121 #endif /* HAVE_LIBCAP_NG */
2123 error("%s", pcap_geterr(pd
));
2124 #ifdef HAVE_CAPSICUM
2125 set_dumper_capsicum_rights(p
);
2127 if (Cflag
!= 0 || Gflag
!= 0) {
2128 #ifdef HAVE_CAPSICUM
2129 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2130 if (dumpinfo
.WFileName
== NULL
) {
2131 error("Unable to allocate memory for file %s",
2134 dumpinfo
.dirfd
= open(dirname(WFileName
),
2135 O_DIRECTORY
| O_RDONLY
);
2136 if (dumpinfo
.dirfd
< 0) {
2137 error("unable to open directory %s",
2138 dirname(WFileName
));
2140 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2141 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2142 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2144 error("unable to limit directory rights");
2146 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2148 error("unable to limit dump descriptor fcntls");
2150 #else /* !HAVE_CAPSICUM */
2151 dumpinfo
.WFileName
= WFileName
;
2153 callback
= dump_packet_and_trunc
;
2156 pcap_userdata
= (u_char
*)&dumpinfo
;
2158 callback
= dump_packet
;
2159 dumpinfo
.WFileName
= WFileName
;
2162 pcap_userdata
= (u_char
*)&dumpinfo
;
2165 dlt
= pcap_datalink(pd
);
2166 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2169 dumpinfo
.ndo
= NULL
;
2171 #ifdef HAVE_PCAP_DUMP_FLUSH
2176 dlt
= pcap_datalink(pd
);
2177 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2178 callback
= print_packet
;
2179 pcap_userdata
= (u_char
*)ndo
;
2182 #ifdef SIGNAL_REQ_INFO
2184 * We can't get statistics when reading from a file rather
2185 * than capturing from a device.
2187 if (RFileName
== NULL
)
2188 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2191 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2193 * When capturing to a file, if "--print" wasn't specified,
2194 *"-v" means tcpdump should, once per second,
2195 * "v"erbosely report the number of packets captured.
2197 #ifdef USE_WIN32_MM_TIMER
2198 /* call verbose_stats_dump() each 1000 +/-100msec */
2199 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
2200 setvbuf(stderr
, NULL
, _IONBF
, 0);
2201 #elif defined(HAVE_ALARM)
2202 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2207 if (RFileName
== NULL
) {
2209 * Live capture (if -V was specified, we set RFileName
2210 * to a file from the -V file). Print a message to
2211 * the standard error on UN*X.
2213 if (!ndo
->ndo_vflag
&& !WFileName
) {
2214 (void)fprintf(stderr
,
2215 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2218 (void)fprintf(stderr
, "%s: ", program_name
);
2219 dlt
= pcap_datalink(pd
);
2220 dlt_name
= pcap_datalink_val_to_name(dlt
);
2221 if (dlt_name
== NULL
) {
2222 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2223 device
, dlt
, ndo
->ndo_snaplen
);
2225 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2227 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2229 (void)fflush(stderr
);
2232 #ifdef HAVE_CAPSICUM
2233 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2235 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2237 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2238 #endif /* HAVE_CASPER */
2239 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2240 error("unable to enter the capability mode");
2241 #endif /* HAVE_CAPSICUM */
2244 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2245 if (WFileName
== NULL
) {
2247 * We're printing packets. Flush the printed output,
2248 * so it doesn't get intermingled with error output.
2252 * We got interrupted, so perhaps we didn't
2253 * manage to finish a line we were printing.
2254 * Print an extra newline, just in case.
2258 (void)fflush(stdout
);
2262 * We got interrupted. If we are reading multiple
2263 * files (via -V) set these so that we stop.
2272 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2273 program_name
, pcap_geterr(pd
));
2275 if (RFileName
== NULL
) {
2277 * We're doing a live capture. Report the capture
2283 if (VFileName
!= NULL
) {
2284 ret
= get_next_file(VFile
, VFileLine
);
2288 RFileName
= VFileLine
;
2289 pd
= pcap_open_offline(RFileName
, ebuf
);
2292 #ifdef HAVE_CAPSICUM
2293 cap_rights_init(&rights
, CAP_READ
);
2294 if (cap_rights_limit(fileno(pcap_file(pd
)),
2295 &rights
) < 0 && errno
!= ENOSYS
) {
2296 error("unable to limit pcap descriptor");
2299 new_dlt
= pcap_datalink(pd
);
2300 if (new_dlt
!= dlt
) {
2302 * The new file has a different
2303 * link-layer header type from the
2306 if (WFileName
!= NULL
) {
2308 * We're writing raw packets
2309 * that match the filter to
2310 * a pcap file. pcap files
2311 * don't support multiple
2312 * different link-layer
2313 * header types, so we fail
2316 error("%s: new dlt does not match original", RFileName
);
2320 * We're printing the decoded packets;
2321 * switch to the new DLT.
2323 * To do that, we need to change
2324 * the printer, change the DLT name,
2325 * and recompile the filter with
2329 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2330 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2331 error("%s", pcap_geterr(pd
));
2335 * Set the filter on the new file.
2337 if (pcap_setfilter(pd
, &fcode
) < 0)
2338 error("%s", pcap_geterr(pd
));
2341 * Report the new file.
2343 dlt_name
= pcap_datalink_val_to_name(dlt
);
2344 if (dlt_name
== NULL
) {
2345 fprintf(stderr
, "reading from file %s, link-type %u\n",
2349 "reading from file %s, link-type %s (%s)\n",
2350 RFileName
, dlt_name
,
2351 pcap_datalink_val_to_description(dlt
));
2356 while (ret
!= NULL
);
2359 pcap_freecode(&fcode
);
2360 exit_tcpdump(status
== -1 ? 1 : 0);
2367 (*setsignal (int sig
, void (*func
)(int)))(int)
2370 return (signal(sig
, func
));
2372 struct sigaction old
, new;
2374 memset(&new, 0, sizeof(new));
2375 new.sa_handler
= func
;
2377 new.sa_flags
= SA_RESTART
;
2378 if (sigaction(sig
, &new, &old
) < 0)
2380 return (old
.sa_handler
);
2384 /* make a clean exit on interrupts */
2386 cleanup(int signo _U_
)
2388 #ifdef USE_WIN32_MM_TIMER
2390 timeKillEvent(timer_id
);
2392 #elif defined(HAVE_ALARM)
2396 #ifdef HAVE_PCAP_BREAKLOOP
2398 * We have "pcap_breakloop()"; use it, so that we do as little
2399 * as possible in the signal handler (it's probably not safe
2400 * to do anything with standard I/O streams in a signal handler -
2401 * the ANSI C standard doesn't say it is).
2406 * We don't have "pcap_breakloop()"; this isn't safe, but
2407 * it's the best we can do. Print the summary if we're
2408 * not reading from a savefile - i.e., if we're doing a
2409 * live capture - and exit.
2411 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2413 * We got interrupted, so perhaps we didn't
2414 * manage to finish a line we were printing.
2415 * Print an extra newline, just in case.
2418 (void)fflush(stdout
);
2426 On windows, we do not use a fork, so we do not care less about
2427 waiting a child processes to die
2429 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2431 child_cleanup(int signo _U_
)
2435 #endif /* HAVE_FORK && HAVE_VFORK */
2438 info(register int verbose
)
2440 struct pcap_stat stats
;
2443 * Older versions of libpcap didn't set ps_ifdrop on some
2444 * platforms; initialize it to 0 to handle that.
2446 stats
.ps_ifdrop
= 0;
2447 if (pcap_stats(pd
, &stats
) < 0) {
2448 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2454 fprintf(stderr
, "%s: ", program_name
);
2456 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2457 PLURAL_SUFFIX(packets_captured
));
2459 fputs(", ", stderr
);
2462 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2463 PLURAL_SUFFIX(stats
.ps_recv
));
2465 fputs(", ", stderr
);
2468 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2469 PLURAL_SUFFIX(stats
.ps_drop
));
2470 if (stats
.ps_ifdrop
!= 0) {
2472 fputs(", ", stderr
);
2475 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2476 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2482 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2484 #define fork_subprocess() fork()
2486 #define fork_subprocess() vfork()
2489 compress_savefile(const char *filename
)
2493 child
= fork_subprocess();
2496 "compress_savefile: fork failed: %s\n",
2497 pcap_strerror(errno
));
2501 /* Parent process. */
2507 * Set to lowest priority so that this doesn't disturb the capture.
2510 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2512 setpriority(PRIO_PROCESS
, 0, 19);
2514 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2516 "compress_savefile: execlp(%s, %s) failed: %s\n",
2519 pcap_strerror(errno
));
2526 #else /* HAVE_FORK && HAVE_VFORK */
2528 compress_savefile(const char *filename
)
2531 "compress_savefile failed. Functionality not implemented under your system\n");
2533 #endif /* HAVE_FORK && HAVE_VFORK */
2536 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2538 struct dump_info
*dump_info
;
2544 dump_info
= (struct dump_info
*)user
;
2547 * XXX - this won't force the file to rotate on the specified time
2548 * boundary, but it will rotate on the first packet received after the
2549 * specified Gflag number of seconds. Note: if a Gflag time boundary
2550 * and a Cflag size boundary coincide, the time rotation will occur
2551 * first thereby cancelling the Cflag boundary (since the file should
2555 /* Check if it is time to rotate */
2558 /* Get the current time */
2559 if ((t
= time(NULL
)) == (time_t)-1) {
2560 error("dump_and_trunc_packet: can't get current_time: %s",
2561 pcap_strerror(errno
));
2565 /* If the time is greater than the specified window, rotate */
2566 if (t
- Gflag_time
>= Gflag
) {
2567 #ifdef HAVE_CAPSICUM
2572 /* Update the Gflag_time */
2574 /* Update Gflag_count */
2577 * Close the current file and open a new one.
2579 pcap_dump_close(dump_info
->p
);
2582 * Compress the file we just closed, if the user asked for it
2585 compress_savefile(dump_info
->CurrentFileName
);
2588 * Check to see if we've exceeded the Wflag (when
2591 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2592 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2598 if (dump_info
->CurrentFileName
!= NULL
)
2599 free(dump_info
->CurrentFileName
);
2600 /* Allocate space for max filename + \0. */
2601 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2602 if (dump_info
->CurrentFileName
== NULL
)
2603 error("dump_packet_and_trunc: malloc");
2605 * Gflag was set otherwise we wouldn't be here. Reset the count
2606 * so multiple files would end with 1,2,3 in the filename.
2607 * The counting is handled with the -C flow after this.
2612 * This is always the first file in the Cflag
2614 * We also don't need numbering if Cflag is not set.
2617 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2620 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2622 #ifdef HAVE_LIBCAP_NG
2623 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2624 capng_apply(CAPNG_SELECT_BOTH
);
2625 #endif /* HAVE_LIBCAP_NG */
2626 #ifdef HAVE_CAPSICUM
2627 fd
= openat(dump_info
->dirfd
,
2628 dump_info
->CurrentFileName
,
2629 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2631 error("unable to open file %s",
2632 dump_info
->CurrentFileName
);
2634 fp
= fdopen(fd
, "w");
2636 error("unable to fdopen file %s",
2637 dump_info
->CurrentFileName
);
2639 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2640 #else /* !HAVE_CAPSICUM */
2641 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2643 #ifdef HAVE_LIBCAP_NG
2644 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2645 capng_apply(CAPNG_SELECT_BOTH
);
2646 #endif /* HAVE_LIBCAP_NG */
2647 if (dump_info
->p
== NULL
)
2648 error("%s", pcap_geterr(pd
));
2649 #ifdef HAVE_CAPSICUM
2650 set_dumper_capsicum_rights(dump_info
->p
);
2656 * XXX - this won't prevent capture files from getting
2657 * larger than Cflag - the last packet written to the
2658 * file could put it over Cflag.
2661 #ifdef HAVE_PCAP_DUMP_FTELL64
2662 int64_t size
= pcap_dump_ftell64(dump_info
->p
);
2665 * XXX - this only handles a Cflag value > 2^31-1 on
2666 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2667 * Windows) or LLP64 (64-bit Windows) would require
2668 * a version of libpcap with pcap_dump_ftell64().
2670 long size
= pcap_dump_ftell(dump_info
->p
);
2674 error("ftell fails on output file");
2676 #ifdef HAVE_CAPSICUM
2682 * Close the current file and open a new one.
2684 pcap_dump_close(dump_info
->p
);
2687 * Compress the file we just closed, if the user
2691 compress_savefile(dump_info
->CurrentFileName
);
2695 if (Cflag_count
>= Wflag
)
2698 if (dump_info
->CurrentFileName
!= NULL
)
2699 free(dump_info
->CurrentFileName
);
2700 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2701 if (dump_info
->CurrentFileName
== NULL
)
2702 error("dump_packet_and_trunc: malloc");
2703 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2704 #ifdef HAVE_LIBCAP_NG
2705 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2706 capng_apply(CAPNG_SELECT_BOTH
);
2707 #endif /* HAVE_LIBCAP_NG */
2708 #ifdef HAVE_CAPSICUM
2709 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2710 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2712 error("unable to open file %s",
2713 dump_info
->CurrentFileName
);
2715 fp
= fdopen(fd
, "w");
2717 error("unable to fdopen file %s",
2718 dump_info
->CurrentFileName
);
2720 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2721 #else /* !HAVE_CAPSICUM */
2722 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2724 #ifdef HAVE_LIBCAP_NG
2725 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2726 capng_apply(CAPNG_SELECT_BOTH
);
2727 #endif /* HAVE_LIBCAP_NG */
2728 if (dump_info
->p
== NULL
)
2729 error("%s", pcap_geterr(pd
));
2730 #ifdef HAVE_CAPSICUM
2731 set_dumper_capsicum_rights(dump_info
->p
);
2736 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2737 #ifdef HAVE_PCAP_DUMP_FLUSH
2739 pcap_dump_flush(dump_info
->p
);
2742 if (dump_info
->ndo
!= NULL
)
2743 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2751 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2753 struct dump_info
*dump_info
;
2759 dump_info
= (struct dump_info
*)user
;
2761 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2762 #ifdef HAVE_PCAP_DUMP_FLUSH
2764 pcap_dump_flush(dump_info
->p
);
2767 if (dump_info
->ndo
!= NULL
)
2768 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2776 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2782 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2791 * XXX - there should really be libpcap calls to get the version
2792 * number as a string (the string would be generated from #defines
2793 * at run time, so that it's not generated from string constants
2794 * in the library, as, on many UNIX systems, those constants would
2795 * be statically linked into the application executable image, and
2796 * would thus reflect the version of libpcap on the system on
2797 * which the application was *linked*, not the system on which it's
2800 * That routine should be documented, unlike the "version[]"
2801 * string, so that UNIX vendors providing their own libpcaps
2802 * don't omit it (as a couple of vendors have...).
2804 * Packet.dll should perhaps also export a routine to return the
2805 * version number of the Packet.dll code, to supply the
2806 * "Wpcap_version" information on Windows.
2808 char WDversion
[]="current-git.tcpdump.org";
2809 #if !defined(HAVE_GENERATED_VERSION)
2810 char version
[]="current-git.tcpdump.org";
2812 char pcap_version
[]="current-git.tcpdump.org";
2813 char Wpcap_version
[]="3.1";
2816 #ifdef SIGNAL_REQ_INFO
2817 void requestinfo(int signo _U_
)
2827 print_packets_captured (void)
2829 static u_int prev_packets_captured
, first
= 1;
2831 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2832 fprintf(stderr
, "Got %u\r", packets_captured
);
2834 prev_packets_captured
= packets_captured
;
2839 * Called once each second in verbose mode while dumping to file
2841 #ifdef USE_WIN32_MM_TIMER
2842 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2843 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2845 print_packets_captured();
2847 #elif defined(HAVE_ALARM)
2848 static void verbose_stats_dump(int sig _U_
)
2850 print_packets_captured();
2855 USES_APPLE_DEPRECATED_API
2859 #ifndef HAVE_PCAP_LIB_VERSION
2860 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2861 extern char pcap_version
[];
2862 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2863 static char pcap_version
[] = "unknown";
2864 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2865 #endif /* HAVE_PCAP_LIB_VERSION */
2866 const char *smi_version_string
;
2868 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
2869 #ifdef HAVE_PCAP_LIB_VERSION
2870 (void)fprintf(stderr
, "%s\n",pcap_lib_version());
2871 #else /* HAVE_PCAP_LIB_VERSION */
2872 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2873 #endif /* HAVE_PCAP_LIB_VERSION */
2875 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2876 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2879 smi_version_string
= nd_smi_version_string();
2880 if (smi_version_string
!= NULL
)
2881 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2882 #ifdef HAVE_DNET_HTOA
2883 (void)fprintf(stderr
, "libdnet unknown version\n");
2886 #if defined(__SANITIZE_ADDRESS__)
2887 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
2888 #elif defined(__has_feature)
2889 # if __has_feature(address_sanitizer)
2890 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
2892 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2900 (void)fprintf(stderr
,
2901 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2902 (void)fprintf(stderr
,
2903 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2904 (void)fprintf(stderr
,
2905 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
2906 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2907 (void)fprintf(stderr
,
2908 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
2910 (void)fprintf(stderr
,
2911 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
2912 (void)fprintf(stderr
,
2913 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
2914 (void)fprintf(stderr
,
2915 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
2916 (void)fprintf(stderr
,
2917 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
2918 (void)fprintf(stderr
,
2919 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");
2923 * c-style: whitesmith