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/time.h>
102 #include <sys/wait.h>
103 #include <sys/resource.h>
108 /* capabilities convenience library */
109 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
110 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
111 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
113 #ifdef HAVE_LIBCAP_NG
117 #undef HAVE_LIBCAP_NG
118 #endif /* HAVE_CAP_NG_H */
119 #endif /* HAVE_LIBCAP_NG */
122 #include <sys/sysctl.h>
123 #endif /* __FreeBSD__ */
125 #include "netdissect.h"
126 #include "interface.h"
127 #include "addrtoname.h"
129 #include "gmt2local.h"
130 #include "pcap-missing.h"
131 #include "ascii_strcasecmp.h"
136 #define PATH_MAX 1024
140 #define SIGNAL_REQ_INFO SIGINFO
142 #define SIGNAL_REQ_INFO SIGUSR1
145 static int Bflag
; /* buffer size */
146 #ifdef HAVE_PCAP_DUMP_FTELL64
147 static int64_t Cflag
; /* rotate dump files after this many bytes */
149 static long Cflag
; /* rotate dump files after this many bytes */
151 static int Cflag_count
; /* Keep track of which file number we're writing */
152 #ifdef HAVE_PCAP_FINDALLDEVS
153 static int Dflag
; /* list available devices and exit */
155 #ifdef HAVE_PCAP_FINDALLDEVS_EX
156 static char *remote_interfaces_source
; /* list available devices from this source and exit */
160 * This is exported because, in some versions of libpcap, if libpcap
161 * is built with optimizer debugging code (which is *NOT* the default
162 * configuration!), the library *imports*(!) a variable named dflag,
163 * under the expectation that tcpdump is exporting it, to govern
164 * how much debugging information to print when optimizing
165 * the generated BPF code.
167 * This is a horrible hack; newer versions of libpcap don't import
168 * dflag but, instead, *if* built with optimizer debugging code,
169 * *export* a routine to set that flag.
171 int dflag
; /* print filter code */
172 static int Gflag
; /* rotate dump files after this many seconds */
173 static int Gflag_count
; /* number of files created with Gflag rotation */
174 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
175 static int Lflag
; /* list available data link types and exit */
176 static int Iflag
; /* rfmon (monitor) mode */
177 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
178 static int Jflag
; /* list available time stamp types */
180 static int jflag
= -1; /* packet time stamp source */
181 static int pflag
; /* don't go promiscuous */
182 #ifdef HAVE_PCAP_SETDIRECTION
183 static int Qflag
= -1; /* restrict captured packet by send/receive direction */
185 static int Uflag
; /* "unbuffered" output of dump files */
186 static int Wflag
; /* recycle output files after this number of files */
187 static int WflagChars
;
188 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
189 static int immediate_mode
;
191 static int infodelay
;
192 static int infoprint
;
197 cap_channel_t
*capdns
;
201 static NORETURN
void error(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
202 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
203 static NORETURN
void exit_tcpdump(int);
204 static void (*setsignal (int sig
, void (*func
)(int)))(int);
205 static void cleanup(int);
206 static void child_cleanup(int);
207 static void print_version(void);
208 static void print_usage(void);
209 static NORETURN
void show_tstamp_types_and_exit(pcap_t
*, const char *device
);
210 static NORETURN
void show_dlts_and_exit(pcap_t
*, const char *device
);
211 #ifdef HAVE_PCAP_FINDALLDEVS
212 static NORETURN
void show_devices_and_exit(void);
214 #ifdef HAVE_PCAP_FINDALLDEVS_EX
215 static NORETURN
void show_remote_devices_and_exit(void);
218 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
219 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
220 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
221 static void droproot(const char *, const char *);
223 #ifdef SIGNAL_REQ_INFO
224 void requestinfo(int);
228 #include <MMsystem.h>
229 static UINT timer_id
;
230 static void CALLBACK
verbose_stats_dump(UINT
, UINT
, DWORD_PTR
, DWORD_PTR
, DWORD_PTR
);
232 static void verbose_stats_dump(int sig
);
235 static void info(int);
236 static u_int packets_captured
;
238 #ifdef HAVE_PCAP_FINDALLDEVS
239 static const struct tok status_flags
[] = {
241 { PCAP_IF_UP
, "Up" },
243 #ifdef PCAP_IF_RUNNING
244 { PCAP_IF_RUNNING
, "Running" },
246 { PCAP_IF_LOOPBACK
, "Loopback" },
253 static int supports_monitor_mode
;
261 char *CurrentFileName
;
264 netdissect_options
*ndo
;
270 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
272 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
273 * by any libpcap header, because it's a special hack, only available if
274 * libpcap was configured to include it, and only intended for use by
275 * libpcap developers trying to debug the parser for filter expressions).
278 __declspec(dllimport
)
282 void pcap_set_parser_debug(int);
283 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
285 * We don't have pcap_set_parser_debug() in libpcap, but we do have
286 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
287 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
290 pcap_set_parser_debug(int value
)
292 #ifdef HAVE_PCAP_DEBUG
293 extern int pcap_debug
;
296 #else /* HAVE_PCAP_DEBUG */
300 #endif /* HAVE_PCAP_DEBUG */
303 #define HAVE_PCAP_SET_PARSER_DEBUG
306 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
308 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
309 * by any libpcap header, because it's a special hack, only available if
310 * libpcap was configured to include it, and only intended for use by
311 * libpcap developers trying to debug the optimizer for filter expressions).
314 __declspec(dllimport
)
318 void pcap_set_optimizer_debug(int);
323 error(const char *fmt
, ...)
327 (void)fprintf(stderr
, "%s: ", program_name
);
329 (void)vfprintf(stderr
, fmt
, ap
);
334 (void)fputc('\n', stderr
);
342 warning(const char *fmt
, ...)
346 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
348 (void)vfprintf(stderr
, fmt
, ap
);
353 (void)fputc('\n', stderr
);
358 exit_tcpdump(int status
)
364 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
366 show_tstamp_types_and_exit(pcap_t
*pc
, const char *device
)
369 int *tstamp_types
= 0;
370 const char *tstamp_type_name
;
373 n_tstamp_types
= pcap_list_tstamp_types(pc
, &tstamp_types
);
374 if (n_tstamp_types
< 0)
375 error("%s", pcap_geterr(pc
));
377 if (n_tstamp_types
== 0) {
378 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
382 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
384 for (i
= 0; i
< n_tstamp_types
; i
++) {
385 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
386 if (tstamp_type_name
!= NULL
) {
387 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
388 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
390 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
393 pcap_free_tstamp_types(tstamp_types
);
399 show_dlts_and_exit(pcap_t
*pc
, const char *device
)
403 const char *dlt_name
;
405 n_dlts
= pcap_list_datalinks(pc
, &dlts
);
407 error("%s", pcap_geterr(pc
));
408 else if (n_dlts
== 0 || !dlts
)
409 error("No data link types.");
412 * If the interface is known to support monitor mode, indicate
413 * whether these are the data link types available when not in
414 * monitor mode, if -I wasn't specified, or when in monitor mode,
415 * when -I was specified (the link-layer types available in
416 * monitor mode might be different from the ones available when
417 * not in monitor mode).
419 if (supports_monitor_mode
)
420 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
422 Iflag
? "when in monitor mode" : "when not in monitor mode");
424 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
427 for (i
= 0; i
< n_dlts
; i
++) {
428 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
429 if (dlt_name
!= NULL
) {
430 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
431 pcap_datalink_val_to_description(dlts
[i
]));
434 * OK, does tcpdump handle that type?
436 if (!has_printer(dlts
[i
]))
437 (void) fprintf(stderr
, " (printing not supported)");
438 fprintf(stderr
, "\n");
440 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
444 #ifdef HAVE_PCAP_FREE_DATALINKS
445 pcap_free_datalinks(dlts
);
450 #ifdef HAVE_PCAP_FINDALLDEVS
452 show_devices_and_exit(void)
454 pcap_if_t
*dev
, *devlist
;
455 char ebuf
[PCAP_ERRBUF_SIZE
];
458 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
460 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
461 printf("%d.%s", i
+1, dev
->name
);
462 if (dev
->description
!= NULL
)
463 printf(" (%s)", dev
->description
);
465 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
468 pcap_freealldevs(devlist
);
471 #endif /* HAVE_PCAP_FINDALLDEVS */
473 #ifdef HAVE_PCAP_FINDALLDEVS_EX
475 show_remote_devices_and_exit(void)
477 pcap_if_t
*dev
, *devlist
;
478 char ebuf
[PCAP_ERRBUF_SIZE
];
481 if (pcap_findalldevs_ex(remote_interfaces_source
, NULL
, &devlist
,
484 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
485 printf("%d.%s", i
+1, dev
->name
);
486 if (dev
->description
!= NULL
)
487 printf(" (%s)", dev
->description
);
489 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
492 pcap_freealldevs(devlist
);
495 #endif /* HAVE_PCAP_FINDALLDEVS */
500 * Note that there we use all letters for short options except for g, k,
501 * o, and P, and those are used by other versions of tcpdump, and we should
502 * only use them for the same purposes that the other versions of tcpdump
505 * OS X tcpdump uses -g to force non--v output for IP to be on one
506 * line, making it more "g"repable;
508 * OS X tcpdump uses -k to specify that packet comments in pcap-ng files
511 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
512 * for hosts sending TCP SYN packets;
514 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
517 * OS X tcpdump also uses -Q to specify expressions that match packet
518 * metadata, including but not limited to the packet direction.
519 * The expression syntax is different from a simple "in|out|inout",
520 * and those expressions aren't accepted by OS X tcpdump, but the
521 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
522 * "inout" = "dir=in or dir=out", and the parser could conceivably
523 * special-case "in", "out", and "inout" as expressions for backwards
524 * compatibility, so all is not (yet) lost.
528 * Set up flags that might or might not be supported depending on the
529 * version of libpcap we're using.
531 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
533 #define B_FLAG_USAGE " [ -B size ]"
534 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
537 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
539 #ifdef HAVE_PCAP_FINDALLDEVS
545 #ifdef HAVE_PCAP_CREATE
547 #else /* HAVE_PCAP_CREATE */
549 #endif /* HAVE_PCAP_CREATE */
551 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
553 #define j_FLAG_USAGE " [ -j tstamptype ]"
555 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
559 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
561 #ifdef HAVE_PCAP_SETDIRECTION
563 #define Q_FLAG_USAGE " [ -Q in|out|inout ]"
569 #ifdef HAVE_PCAP_DUMP_FLUSH
575 #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:#"
580 * We do not currently have long options corresponding to all short
581 * options; we should probably pick appropriate option names for them.
583 * However, the short options where the number of times the option is
584 * specified matters, such as -v and -d and -t, should probably not
585 * just map to a long option, as saying
587 * tcpdump --verbose --verbose
589 * doesn't make sense; it should be --verbosity={N} or something such
592 * For long options with no corresponding short options, we define values
593 * outside the range of ASCII graphic characters, make that the last
594 * component of the entry for the long option, and have a case for that
595 * option in the switch statement.
597 #define OPTION_VERSION 128
598 #define OPTION_TSTAMP_PRECISION 129
599 #define OPTION_IMMEDIATE_MODE 130
600 #define OPTION_PRINT 131
601 #define OPTION_LIST_REMOTE_INTERFACES 132
603 static const struct option longopts
[] = {
604 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
605 { "buffer-size", required_argument
, NULL
, 'B' },
607 { "list-interfaces", no_argument
, NULL
, 'D' },
608 #ifdef HAVE_PCAP_FINDALLDEVS_EX
609 { "list-remote-interfaces", required_argument
, NULL
, OPTION_LIST_REMOTE_INTERFACES
},
611 { "help", no_argument
, NULL
, 'h' },
612 { "interface", required_argument
, NULL
, 'i' },
613 #ifdef HAVE_PCAP_CREATE
614 { "monitor-mode", no_argument
, NULL
, 'I' },
616 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
617 { "time-stamp-type", required_argument
, NULL
, 'j' },
618 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
620 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
621 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
623 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
624 { "list-data-link-types", no_argument
, NULL
, 'L' },
625 { "no-optimize", no_argument
, NULL
, 'O' },
626 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
627 #ifdef HAVE_PCAP_SETDIRECTION
628 { "direction", required_argument
, NULL
, 'Q' },
630 { "snapshot-length", required_argument
, NULL
, 's' },
631 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
632 #ifdef HAVE_PCAP_DUMP_FLUSH
633 { "packet-buffered", no_argument
, NULL
, 'U' },
635 { "linktype", required_argument
, NULL
, 'y' },
636 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
637 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
639 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
640 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
642 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
643 { "number", no_argument
, NULL
, '#' },
644 { "print", no_argument
, NULL
, OPTION_PRINT
},
645 { "version", no_argument
, NULL
, OPTION_VERSION
},
649 #ifdef HAVE_PCAP_FINDALLDEVS_EX
650 #define LIST_REMOTE_INTERFACES_USAGE "[ --list-remote-interfaces remote-source ]"
652 #define LIST_REMOTE_INTERFACES_USAGE
655 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
656 #define IMMEDIATE_MODE_USAGE " [ --immediate-mode ]"
658 #define IMMEDIATE_MODE_USAGE ""
661 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
662 #define TIME_STAMP_PRECISION_USAGE " [ --time-stamp-precision precision ]"
664 #define TIME_STAMP_PRECISION_USAGE
668 /* Drop root privileges and chroot if necessary */
670 droproot(const char *username
, const char *chroot_dir
)
672 struct passwd
*pw
= NULL
;
674 if (chroot_dir
&& !username
) {
675 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
680 pw
= getpwnam(username
);
683 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
684 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
685 program_name
, chroot_dir
, pcap_strerror(errno
));
689 #ifdef HAVE_LIBCAP_NG
691 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
693 fprintf(stderr
, "error : ret %d\n", ret
);
695 fprintf(stderr
, "dropped privs to %s\n", username
);
699 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
700 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
701 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
702 program_name
, username
,
703 (unsigned long)pw
->pw_uid
,
704 (unsigned long)pw
->pw_gid
,
705 pcap_strerror(errno
));
709 fprintf(stderr
, "dropped privs to %s\n", username
);
711 #endif /* HAVE_LIBCAP_NG */
714 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
715 program_name
, username
);
718 #ifdef HAVE_LIBCAP_NG
719 /* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
720 DIAG_OFF_CLANG(assign
-enum)
723 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
728 DIAG_ON_CLANG(assign
-enum)
729 capng_apply(CAPNG_SELECT_BOTH
);
730 #endif /* HAVE_LIBCAP_NG */
751 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
753 char *filename
= malloc(PATH_MAX
+ 1);
754 if (filename
== NULL
)
755 error("Makefilename: malloc");
757 /* Process with strftime if Gflag is set. */
761 /* Convert Gflag_time to a usable format */
762 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
763 error("MakeTimedFilename: localtime");
766 /* There's no good way to detect an error in strftime since a return
767 * value of 0 isn't necessarily failure.
769 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
771 strncpy(filename
, orig_name
, PATH_MAX
);
774 if (cnt
== 0 && max_chars
== 0)
775 strncpy(buffer
, filename
, PATH_MAX
+ 1);
777 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
778 /* Report an error if the filename is too large */
779 error("too many output files or filename is too long (> %d)", PATH_MAX
);
784 get_next_file(FILE *VFile
, char *ptr
)
788 ret
= fgets(ptr
, PATH_MAX
, VFile
);
792 if (ptr
[strlen(ptr
) - 1] == '\n')
793 ptr
[strlen(ptr
) - 1] = '\0';
799 static cap_channel_t
*
802 cap_channel_t
*capcas
, *capdnsloc
;
803 const char *types
[1];
808 error("unable to create casper process");
809 capdnsloc
= cap_service_open(capcas
, "system.dns");
810 /* Casper capability no longer needed. */
812 if (capdnsloc
== NULL
)
813 error("unable to open system.dns service");
814 /* Limit system.dns to reverse DNS lookups. */
816 if (cap_dns_type_limit(capdnsloc
, types
, 1) < 0)
817 error("unable to limit access to system.dns service");
818 families
[0] = AF_INET
;
819 families
[1] = AF_INET6
;
820 if (cap_dns_family_limit(capdnsloc
, families
, 2) < 0)
821 error("unable to limit access to system.dns service");
825 #endif /* HAVE_CASPER */
827 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
829 tstamp_precision_from_string(const char *precision
)
831 if (strncmp(precision
, "nano", strlen("nano")) == 0)
832 return PCAP_TSTAMP_PRECISION_NANO
;
834 if (strncmp(precision
, "micro", strlen("micro")) == 0)
835 return PCAP_TSTAMP_PRECISION_MICRO
;
841 tstamp_precision_to_string(int precision
)
845 case PCAP_TSTAMP_PRECISION_MICRO
:
848 case PCAP_TSTAMP_PRECISION_NANO
:
859 * Ensure that, on a dump file's descriptor, we have all the rights
860 * necessary to make the standard I/O library work with an fdopen()ed
861 * FILE * from that descriptor.
863 * A long time ago, in a galaxy far far away, AT&T decided that, instead
864 * of providing separate APIs for getting and setting the FD_ flags on a
865 * descriptor, getting and setting the O_ flags on a descriptor, and
866 * locking files, they'd throw them all into a kitchen-sink fcntl() call
867 * along the lines of ioctl(), the fact that ioctl() operations are
868 * largely specific to particular character devices but fcntl() operations
869 * are either generic to all descriptors or generic to all descriptors for
870 * regular files nonwithstanding.
872 * The Capsicum people decided that fine-grained control of descriptor
873 * operations was required, so that you need to grant permission for
874 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
875 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
876 * collection of things, so there are *individual* fcntls for which
877 * permission needs to be granted.
879 * The FreeBSD standard I/O people implemented some optimizations that
880 * requires that the standard I/O routines be able to determine whether
881 * the descriptor for the FILE * is open append-only or not; as that
882 * descriptor could have come from an open() rather than an fopen(),
883 * that requires that it be able to do an F_GETFL fcntl() to read
886 * Tcpdump uses ftell() to determine how much data has been written
887 * to a file in order to, when used with -C, determine when it's time
888 * to rotate capture files. ftell() therefore needs to do an lseek()
889 * to find out the file offset and must, thanks to the aforementioned
890 * optimization, also know whether the descriptor is open append-only
893 * The net result of all the above is that we need to grant CAP_SEEK,
894 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
896 * Perhaps this is the universe's way of saying that either
898 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
899 * using it, so that Capsicum-capable tcpdump wouldn't need to do
904 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
905 * I/O library that knows what rights are needed by the standard
906 * I/O library, based on the open mode, and assigns them, perhaps
907 * with an additional argument indicating, for example, whether
908 * seeking should be allowed, so that tcpdump doesn't need to know
909 * what the standard I/O library happens to require this week.
912 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
914 int fd
= fileno(pcap_dump_file(p
));
917 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
918 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
919 error("unable to limit dump descriptor");
921 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
922 error("unable to limit dump descriptor fcntls");
928 * Copy arg vector into a new buffer, concatenating arguments with spaces.
931 copy_argv(register char **argv
)
934 register u_int len
= 0;
943 len
+= strlen(*p
++) + 1;
945 buf
= (char *)malloc(len
);
947 error("copy_argv: malloc");
951 while ((src
= *p
++) != NULL
) {
952 while ((*dst
++ = *src
++) != '\0')
962 * On Windows, we need to open the file in binary mode, so that
963 * we get all the bytes specified by the size we get from "fstat()".
964 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
965 * we define it as 0 if it's not defined, so it does nothing.
972 read_infile(char *fname
)
974 register int i
, fd
, cc
;
978 fd
= open(fname
, O_RDONLY
|O_BINARY
);
980 error("can't open %s: %s", fname
, pcap_strerror(errno
));
982 if (fstat(fd
, &buf
) < 0)
983 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
985 cp
= malloc((u_int
)buf
.st_size
+ 1);
987 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
988 fname
, pcap_strerror(errno
));
989 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
991 error("read %s: %s", fname
, pcap_strerror(errno
));
992 if (cc
!= buf
.st_size
)
993 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
996 /* replace "# comment" with spaces */
997 for (i
= 0; i
< cc
; i
++) {
999 while (i
< cc
&& cp
[i
] != '\n')
1006 #ifdef HAVE_PCAP_FINDALLDEVS
1008 parse_interface_number(const char *device
)
1013 devnum
= strtol(device
, &end
, 10);
1014 if (device
!= end
&& *end
== '\0') {
1016 * It's all-numeric, but is it a valid number?
1020 * No, it's not an ordinal.
1022 error("Invalid adapter index");
1027 * It's not all-numeric; return -1, so our caller
1035 find_interface_by_number(long devnum
)
1037 pcap_if_t
*dev
, *devlist
;
1039 char ebuf
[PCAP_ERRBUF_SIZE
];
1042 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
1045 * Look for the devnum-th entry in the list of devices (1-based).
1047 for (i
= 0, dev
= devlist
; i
< devnum
-1 && dev
!= NULL
;
1048 i
++, dev
= dev
->next
)
1051 error("Invalid adapter index");
1052 device
= strdup(dev
->name
);
1053 pcap_freealldevs(devlist
);
1058 #ifdef HAVE_PCAP_OPEN
1060 * Prefix for rpcap URLs.
1062 static char rpcap_prefix
[] = "rpcap://";
1066 open_interface(const char *device
, netdissect_options
*ndo
, char *ebuf
)
1069 #ifdef HAVE_PCAP_CREATE
1074 #ifdef HAVE_PCAP_OPEN
1076 * Is this an rpcap URL?
1078 if (strncmp(device
, rpcap_prefix
, sizeof(rpcap_prefix
) - 1) == 0) {
1080 * Yes. Open it with pcap_open().
1083 fprintf(stderr
, "Opening %s\n", device
);
1084 pc
= pcap_open(device
, ndo
->ndo_snaplen
,
1085 pflag
? 0 : PCAP_OPENFLAG_PROMISCUOUS
, 1000, NULL
,
1089 * If this failed with "No such device", that means
1090 * the interface doesn't exist; return NULL, so that
1091 * the caller can see whether the device name is
1092 * actually an interface index.
1094 if (strstr(ebuf
, "No such device") != NULL
)
1099 warning("%s", ebuf
);
1102 #endif /* HAVE_PCAP_OPEN */
1104 #ifdef HAVE_PCAP_CREATE
1105 pc
= pcap_create(device
, ebuf
);
1108 * If this failed with "No such device", that means
1109 * the interface doesn't exist; return NULL, so that
1110 * the caller can see whether the device name is
1111 * actually an interface index.
1113 if (strstr(ebuf
, "No such device") != NULL
)
1117 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1119 show_tstamp_types_and_exit(pc
, device
);
1121 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1122 status
= pcap_set_tstamp_precision(pc
, ndo
->ndo_tstamp_precision
);
1124 error("%s: Can't set %ssecond time stamp precision: %s",
1126 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1127 pcap_statustostr(status
));
1130 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1131 if (immediate_mode
) {
1132 status
= pcap_set_immediate_mode(pc
, 1);
1134 error("%s: Can't set immediate mode: %s",
1136 pcap_statustostr(status
));
1140 * Is this an interface that supports monitor mode?
1142 if (pcap_can_set_rfmon(pc
) == 1)
1143 supports_monitor_mode
= 1;
1145 supports_monitor_mode
= 0;
1146 if (ndo
->ndo_snaplen
!= 0) {
1148 * A snapshot length was explicitly specified;
1151 status
= pcap_set_snaplen(pc
, ndo
->ndo_snaplen
);
1153 error("%s: Can't set snapshot length: %s",
1154 device
, pcap_statustostr(status
));
1156 status
= pcap_set_promisc(pc
, !pflag
);
1158 error("%s: Can't set promiscuous mode: %s",
1159 device
, pcap_statustostr(status
));
1161 status
= pcap_set_rfmon(pc
, 1);
1163 error("%s: Can't set monitor mode: %s",
1164 device
, pcap_statustostr(status
));
1166 status
= pcap_set_timeout(pc
, 1000);
1168 error("%s: pcap_set_timeout failed: %s",
1169 device
, pcap_statustostr(status
));
1171 status
= pcap_set_buffer_size(pc
, Bflag
);
1173 error("%s: Can't set buffer size: %s",
1174 device
, pcap_statustostr(status
));
1176 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1178 status
= pcap_set_tstamp_type(pc
, jflag
);
1180 error("%s: Can't set time stamp type: %s",
1181 device
, pcap_statustostr(status
));
1184 status
= pcap_activate(pc
);
1187 * pcap_activate() failed.
1189 cp
= pcap_geterr(pc
);
1190 if (status
== PCAP_ERROR
)
1192 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
) {
1194 * Return an error for our caller to handle.
1196 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "%s: %s\n(%s)",
1197 device
, pcap_statustostr(status
), cp
);
1200 } else if (status
== PCAP_ERROR_PERM_DENIED
&& *cp
!= '\0')
1201 error("%s: %s\n(%s)", device
,
1202 pcap_statustostr(status
), cp
);
1204 else if (status
== PCAP_ERROR_RFMON_NOTSUP
&&
1205 strncmp(device
, "wlan", 4) == 0) {
1206 char parent
[8], newdev
[8];
1208 size_t s
= sizeof(parent
);
1210 snprintf(sysctl
, sizeof(sysctl
),
1211 "net.wlan.%d.%%parent", atoi(device
+ 4));
1212 sysctlbyname(sysctl
, parent
, &s
, NULL
, 0);
1213 strlcpy(newdev
, device
, sizeof(newdev
));
1214 /* Suggest a new wlan device. */
1215 /* FIXME: incrementing the index this way is not going to work well
1216 * when the index is 9 or greater but the only consequence in this
1217 * specific case would be an error message that looks a bit odd.
1219 newdev
[strlen(newdev
)-1]++;
1220 error("%s is not a monitor mode VAP\n"
1221 "To create a new monitor mode VAP use:\n"
1222 " ifconfig %s create wlandev %s wlanmode monitor\n"
1223 "and use %s as the tcpdump interface",
1224 device
, newdev
, parent
, newdev
);
1228 error("%s: %s", device
,
1229 pcap_statustostr(status
));
1230 } else if (status
> 0) {
1232 * pcap_activate() succeeded, but it's warning us
1233 * of a problem it had.
1235 cp
= pcap_geterr(pc
);
1236 if (status
== PCAP_WARNING
)
1238 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1240 warning("%s: %s\n(%s)", device
,
1241 pcap_statustostr(status
), cp
);
1243 warning("%s: %s", device
,
1244 pcap_statustostr(status
));
1246 #ifdef HAVE_PCAP_SETDIRECTION
1248 status
= pcap_setdirection(pc
, Qflag
);
1250 error("%s: pcap_setdirection() failed: %s",
1251 device
, pcap_geterr(pc
));
1253 #endif /* HAVE_PCAP_SETDIRECTION */
1254 #else /* HAVE_PCAP_CREATE */
1257 * If no snapshot length was specified, or a length of 0 was
1258 * specified, default to 256KB.
1260 if (ndo
->ndo_snaplen
== 0)
1261 ndo
->ndo_snaplen
= 262144;
1262 pc
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000, ebuf
);
1265 * If this failed with "No such device", that means
1266 * the interface doesn't exist; return NULL, so that
1267 * the caller can see whether the device name is
1268 * actually an interface index.
1270 if (strstr(ebuf
, "No such device") != NULL
)
1275 warning("%s", ebuf
);
1276 #endif /* HAVE_PCAP_CREATE */
1282 main(int argc
, char **argv
)
1284 register int cnt
, op
, i
;
1285 bpf_u_int32 localnet
= 0, netmask
= 0;
1286 int timezone_offset
= 0;
1287 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
1289 pcap_handler callback
;
1291 const char *dlt_name
;
1292 struct bpf_program fcode
;
1294 void (*oldhandler
)(int);
1296 struct dump_info dumpinfo
;
1297 u_char
*pcap_userdata
;
1298 char ebuf
[PCAP_ERRBUF_SIZE
];
1299 char VFileLine
[PATH_MAX
+ 1];
1300 char *username
= NULL
;
1301 char *chroot_dir
= NULL
;
1304 #ifdef HAVE_PCAP_FINDALLDEVS
1310 #ifdef HAVE_CAPSICUM
1311 cap_rights_t rights
;
1313 #endif /* HAVE_CAPSICUM */
1314 int Oflag
= 1; /* run filter code optimizer */
1316 const char *yflag_dlt_name
= NULL
;
1319 netdissect_options Ndo
;
1320 netdissect_options
*ndo
= &Ndo
;
1323 * Initialize the netdissect code.
1325 if (nd_init(ebuf
, sizeof ebuf
) == -1)
1328 memset(ndo
, 0, sizeof(*ndo
));
1329 ndo_set_function_pointers(ndo
);
1339 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
1340 ndo
->program_name
= program_name
= cp
+ 1;
1342 ndo
->program_name
= program_name
= argv
[0];
1345 if (pcap_wsockinit() != 0)
1346 error("Attempting to initialize Winsock failed");
1350 * On platforms where the CPU doesn't support unaligned loads,
1351 * force unaligned accesses to abort with SIGBUS, rather than
1352 * being fixed up (slowly) by the OS kernel; on those platforms,
1353 * misaligned accesses are bugs, and we want tcpdump to crash so
1354 * that the bugs are reported.
1356 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
1360 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
1364 /* compatibility for old -a */
1375 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1377 Bflag
= atoi(optarg
)*1024;
1379 error("invalid packet buffer size %s", optarg
);
1381 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1386 error("invalid packet count %s", optarg
);
1391 #ifdef HAVE_PCAP_DUMP_FTELL64
1392 Cflag
= strtoint64_t(optarg
, &endp
, 10);
1394 Cflag
= strtol(optarg
, &endp
, 10);
1396 if (endp
== optarg
|| *endp
!= '\0' || errno
!= 0
1398 error("invalid file size %s", optarg
);
1400 * Will multiplying it by 1000000 overflow?
1402 #ifdef HAVE_PCAP_DUMP_FTELL64
1403 if (Cflag
> INT64_T_CONSTANT(0x7fffffffffffffff) / 1000000)
1405 if (Cflag
> LONG_MAX
/ 1000000)
1407 error("file size %s is too large", optarg
);
1415 #ifdef HAVE_PCAP_FINDALLDEVS
1421 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1422 case OPTION_LIST_REMOTE_INTERFACES
:
1423 remote_interfaces_source
= optarg
;
1436 #ifndef HAVE_LIBCRYPTO
1437 warning("crypto code not compiled in");
1439 ndo
->ndo_espsecret
= optarg
;
1451 Gflag
= atoi(optarg
);
1453 error("invalid number of seconds %s", optarg
);
1455 /* We will create one file initially. */
1458 /* Grab the current time for rotation use. */
1459 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1460 error("main: can't get current time: %s",
1461 pcap_strerror(errno
));
1478 #ifdef HAVE_PCAP_CREATE
1482 #endif /* HAVE_PCAP_CREATE */
1484 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1486 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1488 error("invalid time stamp type %s", optarg
);
1499 * _IOLBF is the same as _IOFBF in Microsoft's C
1500 * libraries; the only alternative they offer
1503 * XXX - this should really be checking for MSVC++,
1504 * not _WIN32, if, for example, MinGW has its own
1505 * C library that is more UNIX-compatible.
1507 setvbuf(stdout
, NULL
, _IONBF
, 0);
1509 #ifdef HAVE_SETLINEBUF
1512 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1522 if (nd_have_smi_support()) {
1523 if (nd_load_smi_module(optarg
, ebuf
, sizeof ebuf
) == -1)
1526 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1527 program_name
, optarg
);
1528 (void)fprintf(stderr
, "(no libsmi support)\n");
1533 /* TCP-MD5 shared secret */
1534 #ifndef HAVE_LIBCRYPTO
1535 warning("crypto code not compiled in");
1537 ndo
->ndo_sigsecret
= optarg
;
1558 ++ndo
->ndo_suppress_default_print
;
1561 #ifdef HAVE_PCAP_SETDIRECTION
1563 if (ascii_strcasecmp(optarg
, "in") == 0)
1565 else if (ascii_strcasecmp(optarg
, "out") == 0)
1567 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1568 Qflag
= PCAP_D_INOUT
;
1570 error("unknown capture direction `%s'", optarg
);
1572 #endif /* HAVE_PCAP_SETDIRECTION */
1579 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1580 if (optarg
== end
|| *end
!= '\0'
1581 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1582 error("invalid snaplen %s", optarg
);
1594 if (ascii_strcasecmp(optarg
, "vat") == 0)
1595 ndo
->ndo_packettype
= PT_VAT
;
1596 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1597 ndo
->ndo_packettype
= PT_WB
;
1598 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1599 ndo
->ndo_packettype
= PT_RPC
;
1600 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1601 ndo
->ndo_packettype
= PT_RTP
;
1602 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1603 ndo
->ndo_packettype
= PT_RTCP
;
1604 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1605 ndo
->ndo_packettype
= PT_SNMP
;
1606 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1607 ndo
->ndo_packettype
= PT_CNFP
;
1608 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1609 ndo
->ndo_packettype
= PT_TFTP
;
1610 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1611 ndo
->ndo_packettype
= PT_AODV
;
1612 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1613 ndo
->ndo_packettype
= PT_CARP
;
1614 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1615 ndo
->ndo_packettype
= PT_RADIUS
;
1616 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1617 ndo
->ndo_packettype
= PT_ZMTP1
;
1618 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1619 ndo
->ndo_packettype
= PT_VXLAN
;
1620 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1621 ndo
->ndo_packettype
= PT_PGM
;
1622 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1623 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1624 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1625 ndo
->ndo_packettype
= PT_LMP
;
1626 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1627 ndo
->ndo_packettype
= PT_RESP
;
1629 error("unknown packet type `%s'", optarg
);
1636 #ifdef HAVE_PCAP_DUMP_FLUSH
1655 Wflag
= atoi(optarg
);
1657 error("invalid number of output files %s", optarg
);
1658 WflagChars
= getWflagChars(Wflag
);
1663 ++ndo
->ndo_suppress_default_print
;
1668 ++ndo
->ndo_suppress_default_print
;
1672 yflag_dlt_name
= optarg
;
1674 pcap_datalink_name_to_val(yflag_dlt_name
);
1676 error("invalid data link type %s", yflag_dlt_name
);
1679 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1682 /* Undocumented flag */
1683 pcap_set_parser_debug(1);
1696 ndo
->ndo_packet_number
= 1;
1699 case OPTION_VERSION
:
1704 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1705 case OPTION_TSTAMP_PRECISION
:
1706 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1707 if (ndo
->ndo_tstamp_precision
< 0)
1708 error("unsupported time stamp precision");
1712 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1713 case OPTION_IMMEDIATE_MODE
:
1728 #ifdef HAVE_PCAP_FINDALLDEVS
1730 show_devices_and_exit();
1732 #ifdef HAVE_PCAP_FINDALLDEVS_EX
1733 if (remote_interfaces_source
!= NULL
)
1734 show_remote_devices_and_exit();
1737 switch (ndo
->ndo_tflag
) {
1739 case 0: /* Default */
1740 case 4: /* Default + Date*/
1741 timezone_offset
= gmt2local(0);
1744 case 1: /* No time stamp */
1745 case 2: /* Unix timeval style */
1746 case 3: /* Microseconds since previous packet */
1747 case 5: /* Microseconds since first packet */
1750 default: /* Not supported */
1751 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1755 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1756 error("-f can not be used with -V or -r");
1758 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1759 error("-V and -r are mutually exclusive.");
1761 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1763 * If we're printing dissected packets to the standard output
1764 * and the standard output is a terminal, use immediate mode,
1765 * as the user's probably expecting to see packets pop up
1768 * XXX - set the timeout to a lower value, instead? If so,
1769 * what value would be appropriate?
1771 if ((WFileName
== NULL
|| print
) && isatty(1))
1776 /* if run as root, prepare for chrooting */
1777 if (getuid() == 0 || geteuid() == 0) {
1778 /* future extensibility for cmd-line arguments */
1780 chroot_dir
= WITH_CHROOT
;
1785 /* if run as root, prepare for dropping root privileges */
1786 if (getuid() == 0 || geteuid() == 0) {
1787 /* Run with '-Z root' to restore old behaviour */
1789 username
= WITH_USER
;
1793 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1795 * If RFileName is non-null, it's the pathname of a
1796 * savefile to read. If VFileName is non-null, it's
1797 * the pathname of a file containing a list of pathnames
1798 * (one per line) of savefiles to read.
1800 * In either case, we're reading a savefile, not doing
1805 * We don't need network access, so relinquish any set-UID
1806 * or set-GID privileges we have (if any).
1808 * We do *not* want set-UID privileges when opening a
1809 * trace file, as that might let the user read other
1810 * people's trace files (especially if we're set-UID
1813 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1814 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1816 if (VFileName
!= NULL
) {
1817 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1820 VFile
= fopen(VFileName
, "r");
1823 error("Unable to open file: %s\n", pcap_strerror(errno
));
1825 ret
= get_next_file(VFile
, VFileLine
);
1827 error("Nothing in %s\n", VFileName
);
1828 RFileName
= VFileLine
;
1831 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1832 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1833 ndo
->ndo_tstamp_precision
, ebuf
);
1835 pd
= pcap_open_offline(RFileName
, ebuf
);
1840 #ifdef HAVE_CAPSICUM
1841 cap_rights_init(&rights
, CAP_READ
);
1842 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1844 error("unable to limit pcap descriptor");
1847 dlt
= pcap_datalink(pd
);
1848 dlt_name
= pcap_datalink_val_to_name(dlt
);
1849 if (dlt_name
== NULL
) {
1850 fprintf(stderr
, "reading from file %s, link-type %u\n",
1854 "reading from file %s, link-type %s (%s)\n",
1855 RFileName
, dlt_name
,
1856 pcap_datalink_val_to_description(dlt
));
1860 * We're doing a live capture.
1862 if (device
== NULL
) {
1864 * No interface was specified. Pick one.
1866 #ifdef HAVE_PCAP_FINDALLDEVS
1868 * Find the list of interfaces, and pick
1869 * the first interface.
1871 if (pcap_findalldevs(&devlist
, ebuf
) == -1)
1873 if (devlist
== NULL
)
1874 error("no interfaces available for capture");
1875 device
= strdup(devlist
->name
);
1876 pcap_freealldevs(devlist
);
1877 #else /* HAVE_PCAP_FINDALLDEVS */
1879 * Use whatever interface pcap_lookupdev()
1882 device
= pcap_lookupdev(ebuf
);
1889 * Try to open the interface with the specified name.
1891 pd
= open_interface(device
, ndo
, ebuf
);
1894 * That failed. If we can get a list of
1895 * interfaces, and the interface name
1896 * is purely numeric, try to use it as
1897 * a 1-based index in the list of
1900 #ifdef HAVE_PCAP_FINDALLDEVS
1901 devnum
= parse_interface_number(device
);
1904 * It's not a number; just report
1905 * the open error and fail.
1911 * OK, it's a number; try to find the
1912 * interface with that index, and try
1915 * find_interface_by_number() exits if it
1916 * couldn't be found.
1918 device
= find_interface_by_number(devnum
);
1919 pd
= open_interface(device
, ndo
, ebuf
);
1922 #else /* HAVE_PCAP_FINDALLDEVS */
1924 * We can't get a list of interfaces; just
1928 #endif /* HAVE_PCAP_FINDALLDEVS */
1932 * Let user own process after capture device has
1936 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1937 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1939 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1941 if(pcap_setbuff(pd
, Bflag
)==-1){
1942 error("%s", pcap_geterr(pd
));
1944 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1946 show_dlts_and_exit(pd
, device
);
1947 if (yflag_dlt
>= 0) {
1948 #ifdef HAVE_PCAP_SET_DATALINK
1949 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1950 error("%s", pcap_geterr(pd
));
1953 * We don't actually support changing the
1954 * data link type, so we only let them
1955 * set it to what it already is.
1957 if (yflag_dlt
!= pcap_datalink(pd
)) {
1958 error("%s is not one of the DLTs supported by this device\n",
1962 (void)fprintf(stderr
, "%s: data link type %s\n",
1963 program_name
, yflag_dlt_name
);
1964 (void)fflush(stderr
);
1966 i
= pcap_snapshot(pd
);
1967 if (ndo
->ndo_snaplen
< i
) {
1968 if (ndo
->ndo_snaplen
!= 0)
1969 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1970 ndo
->ndo_snaplen
= i
;
1971 } else if (ndo
->ndo_snaplen
> i
) {
1972 warning("snaplen lowered from %d to %d", ndo
->ndo_snaplen
, i
);
1973 ndo
->ndo_snaplen
= i
;
1975 if(ndo
->ndo_fflag
!= 0) {
1976 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1977 warning("foreign (-f) flag used but: %s", ebuf
);
1983 cmdbuf
= read_infile(infile
);
1985 cmdbuf
= copy_argv(&argv
[optind
]);
1987 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1988 pcap_set_optimizer_debug(dflag
);
1990 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1991 error("%s", pcap_geterr(pd
));
1993 bpf_dump(&fcode
, dflag
);
1996 pcap_freecode(&fcode
);
2001 if (!ndo
->ndo_nflag
)
2002 capdns
= capdns_setup();
2003 #endif /* HAVE_CASPER */
2005 init_print(ndo
, localnet
, netmask
, timezone_offset
);
2008 (void)setsignal(SIGPIPE
, cleanup
);
2009 (void)setsignal(SIGTERM
, cleanup
);
2011 (void)setsignal(SIGINT
, cleanup
);
2012 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2013 (void)setsignal(SIGCHLD
, child_cleanup
);
2015 /* Cooperate with nohup(1) */
2017 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
2018 (void)setsignal(SIGHUP
, oldhandler
);
2023 * If a user name was specified with "-Z", attempt to switch to
2024 * that user's UID. This would probably be used with sudo,
2025 * to allow tcpdump to be run in a special restricted
2026 * account (if you just want to allow users to open capture
2027 * devices, and can't just give users that permission,
2028 * you'd make tcpdump set-UID or set-GID).
2030 * Tcpdump doesn't necessarily write only to one savefile;
2031 * the general only way to allow a -Z instance to write to
2032 * savefiles as the user under whose UID it's run, rather
2033 * than as the user specified with -Z, would thus be to switch
2034 * to the original user ID before opening a capture file and
2035 * then switch back to the -Z user ID after opening the savefile.
2036 * Switching to the -Z user ID only after opening the first
2037 * savefile doesn't handle the general case.
2040 if (getuid() == 0 || geteuid() == 0) {
2041 #ifdef HAVE_LIBCAP_NG
2042 /* Initialize capng */
2043 capng_clear(CAPNG_SELECT_BOTH
);
2045 DIAG_OFF_CLANG(assign
-enum)
2048 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2052 DIAG_ON_CLANG(assign
-enum)
2055 DIAG_OFF_CLANG(assign
-enum)
2058 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2061 DIAG_ON_CLANG(assign
-enum)
2065 DIAG_OFF_CLANG(assign
-enum)
2068 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
2071 DIAG_ON_CLANG(assign
-enum)
2073 capng_apply(CAPNG_SELECT_BOTH
);
2074 #endif /* HAVE_LIBCAP_NG */
2075 if (username
|| chroot_dir
)
2076 droproot(username
, chroot_dir
);
2081 if (pcap_setfilter(pd
, &fcode
) < 0)
2082 error("%s", pcap_geterr(pd
));
2083 #ifdef HAVE_CAPSICUM
2084 if (RFileName
== NULL
&& VFileName
== NULL
) {
2085 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
2088 * The various libpcap devices use a combination of
2089 * read (bpf), ioctl (bpf, netmap), poll (netmap)
2090 * so we add the relevant access rights.
2092 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
, CAP_EVENT
);
2093 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
2095 error("unable to limit pcap descriptor");
2097 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
2098 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
2099 error("unable to limit ioctls on pcap descriptor");
2105 /* Do not exceed the default PATH_MAX for files. */
2106 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2108 if (dumpinfo
.CurrentFileName
== NULL
)
2109 error("malloc of dumpinfo.CurrentFileName");
2111 /* We do not need numbering for dumpfiles if Cflag isn't set. */
2113 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
2115 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
2117 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
2118 #ifdef HAVE_LIBCAP_NG
2119 /* Give up CAP_DAC_OVERRIDE capability.
2120 * Only allow it to be restored if the -C or -G flag have been
2121 * set since we may need to create more files later on.
2125 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
2129 capng_apply(CAPNG_SELECT_BOTH
);
2130 #endif /* HAVE_LIBCAP_NG */
2132 error("%s", pcap_geterr(pd
));
2133 #ifdef HAVE_CAPSICUM
2134 set_dumper_capsicum_rights(p
);
2136 if (Cflag
!= 0 || Gflag
!= 0) {
2137 #ifdef HAVE_CAPSICUM
2138 dumpinfo
.WFileName
= strdup(basename(WFileName
));
2139 if (dumpinfo
.WFileName
== NULL
) {
2140 error("Unable to allocate memory for file %s",
2143 dumpinfo
.dirfd
= open(dirname(WFileName
),
2144 O_DIRECTORY
| O_RDONLY
);
2145 if (dumpinfo
.dirfd
< 0) {
2146 error("unable to open directory %s",
2147 dirname(WFileName
));
2149 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
2150 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
2151 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
2153 error("unable to limit directory rights");
2155 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
2157 error("unable to limit dump descriptor fcntls");
2159 #else /* !HAVE_CAPSICUM */
2160 dumpinfo
.WFileName
= WFileName
;
2162 callback
= dump_packet_and_trunc
;
2165 pcap_userdata
= (u_char
*)&dumpinfo
;
2167 callback
= dump_packet
;
2168 dumpinfo
.WFileName
= WFileName
;
2171 pcap_userdata
= (u_char
*)&dumpinfo
;
2174 dlt
= pcap_datalink(pd
);
2175 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2178 dumpinfo
.ndo
= NULL
;
2180 #ifdef HAVE_PCAP_DUMP_FLUSH
2185 dlt
= pcap_datalink(pd
);
2186 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2187 callback
= print_packet
;
2188 pcap_userdata
= (u_char
*)ndo
;
2191 #ifdef SIGNAL_REQ_INFO
2193 * We can't get statistics when reading from a file rather
2194 * than capturing from a device.
2196 if (RFileName
== NULL
)
2197 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
2200 if (ndo
->ndo_vflag
> 0 && WFileName
&& !print
) {
2202 * When capturing to a file, if "--print" wasn't specified,
2203 *"-v" means tcpdump should, once per second,
2204 * "v"erbosely report the number of packets captured.
2208 * call verbose_stats_dump() each 1000 +/-100msec
2210 * XXX - as of XP/Server 2003, this is deprecated in
2211 * favor of CreateTimerQueueTimer(). We should
2212 * probably use that, instead. (And
2214 * https://blogs.msdn.microsoft.com/oldnewthing/20151230-00/?p=92741
2216 * suggests that it dates back to W2K.)
2218 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
2219 setvbuf(stderr
, NULL
, _IONBF
, 0);
2222 * Assume this is UN*X, and that it has setitimer(); that
2223 * dates back to UNIX 95.
2225 struct itimerval timer
;
2226 (void)setsignal(SIGALRM
, verbose_stats_dump
);
2227 timer
.it_interval
.tv_sec
= 1;
2228 timer
.it_interval
.tv_usec
= 0;
2229 timer
.it_value
.tv_sec
= 1;
2230 timer
.it_value
.tv_usec
= 1;
2231 setitimer(ITIMER_REAL
, &timer
, NULL
);
2235 if (RFileName
== NULL
) {
2237 * Live capture (if -V was specified, we set RFileName
2238 * to a file from the -V file). Print a message to
2239 * the standard error on UN*X.
2241 if (!ndo
->ndo_vflag
&& !WFileName
) {
2242 (void)fprintf(stderr
,
2243 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2246 (void)fprintf(stderr
, "%s: ", program_name
);
2247 dlt
= pcap_datalink(pd
);
2248 dlt_name
= pcap_datalink_val_to_name(dlt
);
2249 if (dlt_name
== NULL
) {
2250 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
2251 device
, dlt
, ndo
->ndo_snaplen
);
2253 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2255 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
2257 (void)fflush(stderr
);
2260 #ifdef HAVE_CAPSICUM
2261 cansandbox
= (VFileName
== NULL
&& zflag
== NULL
);
2263 cansandbox
= (cansandbox
&& (ndo
->ndo_nflag
|| capdns
!= NULL
));
2265 cansandbox
= (cansandbox
&& ndo
->ndo_nflag
);
2266 #endif /* HAVE_CASPER */
2267 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
2268 error("unable to enter the capability mode");
2269 #endif /* HAVE_CAPSICUM */
2272 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
2273 if (WFileName
== NULL
) {
2275 * We're printing packets. Flush the printed output,
2276 * so it doesn't get intermingled with error output.
2280 * We got interrupted, so perhaps we didn't
2281 * manage to finish a line we were printing.
2282 * Print an extra newline, just in case.
2286 (void)fflush(stdout
);
2290 * We got interrupted. If we are reading multiple
2291 * files (via -V) set these so that we stop.
2300 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
2301 program_name
, pcap_geterr(pd
));
2303 if (RFileName
== NULL
) {
2305 * We're doing a live capture. Report the capture
2311 if (VFileName
!= NULL
) {
2312 ret
= get_next_file(VFile
, VFileLine
);
2316 RFileName
= VFileLine
;
2317 pd
= pcap_open_offline(RFileName
, ebuf
);
2320 #ifdef HAVE_CAPSICUM
2321 cap_rights_init(&rights
, CAP_READ
);
2322 if (cap_rights_limit(fileno(pcap_file(pd
)),
2323 &rights
) < 0 && errno
!= ENOSYS
) {
2324 error("unable to limit pcap descriptor");
2327 new_dlt
= pcap_datalink(pd
);
2328 if (new_dlt
!= dlt
) {
2330 * The new file has a different
2331 * link-layer header type from the
2334 if (WFileName
!= NULL
) {
2336 * We're writing raw packets
2337 * that match the filter to
2338 * a pcap file. pcap files
2339 * don't support multiple
2340 * different link-layer
2341 * header types, so we fail
2344 error("%s: new dlt does not match original", RFileName
);
2348 * We're printing the decoded packets;
2349 * switch to the new DLT.
2351 * To do that, we need to change
2352 * the printer, change the DLT name,
2353 * and recompile the filter with
2357 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
2358 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
2359 error("%s", pcap_geterr(pd
));
2363 * Set the filter on the new file.
2365 if (pcap_setfilter(pd
, &fcode
) < 0)
2366 error("%s", pcap_geterr(pd
));
2369 * Report the new file.
2371 dlt_name
= pcap_datalink_val_to_name(dlt
);
2372 if (dlt_name
== NULL
) {
2373 fprintf(stderr
, "reading from file %s, link-type %u\n",
2377 "reading from file %s, link-type %s (%s)\n",
2378 RFileName
, dlt_name
,
2379 pcap_datalink_val_to_description(dlt
));
2384 while (ret
!= NULL
);
2387 pcap_freecode(&fcode
);
2388 exit_tcpdump(status
== -1 ? 1 : 0);
2395 (*setsignal (int sig
, void (*func
)(int)))(int)
2398 return (signal(sig
, func
));
2400 struct sigaction old
, new;
2402 memset(&new, 0, sizeof(new));
2403 new.sa_handler
= func
;
2405 new.sa_flags
= SA_RESTART
;
2406 if (sigaction(sig
, &new, &old
) < 0)
2408 return (old
.sa_handler
);
2412 /* make a clean exit on interrupts */
2414 cleanup(int signo _U_
)
2418 timeKillEvent(timer_id
);
2421 struct itimerval timer
;
2423 timer
.it_interval
.tv_sec
= 0;
2424 timer
.it_interval
.tv_usec
= 0;
2425 timer
.it_value
.tv_sec
= 0;
2426 timer
.it_value
.tv_usec
= 0;
2427 setitimer(ITIMER_REAL
, &timer
, NULL
);
2430 #ifdef HAVE_PCAP_BREAKLOOP
2432 * We have "pcap_breakloop()"; use it, so that we do as little
2433 * as possible in the signal handler (it's probably not safe
2434 * to do anything with standard I/O streams in a signal handler -
2435 * the ANSI C standard doesn't say it is).
2440 * We don't have "pcap_breakloop()"; this isn't safe, but
2441 * it's the best we can do. Print the summary if we're
2442 * not reading from a savefile - i.e., if we're doing a
2443 * live capture - and exit.
2445 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2447 * We got interrupted, so perhaps we didn't
2448 * manage to finish a line we were printing.
2449 * Print an extra newline, just in case.
2452 (void)fflush(stdout
);
2460 On windows, we do not use a fork, so we do not care less about
2461 waiting a child processes to die
2463 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2465 child_cleanup(int signo _U_
)
2469 #endif /* HAVE_FORK && HAVE_VFORK */
2472 info(register int verbose
)
2474 struct pcap_stat stats
;
2477 * Older versions of libpcap didn't set ps_ifdrop on some
2478 * platforms; initialize it to 0 to handle that.
2480 stats
.ps_ifdrop
= 0;
2481 if (pcap_stats(pd
, &stats
) < 0) {
2482 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2488 fprintf(stderr
, "%s: ", program_name
);
2490 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2491 PLURAL_SUFFIX(packets_captured
));
2493 fputs(", ", stderr
);
2496 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2497 PLURAL_SUFFIX(stats
.ps_recv
));
2499 fputs(", ", stderr
);
2502 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2503 PLURAL_SUFFIX(stats
.ps_drop
));
2504 if (stats
.ps_ifdrop
!= 0) {
2506 fputs(", ", stderr
);
2509 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2510 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2516 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2518 #define fork_subprocess() fork()
2520 #define fork_subprocess() vfork()
2523 compress_savefile(const char *filename
)
2527 child
= fork_subprocess();
2530 "compress_savefile: fork failed: %s\n",
2531 pcap_strerror(errno
));
2535 /* Parent process. */
2541 * Set to lowest priority so that this doesn't disturb the capture.
2544 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2546 setpriority(PRIO_PROCESS
, 0, 19);
2548 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2550 "compress_savefile: execlp(%s, %s) failed: %s\n",
2553 pcap_strerror(errno
));
2560 #else /* HAVE_FORK && HAVE_VFORK */
2562 compress_savefile(const char *filename
)
2565 "compress_savefile failed. Functionality not implemented under your system\n");
2567 #endif /* HAVE_FORK && HAVE_VFORK */
2570 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2572 struct dump_info
*dump_info
;
2578 dump_info
= (struct dump_info
*)user
;
2581 * XXX - this won't force the file to rotate on the specified time
2582 * boundary, but it will rotate on the first packet received after the
2583 * specified Gflag number of seconds. Note: if a Gflag time boundary
2584 * and a Cflag size boundary coincide, the time rotation will occur
2585 * first thereby cancelling the Cflag boundary (since the file should
2589 /* Check if it is time to rotate */
2592 /* Get the current time */
2593 if ((t
= time(NULL
)) == (time_t)-1) {
2594 error("dump_and_trunc_packet: can't get current_time: %s",
2595 pcap_strerror(errno
));
2599 /* If the time is greater than the specified window, rotate */
2600 if (t
- Gflag_time
>= Gflag
) {
2601 #ifdef HAVE_CAPSICUM
2606 /* Update the Gflag_time */
2608 /* Update Gflag_count */
2611 * Close the current file and open a new one.
2613 pcap_dump_close(dump_info
->p
);
2616 * Compress the file we just closed, if the user asked for it
2619 compress_savefile(dump_info
->CurrentFileName
);
2622 * Check to see if we've exceeded the Wflag (when
2625 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2626 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2632 if (dump_info
->CurrentFileName
!= NULL
)
2633 free(dump_info
->CurrentFileName
);
2634 /* Allocate space for max filename + \0. */
2635 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2636 if (dump_info
->CurrentFileName
== NULL
)
2637 error("dump_packet_and_trunc: malloc");
2639 * Gflag was set otherwise we wouldn't be here. Reset the count
2640 * so multiple files would end with 1,2,3 in the filename.
2641 * The counting is handled with the -C flow after this.
2646 * This is always the first file in the Cflag
2648 * We also don't need numbering if Cflag is not set.
2651 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2654 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2656 #ifdef HAVE_LIBCAP_NG
2657 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2658 capng_apply(CAPNG_SELECT_BOTH
);
2659 #endif /* HAVE_LIBCAP_NG */
2660 #ifdef HAVE_CAPSICUM
2661 fd
= openat(dump_info
->dirfd
,
2662 dump_info
->CurrentFileName
,
2663 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2665 error("unable to open file %s",
2666 dump_info
->CurrentFileName
);
2668 fp
= fdopen(fd
, "w");
2670 error("unable to fdopen file %s",
2671 dump_info
->CurrentFileName
);
2673 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2674 #else /* !HAVE_CAPSICUM */
2675 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2677 #ifdef HAVE_LIBCAP_NG
2678 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2679 capng_apply(CAPNG_SELECT_BOTH
);
2680 #endif /* HAVE_LIBCAP_NG */
2681 if (dump_info
->p
== NULL
)
2682 error("%s", pcap_geterr(pd
));
2683 #ifdef HAVE_CAPSICUM
2684 set_dumper_capsicum_rights(dump_info
->p
);
2690 * XXX - this won't prevent capture files from getting
2691 * larger than Cflag - the last packet written to the
2692 * file could put it over Cflag.
2695 #ifdef HAVE_PCAP_DUMP_FTELL64
2696 int64_t size
= pcap_dump_ftell64(dump_info
->p
);
2699 * XXX - this only handles a Cflag value > 2^31-1 on
2700 * LP64 platforms; to handle ILP32 (32-bit UN*X and
2701 * Windows) or LLP64 (64-bit Windows) would require
2702 * a version of libpcap with pcap_dump_ftell64().
2704 long size
= pcap_dump_ftell(dump_info
->p
);
2708 error("ftell fails on output file");
2710 #ifdef HAVE_CAPSICUM
2716 * Close the current file and open a new one.
2718 pcap_dump_close(dump_info
->p
);
2721 * Compress the file we just closed, if the user
2725 compress_savefile(dump_info
->CurrentFileName
);
2729 if (Cflag_count
>= Wflag
)
2732 if (dump_info
->CurrentFileName
!= NULL
)
2733 free(dump_info
->CurrentFileName
);
2734 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2735 if (dump_info
->CurrentFileName
== NULL
)
2736 error("dump_packet_and_trunc: malloc");
2737 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2738 #ifdef HAVE_LIBCAP_NG
2739 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2740 capng_apply(CAPNG_SELECT_BOTH
);
2741 #endif /* HAVE_LIBCAP_NG */
2742 #ifdef HAVE_CAPSICUM
2743 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2744 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2746 error("unable to open file %s",
2747 dump_info
->CurrentFileName
);
2749 fp
= fdopen(fd
, "w");
2751 error("unable to fdopen file %s",
2752 dump_info
->CurrentFileName
);
2754 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2755 #else /* !HAVE_CAPSICUM */
2756 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2758 #ifdef HAVE_LIBCAP_NG
2759 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2760 capng_apply(CAPNG_SELECT_BOTH
);
2761 #endif /* HAVE_LIBCAP_NG */
2762 if (dump_info
->p
== NULL
)
2763 error("%s", pcap_geterr(pd
));
2764 #ifdef HAVE_CAPSICUM
2765 set_dumper_capsicum_rights(dump_info
->p
);
2770 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2771 #ifdef HAVE_PCAP_DUMP_FLUSH
2773 pcap_dump_flush(dump_info
->p
);
2776 if (dump_info
->ndo
!= NULL
)
2777 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2785 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2787 struct dump_info
*dump_info
;
2793 dump_info
= (struct dump_info
*)user
;
2795 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2796 #ifdef HAVE_PCAP_DUMP_FLUSH
2798 pcap_dump_flush(dump_info
->p
);
2801 if (dump_info
->ndo
!= NULL
)
2802 pretty_print_packet(dump_info
->ndo
, h
, sp
, packets_captured
);
2810 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2816 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2823 #ifdef SIGNAL_REQ_INFO
2824 void requestinfo(int signo _U_
)
2834 print_packets_captured (void)
2836 static u_int prev_packets_captured
, first
= 1;
2838 if (infodelay
== 0 && (first
|| packets_captured
!= prev_packets_captured
)) {
2839 fprintf(stderr
, "Got %u\r", packets_captured
);
2841 prev_packets_captured
= packets_captured
;
2846 * Called once each second in verbose mode while dumping to file
2849 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2850 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2852 print_packets_captured();
2855 static void verbose_stats_dump(int sig _U_
)
2857 print_packets_captured();
2861 USES_APPLE_DEPRECATED_API
2865 #ifndef HAVE_PCAP_LIB_VERSION
2866 #ifdef HAVE_PCAP_VERSION
2867 extern char pcap_version
[];
2868 #else /* HAVE_PCAP_VERSION */
2869 static char pcap_version
[] = "unknown";
2870 #endif /* HAVE_PCAP_VERSION */
2871 #endif /* HAVE_PCAP_LIB_VERSION */
2872 const char *smi_version_string
;
2874 (void)fprintf(stderr
, "%s version " PACKAGE_VERSION
"\n", program_name
);
2875 #ifdef HAVE_PCAP_LIB_VERSION
2876 (void)fprintf(stderr
, "%s\n", pcap_lib_version());
2877 #else /* HAVE_PCAP_LIB_VERSION */
2878 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2879 #endif /* HAVE_PCAP_LIB_VERSION */
2881 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2882 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2885 smi_version_string
= nd_smi_version_string();
2886 if (smi_version_string
!= NULL
)
2887 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2888 #ifdef HAVE_DNET_HTOA
2889 (void)fprintf(stderr
, "libdnet unknown version\n");
2892 #if defined(__SANITIZE_ADDRESS__)
2893 (void)fprintf (stderr
, "Compiled with AddressSanitizer/GCC.\n");
2894 #elif defined(__has_feature)
2895 # if __has_feature(address_sanitizer)
2896 (void)fprintf (stderr
, "Compiled with AddressSanitizer/CLang.\n");
2898 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2906 (void)fprintf(stderr
,
2907 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2908 (void)fprintf(stderr
,
2909 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2910 (void)fprintf(stderr
,
2911 "\t\t[ -i interface ]" IMMEDIATE_MODE_USAGE j_FLAG_USAGE
"\n");
2912 #ifdef HAVE_PCAP_FINDALLDEVS_EX
2913 (void)fprintf(stderr
,
2914 "\t\t" LIST_REMOTE_INTERFACES_USAGE
"\n");
2916 (void)fprintf(stderr
,
2917 "\t\t[ -M secret ] [ --number ] [ --print ]" Q_FLAG_USAGE
"\n");
2918 (void)fprintf(stderr
,
2919 "\t\t[ -r file ] [ -s snaplen ]" TIME_STAMP_PRECISION_USAGE
"\n");
2920 (void)fprintf(stderr
,
2921 "\t\t[ -T type ] [ --version ] [ -V file ] [ -w file ]\n");
2922 (void)fprintf(stderr
,
2923 "\t\t[ -W filecount ] [ -y datalinktype ]\n");
2924 (void)fprintf(stderr
,
2925 "\t\t[ -z postrotate-command ] [ -Z user ] [ expression ]\n");
2929 * c-style: whitesmith