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 * Mac OS X may ship pcap.h from libpcap 0.6 with a libpcap based on
48 * 0.8. That means it has pcap_findalldevs() but the header doesn't
49 * define pcap_if_t, meaning that we can't actually *use* pcap_findalldevs().
51 #ifdef HAVE_PCAP_FINDALLDEVS
52 #ifndef HAVE_PCAP_IF_T
53 #undef HAVE_PCAP_FINDALLDEVS
57 #include <netdissect-stdinc.h>
70 #include <openssl/crypto.h>
73 #ifdef HAVE_GETOPT_LONG
76 #include "getopt_long.h"
78 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
79 * to compile if <pcap.h> has already been included; including the headers
80 * in the opposite order works fine.
83 #include <sys/capability.h>
84 #include <sys/ioccom.h>
87 #endif /* HAVE_CAPSICUM */
97 #include <sys/resource.h>
102 /* capabilities convenience library */
103 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
104 * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
105 * Thus, the later tests are done only on HAVE_LIBCAP_NG.
107 #ifdef HAVE_LIBCAP_NG
111 #undef HAVE_LIBCAP_NG
112 #endif /* HAVE_CAP_NG_H */
113 #endif /* HAVE_LIBCAP_NG */
115 #include "netdissect.h"
116 #include "interface.h"
117 #include "addrtoname.h"
119 #include "setsignal.h"
120 #include "gmt2local.h"
121 #include "pcap-missing.h"
122 #include "ascii_strcasecmp.h"
127 #define PATH_MAX 1024
131 #define SIGNAL_REQ_INFO SIGINFO
133 #define SIGNAL_REQ_INFO SIGUSR1
136 static int Cflag
; /* rotate dump files after this many bytes */
137 static int Cflag_count
; /* Keep track of which file number we're writing */
138 static int Dflag
; /* list available devices and exit */
140 * This is exported because, in some versions of libpcap, if libpcap
141 * is built with optimizer debugging code (which is *NOT* the default
142 * configuration!), the library *imports*(!) a variable named dflag,
143 * under the expectation that tcpdump is exporting it, to govern
144 * how much debugging information to print when optimizing
145 * the generated BPF code.
147 * This is a horrible hack; newer versions of libpcap don't import
148 * dflag but, instead, *if* built with optimizer debugging code,
149 * *export* a routine to set that flag.
151 int dflag
; /* print filter code */
152 static int Gflag
; /* rotate dump files after this many seconds */
153 static int Gflag_count
; /* number of files created with Gflag rotation */
154 static time_t Gflag_time
; /* The last time_t the dump file was rotated. */
155 static int Lflag
; /* list available data link types and exit */
156 static int Iflag
; /* rfmon (monitor) mode */
157 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
158 static int Jflag
; /* list available time stamp types */
160 #ifdef HAVE_PCAP_SETDIRECTION
161 int Qflag
= -1; /* restrict captured packet by send/receive direction */
163 static int Uflag
; /* "unbuffered" output of dump files */
164 static int Wflag
; /* recycle output files after this number of files */
165 static int WflagChars
;
166 static char *zflag
= NULL
; /* compress each savefile using a specified command (like gzip or bzip2) */
168 static int infodelay
;
169 static int infoprint
;
174 static void error(const char *, ...)
175 __attribute__((noreturn
))
176 #ifdef __ATTRIBUTE___FORMAT_OK
177 __attribute__((format (printf
, 1, 2)))
178 #endif /* __ATTRIBUTE___FORMAT_OK */
180 static void warning(const char *, ...)
181 #ifdef __ATTRIBUTE___FORMAT_OK
182 __attribute__((format (printf
, 1, 2)))
183 #endif /* __ATTRIBUTE___FORMAT_OK */
185 static void exit_tcpdump(int) __attribute__((noreturn
));
186 static RETSIGTYPE
cleanup(int);
187 static RETSIGTYPE
child_cleanup(int);
188 static void print_version(void);
189 static void print_usage(void);
190 static void show_tstamp_types_and_exit(const char *device
) __attribute__((noreturn
));
191 static void show_dlts_and_exit(const char *device
) __attribute__((noreturn
));
193 static void print_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
194 static void dump_packet_and_trunc(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
195 static void dump_packet(u_char
*, const struct pcap_pkthdr
*, const u_char
*);
196 static void droproot(const char *, const char *);
198 #ifdef SIGNAL_REQ_INFO
199 RETSIGTYPE
requestinfo(int);
202 #if defined(USE_WIN32_MM_TIMER)
203 #include <MMsystem.h>
204 static UINT timer_id
;
205 static void CALLBACK
verbose_stats_dump(UINT
, UINT
, DWORD_PTR
, DWORD_PTR
, DWORD_PTR
);
206 #elif defined(HAVE_ALARM)
207 static void verbose_stats_dump(int sig
);
210 static void info(int);
211 static u_int packets_captured
;
213 static const struct tok status_flags
[] = {
215 { PCAP_IF_UP
, "Up" },
217 #ifdef PCAP_IF_RUNNING
218 { PCAP_IF_RUNNING
, "Running" },
220 { PCAP_IF_LOOPBACK
, "Loopback" },
226 static int supports_monitor_mode
;
234 char *CurrentFileName
;
242 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
244 * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
245 * by any libpcap header, because it's a special hack, only available if
246 * libpcap was configured to include it, and only intended for use by
247 * libpcap developers trying to debug the parser for filter expressions).
250 __declspec(dllimport
)
254 void pcap_set_parser_debug(int);
255 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
257 * We don't have pcap_set_parser_debug() in libpcap, but we do have
258 * pcap_debug or yydebug. Make a local version of pcap_set_parser_debug()
259 * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
262 pcap_set_parser_debug(int value
)
264 #ifdef HAVE_PCAP_DEBUG
265 extern int pcap_debug
;
268 #else /* HAVE_PCAP_DEBUG */
272 #endif /* HAVE_PCAP_DEBUG */
275 #define HAVE_PCAP_SET_PARSER_DEBUG
278 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
280 * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
281 * by any libpcap header, because it's a special hack, only available if
282 * libpcap was configured to include it, and only intended for use by
283 * libpcap developers trying to debug the optimizer for filter expressions).
286 __declspec(dllimport
)
290 void pcap_set_optimizer_debug(int);
295 error(const char *fmt
, ...)
299 (void)fprintf(stderr
, "%s: ", program_name
);
301 (void)vfprintf(stderr
, fmt
, ap
);
306 (void)fputc('\n', stderr
);
314 warning(const char *fmt
, ...)
318 (void)fprintf(stderr
, "%s: WARNING: ", program_name
);
320 (void)vfprintf(stderr
, fmt
, ap
);
325 (void)fputc('\n', stderr
);
330 exit_tcpdump(int status
)
336 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
338 show_tstamp_types_and_exit(const char *device
)
341 int *tstamp_types
= 0;
342 const char *tstamp_type_name
;
345 n_tstamp_types
= pcap_list_tstamp_types(pd
, &tstamp_types
);
346 if (n_tstamp_types
< 0)
347 error("%s", pcap_geterr(pd
));
349 if (n_tstamp_types
== 0) {
350 fprintf(stderr
, "Time stamp type cannot be set for %s\n",
354 fprintf(stderr
, "Time stamp types for %s (use option -j to set):\n",
356 for (i
= 0; i
< n_tstamp_types
; i
++) {
357 tstamp_type_name
= pcap_tstamp_type_val_to_name(tstamp_types
[i
]);
358 if (tstamp_type_name
!= NULL
) {
359 (void) fprintf(stderr
, " %s (%s)\n", tstamp_type_name
,
360 pcap_tstamp_type_val_to_description(tstamp_types
[i
]));
362 (void) fprintf(stderr
, " %d\n", tstamp_types
[i
]);
365 pcap_free_tstamp_types(tstamp_types
);
371 show_dlts_and_exit(const char *device
)
375 const char *dlt_name
;
377 n_dlts
= pcap_list_datalinks(pd
, &dlts
);
379 error("%s", pcap_geterr(pd
));
380 else if (n_dlts
== 0 || !dlts
)
381 error("No data link types.");
384 * If the interface is known to support monitor mode, indicate
385 * whether these are the data link types available when not in
386 * monitor mode, if -I wasn't specified, or when in monitor mode,
387 * when -I was specified (the link-layer types available in
388 * monitor mode might be different from the ones available when
389 * not in monitor mode).
391 if (supports_monitor_mode
)
392 (void) fprintf(stderr
, "Data link types for %s %s (use option -y to set):\n",
394 Iflag
? "when in monitor mode" : "when not in monitor mode");
396 (void) fprintf(stderr
, "Data link types for %s (use option -y to set):\n",
399 for (i
= 0; i
< n_dlts
; i
++) {
400 dlt_name
= pcap_datalink_val_to_name(dlts
[i
]);
401 if (dlt_name
!= NULL
) {
402 (void) fprintf(stderr
, " %s (%s)", dlt_name
,
403 pcap_datalink_val_to_description(dlts
[i
]));
406 * OK, does tcpdump handle that type?
408 if (!has_printer(dlts
[i
]))
409 (void) fprintf(stderr
, " (printing not supported)");
410 fprintf(stderr
, "\n");
412 (void) fprintf(stderr
, " DLT %d (printing not supported)\n",
416 #ifdef HAVE_PCAP_FREE_DATALINKS
417 pcap_free_datalinks(dlts
);
422 #ifdef HAVE_PCAP_FINDALLDEVS
424 show_devices_and_exit (void)
426 pcap_if_t
*dev
, *devlist
;
427 char ebuf
[PCAP_ERRBUF_SIZE
];
430 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
432 for (i
= 0, dev
= devlist
; dev
!= NULL
; i
++, dev
= dev
->next
) {
433 printf("%d.%s", i
+1, dev
->name
);
434 if (dev
->description
!= NULL
)
435 printf(" (%s)", dev
->description
);
437 printf(" [%s]", bittok2str(status_flags
, "none", dev
->flags
));
440 pcap_freealldevs(devlist
);
443 #endif /* HAVE_PCAP_FINDALLDEVS */
448 * Note that there we use all letters for short options except for g, k,
449 * o, and P, and those are used by other versions of tcpdump, and we should
450 * only use them for the same purposes that the other versions of tcpdump
453 * OS X tcpdump uses -g to force non--v output for IP to be on one
454 * line, making it more "g"repable;
456 * OS X tcpdump uses -k tospecify that packet comments in pcap-ng files
459 * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
460 * for hosts sending TCP SYN packets;
462 * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
465 * OS X tcpdump also uses -Q to specify expressions that match packet
466 * metadata, including but not limited to the packet direction.
467 * The expression syntax is different from a simple "in|out|inout",
468 * and those expressions aren't accepted by OS X tcpdump, but the
469 * equivalents would be "in" = "dir=in", "out" = "dir=out", and
470 * "inout" = "dir=in or dir=out", and the parser could conceivably
471 * special-case "in", "out", and "inout" as expressions for backwards
472 * compatibility, so all is not (yet) lost.
476 * Set up flags that might or might not be supported depending on the
477 * version of libpcap we're using.
479 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
481 #define B_FLAG_USAGE " [ -B size ]"
482 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
485 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
487 #ifdef HAVE_PCAP_CREATE
489 #else /* HAVE_PCAP_CREATE */
491 #endif /* HAVE_PCAP_CREATE */
493 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
495 #define j_FLAG_USAGE " [ -j tstamptype ]"
497 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
501 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
503 #ifdef HAVE_PCAP_FINDALLDEVS
509 #ifdef HAVE_PCAP_DUMP_FLUSH
515 #ifdef HAVE_PCAP_SETDIRECTION
521 #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:#"
526 * We do not currently have long options corresponding to all short
527 * options; we should probably pick appropriate option names for them.
529 * However, the short options where the number of times the option is
530 * specified matters, such as -v and -d and -t, should probably not
531 * just map to a long option, as saying
533 * tcpdump --verbose --verbose
535 * doesn't make sense; it should be --verbosity={N} or something such
538 * For long options with no corresponding short options, we define values
539 * outside the range of ASCII graphic characters, make that the last
540 * component of the entry for the long option, and have a case for that
541 * option in the switch statement.
543 #define OPTION_VERSION 128
544 #define OPTION_TSTAMP_PRECISION 129
545 #define OPTION_IMMEDIATE_MODE 130
547 static const struct option longopts
[] = {
548 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
549 { "buffer-size", required_argument
, NULL
, 'B' },
551 { "list-interfaces", no_argument
, NULL
, 'D' },
552 { "help", no_argument
, NULL
, 'h' },
553 { "interface", required_argument
, NULL
, 'i' },
554 #ifdef HAVE_PCAP_CREATE
555 { "monitor-mode", no_argument
, NULL
, 'I' },
557 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
558 { "time-stamp-type", required_argument
, NULL
, 'j' },
559 { "list-time-stamp-types", no_argument
, NULL
, 'J' },
561 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
562 { "time-stamp-precision", required_argument
, NULL
, OPTION_TSTAMP_PRECISION
},
564 { "dont-verify-checksums", no_argument
, NULL
, 'K' },
565 { "list-data-link-types", no_argument
, NULL
, 'L' },
566 { "no-optimize", no_argument
, NULL
, 'O' },
567 { "no-promiscuous-mode", no_argument
, NULL
, 'p' },
568 #ifdef HAVE_PCAP_SETDIRECTION
569 { "direction", required_argument
, NULL
, 'Q' },
571 { "snapshot-length", required_argument
, NULL
, 's' },
572 { "absolute-tcp-sequence-numbers", no_argument
, NULL
, 'S' },
573 #ifdef HAVE_PCAP_DUMP_FLUSH
574 { "packet-buffered", no_argument
, NULL
, 'U' },
576 { "linktype", required_argument
, NULL
, 'y' },
577 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
578 { "immediate-mode", no_argument
, NULL
, OPTION_IMMEDIATE_MODE
},
580 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
581 { "debug-filter-parser", no_argument
, NULL
, 'Y' },
583 { "relinquish-privileges", required_argument
, NULL
, 'Z' },
584 { "number", no_argument
, NULL
, '#' },
585 { "version", no_argument
, NULL
, OPTION_VERSION
},
590 /* Drop root privileges and chroot if necessary */
592 droproot(const char *username
, const char *chroot_dir
)
594 struct passwd
*pw
= NULL
;
596 if (chroot_dir
&& !username
) {
597 fprintf(stderr
, "%s: Chroot without dropping root is insecure\n",
602 pw
= getpwnam(username
);
605 if (chroot(chroot_dir
) != 0 || chdir ("/") != 0) {
606 fprintf(stderr
, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
607 program_name
, chroot_dir
, pcap_strerror(errno
));
611 #ifdef HAVE_LIBCAP_NG
613 int ret
= capng_change_id(pw
->pw_uid
, pw
->pw_gid
, CAPNG_NO_FLAG
);
615 fprintf(stderr
, "error : ret %d\n", ret
);
617 fprintf(stderr
, "dropped privs to %s\n", username
);
621 if (initgroups(pw
->pw_name
, pw
->pw_gid
) != 0 ||
622 setgid(pw
->pw_gid
) != 0 || setuid(pw
->pw_uid
) != 0) {
623 fprintf(stderr
, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
624 program_name
, username
,
625 (unsigned long)pw
->pw_uid
,
626 (unsigned long)pw
->pw_gid
,
627 pcap_strerror(errno
));
631 fprintf(stderr
, "dropped privs to %s\n", username
);
633 #endif /* HAVE_LIBCAP_NG */
636 fprintf(stderr
, "%s: Couldn't find user '%.32s'\n",
637 program_name
, username
);
640 #ifdef HAVE_LIBCAP_NG
641 /* We don't need CAP_SETUID and CAP_SETGID any more. */
644 CAPNG_EFFECTIVE
| CAPNG_PERMITTED
,
648 capng_apply(CAPNG_SELECT_BOTH
);
649 #endif /* HAVE_LIBCAP_NG */
670 MakeFilename(char *buffer
, char *orig_name
, int cnt
, int max_chars
)
672 char *filename
= malloc(PATH_MAX
+ 1);
673 if (filename
== NULL
)
674 error("Makefilename: malloc");
676 /* Process with strftime if Gflag is set. */
680 /* Convert Gflag_time to a usable format */
681 if ((local_tm
= localtime(&Gflag_time
)) == NULL
) {
682 error("MakeTimedFilename: localtime");
685 /* There's no good way to detect an error in strftime since a return
686 * value of 0 isn't necessarily failure.
688 strftime(filename
, PATH_MAX
, orig_name
, local_tm
);
690 strncpy(filename
, orig_name
, PATH_MAX
);
693 if (cnt
== 0 && max_chars
== 0)
694 strncpy(buffer
, filename
, PATH_MAX
+ 1);
696 if (snprintf(buffer
, PATH_MAX
+ 1, "%s%0*d", filename
, max_chars
, cnt
) > PATH_MAX
)
697 /* Report an error if the filename is too large */
698 error("too many output files or filename is too long (> %d)", PATH_MAX
);
703 get_next_file(FILE *VFile
, char *ptr
)
707 ret
= fgets(ptr
, PATH_MAX
, VFile
);
711 if (ptr
[strlen(ptr
) - 1] == '\n')
712 ptr
[strlen(ptr
) - 1] = '\0';
717 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
719 tstamp_precision_from_string(const char *precision
)
721 if (strncmp(precision
, "nano", strlen("nano")) == 0)
722 return PCAP_TSTAMP_PRECISION_NANO
;
724 if (strncmp(precision
, "micro", strlen("micro")) == 0)
725 return PCAP_TSTAMP_PRECISION_MICRO
;
731 tstamp_precision_to_string(int precision
)
735 case PCAP_TSTAMP_PRECISION_MICRO
:
738 case PCAP_TSTAMP_PRECISION_NANO
:
749 * Ensure that, on a dump file's descriptor, we have all the rights
750 * necessary to make the standard I/O library work with an fdopen()ed
751 * FILE * from that descriptor.
753 * A long time ago, in a galaxy far far away, AT&T decided that, instead
754 * of providing separate APIs for getting and setting the FD_ flags on a
755 * descriptor, getting and setting the O_ flags on a descriptor, and
756 * locking files, they'd throw them all into a kitchen-sink fcntl() call
757 * along the lines of ioctl(), the fact that ioctl() operations are
758 * largely specific to particular character devices but fcntl() operations
759 * are either generic to all descriptors or generic to all descriptors for
760 * regular files nonwithstanding.
762 * The Capsicum people decided that fine-grained control of descriptor
763 * operations was required, so that you need to grant permission for
764 * reading, writing, seeking, and fcntl-ing. The latter, courtesy of
765 * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
766 * collection of things, so there are *individual* fcntls for which
767 * permission needs to be granted.
769 * The FreeBSD standard I/O people implemented some optimizations that
770 * requires that the standard I/O routines be able to determine whether
771 * the descriptor for the FILE * is open append-only or not; as that
772 * descriptor could have come from an open() rather than an fopen(),
773 * that requires that it be able to do an F_GETFL fcntl() to read
776 * Tcpdump uses ftell() to determine how much data has been written
777 * to a file in order to, when used with -C, determine when it's time
778 * to rotate capture files. ftell() therefore needs to do an lseek()
779 * to find out the file offset and must, thanks to the aforementioned
780 * optimization, also know whether the descriptor is open append-only
783 * The net result of all the above is that we need to grant CAP_SEEK,
784 * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
786 * Perhaps this is the universe's way of saying that either
788 * 1) there needs to be an fopenat() call and a pcap_dump_openat() call
789 * using it, so that Capsicum-capable tcpdump wouldn't need to do
794 * 2) there needs to be a cap_fdopen() call in the FreeBSD standard
795 * I/O library that knows what rights are needed by the standard
796 * I/O library, based on the open mode, and assigns them, perhaps
797 * with an additional argument indicating, for example, whether
798 * seeking should be allowed, so that tcpdump doesn't need to know
799 * what the standard I/O library happens to require this week.
802 set_dumper_capsicum_rights(pcap_dumper_t
*p
)
804 int fd
= fileno(pcap_dump_file(p
));
807 cap_rights_init(&rights
, CAP_SEEK
, CAP_WRITE
, CAP_FCNTL
);
808 if (cap_rights_limit(fd
, &rights
) < 0 && errno
!= ENOSYS
) {
809 error("unable to limit dump descriptor");
811 if (cap_fcntls_limit(fd
, CAP_FCNTL_GETFL
) < 0 && errno
!= ENOSYS
) {
812 error("unable to limit dump descriptor fcntls");
818 * Copy arg vector into a new buffer, concatenating arguments with spaces.
821 copy_argv(register char **argv
)
824 register u_int len
= 0;
833 len
+= strlen(*p
++) + 1;
835 buf
= (char *)malloc(len
);
837 error("copy_argv: malloc");
841 while ((src
= *p
++) != NULL
) {
842 while ((*dst
++ = *src
++) != '\0')
852 * On Windows, we need to open the file in binary mode, so that
853 * we get all the bytes specified by the size we get from "fstat()".
854 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
855 * we define it as 0 if it's not defined, so it does nothing.
862 read_infile(char *fname
)
864 register int i
, fd
, cc
;
868 fd
= open(fname
, O_RDONLY
|O_BINARY
);
870 error("can't open %s: %s", fname
, pcap_strerror(errno
));
872 if (fstat(fd
, &buf
) < 0)
873 error("can't stat %s: %s", fname
, pcap_strerror(errno
));
875 cp
= malloc((u_int
)buf
.st_size
+ 1);
877 error("malloc(%d) for %s: %s", (u_int
)buf
.st_size
+ 1,
878 fname
, pcap_strerror(errno
));
879 cc
= read(fd
, cp
, (u_int
)buf
.st_size
);
881 error("read %s: %s", fname
, pcap_strerror(errno
));
882 if (cc
!= buf
.st_size
)
883 error("short read %s (%d != %d)", fname
, cc
, (int)buf
.st_size
);
886 /* replace "# comment" with spaces */
887 for (i
= 0; i
< cc
; i
++) {
889 while (i
< cc
&& cp
[i
] != '\n')
897 main(int argc
, char **argv
)
899 register int cnt
, op
, i
;
900 bpf_u_int32 localnet
=0 , netmask
= 0;
901 int timezone_offset
= 0;
902 register char *cp
, *infile
, *cmdbuf
, *device
, *RFileName
, *VFileName
, *WFileName
;
903 pcap_handler callback
;
905 const char *dlt_name
;
906 struct bpf_program fcode
;
908 RETSIGTYPE (*oldhandler
)(int);
910 struct dump_info dumpinfo
;
911 u_char
*pcap_userdata
;
912 char ebuf
[PCAP_ERRBUF_SIZE
];
913 char VFileLine
[PATH_MAX
+ 1];
914 char *username
= NULL
;
915 char *chroot_dir
= NULL
;
918 #ifdef HAVE_PCAP_FINDALLDEVS
919 pcap_if_t
*dev
, *devlist
;
927 #endif /* HAVE_CAPSICUM */
928 int Bflag
= 0; /* buffer size */
929 int jflag
= -1; /* packet time stamp source */
930 int Oflag
= 1; /* run filter code optimizer */
931 int pflag
= 0; /* don't go promiscuous */
933 const char *yflag_dlt_name
= NULL
;
935 netdissect_options Ndo
;
936 netdissect_options
*ndo
= &Ndo
;
937 int immediate_mode
= 0;
940 * Initialize the netdissect code.
942 if (nd_init(ebuf
, sizeof ebuf
) == -1)
945 memset(ndo
, 0, sizeof(*ndo
));
946 ndo_set_function_pointers(ndo
);
947 ndo
->ndo_snaplen
= DEFAULT_SNAPLEN
;
957 if ((cp
= strrchr(argv
[0], '/')) != NULL
)
958 ndo
->program_name
= program_name
= cp
+ 1;
960 ndo
->program_name
= program_name
= argv
[0];
963 if (pcap_wsockinit() != 0)
964 error("Attempting to initialize Winsock failed");
968 * On platforms where the CPU doesn't support unaligned loads,
969 * force unaligned accesses to abort with SIGBUS, rather than
970 * being fixed up (slowly) by the OS kernel; on those platforms,
971 * misaligned accesses are bugs, and we want tcpdump to crash so
972 * that the bugs are reported.
974 if (abort_on_misalignment(ebuf
, sizeof(ebuf
)) < 0)
978 (op
= getopt_long(argc
, argv
, SHORTOPTS
, longopts
, NULL
)) != -1)
982 /* compatibility for old -a */
993 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
995 Bflag
= atoi(optarg
)*1024;
997 error("invalid packet buffer size %s", optarg
);
999 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1004 error("invalid packet count %s", optarg
);
1008 Cflag
= atoi(optarg
) * 1000000;
1010 error("invalid file size %s", optarg
);
1030 #ifndef HAVE_LIBCRYPTO
1031 warning("crypto code not compiled in");
1033 ndo
->ndo_espsecret
= optarg
;
1045 Gflag
= atoi(optarg
);
1047 error("invalid number of seconds %s", optarg
);
1049 /* We will create one file initially. */
1052 /* Grab the current time for rotation use. */
1053 if ((Gflag_time
= time(NULL
)) == (time_t)-1) {
1054 error("main: can't get current time: %s",
1055 pcap_strerror(errno
));
1069 if (optarg
[0] == '0' && optarg
[1] == 0)
1070 error("Invalid adapter index");
1072 #ifdef HAVE_PCAP_FINDALLDEVS
1074 * If the argument is a number, treat it as
1075 * an index into the list of adapters, as
1076 * printed by "tcpdump -D".
1078 * This should be OK on UNIX systems, as interfaces
1079 * shouldn't have names that begin with digits.
1080 * It can be useful on Windows, where more than
1081 * one interface can have the same name.
1083 devnum
= strtol(optarg
, &end
, 10);
1084 if (optarg
!= end
&& *end
== '\0') {
1086 error("Invalid adapter index");
1088 if (pcap_findalldevs(&devlist
, ebuf
) < 0)
1091 * Look for the devnum-th entry in the
1092 * list of devices (1-based).
1094 for (i
= 0, dev
= devlist
;
1095 i
< devnum
-1 && dev
!= NULL
;
1096 i
++, dev
= dev
->next
)
1099 error("Invalid adapter index");
1100 device
= strdup(dev
->name
);
1101 pcap_freealldevs(devlist
);
1104 #endif /* HAVE_PCAP_FINDALLDEVS */
1108 #ifdef HAVE_PCAP_CREATE
1112 #endif /* HAVE_PCAP_CREATE */
1114 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1116 jflag
= pcap_tstamp_type_name_to_val(optarg
);
1118 error("invalid time stamp type %s", optarg
);
1129 * _IOLBF is the same as _IOFBF in Microsoft's C
1130 * libraries; the only alternative they offer
1133 * XXX - this should really be checking for MSVC++,
1134 * not _WIN32, if, for example, MinGW has its own
1135 * C library that is more UNIX-compatible.
1137 setvbuf(stdout
, NULL
, _IONBF
, 0);
1139 #ifdef HAVE_SETLINEBUF
1142 setvbuf(stdout
, NULL
, _IOLBF
, 0);
1153 if (smiLoadModule(optarg
) == 0) {
1154 error("could not load MIB module %s", optarg
);
1158 (void)fprintf(stderr
, "%s: ignoring option `-m %s' ",
1159 program_name
, optarg
);
1160 (void)fprintf(stderr
, "(no libsmi support)\n");
1165 /* TCP-MD5 shared secret */
1166 #ifndef HAVE_LIBCRYPTO
1167 warning("crypto code not compiled in");
1169 ndo
->ndo_sigsecret
= optarg
;
1190 ++ndo
->ndo_suppress_default_print
;
1193 #ifdef HAVE_PCAP_SETDIRECTION
1195 if (ascii_strcasecmp(optarg
, "in") == 0)
1197 else if (ascii_strcasecmp(optarg
, "out") == 0)
1199 else if (ascii_strcasecmp(optarg
, "inout") == 0)
1200 Qflag
= PCAP_D_INOUT
;
1202 error("unknown capture direction `%s'", optarg
);
1204 #endif /* HAVE_PCAP_SETDIRECTION */
1211 ndo
->ndo_snaplen
= strtol(optarg
, &end
, 0);
1212 if (optarg
== end
|| *end
!= '\0'
1213 || ndo
->ndo_snaplen
< 0 || ndo
->ndo_snaplen
> MAXIMUM_SNAPLEN
)
1214 error("invalid snaplen %s", optarg
);
1215 else if (ndo
->ndo_snaplen
== 0)
1216 ndo
->ndo_snaplen
= MAXIMUM_SNAPLEN
;
1228 if (ascii_strcasecmp(optarg
, "vat") == 0)
1229 ndo
->ndo_packettype
= PT_VAT
;
1230 else if (ascii_strcasecmp(optarg
, "wb") == 0)
1231 ndo
->ndo_packettype
= PT_WB
;
1232 else if (ascii_strcasecmp(optarg
, "rpc") == 0)
1233 ndo
->ndo_packettype
= PT_RPC
;
1234 else if (ascii_strcasecmp(optarg
, "rtp") == 0)
1235 ndo
->ndo_packettype
= PT_RTP
;
1236 else if (ascii_strcasecmp(optarg
, "rtcp") == 0)
1237 ndo
->ndo_packettype
= PT_RTCP
;
1238 else if (ascii_strcasecmp(optarg
, "snmp") == 0)
1239 ndo
->ndo_packettype
= PT_SNMP
;
1240 else if (ascii_strcasecmp(optarg
, "cnfp") == 0)
1241 ndo
->ndo_packettype
= PT_CNFP
;
1242 else if (ascii_strcasecmp(optarg
, "tftp") == 0)
1243 ndo
->ndo_packettype
= PT_TFTP
;
1244 else if (ascii_strcasecmp(optarg
, "aodv") == 0)
1245 ndo
->ndo_packettype
= PT_AODV
;
1246 else if (ascii_strcasecmp(optarg
, "carp") == 0)
1247 ndo
->ndo_packettype
= PT_CARP
;
1248 else if (ascii_strcasecmp(optarg
, "radius") == 0)
1249 ndo
->ndo_packettype
= PT_RADIUS
;
1250 else if (ascii_strcasecmp(optarg
, "zmtp1") == 0)
1251 ndo
->ndo_packettype
= PT_ZMTP1
;
1252 else if (ascii_strcasecmp(optarg
, "vxlan") == 0)
1253 ndo
->ndo_packettype
= PT_VXLAN
;
1254 else if (ascii_strcasecmp(optarg
, "pgm") == 0)
1255 ndo
->ndo_packettype
= PT_PGM
;
1256 else if (ascii_strcasecmp(optarg
, "pgm_zmtp1") == 0)
1257 ndo
->ndo_packettype
= PT_PGM_ZMTP1
;
1258 else if (ascii_strcasecmp(optarg
, "lmp") == 0)
1259 ndo
->ndo_packettype
= PT_LMP
;
1260 else if (ascii_strcasecmp(optarg
, "resp") == 0)
1261 ndo
->ndo_packettype
= PT_RESP
;
1263 error("unknown packet type `%s'", optarg
);
1270 #ifdef HAVE_PCAP_DUMP_FLUSH
1289 Wflag
= atoi(optarg
);
1291 error("invalid number of output files %s", optarg
);
1292 WflagChars
= getWflagChars(Wflag
);
1297 ++ndo
->ndo_suppress_default_print
;
1302 ++ndo
->ndo_suppress_default_print
;
1306 yflag_dlt_name
= optarg
;
1308 pcap_datalink_name_to_val(yflag_dlt_name
);
1310 error("invalid data link type %s", yflag_dlt_name
);
1313 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1316 /* Undocumented flag */
1317 pcap_set_parser_debug(1);
1330 ndo
->ndo_packet_number
= 1;
1333 case OPTION_VERSION
:
1338 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1339 case OPTION_TSTAMP_PRECISION
:
1340 ndo
->ndo_tstamp_precision
= tstamp_precision_from_string(optarg
);
1341 if (ndo
->ndo_tstamp_precision
< 0)
1342 error("unsupported time stamp precision");
1346 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1347 case OPTION_IMMEDIATE_MODE
:
1358 #ifdef HAVE_PCAP_FINDALLDEVS
1360 show_devices_and_exit();
1363 switch (ndo
->ndo_tflag
) {
1365 case 0: /* Default */
1366 case 4: /* Default + Date*/
1367 timezone_offset
= gmt2local(0);
1370 case 1: /* No time stamp */
1371 case 2: /* Unix timeval style */
1372 case 3: /* Microseconds since previous packet */
1373 case 5: /* Microseconds since first packet */
1376 default: /* Not supported */
1377 error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1381 if (ndo
->ndo_fflag
!= 0 && (VFileName
!= NULL
|| RFileName
!= NULL
))
1382 error("-f can not be used with -V or -r");
1384 if (VFileName
!= NULL
&& RFileName
!= NULL
)
1385 error("-V and -r are mutually exclusive.");
1387 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1389 * If we're printing dissected packets to the standard output
1390 * rather than saving raw packets to a file, and the standard
1391 * output is a terminal, use immediate mode, as the user's
1392 * probably expecting to see packets pop up immediately.
1394 if (WFileName
== NULL
&& isatty(1))
1399 /* if run as root, prepare for chrooting */
1400 if (getuid() == 0 || geteuid() == 0) {
1401 /* future extensibility for cmd-line arguments */
1403 chroot_dir
= WITH_CHROOT
;
1408 /* if run as root, prepare for dropping root privileges */
1409 if (getuid() == 0 || geteuid() == 0) {
1410 /* Run with '-Z root' to restore old behaviour */
1412 username
= WITH_USER
;
1416 if (RFileName
!= NULL
|| VFileName
!= NULL
) {
1418 * If RFileName is non-null, it's the pathname of a
1419 * savefile to read. If VFileName is non-null, it's
1420 * the pathname of a file containing a list of pathnames
1421 * (one per line) of savefiles to read.
1423 * In either case, we're reading a savefile, not doing
1428 * We don't need network access, so relinquish any set-UID
1429 * or set-GID privileges we have (if any).
1431 * We do *not* want set-UID privileges when opening a
1432 * trace file, as that might let the user read other
1433 * people's trace files (especially if we're set-UID
1436 if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1437 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1439 if (VFileName
!= NULL
) {
1440 if (VFileName
[0] == '-' && VFileName
[1] == '\0')
1443 VFile
= fopen(VFileName
, "r");
1446 error("Unable to open file: %s\n", pcap_strerror(errno
));
1448 ret
= get_next_file(VFile
, VFileLine
);
1450 error("Nothing in %s\n", VFileName
);
1451 RFileName
= VFileLine
;
1454 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1455 pd
= pcap_open_offline_with_tstamp_precision(RFileName
,
1456 ndo
->ndo_tstamp_precision
, ebuf
);
1458 pd
= pcap_open_offline(RFileName
, ebuf
);
1463 #ifdef HAVE_CAPSICUM
1464 cap_rights_init(&rights
, CAP_READ
);
1465 if (cap_rights_limit(fileno(pcap_file(pd
)), &rights
) < 0 &&
1467 error("unable to limit pcap descriptor");
1470 dlt
= pcap_datalink(pd
);
1471 dlt_name
= pcap_datalink_val_to_name(dlt
);
1472 if (dlt_name
== NULL
) {
1473 fprintf(stderr
, "reading from file %s, link-type %u\n",
1477 "reading from file %s, link-type %s (%s)\n",
1478 RFileName
, dlt_name
,
1479 pcap_datalink_val_to_description(dlt
));
1483 * We're doing a live capture.
1485 if (device
== NULL
) {
1486 #ifdef HAVE_PCAP_FINDALLDEVS
1487 if (pcap_findalldevs(&devlist
, ebuf
) >= 0 &&
1489 device
= strdup(devlist
->name
);
1490 pcap_freealldevs(devlist
);
1492 #else /* HAVE_PCAP_FINDALLDEVS */
1493 device
= pcap_lookupdev(ebuf
);
1500 * Print a message to the standard error on Windows.
1501 * XXX - why do it here, with a different message?
1503 if(strlen(device
) == 1) /* we assume that an ASCII string is always longer than 1 char */
1504 { /* a Unicode string has a \0 as second byte (so strlen() is 1) */
1505 fprintf(stderr
, "%s: listening on %ws\n", program_name
, device
);
1509 fprintf(stderr
, "%s: listening on %s\n", program_name
, device
);
1514 #ifdef HAVE_PCAP_CREATE
1515 pd
= pcap_create(device
, ebuf
);
1518 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1520 show_tstamp_types_and_exit(device
);
1522 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1523 status
= pcap_set_tstamp_precision(pd
, ndo
->ndo_tstamp_precision
);
1525 error("%s: Can't set %ssecond time stamp precision: %s",
1527 tstamp_precision_to_string(ndo
->ndo_tstamp_precision
),
1528 pcap_statustostr(status
));
1531 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1532 if (immediate_mode
) {
1533 status
= pcap_set_immediate_mode(pd
, 1);
1535 error("%s: Can't set immediate mode: %s",
1537 pcap_statustostr(status
));
1541 * Is this an interface that supports monitor mode?
1543 if (pcap_can_set_rfmon(pd
) == 1)
1544 supports_monitor_mode
= 1;
1546 supports_monitor_mode
= 0;
1547 status
= pcap_set_snaplen(pd
, ndo
->ndo_snaplen
);
1549 error("%s: Can't set snapshot length: %s",
1550 device
, pcap_statustostr(status
));
1551 status
= pcap_set_promisc(pd
, !pflag
);
1553 error("%s: Can't set promiscuous mode: %s",
1554 device
, pcap_statustostr(status
));
1556 status
= pcap_set_rfmon(pd
, 1);
1558 error("%s: Can't set monitor mode: %s",
1559 device
, pcap_statustostr(status
));
1561 status
= pcap_set_timeout(pd
, 1000);
1563 error("%s: pcap_set_timeout failed: %s",
1564 device
, pcap_statustostr(status
));
1566 status
= pcap_set_buffer_size(pd
, Bflag
);
1568 error("%s: Can't set buffer size: %s",
1569 device
, pcap_statustostr(status
));
1571 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1573 status
= pcap_set_tstamp_type(pd
, jflag
);
1575 error("%s: Can't set time stamp type: %s",
1576 device
, pcap_statustostr(status
));
1579 status
= pcap_activate(pd
);
1582 * pcap_activate() failed.
1584 cp
= pcap_geterr(pd
);
1585 if (status
== PCAP_ERROR
)
1587 else if ((status
== PCAP_ERROR_NO_SUCH_DEVICE
||
1588 status
== PCAP_ERROR_PERM_DENIED
) &&
1590 error("%s: %s\n(%s)", device
,
1591 pcap_statustostr(status
), cp
);
1593 error("%s: %s", device
,
1594 pcap_statustostr(status
));
1595 } else if (status
> 0) {
1597 * pcap_activate() succeeded, but it's warning us
1598 * of a problem it had.
1600 cp
= pcap_geterr(pd
);
1601 if (status
== PCAP_WARNING
)
1603 else if (status
== PCAP_WARNING_PROMISC_NOTSUP
&&
1605 warning("%s: %s\n(%s)", device
,
1606 pcap_statustostr(status
), cp
);
1608 warning("%s: %s", device
,
1609 pcap_statustostr(status
));
1611 #ifdef HAVE_PCAP_SETDIRECTION
1613 status
= pcap_setdirection(pd
, Qflag
);
1615 error("%s: pcap_setdirection() failed: %s",
1616 device
, pcap_geterr(pd
));
1618 #endif /* HAVE_PCAP_SETDIRECTION */
1621 pd
= pcap_open_live(device
, ndo
->ndo_snaplen
, !pflag
, 1000,
1626 warning("%s", ebuf
);
1627 #endif /* HAVE_PCAP_CREATE */
1629 * Let user own process after socket has been opened.
1632 if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1633 fprintf(stderr
, "Warning: setgid/setuid failed !\n");
1635 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1637 if(pcap_setbuff(pd
, Bflag
)==-1){
1638 error("%s", pcap_geterr(pd
));
1640 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1642 show_dlts_and_exit(device
);
1643 if (yflag_dlt
>= 0) {
1644 #ifdef HAVE_PCAP_SET_DATALINK
1645 if (pcap_set_datalink(pd
, yflag_dlt
) < 0)
1646 error("%s", pcap_geterr(pd
));
1649 * We don't actually support changing the
1650 * data link type, so we only let them
1651 * set it to what it already is.
1653 if (yflag_dlt
!= pcap_datalink(pd
)) {
1654 error("%s is not one of the DLTs supported by this device\n",
1658 (void)fprintf(stderr
, "%s: data link type %s\n",
1659 program_name
, yflag_dlt_name
);
1660 (void)fflush(stderr
);
1662 i
= pcap_snapshot(pd
);
1663 if (ndo
->ndo_snaplen
< i
) {
1664 warning("snaplen raised from %d to %d", ndo
->ndo_snaplen
, i
);
1665 ndo
->ndo_snaplen
= i
;
1667 if(ndo
->ndo_fflag
!= 0) {
1668 if (pcap_lookupnet(device
, &localnet
, &netmask
, ebuf
) < 0) {
1669 warning("foreign (-f) flag used but: %s", ebuf
);
1675 cmdbuf
= read_infile(infile
);
1677 cmdbuf
= copy_argv(&argv
[optind
]);
1679 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1680 pcap_set_optimizer_debug(dflag
);
1682 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1683 error("%s", pcap_geterr(pd
));
1685 bpf_dump(&fcode
, dflag
);
1688 pcap_freecode(&fcode
);
1691 init_print(ndo
, localnet
, netmask
, timezone_offset
);
1694 (void)setsignal(SIGPIPE
, cleanup
);
1695 (void)setsignal(SIGTERM
, cleanup
);
1696 (void)setsignal(SIGINT
, cleanup
);
1698 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1699 (void)setsignal(SIGCHLD
, child_cleanup
);
1701 /* Cooperate with nohup(1) */
1703 if ((oldhandler
= setsignal(SIGHUP
, cleanup
)) != SIG_DFL
)
1704 (void)setsignal(SIGHUP
, oldhandler
);
1709 * If a user name was specified with "-Z", attempt to switch to
1710 * that user's UID. This would probably be used with sudo,
1711 * to allow tcpdump to be run in a special restricted
1712 * account (if you just want to allow users to open capture
1713 * devices, and can't just give users that permission,
1714 * you'd make tcpdump set-UID or set-GID).
1716 * Tcpdump doesn't necessarily write only to one savefile;
1717 * the general only way to allow a -Z instance to write to
1718 * savefiles as the user under whose UID it's run, rather
1719 * than as the user specified with -Z, would thus be to switch
1720 * to the original user ID before opening a capture file and
1721 * then switch back to the -Z user ID after opening the savefile.
1722 * Switching to the -Z user ID only after opening the first
1723 * savefile doesn't handle the general case.
1726 if (getuid() == 0 || geteuid() == 0) {
1727 #ifdef HAVE_LIBCAP_NG
1728 /* Initialize capng */
1729 capng_clear(CAPNG_SELECT_BOTH
);
1733 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1742 CAPNG_PERMITTED
| CAPNG_EFFECTIVE
,
1746 capng_apply(CAPNG_SELECT_BOTH
);
1747 #endif /* HAVE_LIBCAP_NG */
1748 if (username
|| chroot_dir
)
1749 droproot(username
, chroot_dir
);
1754 if (pcap_setfilter(pd
, &fcode
) < 0)
1755 error("%s", pcap_geterr(pd
));
1756 #ifdef HAVE_CAPSICUM
1757 if (RFileName
== NULL
&& VFileName
== NULL
) {
1758 static const unsigned long cmds
[] = { BIOCGSTATS
, BIOCROTZBUF
};
1760 cap_rights_init(&rights
, CAP_IOCTL
, CAP_READ
);
1761 if (cap_rights_limit(pcap_fileno(pd
), &rights
) < 0 &&
1763 error("unable to limit pcap descriptor");
1765 if (cap_ioctls_limit(pcap_fileno(pd
), cmds
,
1766 sizeof(cmds
) / sizeof(cmds
[0])) < 0 && errno
!= ENOSYS
) {
1767 error("unable to limit ioctls on pcap descriptor");
1773 /* Do not exceed the default PATH_MAX for files. */
1774 dumpinfo
.CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
1776 if (dumpinfo
.CurrentFileName
== NULL
)
1777 error("malloc of dumpinfo.CurrentFileName");
1779 /* We do not need numbering for dumpfiles if Cflag isn't set. */
1781 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, WflagChars
);
1783 MakeFilename(dumpinfo
.CurrentFileName
, WFileName
, 0, 0);
1785 p
= pcap_dump_open(pd
, dumpinfo
.CurrentFileName
);
1786 #ifdef HAVE_LIBCAP_NG
1787 /* Give up CAP_DAC_OVERRIDE capability.
1788 * Only allow it to be restored if the -C or -G flag have been
1789 * set since we may need to create more files later on.
1793 (Cflag
|| Gflag
? 0 : CAPNG_PERMITTED
)
1797 capng_apply(CAPNG_SELECT_BOTH
);
1798 #endif /* HAVE_LIBCAP_NG */
1800 error("%s", pcap_geterr(pd
));
1801 #ifdef HAVE_CAPSICUM
1802 set_dumper_capsicum_rights(p
);
1804 if (Cflag
!= 0 || Gflag
!= 0) {
1805 #ifdef HAVE_CAPSICUM
1806 dumpinfo
.WFileName
= strdup(basename(WFileName
));
1807 if (dumpinfo
.WFileName
== NULL
) {
1808 error("Unable to allocate memory for file %s",
1811 dumpinfo
.dirfd
= open(dirname(WFileName
),
1812 O_DIRECTORY
| O_RDONLY
);
1813 if (dumpinfo
.dirfd
< 0) {
1814 error("unable to open directory %s",
1815 dirname(WFileName
));
1817 cap_rights_init(&rights
, CAP_CREATE
, CAP_FCNTL
,
1818 CAP_FTRUNCATE
, CAP_LOOKUP
, CAP_SEEK
, CAP_WRITE
);
1819 if (cap_rights_limit(dumpinfo
.dirfd
, &rights
) < 0 &&
1821 error("unable to limit directory rights");
1823 if (cap_fcntls_limit(dumpinfo
.dirfd
, CAP_FCNTL_GETFL
) < 0 &&
1825 error("unable to limit dump descriptor fcntls");
1827 #else /* !HAVE_CAPSICUM */
1828 dumpinfo
.WFileName
= WFileName
;
1830 callback
= dump_packet_and_trunc
;
1833 pcap_userdata
= (u_char
*)&dumpinfo
;
1835 callback
= dump_packet
;
1836 pcap_userdata
= (u_char
*)p
;
1838 #ifdef HAVE_PCAP_DUMP_FLUSH
1843 dlt
= pcap_datalink(pd
);
1844 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1845 callback
= print_packet
;
1846 pcap_userdata
= (u_char
*)ndo
;
1849 #ifdef SIGNAL_REQ_INFO
1851 * We can't get statistics when reading from a file rather
1852 * than capturing from a device.
1854 if (RFileName
== NULL
)
1855 (void)setsignal(SIGNAL_REQ_INFO
, requestinfo
);
1858 if (ndo
->ndo_vflag
> 0 && WFileName
) {
1860 * When capturing to a file, "-v" means tcpdump should,
1861 * every 10 seconds, "v"erbosely report the number of
1864 #ifdef USE_WIN32_MM_TIMER
1865 /* call verbose_stats_dump() each 1000 +/-100msec */
1866 timer_id
= timeSetEvent(1000, 100, verbose_stats_dump
, 0, TIME_PERIODIC
);
1867 setvbuf(stderr
, NULL
, _IONBF
, 0);
1868 #elif defined(HAVE_ALARM)
1869 (void)setsignal(SIGALRM
, verbose_stats_dump
);
1875 if (RFileName
== NULL
) {
1877 * Live capture (if -V was specified, we set RFileName
1878 * to a file from the -V file). Print a message to
1879 * the standard error on UN*X.
1881 if (!ndo
->ndo_vflag
&& !WFileName
) {
1882 (void)fprintf(stderr
,
1883 "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1886 (void)fprintf(stderr
, "%s: ", program_name
);
1887 dlt
= pcap_datalink(pd
);
1888 dlt_name
= pcap_datalink_val_to_name(dlt
);
1889 if (dlt_name
== NULL
) {
1890 (void)fprintf(stderr
, "listening on %s, link-type %u, capture size %u bytes\n",
1891 device
, dlt
, ndo
->ndo_snaplen
);
1893 (void)fprintf(stderr
, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1895 pcap_datalink_val_to_description(dlt
), ndo
->ndo_snaplen
);
1897 (void)fflush(stderr
);
1901 #ifdef HAVE_CAPSICUM
1902 cansandbox
= (ndo
->ndo_nflag
&& VFileName
== NULL
&& zflag
== NULL
);
1903 if (cansandbox
&& cap_enter() < 0 && errno
!= ENOSYS
)
1904 error("unable to enter the capability mode");
1905 #endif /* HAVE_CAPSICUM */
1908 status
= pcap_loop(pd
, cnt
, callback
, pcap_userdata
);
1909 if (WFileName
== NULL
) {
1911 * We're printing packets. Flush the printed output,
1912 * so it doesn't get intermingled with error output.
1916 * We got interrupted, so perhaps we didn't
1917 * manage to finish a line we were printing.
1918 * Print an extra newline, just in case.
1922 (void)fflush(stdout
);
1926 * We got interrupted. If we are reading multiple
1927 * files (via -V) set these so that we stop.
1936 (void)fprintf(stderr
, "%s: pcap_loop: %s\n",
1937 program_name
, pcap_geterr(pd
));
1939 if (RFileName
== NULL
) {
1941 * We're doing a live capture. Report the capture
1947 if (VFileName
!= NULL
) {
1948 ret
= get_next_file(VFile
, VFileLine
);
1952 RFileName
= VFileLine
;
1953 pd
= pcap_open_offline(RFileName
, ebuf
);
1956 #ifdef HAVE_CAPSICUM
1957 cap_rights_init(&rights
, CAP_READ
);
1958 if (cap_rights_limit(fileno(pcap_file(pd
)),
1959 &rights
) < 0 && errno
!= ENOSYS
) {
1960 error("unable to limit pcap descriptor");
1963 new_dlt
= pcap_datalink(pd
);
1964 if (new_dlt
!= dlt
) {
1966 * The new file has a different
1967 * link-layer header type from the
1970 if (WFileName
!= NULL
) {
1972 * We're writing raw packets
1973 * that match the filter to
1974 * a pcap file. pcap files
1975 * don't support multiple
1976 * different link-layer
1977 * header types, so we fail
1980 error("%s: new dlt does not match original", RFileName
);
1984 * We're printing the decoded packets;
1985 * switch to the new DLT.
1987 * To do that, we need to change
1988 * the printer, change the DLT name,
1989 * and recompile the filter with
1993 ndo
->ndo_if_printer
= get_if_printer(ndo
, dlt
);
1994 if (pcap_compile(pd
, &fcode
, cmdbuf
, Oflag
, netmask
) < 0)
1995 error("%s", pcap_geterr(pd
));
1999 * Set the filter on the new file.
2001 if (pcap_setfilter(pd
, &fcode
) < 0)
2002 error("%s", pcap_geterr(pd
));
2005 * Report the new file.
2007 dlt_name
= pcap_datalink_val_to_name(dlt
);
2008 if (dlt_name
== NULL
) {
2009 fprintf(stderr
, "reading from file %s, link-type %u\n",
2013 "reading from file %s, link-type %s (%s)\n",
2014 RFileName
, dlt_name
,
2015 pcap_datalink_val_to_description(dlt
));
2020 while (ret
!= NULL
);
2023 pcap_freecode(&fcode
);
2024 exit_tcpdump(status
== -1 ? 1 : 0);
2027 /* make a clean exit on interrupts */
2029 cleanup(int signo _U_
)
2031 #ifdef USE_WIN32_MM_TIMER
2033 timeKillEvent(timer_id
);
2035 #elif defined(HAVE_ALARM)
2039 #ifdef HAVE_PCAP_BREAKLOOP
2041 * We have "pcap_breakloop()"; use it, so that we do as little
2042 * as possible in the signal handler (it's probably not safe
2043 * to do anything with standard I/O streams in a signal handler -
2044 * the ANSI C standard doesn't say it is).
2049 * We don't have "pcap_breakloop()"; this isn't safe, but
2050 * it's the best we can do. Print the summary if we're
2051 * not reading from a savefile - i.e., if we're doing a
2052 * live capture - and exit.
2054 if (pd
!= NULL
&& pcap_file(pd
) == NULL
) {
2056 * We got interrupted, so perhaps we didn't
2057 * manage to finish a line we were printing.
2058 * Print an extra newline, just in case.
2061 (void)fflush(stdout
);
2069 On windows, we do not use a fork, so we do not care less about
2070 waiting a child processes to die
2072 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2074 child_cleanup(int signo _U_
)
2078 #endif /* HAVE_FORK && HAVE_VFORK */
2081 info(register int verbose
)
2083 struct pcap_stat stats
;
2086 * Older versions of libpcap didn't set ps_ifdrop on some
2087 * platforms; initialize it to 0 to handle that.
2089 stats
.ps_ifdrop
= 0;
2090 if (pcap_stats(pd
, &stats
) < 0) {
2091 (void)fprintf(stderr
, "pcap_stats: %s\n", pcap_geterr(pd
));
2097 fprintf(stderr
, "%s: ", program_name
);
2099 (void)fprintf(stderr
, "%u packet%s captured", packets_captured
,
2100 PLURAL_SUFFIX(packets_captured
));
2102 fputs(", ", stderr
);
2105 (void)fprintf(stderr
, "%u packet%s received by filter", stats
.ps_recv
,
2106 PLURAL_SUFFIX(stats
.ps_recv
));
2108 fputs(", ", stderr
);
2111 (void)fprintf(stderr
, "%u packet%s dropped by kernel", stats
.ps_drop
,
2112 PLURAL_SUFFIX(stats
.ps_drop
));
2113 if (stats
.ps_ifdrop
!= 0) {
2115 fputs(", ", stderr
);
2118 (void)fprintf(stderr
, "%u packet%s dropped by interface\n",
2119 stats
.ps_ifdrop
, PLURAL_SUFFIX(stats
.ps_ifdrop
));
2125 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2127 #define fork_subprocess() fork()
2129 #define fork_subprocess() vfork()
2132 compress_savefile(const char *filename
)
2136 child
= fork_subprocess();
2139 "compress_savefile: fork failed: %s\n",
2140 pcap_strerror(errno
));
2144 /* Parent process. */
2150 * Set to lowest priority so that this doesn't disturb the capture.
2153 setpriority(PRIO_PROCESS
, 0, NZERO
- 1);
2155 setpriority(PRIO_PROCESS
, 0, 19);
2157 if (execlp(zflag
, zflag
, filename
, (char *)NULL
) == -1)
2159 "compress_savefile: execlp(%s, %s) failed: %s\n",
2162 pcap_strerror(errno
));
2169 #else /* HAVE_FORK && HAVE_VFORK */
2171 compress_savefile(const char *filename
)
2174 "compress_savefile failed. Functionality not implemented under your system\n");
2176 #endif /* HAVE_FORK && HAVE_VFORK */
2179 dump_packet_and_trunc(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2181 struct dump_info
*dump_info
;
2187 dump_info
= (struct dump_info
*)user
;
2190 * XXX - this won't force the file to rotate on the specified time
2191 * boundary, but it will rotate on the first packet received after the
2192 * specified Gflag number of seconds. Note: if a Gflag time boundary
2193 * and a Cflag size boundary coincide, the time rotation will occur
2194 * first thereby cancelling the Cflag boundary (since the file should
2198 /* Check if it is time to rotate */
2201 /* Get the current time */
2202 if ((t
= time(NULL
)) == (time_t)-1) {
2203 error("dump_and_trunc_packet: can't get current_time: %s",
2204 pcap_strerror(errno
));
2208 /* If the time is greater than the specified window, rotate */
2209 if (t
- Gflag_time
>= Gflag
) {
2210 #ifdef HAVE_CAPSICUM
2215 /* Update the Gflag_time */
2217 /* Update Gflag_count */
2220 * Close the current file and open a new one.
2222 pcap_dump_close(dump_info
->p
);
2225 * Compress the file we just closed, if the user asked for it
2228 compress_savefile(dump_info
->CurrentFileName
);
2231 * Check to see if we've exceeded the Wflag (when
2234 if (Cflag
== 0 && Wflag
> 0 && Gflag_count
>= Wflag
) {
2235 (void)fprintf(stderr
, "Maximum file limit reached: %d\n",
2240 if (dump_info
->CurrentFileName
!= NULL
)
2241 free(dump_info
->CurrentFileName
);
2242 /* Allocate space for max filename + \0. */
2243 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2244 if (dump_info
->CurrentFileName
== NULL
)
2245 error("dump_packet_and_trunc: malloc");
2247 * Gflag was set otherwise we wouldn't be here. Reset the count
2248 * so multiple files would end with 1,2,3 in the filename.
2249 * The counting is handled with the -C flow after this.
2254 * This is always the first file in the Cflag
2256 * We also don't need numbering if Cflag is not set.
2259 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0,
2262 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, 0, 0);
2264 #ifdef HAVE_LIBCAP_NG
2265 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2266 capng_apply(CAPNG_SELECT_BOTH
);
2267 #endif /* HAVE_LIBCAP_NG */
2268 #ifdef HAVE_CAPSICUM
2269 fd
= openat(dump_info
->dirfd
,
2270 dump_info
->CurrentFileName
,
2271 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2273 error("unable to open file %s",
2274 dump_info
->CurrentFileName
);
2276 fp
= fdopen(fd
, "w");
2278 error("unable to fdopen file %s",
2279 dump_info
->CurrentFileName
);
2281 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2282 #else /* !HAVE_CAPSICUM */
2283 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2285 #ifdef HAVE_LIBCAP_NG
2286 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2287 capng_apply(CAPNG_SELECT_BOTH
);
2288 #endif /* HAVE_LIBCAP_NG */
2289 if (dump_info
->p
== NULL
)
2290 error("%s", pcap_geterr(pd
));
2291 #ifdef HAVE_CAPSICUM
2292 set_dumper_capsicum_rights(dump_info
->p
);
2298 * XXX - this won't prevent capture files from getting
2299 * larger than Cflag - the last packet written to the
2300 * file could put it over Cflag.
2303 long size
= pcap_dump_ftell(dump_info
->p
);
2306 error("ftell fails on output file");
2308 #ifdef HAVE_CAPSICUM
2314 * Close the current file and open a new one.
2316 pcap_dump_close(dump_info
->p
);
2319 * Compress the file we just closed, if the user
2323 compress_savefile(dump_info
->CurrentFileName
);
2327 if (Cflag_count
>= Wflag
)
2330 if (dump_info
->CurrentFileName
!= NULL
)
2331 free(dump_info
->CurrentFileName
);
2332 dump_info
->CurrentFileName
= (char *)malloc(PATH_MAX
+ 1);
2333 if (dump_info
->CurrentFileName
== NULL
)
2334 error("dump_packet_and_trunc: malloc");
2335 MakeFilename(dump_info
->CurrentFileName
, dump_info
->WFileName
, Cflag_count
, WflagChars
);
2336 #ifdef HAVE_LIBCAP_NG
2337 capng_update(CAPNG_ADD
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2338 capng_apply(CAPNG_SELECT_BOTH
);
2339 #endif /* HAVE_LIBCAP_NG */
2340 #ifdef HAVE_CAPSICUM
2341 fd
= openat(dump_info
->dirfd
, dump_info
->CurrentFileName
,
2342 O_CREAT
| O_WRONLY
| O_TRUNC
, 0644);
2344 error("unable to open file %s",
2345 dump_info
->CurrentFileName
);
2347 fp
= fdopen(fd
, "w");
2349 error("unable to fdopen file %s",
2350 dump_info
->CurrentFileName
);
2352 dump_info
->p
= pcap_dump_fopen(dump_info
->pd
, fp
);
2353 #else /* !HAVE_CAPSICUM */
2354 dump_info
->p
= pcap_dump_open(dump_info
->pd
, dump_info
->CurrentFileName
);
2356 #ifdef HAVE_LIBCAP_NG
2357 capng_update(CAPNG_DROP
, CAPNG_EFFECTIVE
, CAP_DAC_OVERRIDE
);
2358 capng_apply(CAPNG_SELECT_BOTH
);
2359 #endif /* HAVE_LIBCAP_NG */
2360 if (dump_info
->p
== NULL
)
2361 error("%s", pcap_geterr(pd
));
2362 #ifdef HAVE_CAPSICUM
2363 set_dumper_capsicum_rights(dump_info
->p
);
2368 pcap_dump((u_char
*)dump_info
->p
, h
, sp
);
2369 #ifdef HAVE_PCAP_DUMP_FLUSH
2371 pcap_dump_flush(dump_info
->p
);
2380 dump_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2386 pcap_dump(user
, h
, sp
);
2387 #ifdef HAVE_PCAP_DUMP_FLUSH
2389 pcap_dump_flush((pcap_dumper_t
*)user
);
2398 print_packet(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*sp
)
2404 pretty_print_packet((netdissect_options
*)user
, h
, sp
, packets_captured
);
2413 * XXX - there should really be libpcap calls to get the version
2414 * number as a string (the string would be generated from #defines
2415 * at run time, so that it's not generated from string constants
2416 * in the library, as, on many UNIX systems, those constants would
2417 * be statically linked into the application executable image, and
2418 * would thus reflect the version of libpcap on the system on
2419 * which the application was *linked*, not the system on which it's
2422 * That routine should be documented, unlike the "version[]"
2423 * string, so that UNIX vendors providing their own libpcaps
2424 * don't omit it (as a couple of vendors have...).
2426 * Packet.dll should perhaps also export a routine to return the
2427 * version number of the Packet.dll code, to supply the
2428 * "Wpcap_version" information on Windows.
2430 char WDversion
[]="current-git.tcpdump.org";
2431 #if !defined(HAVE_GENERATED_VERSION)
2432 char version
[]="current-git.tcpdump.org";
2434 char pcap_version
[]="current-git.tcpdump.org";
2435 char Wpcap_version
[]="3.1";
2438 #ifdef SIGNAL_REQ_INFO
2439 RETSIGTYPE
requestinfo(int signo _U_
)
2449 * Called once each second in verbose mode while dumping to file
2451 #ifdef USE_WIN32_MM_TIMER
2452 void CALLBACK
verbose_stats_dump (UINT timer_id _U_
, UINT msg _U_
, DWORD_PTR arg _U_
,
2453 DWORD_PTR dw1 _U_
, DWORD_PTR dw2 _U_
)
2456 fprintf(stderr
, "Got %u\r", packets_captured
);
2458 #elif defined(HAVE_ALARM)
2459 static void verbose_stats_dump(int sig _U_
)
2462 fprintf(stderr
, "Got %u\r", packets_captured
);
2467 USES_APPLE_DEPRECATED_API
2471 extern char version
[];
2472 #ifndef HAVE_PCAP_LIB_VERSION
2473 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2474 extern char pcap_version
[];
2475 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2476 static char pcap_version
[] = "unknown";
2477 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2478 #endif /* HAVE_PCAP_LIB_VERSION */
2480 #ifdef HAVE_PCAP_LIB_VERSION
2482 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2484 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2486 (void)fprintf(stderr
, "%s\n",pcap_lib_version());
2487 #else /* HAVE_PCAP_LIB_VERSION */
2489 (void)fprintf(stderr
, "%s version %s, based on tcpdump version %s\n", program_name
, WDversion
, version
);
2490 (void)fprintf(stderr
, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version
, pcap_version
);
2492 (void)fprintf(stderr
, "%s version %s\n", program_name
, version
);
2493 (void)fprintf(stderr
, "libpcap version %s\n", pcap_version
);
2495 #endif /* HAVE_PCAP_LIB_VERSION */
2497 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2498 (void)fprintf (stderr
, "%s\n", SSLeay_version(SSLEAY_VERSION
));
2502 (void)fprintf (stderr
, "SMI-library: %s\n", smi_version_string
);
2511 (void)fprintf(stderr
,
2512 "Usage: %s [-aAbd" D_FLAG
"efhH" I_FLAG J_FLAG
"KlLnNOpqStu" U_FLAG
"vxX#]" B_FLAG_USAGE
" [ -c count ]\n", program_name
);
2513 (void)fprintf(stderr
,
2514 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2515 (void)fprintf(stderr
,
2516 "\t\t[ -i interface ]" j_FLAG_USAGE
" [ -M secret ] [ --number ]\n");
2517 #ifdef HAVE_PCAP_SETDIRECTION
2518 (void)fprintf(stderr
,
2519 "\t\t[ -Q in|out|inout ]\n");
2521 (void)fprintf(stderr
,
2522 "\t\t[ -r file ] [ -s snaplen ] ");
2523 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2524 (void)fprintf(stderr
, "[ --time-stamp-precision precision ]\n");
2525 (void)fprintf(stderr
,
2528 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2529 (void)fprintf(stderr
, "[ --immediate-mode ] ");
2531 (void)fprintf(stderr
, "[ -T type ] [ --version ] [ -V file ]\n");
2532 (void)fprintf(stderr
,
2533 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2534 (void)fprintf(stderr
,
2535 "\t\t[ -Z user ] [ expression ]\n");
2539 * c-style: whitesmith