xref: /freebsd/contrib/tcpdump/tcpdump.c (revision 5bf5ca772c6de2d53344a78cf461447cc322ccea)
1 /*
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.
4  *
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
16  * written permission.
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.
20  *
21  * Support for splitting captures into multiple files with a maximum
22  * file size:
23  *
24  * Copyright (c) 2001
25  *	Seth Webster <swebster@sst.ll.mit.edu>
26  */
27 
28 #ifndef lint
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";
32 #endif
33 
34 /*
35  * tcpdump - dump traffic on a network
36  *
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.
40  */
41 
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #endif
45 
46 /*
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().
50  */
51 #ifdef HAVE_PCAP_FINDALLDEVS
52 #ifndef HAVE_PCAP_IF_T
53 #undef HAVE_PCAP_FINDALLDEVS
54 #endif
55 #endif
56 
57 #include <netdissect-stdinc.h>
58 
59 #include <sys/stat.h>
60 
61 #ifdef HAVE_FCNTL_H
62 #include <fcntl.h>
63 #endif
64 
65 #ifdef HAVE_LIBCRYPTO
66 #include <openssl/crypto.h>
67 #endif
68 
69 #ifdef HAVE_GETOPT_LONG
70 #include <getopt.h>
71 #else
72 #include "getopt_long.h"
73 #endif
74 /* Capsicum-specific code requires macros from <net/bpf.h>, which will fail
75  * to compile if <pcap.h> has already been included; including the headers
76  * in the opposite order works fine.
77  */
78 #ifdef HAVE_CAPSICUM
79 #include <sys/capsicum.h>
80 #include <sys/sysctl.h>
81 #include <sys/nv.h>
82 #include <sys/ioccom.h>
83 #include <net/bpf.h>
84 #include <libgen.h>
85 #ifdef HAVE_CASPER
86 #include <libcasper.h>
87 #include <casper/cap_dns.h>
88 #endif	/* HAVE_CASPER */
89 #endif	/* HAVE_CAPSICUM */
90 #include <pcap.h>
91 #include <signal.h>
92 #include <stdio.h>
93 #include <stdarg.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <limits.h>
97 #ifndef _WIN32
98 #include <sys/wait.h>
99 #include <sys/resource.h>
100 #include <pwd.h>
101 #include <grp.h>
102 #endif /* _WIN32 */
103 
104 /* capabilities convenience library */
105 /* If a code depends on HAVE_LIBCAP_NG, it depends also on HAVE_CAP_NG_H.
106  * If HAVE_CAP_NG_H is not defined, undefine HAVE_LIBCAP_NG.
107  * Thus, the later tests are done only on HAVE_LIBCAP_NG.
108  */
109 #ifdef HAVE_LIBCAP_NG
110 #ifdef HAVE_CAP_NG_H
111 #include <cap-ng.h>
112 #else
113 #undef HAVE_LIBCAP_NG
114 #endif /* HAVE_CAP_NG_H */
115 #endif /* HAVE_LIBCAP_NG */
116 
117 #include "netdissect.h"
118 #include "interface.h"
119 #include "addrtoname.h"
120 #include "machdep.h"
121 #include "setsignal.h"
122 #include "gmt2local.h"
123 #include "pcap-missing.h"
124 #include "ascii_strcasecmp.h"
125 
126 #include "print.h"
127 
128 #ifndef PATH_MAX
129 #define PATH_MAX 1024
130 #endif
131 
132 #ifdef SIGINFO
133 #define SIGNAL_REQ_INFO SIGINFO
134 #elif SIGUSR1
135 #define SIGNAL_REQ_INFO SIGUSR1
136 #endif
137 
138 static int Bflag;			/* buffer size */
139 static long Cflag;			/* rotate dump files after this many bytes */
140 static int Cflag_count;			/* Keep track of which file number we're writing */
141 static int Dflag;			/* list available devices and exit */
142 /*
143  * This is exported because, in some versions of libpcap, if libpcap
144  * is built with optimizer debugging code (which is *NOT* the default
145  * configuration!), the library *imports*(!) a variable named dflag,
146  * under the expectation that tcpdump is exporting it, to govern
147  * how much debugging information to print when optimizing
148  * the generated BPF code.
149  *
150  * This is a horrible hack; newer versions of libpcap don't import
151  * dflag but, instead, *if* built with optimizer debugging code,
152  * *export* a routine to set that flag.
153  */
154 int dflag;				/* print filter code */
155 static int Gflag;			/* rotate dump files after this many seconds */
156 static int Gflag_count;			/* number of files created with Gflag rotation */
157 static time_t Gflag_time;		/* The last time_t the dump file was rotated. */
158 static int Lflag;			/* list available data link types and exit */
159 static int Iflag;			/* rfmon (monitor) mode */
160 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
161 static int Jflag;			/* list available time stamp types */
162 #endif
163 static int jflag = -1;			/* packet time stamp source */
164 static int pflag;			/* don't go promiscuous */
165 #ifdef HAVE_PCAP_SETDIRECTION
166 static int Qflag = -1;			/* restrict captured packet by send/receive direction */
167 #endif
168 static int Uflag;			/* "unbuffered" output of dump files */
169 static int Wflag;			/* recycle output files after this number of files */
170 static int WflagChars;
171 static char *zflag = NULL;		/* compress each savefile using a specified command (like gzip or bzip2) */
172 static int immediate_mode;
173 
174 static int infodelay;
175 static int infoprint;
176 
177 char *program_name;
178 
179 #ifdef HAVE_CASPER
180 cap_channel_t *capdns;
181 #endif
182 
183 /* Forwards */
184 static void error(FORMAT_STRING(const char *), ...) NORETURN PRINTFLIKE(1, 2);
185 static void warning(FORMAT_STRING(const char *), ...) PRINTFLIKE(1, 2);
186 static void exit_tcpdump(int) NORETURN;
187 static RETSIGTYPE cleanup(int);
188 static RETSIGTYPE child_cleanup(int);
189 static void print_version(void);
190 static void print_usage(void);
191 static void show_tstamp_types_and_exit(pcap_t *, const char *device) NORETURN;
192 static void show_dlts_and_exit(pcap_t *, const char *device) NORETURN;
193 #ifdef HAVE_PCAP_FINDALLDEVS
194 static void show_devices_and_exit (void) NORETURN;
195 #endif
196 
197 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
198 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
199 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
200 static void droproot(const char *, const char *);
201 
202 #ifdef SIGNAL_REQ_INFO
203 RETSIGTYPE requestinfo(int);
204 #endif
205 
206 #if defined(USE_WIN32_MM_TIMER)
207   #include <MMsystem.h>
208   static UINT timer_id;
209   static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
210 #elif defined(HAVE_ALARM)
211   static void verbose_stats_dump(int sig);
212 #endif
213 
214 static void info(int);
215 static u_int packets_captured;
216 
217 #ifdef HAVE_PCAP_FINDALLDEVS
218 static const struct tok status_flags[] = {
219 #ifdef PCAP_IF_UP
220 	{ PCAP_IF_UP,       "Up"       },
221 #endif
222 #ifdef PCAP_IF_RUNNING
223 	{ PCAP_IF_RUNNING,  "Running"  },
224 #endif
225 	{ PCAP_IF_LOOPBACK, "Loopback" },
226 	{ 0, NULL }
227 };
228 #endif
229 
230 static pcap_t *pd;
231 
232 static int supports_monitor_mode;
233 
234 extern int optind;
235 extern int opterr;
236 extern char *optarg;
237 
238 struct dump_info {
239 	char	*WFileName;
240 	char	*CurrentFileName;
241 	pcap_t	*pd;
242 	pcap_dumper_t *p;
243 #ifdef HAVE_CAPSICUM
244 	int	dirfd;
245 #endif
246 };
247 
248 #if defined(HAVE_PCAP_SET_PARSER_DEBUG)
249 /*
250  * We have pcap_set_parser_debug() in libpcap; declare it (it's not declared
251  * by any libpcap header, because it's a special hack, only available if
252  * libpcap was configured to include it, and only intended for use by
253  * libpcap developers trying to debug the parser for filter expressions).
254  */
255 #ifdef _WIN32
256 __declspec(dllimport)
257 #else /* _WIN32 */
258 extern
259 #endif /* _WIN32 */
260 void pcap_set_parser_debug(int);
261 #elif defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
262 /*
263  * We don't have pcap_set_parser_debug() in libpcap, but we do have
264  * pcap_debug or yydebug.  Make a local version of pcap_set_parser_debug()
265  * to set the flag, and define HAVE_PCAP_SET_PARSER_DEBUG.
266  */
267 static void
268 pcap_set_parser_debug(int value)
269 {
270 #ifdef HAVE_PCAP_DEBUG
271 	extern int pcap_debug;
272 
273 	pcap_debug = value;
274 #else /* HAVE_PCAP_DEBUG */
275 	extern int yydebug;
276 
277 	yydebug = value;
278 #endif /* HAVE_PCAP_DEBUG */
279 }
280 
281 #define HAVE_PCAP_SET_PARSER_DEBUG
282 #endif
283 
284 #if defined(HAVE_PCAP_SET_OPTIMIZER_DEBUG)
285 /*
286  * We have pcap_set_optimizer_debug() in libpcap; declare it (it's not declared
287  * by any libpcap header, because it's a special hack, only available if
288  * libpcap was configured to include it, and only intended for use by
289  * libpcap developers trying to debug the optimizer for filter expressions).
290  */
291 #ifdef _WIN32
292 __declspec(dllimport)
293 #else /* _WIN32 */
294 extern
295 #endif /* _WIN32 */
296 void pcap_set_optimizer_debug(int);
297 #endif
298 
299 /* VARARGS */
300 static void
301 error(const char *fmt, ...)
302 {
303 	va_list ap;
304 
305 	(void)fprintf(stderr, "%s: ", program_name);
306 	va_start(ap, fmt);
307 	(void)vfprintf(stderr, fmt, ap);
308 	va_end(ap);
309 	if (*fmt) {
310 		fmt += strlen(fmt);
311 		if (fmt[-1] != '\n')
312 			(void)fputc('\n', stderr);
313 	}
314 	exit_tcpdump(1);
315 	/* NOTREACHED */
316 }
317 
318 /* VARARGS */
319 static void
320 warning(const char *fmt, ...)
321 {
322 	va_list ap;
323 
324 	(void)fprintf(stderr, "%s: WARNING: ", program_name);
325 	va_start(ap, fmt);
326 	(void)vfprintf(stderr, fmt, ap);
327 	va_end(ap);
328 	if (*fmt) {
329 		fmt += strlen(fmt);
330 		if (fmt[-1] != '\n')
331 			(void)fputc('\n', stderr);
332 	}
333 }
334 
335 static void
336 exit_tcpdump(int status)
337 {
338 	nd_cleanup();
339 	exit(status);
340 }
341 
342 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
343 static void
344 show_tstamp_types_and_exit(pcap_t *pc, const char *device)
345 {
346 	int n_tstamp_types;
347 	int *tstamp_types = 0;
348 	const char *tstamp_type_name;
349 	int i;
350 
351 	n_tstamp_types = pcap_list_tstamp_types(pc, &tstamp_types);
352 	if (n_tstamp_types < 0)
353 		error("%s", pcap_geterr(pc));
354 
355 	if (n_tstamp_types == 0) {
356 		fprintf(stderr, "Time stamp type cannot be set for %s\n",
357 		    device);
358 		exit_tcpdump(0);
359 	}
360 	fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
361 	    device);
362 	for (i = 0; i < n_tstamp_types; i++) {
363 		tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
364 		if (tstamp_type_name != NULL) {
365 			(void) fprintf(stderr, "  %s (%s)\n", tstamp_type_name,
366 			    pcap_tstamp_type_val_to_description(tstamp_types[i]));
367 		} else {
368 			(void) fprintf(stderr, "  %d\n", tstamp_types[i]);
369 		}
370 	}
371 	pcap_free_tstamp_types(tstamp_types);
372 	exit_tcpdump(0);
373 }
374 #endif
375 
376 static void
377 show_dlts_and_exit(pcap_t *pc, const char *device)
378 {
379 	int n_dlts, i;
380 	int *dlts = 0;
381 	const char *dlt_name;
382 
383 	n_dlts = pcap_list_datalinks(pc, &dlts);
384 	if (n_dlts < 0)
385 		error("%s", pcap_geterr(pc));
386 	else if (n_dlts == 0 || !dlts)
387 		error("No data link types.");
388 
389 	/*
390 	 * If the interface is known to support monitor mode, indicate
391 	 * whether these are the data link types available when not in
392 	 * monitor mode, if -I wasn't specified, or when in monitor mode,
393 	 * when -I was specified (the link-layer types available in
394 	 * monitor mode might be different from the ones available when
395 	 * not in monitor mode).
396 	 */
397 	if (supports_monitor_mode)
398 		(void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
399 		    device,
400 		    Iflag ? "when in monitor mode" : "when not in monitor mode");
401 	else
402 		(void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
403 		    device);
404 
405 	for (i = 0; i < n_dlts; i++) {
406 		dlt_name = pcap_datalink_val_to_name(dlts[i]);
407 		if (dlt_name != NULL) {
408 			(void) fprintf(stderr, "  %s (%s)", dlt_name,
409 			    pcap_datalink_val_to_description(dlts[i]));
410 
411 			/*
412 			 * OK, does tcpdump handle that type?
413 			 */
414 			if (!has_printer(dlts[i]))
415 				(void) fprintf(stderr, " (printing not supported)");
416 			fprintf(stderr, "\n");
417 		} else {
418 			(void) fprintf(stderr, "  DLT %d (printing not supported)\n",
419 			    dlts[i]);
420 		}
421 	}
422 #ifdef HAVE_PCAP_FREE_DATALINKS
423 	pcap_free_datalinks(dlts);
424 #endif
425 	exit_tcpdump(0);
426 }
427 
428 #ifdef HAVE_PCAP_FINDALLDEVS
429 static void
430 show_devices_and_exit (void)
431 {
432 	pcap_if_t *dev, *devlist;
433 	char ebuf[PCAP_ERRBUF_SIZE];
434 	int i;
435 
436 	if (pcap_findalldevs(&devlist, ebuf) < 0)
437 		error("%s", ebuf);
438 	for (i = 0, dev = devlist; dev != NULL; i++, dev = dev->next) {
439 		printf("%d.%s", i+1, dev->name);
440 		if (dev->description != NULL)
441 			printf(" (%s)", dev->description);
442 		if (dev->flags != 0)
443 			printf(" [%s]", bittok2str(status_flags, "none", dev->flags));
444 		printf("\n");
445 	}
446 	pcap_freealldevs(devlist);
447 	exit_tcpdump(0);
448 }
449 #endif /* HAVE_PCAP_FINDALLDEVS */
450 
451 /*
452  * Short options.
453  *
454  * Note that there we use all letters for short options except for g, k,
455  * o, and P, and those are used by other versions of tcpdump, and we should
456  * only use them for the same purposes that the other versions of tcpdump
457  * use them:
458  *
459  * OS X tcpdump uses -g to force non--v output for IP to be on one
460  * line, making it more "g"repable;
461  *
462  * OS X tcpdump uses -k to specify that packet comments in pcap-ng files
463  * should be printed;
464  *
465  * OpenBSD tcpdump uses -o to indicate that OS fingerprinting should be done
466  * for hosts sending TCP SYN packets;
467  *
468  * OS X tcpdump uses -P to indicate that -w should write pcap-ng rather
469  * than pcap files.
470  *
471  * OS X tcpdump also uses -Q to specify expressions that match packet
472  * metadata, including but not limited to the packet direction.
473  * The expression syntax is different from a simple "in|out|inout",
474  * and those expressions aren't accepted by OS X tcpdump, but the
475  * equivalents would be "in" = "dir=in", "out" = "dir=out", and
476  * "inout" = "dir=in or dir=out", and the parser could conceivably
477  * special-case "in", "out", and "inout" as expressions for backwards
478  * compatibility, so all is not (yet) lost.
479  */
480 
481 /*
482  * Set up flags that might or might not be supported depending on the
483  * version of libpcap we're using.
484  */
485 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
486 #define B_FLAG		"B:"
487 #define B_FLAG_USAGE	" [ -B size ]"
488 #else /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
489 #define B_FLAG
490 #define B_FLAG_USAGE
491 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
492 
493 #ifdef HAVE_PCAP_CREATE
494 #define I_FLAG		"I"
495 #else /* HAVE_PCAP_CREATE */
496 #define I_FLAG
497 #endif /* HAVE_PCAP_CREATE */
498 
499 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
500 #define j_FLAG		"j:"
501 #define j_FLAG_USAGE	" [ -j tstamptype ]"
502 #define J_FLAG		"J"
503 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
504 #define j_FLAG
505 #define j_FLAG_USAGE
506 #define J_FLAG
507 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
508 
509 #ifdef HAVE_PCAP_FINDALLDEVS
510 #define D_FLAG	"D"
511 #else
512 #define D_FLAG
513 #endif
514 
515 #ifdef HAVE_PCAP_DUMP_FLUSH
516 #define U_FLAG	"U"
517 #else
518 #define U_FLAG
519 #endif
520 
521 #ifdef HAVE_PCAP_SETDIRECTION
522 #define Q_FLAG "Q:"
523 #else
524 #define Q_FLAG
525 #endif
526 
527 #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:#"
528 
529 /*
530  * Long options.
531  *
532  * We do not currently have long options corresponding to all short
533  * options; we should probably pick appropriate option names for them.
534  *
535  * However, the short options where the number of times the option is
536  * specified matters, such as -v and -d and -t, should probably not
537  * just map to a long option, as saying
538  *
539  *  tcpdump --verbose --verbose
540  *
541  * doesn't make sense; it should be --verbosity={N} or something such
542  * as that.
543  *
544  * For long options with no corresponding short options, we define values
545  * outside the range of ASCII graphic characters, make that the last
546  * component of the entry for the long option, and have a case for that
547  * option in the switch statement.
548  */
549 #define OPTION_VERSION		128
550 #define OPTION_TSTAMP_PRECISION	129
551 #define OPTION_IMMEDIATE_MODE	130
552 
553 static const struct option longopts[] = {
554 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
555 	{ "buffer-size", required_argument, NULL, 'B' },
556 #endif
557 	{ "list-interfaces", no_argument, NULL, 'D' },
558 	{ "help", no_argument, NULL, 'h' },
559 	{ "interface", required_argument, NULL, 'i' },
560 #ifdef HAVE_PCAP_CREATE
561 	{ "monitor-mode", no_argument, NULL, 'I' },
562 #endif
563 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
564 	{ "time-stamp-type", required_argument, NULL, 'j' },
565 	{ "list-time-stamp-types", no_argument, NULL, 'J' },
566 #endif
567 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
568 	{ "time-stamp-precision", required_argument, NULL, OPTION_TSTAMP_PRECISION},
569 #endif
570 	{ "dont-verify-checksums", no_argument, NULL, 'K' },
571 	{ "list-data-link-types", no_argument, NULL, 'L' },
572 	{ "no-optimize", no_argument, NULL, 'O' },
573 	{ "no-promiscuous-mode", no_argument, NULL, 'p' },
574 #ifdef HAVE_PCAP_SETDIRECTION
575 	{ "direction", required_argument, NULL, 'Q' },
576 #endif
577 	{ "snapshot-length", required_argument, NULL, 's' },
578 	{ "absolute-tcp-sequence-numbers", no_argument, NULL, 'S' },
579 #ifdef HAVE_PCAP_DUMP_FLUSH
580 	{ "packet-buffered", no_argument, NULL, 'U' },
581 #endif
582 	{ "linktype", required_argument, NULL, 'y' },
583 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
584 	{ "immediate-mode", no_argument, NULL, OPTION_IMMEDIATE_MODE },
585 #endif
586 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
587 	{ "debug-filter-parser", no_argument, NULL, 'Y' },
588 #endif
589 	{ "relinquish-privileges", required_argument, NULL, 'Z' },
590 	{ "number", no_argument, NULL, '#' },
591 	{ "version", no_argument, NULL, OPTION_VERSION },
592 	{ NULL, 0, NULL, 0 }
593 };
594 
595 #ifndef _WIN32
596 /* Drop root privileges and chroot if necessary */
597 static void
598 droproot(const char *username, const char *chroot_dir)
599 {
600 	struct passwd *pw = NULL;
601 
602 	if (chroot_dir && !username) {
603 		fprintf(stderr, "%s: Chroot without dropping root is insecure\n",
604 			program_name);
605 		exit_tcpdump(1);
606 	}
607 
608 	pw = getpwnam(username);
609 	if (pw) {
610 		if (chroot_dir) {
611 			if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
612 				fprintf(stderr, "%s: Couldn't chroot/chdir to '%.64s': %s\n",
613 					program_name, chroot_dir, pcap_strerror(errno));
614 				exit_tcpdump(1);
615 			}
616 		}
617 #ifdef HAVE_LIBCAP_NG
618 		{
619 			int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
620 			if (ret < 0) {
621 				fprintf(stderr, "error : ret %d\n", ret);
622 			} else {
623 				fprintf(stderr, "dropped privs to %s\n", username);
624 			}
625 		}
626 #else
627 		if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
628 		    setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
629 			fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
630 				program_name, username,
631 				(unsigned long)pw->pw_uid,
632 				(unsigned long)pw->pw_gid,
633 				pcap_strerror(errno));
634 			exit_tcpdump(1);
635 		}
636 		else {
637 			fprintf(stderr, "dropped privs to %s\n", username);
638 		}
639 #endif /* HAVE_LIBCAP_NG */
640 	}
641 	else {
642 		fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
643 			program_name, username);
644 		exit_tcpdump(1);
645 	}
646 #ifdef HAVE_LIBCAP_NG
647 	/* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
648 	capng_updatev(
649 		CAPNG_DROP,
650 		CAPNG_EFFECTIVE | CAPNG_PERMITTED,
651 		CAP_SETUID,
652 		CAP_SETGID,
653 		CAP_SYS_CHROOT,
654 		-1);
655 	capng_apply(CAPNG_SELECT_BOTH);
656 #endif /* HAVE_LIBCAP_NG */
657 
658 }
659 #endif /* _WIN32 */
660 
661 static int
662 getWflagChars(int x)
663 {
664 	int c = 0;
665 
666 	x -= 1;
667 	while (x > 0) {
668 		c += 1;
669 		x /= 10;
670 	}
671 
672 	return c;
673 }
674 
675 
676 static void
677 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
678 {
679         char *filename = malloc(PATH_MAX + 1);
680         if (filename == NULL)
681             error("Makefilename: malloc");
682 
683         /* Process with strftime if Gflag is set. */
684         if (Gflag != 0) {
685           struct tm *local_tm;
686 
687           /* Convert Gflag_time to a usable format */
688           if ((local_tm = localtime(&Gflag_time)) == NULL) {
689                   error("MakeTimedFilename: localtime");
690           }
691 
692           /* There's no good way to detect an error in strftime since a return
693            * value of 0 isn't necessarily failure.
694            */
695           strftime(filename, PATH_MAX, orig_name, local_tm);
696         } else {
697           strncpy(filename, orig_name, PATH_MAX);
698         }
699 
700 	if (cnt == 0 && max_chars == 0)
701 		strncpy(buffer, filename, PATH_MAX + 1);
702 	else
703 		if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
704                   /* Report an error if the filename is too large */
705                   error("too many output files or filename is too long (> %d)", PATH_MAX);
706         free(filename);
707 }
708 
709 static char *
710 get_next_file(FILE *VFile, char *ptr)
711 {
712 	char *ret;
713 
714 	ret = fgets(ptr, PATH_MAX, VFile);
715 	if (!ret)
716 		return NULL;
717 
718 	if (ptr[strlen(ptr) - 1] == '\n')
719 		ptr[strlen(ptr) - 1] = '\0';
720 
721 	return ret;
722 }
723 
724 #ifdef HAVE_CASPER
725 static cap_channel_t *
726 capdns_setup(void)
727 {
728 	cap_channel_t *capcas, *capdnsloc;
729 	const char *types[1];
730 	int families[2];
731 
732 	capcas = cap_init();
733 	if (capcas == NULL)
734 		error("unable to create casper process");
735 	capdnsloc = cap_service_open(capcas, "system.dns");
736 	/* Casper capability no longer needed. */
737 	cap_close(capcas);
738 	if (capdnsloc == NULL)
739 		error("unable to open system.dns service");
740 	/* Limit system.dns to reverse DNS lookups. */
741 	types[0] = "ADDR";
742 	if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
743 		error("unable to limit access to system.dns service");
744 	families[0] = AF_INET;
745 	families[1] = AF_INET6;
746 	if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
747 		error("unable to limit access to system.dns service");
748 
749 	return (capdnsloc);
750 }
751 #endif	/* HAVE_CASPER */
752 
753 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
754 static int
755 tstamp_precision_from_string(const char *precision)
756 {
757 	if (strncmp(precision, "nano", strlen("nano")) == 0)
758 		return PCAP_TSTAMP_PRECISION_NANO;
759 
760 	if (strncmp(precision, "micro", strlen("micro")) == 0)
761 		return PCAP_TSTAMP_PRECISION_MICRO;
762 
763 	return -EINVAL;
764 }
765 
766 static const char *
767 tstamp_precision_to_string(int precision)
768 {
769 	switch (precision) {
770 
771 	case PCAP_TSTAMP_PRECISION_MICRO:
772 		return "micro";
773 
774 	case PCAP_TSTAMP_PRECISION_NANO:
775 		return "nano";
776 
777 	default:
778 		return "unknown";
779 	}
780 }
781 #endif
782 
783 #ifdef HAVE_CAPSICUM
784 /*
785  * Ensure that, on a dump file's descriptor, we have all the rights
786  * necessary to make the standard I/O library work with an fdopen()ed
787  * FILE * from that descriptor.
788  *
789  * A long time ago, in a galaxy far far away, AT&T decided that, instead
790  * of providing separate APIs for getting and setting the FD_ flags on a
791  * descriptor, getting and setting the O_ flags on a descriptor, and
792  * locking files, they'd throw them all into a kitchen-sink fcntl() call
793  * along the lines of ioctl(), the fact that ioctl() operations are
794  * largely specific to particular character devices but fcntl() operations
795  * are either generic to all descriptors or generic to all descriptors for
796  * regular files nonwithstanding.
797  *
798  * The Capsicum people decided that fine-grained control of descriptor
799  * operations was required, so that you need to grant permission for
800  * reading, writing, seeking, and fcntl-ing.  The latter, courtesy of
801  * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
802  * collection of things, so there are *individual* fcntls for which
803  * permission needs to be granted.
804  *
805  * The FreeBSD standard I/O people implemented some optimizations that
806  * requires that the standard I/O routines be able to determine whether
807  * the descriptor for the FILE * is open append-only or not; as that
808  * descriptor could have come from an open() rather than an fopen(),
809  * that requires that it be able to do an F_GETFL fcntl() to read
810  * the O_ flags.
811  *
812  * Tcpdump uses ftell() to determine how much data has been written
813  * to a file in order to, when used with -C, determine when it's time
814  * to rotate capture files.  ftell() therefore needs to do an lseek()
815  * to find out the file offset and must, thanks to the aforementioned
816  * optimization, also know whether the descriptor is open append-only
817  * or not.
818  *
819  * The net result of all the above is that we need to grant CAP_SEEK,
820  * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
821  *
822  * Perhaps this is the universe's way of saying that either
823  *
824  *	1) there needs to be an fopenat() call and a pcap_dump_openat() call
825  *	   using it, so that Capsicum-capable tcpdump wouldn't need to do
826  *	   an fdopen()
827  *
828  * or
829  *
830  *	2) there needs to be a cap_fdopen() call in the FreeBSD standard
831  *	   I/O library that knows what rights are needed by the standard
832  *	   I/O library, based on the open mode, and assigns them, perhaps
833  *	   with an additional argument indicating, for example, whether
834  *	   seeking should be allowed, so that tcpdump doesn't need to know
835  *	   what the standard I/O library happens to require this week.
836  */
837 static void
838 set_dumper_capsicum_rights(pcap_dumper_t *p)
839 {
840 	int fd = fileno(pcap_dump_file(p));
841 	cap_rights_t rights;
842 
843 	cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
844 	if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
845 		error("unable to limit dump descriptor");
846 	}
847 	if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
848 		error("unable to limit dump descriptor fcntls");
849 	}
850 }
851 #endif
852 
853 /*
854  * Copy arg vector into a new buffer, concatenating arguments with spaces.
855  */
856 static char *
857 copy_argv(register char **argv)
858 {
859 	register char **p;
860 	register u_int len = 0;
861 	char *buf;
862 	char *src, *dst;
863 
864 	p = argv;
865 	if (*p == NULL)
866 		return 0;
867 
868 	while (*p)
869 		len += strlen(*p++) + 1;
870 
871 	buf = (char *)malloc(len);
872 	if (buf == NULL)
873 		error("copy_argv: malloc");
874 
875 	p = argv;
876 	dst = buf;
877 	while ((src = *p++) != NULL) {
878 		while ((*dst++ = *src++) != '\0')
879 			;
880 		dst[-1] = ' ';
881 	}
882 	dst[-1] = '\0';
883 
884 	return buf;
885 }
886 
887 /*
888  * On Windows, we need to open the file in binary mode, so that
889  * we get all the bytes specified by the size we get from "fstat()".
890  * On UNIX, that's not necessary.  O_BINARY is defined on Windows;
891  * we define it as 0 if it's not defined, so it does nothing.
892  */
893 #ifndef O_BINARY
894 #define O_BINARY	0
895 #endif
896 
897 static char *
898 read_infile(char *fname)
899 {
900 	register int i, fd, cc;
901 	register char *cp;
902 	struct stat buf;
903 
904 	fd = open(fname, O_RDONLY|O_BINARY);
905 	if (fd < 0)
906 		error("can't open %s: %s", fname, pcap_strerror(errno));
907 
908 	if (fstat(fd, &buf) < 0)
909 		error("can't stat %s: %s", fname, pcap_strerror(errno));
910 
911 	cp = malloc((u_int)buf.st_size + 1);
912 	if (cp == NULL)
913 		error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
914 			fname, pcap_strerror(errno));
915 	cc = read(fd, cp, (u_int)buf.st_size);
916 	if (cc < 0)
917 		error("read %s: %s", fname, pcap_strerror(errno));
918 	if (cc != buf.st_size)
919 		error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
920 
921 	close(fd);
922 	/* replace "# comment" with spaces */
923 	for (i = 0; i < cc; i++) {
924 		if (cp[i] == '#')
925 			while (i < cc && cp[i] != '\n')
926 				cp[i++] = ' ';
927 	}
928 	cp[cc] = '\0';
929 	return (cp);
930 }
931 
932 #ifdef HAVE_PCAP_FINDALLDEVS
933 static long
934 parse_interface_number(const char *device)
935 {
936 	long devnum;
937 	char *end;
938 
939 	devnum = strtol(device, &end, 10);
940 	if (device != end && *end == '\0') {
941 		/*
942 		 * It's all-numeric, but is it a valid number?
943 		 */
944 		if (devnum <= 0) {
945 			/*
946 			 * No, it's not an ordinal.
947 			 */
948 			error("Invalid adapter index");
949 		}
950 		return (devnum);
951 	} else {
952 		/*
953 		 * It's not all-numeric; return -1, so our caller
954 		 * knows that.
955 		 */
956 		return (-1);
957 	}
958 }
959 
960 static char *
961 find_interface_by_number(long devnum)
962 {
963 	pcap_if_t *dev, *devlist;
964 	long i;
965 	char ebuf[PCAP_ERRBUF_SIZE];
966 	char *device;
967 
968 	if (pcap_findalldevs(&devlist, ebuf) < 0)
969 		error("%s", ebuf);
970 	/*
971 	 * Look for the devnum-th entry in the list of devices (1-based).
972 	 */
973 	for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
974 	    i++, dev = dev->next)
975 		;
976 	if (dev == NULL)
977 		error("Invalid adapter index");
978 	device = strdup(dev->name);
979 	pcap_freealldevs(devlist);
980 	return (device);
981 }
982 #endif
983 
984 static pcap_t *
985 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
986 {
987 	pcap_t *pc;
988 #ifdef HAVE_PCAP_CREATE
989 	int status;
990 	char *cp;
991 #endif
992 
993 #ifdef HAVE_PCAP_CREATE
994 	pc = pcap_create(device, ebuf);
995 	if (pc == NULL) {
996 		/*
997 		 * If this failed with "No such device", that means
998 		 * the interface doesn't exist; return NULL, so that
999 		 * the caller can see whether the device name is
1000 		 * actually an interface index.
1001 		 */
1002 		if (strstr(ebuf, "No such device") != NULL)
1003 			return (NULL);
1004 		error("%s", ebuf);
1005 	}
1006 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1007 	if (Jflag)
1008 		show_tstamp_types_and_exit(pc, device);
1009 #endif
1010 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1011 	status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
1012 	if (status != 0)
1013 		error("%s: Can't set %ssecond time stamp precision: %s",
1014 			device,
1015 			tstamp_precision_to_string(ndo->ndo_tstamp_precision),
1016 			pcap_statustostr(status));
1017 #endif
1018 
1019 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1020 	if (immediate_mode) {
1021 		status = pcap_set_immediate_mode(pc, 1);
1022 		if (status != 0)
1023 			error("%s: Can't set immediate mode: %s",
1024 			device,
1025 			pcap_statustostr(status));
1026 	}
1027 #endif
1028 	/*
1029 	 * Is this an interface that supports monitor mode?
1030 	 */
1031 	if (pcap_can_set_rfmon(pc) == 1)
1032 		supports_monitor_mode = 1;
1033 	else
1034 		supports_monitor_mode = 0;
1035 	status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
1036 	if (status != 0)
1037 		error("%s: Can't set snapshot length: %s",
1038 		    device, pcap_statustostr(status));
1039 	status = pcap_set_promisc(pc, !pflag);
1040 	if (status != 0)
1041 		error("%s: Can't set promiscuous mode: %s",
1042 		    device, pcap_statustostr(status));
1043 	if (Iflag) {
1044 		status = pcap_set_rfmon(pc, 1);
1045 		if (status != 0)
1046 			error("%s: Can't set monitor mode: %s",
1047 			    device, pcap_statustostr(status));
1048 	}
1049 	status = pcap_set_timeout(pc, 1000);
1050 	if (status != 0)
1051 		error("%s: pcap_set_timeout failed: %s",
1052 		    device, pcap_statustostr(status));
1053 	if (Bflag != 0) {
1054 		status = pcap_set_buffer_size(pc, Bflag);
1055 		if (status != 0)
1056 			error("%s: Can't set buffer size: %s",
1057 			    device, pcap_statustostr(status));
1058 	}
1059 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1060 	if (jflag != -1) {
1061 		status = pcap_set_tstamp_type(pc, jflag);
1062 		if (status < 0)
1063 			error("%s: Can't set time stamp type: %s",
1064 		              device, pcap_statustostr(status));
1065 	}
1066 #endif
1067 	status = pcap_activate(pc);
1068 	if (status < 0) {
1069 		/*
1070 		 * pcap_activate() failed.
1071 		 */
1072 		cp = pcap_geterr(pc);
1073 		if (status == PCAP_ERROR)
1074 			error("%s", cp);
1075 		else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1076 			/*
1077 			 * Return an error for our caller to handle.
1078 			 */
1079 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1080 			    device, pcap_statustostr(status), cp);
1081 			pcap_close(pc);
1082 			return (NULL);
1083 		} else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1084 			error("%s: %s\n(%s)", device,
1085 			    pcap_statustostr(status), cp);
1086 #ifdef __FreeBSD__
1087 		else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1088 		    strncmp(device, "wlan", 4) == 0) {
1089 			char parent[8], newdev[8];
1090 			char sysctl[32];
1091 			size_t s = sizeof(parent);
1092 
1093 			snprintf(sysctl, sizeof(sysctl),
1094 			    "net.wlan.%d.%%parent", atoi(device + 4));
1095 			sysctlbyname(sysctl, parent, &s, NULL, 0);
1096 			strlcpy(newdev, device, sizeof(newdev));
1097 			/* Suggest a new wlan device. */
1098 			newdev[strlen(newdev)-1]++;
1099 			error("%s is not a monitor mode VAP\n"
1100 			    "To create a new monitor mode VAP use:\n"
1101 			    "  ifconfig %s create wlandev %s wlanmode monitor\n"
1102 			    "and use %s as the tcpdump interface",
1103 			    device, newdev, parent, newdev);
1104 		}
1105 #endif
1106 		else
1107 			error("%s: %s", device,
1108 			    pcap_statustostr(status));
1109 	} else if (status > 0) {
1110 		/*
1111 		 * pcap_activate() succeeded, but it's warning us
1112 		 * of a problem it had.
1113 		 */
1114 		cp = pcap_geterr(pc);
1115 		if (status == PCAP_WARNING)
1116 			warning("%s", cp);
1117 		else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1118 		         *cp != '\0')
1119 			warning("%s: %s\n(%s)", device,
1120 			    pcap_statustostr(status), cp);
1121 		else
1122 			warning("%s: %s", device,
1123 			    pcap_statustostr(status));
1124 	}
1125 #ifdef HAVE_PCAP_SETDIRECTION
1126 	if (Qflag != -1) {
1127 		status = pcap_setdirection(pc, Qflag);
1128 		if (status != 0)
1129 			error("%s: pcap_setdirection() failed: %s",
1130 			      device,  pcap_geterr(pc));
1131 		}
1132 #endif /* HAVE_PCAP_SETDIRECTION */
1133 #else /* HAVE_PCAP_CREATE */
1134 	*ebuf = '\0';
1135 	pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf);
1136 	if (pc == NULL) {
1137 		/*
1138 		 * If this failed with "No such device", that means
1139 		 * the interface doesn't exist; return NULL, so that
1140 		 * the caller can see whether the device name is
1141 		 * actually an interface index.
1142 		 */
1143 		if (strstr(ebuf, "No such device") != NULL)
1144 			return (NULL);
1145 		error("%s", ebuf);
1146 	}
1147 	if (*ebuf)
1148 		warning("%s", ebuf);
1149 #endif /* HAVE_PCAP_CREATE */
1150 
1151 	return (pc);
1152 }
1153 
1154 int
1155 main(int argc, char **argv)
1156 {
1157 	register int cnt, op, i;
1158 	bpf_u_int32 localnet =0 , netmask = 0;
1159 	int timezone_offset = 0;
1160 	register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1161 	pcap_handler callback;
1162 	int dlt;
1163 	const char *dlt_name;
1164 	struct bpf_program fcode;
1165 #ifndef _WIN32
1166 	RETSIGTYPE (*oldhandler)(int);
1167 #endif
1168 	struct dump_info dumpinfo;
1169 	u_char *pcap_userdata;
1170 	char ebuf[PCAP_ERRBUF_SIZE];
1171 	char VFileLine[PATH_MAX + 1];
1172 	char *username = NULL;
1173 	char *chroot_dir = NULL;
1174 	char *ret = NULL;
1175 	char *end;
1176 #ifdef HAVE_PCAP_FINDALLDEVS
1177 	pcap_if_t *devlist;
1178 	long devnum;
1179 #endif
1180 	int status;
1181 	FILE *VFile;
1182 #ifdef HAVE_CAPSICUM
1183 	cap_rights_t rights;
1184 	int cansandbox;
1185 #endif	/* HAVE_CAPSICUM */
1186 	int Oflag = 1;			/* run filter code optimizer */
1187 	int yflag_dlt = -1;
1188 	const char *yflag_dlt_name = NULL;
1189 
1190 	netdissect_options Ndo;
1191 	netdissect_options *ndo = &Ndo;
1192 
1193 	/*
1194 	 * Initialize the netdissect code.
1195 	 */
1196 	if (nd_init(ebuf, sizeof ebuf) == -1)
1197 		error("%s", ebuf);
1198 
1199 	memset(ndo, 0, sizeof(*ndo));
1200 	ndo_set_function_pointers(ndo);
1201 	ndo->ndo_snaplen = DEFAULT_SNAPLEN;
1202 
1203 	cnt = -1;
1204 	device = NULL;
1205 	infile = NULL;
1206 	RFileName = NULL;
1207 	VFileName = NULL;
1208 	VFile = NULL;
1209 	WFileName = NULL;
1210 	dlt = -1;
1211 	if ((cp = strrchr(argv[0], '/')) != NULL)
1212 		ndo->program_name = program_name = cp + 1;
1213 	else
1214 		ndo->program_name = program_name = argv[0];
1215 
1216 #ifdef _WIN32
1217 	if (pcap_wsockinit() != 0)
1218 		error("Attempting to initialize Winsock failed");
1219 #endif /* _WIN32 */
1220 
1221 	/*
1222 	 * On platforms where the CPU doesn't support unaligned loads,
1223 	 * force unaligned accesses to abort with SIGBUS, rather than
1224 	 * being fixed up (slowly) by the OS kernel; on those platforms,
1225 	 * misaligned accesses are bugs, and we want tcpdump to crash so
1226 	 * that the bugs are reported.
1227 	 */
1228 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1229 		error("%s", ebuf);
1230 
1231 	while (
1232 	    (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1233 		switch (op) {
1234 
1235 		case 'a':
1236 			/* compatibility for old -a */
1237 			break;
1238 
1239 		case 'A':
1240 			++ndo->ndo_Aflag;
1241 			break;
1242 
1243 		case 'b':
1244 			++ndo->ndo_bflag;
1245 			break;
1246 
1247 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1248 		case 'B':
1249 			Bflag = atoi(optarg)*1024;
1250 			if (Bflag <= 0)
1251 				error("invalid packet buffer size %s", optarg);
1252 			break;
1253 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1254 
1255 		case 'c':
1256 			cnt = atoi(optarg);
1257 			if (cnt <= 0)
1258 				error("invalid packet count %s", optarg);
1259 			break;
1260 
1261 		case 'C':
1262 			Cflag = atoi(optarg) * 1000000;
1263 			if (Cflag <= 0)
1264 				error("invalid file size %s", optarg);
1265 			break;
1266 
1267 		case 'd':
1268 			++dflag;
1269 			break;
1270 
1271 		case 'D':
1272 			Dflag++;
1273 			break;
1274 
1275 		case 'L':
1276 			Lflag++;
1277 			break;
1278 
1279 		case 'e':
1280 			++ndo->ndo_eflag;
1281 			break;
1282 
1283 		case 'E':
1284 #ifndef HAVE_LIBCRYPTO
1285 			warning("crypto code not compiled in");
1286 #endif
1287 			ndo->ndo_espsecret = optarg;
1288 			break;
1289 
1290 		case 'f':
1291 			++ndo->ndo_fflag;
1292 			break;
1293 
1294 		case 'F':
1295 			infile = optarg;
1296 			break;
1297 
1298 		case 'G':
1299 			Gflag = atoi(optarg);
1300 			if (Gflag < 0)
1301 				error("invalid number of seconds %s", optarg);
1302 
1303                         /* We will create one file initially. */
1304                         Gflag_count = 0;
1305 
1306 			/* Grab the current time for rotation use. */
1307 			if ((Gflag_time = time(NULL)) == (time_t)-1) {
1308 				error("main: can't get current time: %s",
1309 				    pcap_strerror(errno));
1310 			}
1311 			break;
1312 
1313 		case 'h':
1314 			print_usage();
1315 			exit_tcpdump(0);
1316 			break;
1317 
1318 		case 'H':
1319 			++ndo->ndo_Hflag;
1320 			break;
1321 
1322 		case 'i':
1323 			device = optarg;
1324 			break;
1325 
1326 #ifdef HAVE_PCAP_CREATE
1327 		case 'I':
1328 			++Iflag;
1329 			break;
1330 #endif /* HAVE_PCAP_CREATE */
1331 
1332 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1333 		case 'j':
1334 			jflag = pcap_tstamp_type_name_to_val(optarg);
1335 			if (jflag < 0)
1336 				error("invalid time stamp type %s", optarg);
1337 			break;
1338 
1339 		case 'J':
1340 			Jflag++;
1341 			break;
1342 #endif
1343 
1344 		case 'l':
1345 #ifdef _WIN32
1346 			/*
1347 			 * _IOLBF is the same as _IOFBF in Microsoft's C
1348 			 * libraries; the only alternative they offer
1349 			 * is _IONBF.
1350 			 *
1351 			 * XXX - this should really be checking for MSVC++,
1352 			 * not _WIN32, if, for example, MinGW has its own
1353 			 * C library that is more UNIX-compatible.
1354 			 */
1355 			setvbuf(stdout, NULL, _IONBF, 0);
1356 #else /* _WIN32 */
1357 #ifdef HAVE_SETLINEBUF
1358 			setlinebuf(stdout);
1359 #else
1360 			setvbuf(stdout, NULL, _IOLBF, 0);
1361 #endif
1362 #endif /* _WIN32 */
1363 			break;
1364 
1365 		case 'K':
1366 			++ndo->ndo_Kflag;
1367 			break;
1368 
1369 		case 'm':
1370 			if (nd_have_smi_support()) {
1371 				if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1)
1372 					error("%s", ebuf);
1373 			} else {
1374 				(void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1375 					      program_name, optarg);
1376 				(void)fprintf(stderr, "(no libsmi support)\n");
1377 			}
1378 			break;
1379 
1380 		case 'M':
1381 			/* TCP-MD5 shared secret */
1382 #ifndef HAVE_LIBCRYPTO
1383 			warning("crypto code not compiled in");
1384 #endif
1385 			ndo->ndo_sigsecret = optarg;
1386 			break;
1387 
1388 		case 'n':
1389 			++ndo->ndo_nflag;
1390 			break;
1391 
1392 		case 'N':
1393 			++ndo->ndo_Nflag;
1394 			break;
1395 
1396 		case 'O':
1397 			Oflag = 0;
1398 			break;
1399 
1400 		case 'p':
1401 			++pflag;
1402 			break;
1403 
1404 		case 'q':
1405 			++ndo->ndo_qflag;
1406 			++ndo->ndo_suppress_default_print;
1407 			break;
1408 
1409 #ifdef HAVE_PCAP_SETDIRECTION
1410 		case 'Q':
1411 			if (ascii_strcasecmp(optarg, "in") == 0)
1412 				Qflag = PCAP_D_IN;
1413 			else if (ascii_strcasecmp(optarg, "out") == 0)
1414 				Qflag = PCAP_D_OUT;
1415 			else if (ascii_strcasecmp(optarg, "inout") == 0)
1416 				Qflag = PCAP_D_INOUT;
1417 			else
1418 				error("unknown capture direction `%s'", optarg);
1419 			break;
1420 #endif /* HAVE_PCAP_SETDIRECTION */
1421 
1422 		case 'r':
1423 			RFileName = optarg;
1424 			break;
1425 
1426 		case 's':
1427 			ndo->ndo_snaplen = strtol(optarg, &end, 0);
1428 			if (optarg == end || *end != '\0'
1429 			    || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1430 				error("invalid snaplen %s", optarg);
1431 			else if (ndo->ndo_snaplen == 0)
1432 				ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1433 			break;
1434 
1435 		case 'S':
1436 			++ndo->ndo_Sflag;
1437 			break;
1438 
1439 		case 't':
1440 			++ndo->ndo_tflag;
1441 			break;
1442 
1443 		case 'T':
1444 			if (ascii_strcasecmp(optarg, "vat") == 0)
1445 				ndo->ndo_packettype = PT_VAT;
1446 			else if (ascii_strcasecmp(optarg, "wb") == 0)
1447 				ndo->ndo_packettype = PT_WB;
1448 			else if (ascii_strcasecmp(optarg, "rpc") == 0)
1449 				ndo->ndo_packettype = PT_RPC;
1450 			else if (ascii_strcasecmp(optarg, "rtp") == 0)
1451 				ndo->ndo_packettype = PT_RTP;
1452 			else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1453 				ndo->ndo_packettype = PT_RTCP;
1454 			else if (ascii_strcasecmp(optarg, "snmp") == 0)
1455 				ndo->ndo_packettype = PT_SNMP;
1456 			else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1457 				ndo->ndo_packettype = PT_CNFP;
1458 			else if (ascii_strcasecmp(optarg, "tftp") == 0)
1459 				ndo->ndo_packettype = PT_TFTP;
1460 			else if (ascii_strcasecmp(optarg, "aodv") == 0)
1461 				ndo->ndo_packettype = PT_AODV;
1462 			else if (ascii_strcasecmp(optarg, "carp") == 0)
1463 				ndo->ndo_packettype = PT_CARP;
1464 			else if (ascii_strcasecmp(optarg, "radius") == 0)
1465 				ndo->ndo_packettype = PT_RADIUS;
1466 			else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1467 				ndo->ndo_packettype = PT_ZMTP1;
1468 			else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1469 				ndo->ndo_packettype = PT_VXLAN;
1470 			else if (ascii_strcasecmp(optarg, "pgm") == 0)
1471 				ndo->ndo_packettype = PT_PGM;
1472 			else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1473 				ndo->ndo_packettype = PT_PGM_ZMTP1;
1474 			else if (ascii_strcasecmp(optarg, "lmp") == 0)
1475 				ndo->ndo_packettype = PT_LMP;
1476 			else if (ascii_strcasecmp(optarg, "resp") == 0)
1477 				ndo->ndo_packettype = PT_RESP;
1478 			else
1479 				error("unknown packet type `%s'", optarg);
1480 			break;
1481 
1482 		case 'u':
1483 			++ndo->ndo_uflag;
1484 			break;
1485 
1486 #ifdef HAVE_PCAP_DUMP_FLUSH
1487 		case 'U':
1488 			++Uflag;
1489 			break;
1490 #endif
1491 
1492 		case 'v':
1493 			++ndo->ndo_vflag;
1494 			break;
1495 
1496 		case 'V':
1497 			VFileName = optarg;
1498 			break;
1499 
1500 		case 'w':
1501 			WFileName = optarg;
1502 			break;
1503 
1504 		case 'W':
1505 			Wflag = atoi(optarg);
1506 			if (Wflag <= 0)
1507 				error("invalid number of output files %s", optarg);
1508 			WflagChars = getWflagChars(Wflag);
1509 			break;
1510 
1511 		case 'x':
1512 			++ndo->ndo_xflag;
1513 			++ndo->ndo_suppress_default_print;
1514 			break;
1515 
1516 		case 'X':
1517 			++ndo->ndo_Xflag;
1518 			++ndo->ndo_suppress_default_print;
1519 			break;
1520 
1521 		case 'y':
1522 			yflag_dlt_name = optarg;
1523 			yflag_dlt =
1524 				pcap_datalink_name_to_val(yflag_dlt_name);
1525 			if (yflag_dlt < 0)
1526 				error("invalid data link type %s", yflag_dlt_name);
1527 			break;
1528 
1529 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1530 		case 'Y':
1531 			{
1532 			/* Undocumented flag */
1533 			pcap_set_parser_debug(1);
1534 			}
1535 			break;
1536 #endif
1537 		case 'z':
1538 			zflag = optarg;
1539 			break;
1540 
1541 		case 'Z':
1542 			username = optarg;
1543 			break;
1544 
1545 		case '#':
1546 			ndo->ndo_packet_number = 1;
1547 			break;
1548 
1549 		case OPTION_VERSION:
1550 			print_version();
1551 			exit_tcpdump(0);
1552 			break;
1553 
1554 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1555 		case OPTION_TSTAMP_PRECISION:
1556 			ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1557 			if (ndo->ndo_tstamp_precision < 0)
1558 				error("unsupported time stamp precision");
1559 			break;
1560 #endif
1561 
1562 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1563 		case OPTION_IMMEDIATE_MODE:
1564 			immediate_mode = 1;
1565 			break;
1566 #endif
1567 
1568 		default:
1569 			print_usage();
1570 			exit_tcpdump(1);
1571 			/* NOTREACHED */
1572 		}
1573 
1574 #ifdef HAVE_PCAP_FINDALLDEVS
1575 	if (Dflag)
1576 		show_devices_and_exit();
1577 #endif
1578 
1579 	switch (ndo->ndo_tflag) {
1580 
1581 	case 0: /* Default */
1582 	case 4: /* Default + Date*/
1583 		timezone_offset = gmt2local(0);
1584 		break;
1585 
1586 	case 1: /* No time stamp */
1587 	case 2: /* Unix timeval style */
1588 	case 3: /* Microseconds since previous packet */
1589         case 5: /* Microseconds since first packet */
1590 		break;
1591 
1592 	default: /* Not supported */
1593 		error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1594 		break;
1595 	}
1596 
1597 	if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1598 		error("-f can not be used with -V or -r");
1599 
1600 	if (VFileName != NULL && RFileName != NULL)
1601 		error("-V and -r are mutually exclusive.");
1602 
1603 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1604 	/*
1605 	 * If we're printing dissected packets to the standard output
1606 	 * rather than saving raw packets to a file, and the standard
1607 	 * output is a terminal, use immediate mode, as the user's
1608 	 * probably expecting to see packets pop up immediately.
1609 	 */
1610 	if (WFileName == NULL && isatty(1))
1611 		immediate_mode = 1;
1612 #endif
1613 
1614 #ifdef WITH_CHROOT
1615 	/* if run as root, prepare for chrooting */
1616 	if (getuid() == 0 || geteuid() == 0) {
1617 		/* future extensibility for cmd-line arguments */
1618 		if (!chroot_dir)
1619 			chroot_dir = WITH_CHROOT;
1620 	}
1621 #endif
1622 
1623 #ifdef WITH_USER
1624 	/* if run as root, prepare for dropping root privileges */
1625 	if (getuid() == 0 || geteuid() == 0) {
1626 		/* Run with '-Z root' to restore old behaviour */
1627 		if (!username)
1628 			username = WITH_USER;
1629 	}
1630 #endif
1631 
1632 	if (RFileName != NULL || VFileName != NULL) {
1633 		/*
1634 		 * If RFileName is non-null, it's the pathname of a
1635 		 * savefile to read.  If VFileName is non-null, it's
1636 		 * the pathname of a file containing a list of pathnames
1637 		 * (one per line) of savefiles to read.
1638 		 *
1639 		 * In either case, we're reading a savefile, not doing
1640 		 * a live capture.
1641 		 */
1642 #ifndef _WIN32
1643 		/*
1644 		 * We don't need network access, so relinquish any set-UID
1645 		 * or set-GID privileges we have (if any).
1646 		 *
1647 		 * We do *not* want set-UID privileges when opening a
1648 		 * trace file, as that might let the user read other
1649 		 * people's trace files (especially if we're set-UID
1650 		 * root).
1651 		 */
1652 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1653 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1654 #endif /* _WIN32 */
1655 		if (VFileName != NULL) {
1656 			if (VFileName[0] == '-' && VFileName[1] == '\0')
1657 				VFile = stdin;
1658 			else
1659 				VFile = fopen(VFileName, "r");
1660 
1661 			if (VFile == NULL)
1662 				error("Unable to open file: %s\n", pcap_strerror(errno));
1663 
1664 			ret = get_next_file(VFile, VFileLine);
1665 			if (!ret)
1666 				error("Nothing in %s\n", VFileName);
1667 			RFileName = VFileLine;
1668 		}
1669 
1670 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1671 		pd = pcap_open_offline_with_tstamp_precision(RFileName,
1672 		    ndo->ndo_tstamp_precision, ebuf);
1673 #else
1674 		pd = pcap_open_offline(RFileName, ebuf);
1675 #endif
1676 
1677 		if (pd == NULL)
1678 			error("%s", ebuf);
1679 #ifdef HAVE_CAPSICUM
1680 		cap_rights_init(&rights, CAP_READ);
1681 		if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1682 		    errno != ENOSYS) {
1683 			error("unable to limit pcap descriptor");
1684 		}
1685 #endif
1686 		dlt = pcap_datalink(pd);
1687 		dlt_name = pcap_datalink_val_to_name(dlt);
1688 		if (dlt_name == NULL) {
1689 			fprintf(stderr, "reading from file %s, link-type %u\n",
1690 			    RFileName, dlt);
1691 		} else {
1692 			fprintf(stderr,
1693 			    "reading from file %s, link-type %s (%s)\n",
1694 			    RFileName, dlt_name,
1695 			    pcap_datalink_val_to_description(dlt));
1696 		}
1697 	} else {
1698 		/*
1699 		 * We're doing a live capture.
1700 		 */
1701 		if (device == NULL) {
1702 			/*
1703 			 * No interface was specified.  Pick one.
1704 			 */
1705 #ifdef HAVE_PCAP_FINDALLDEVS
1706 			/*
1707 			 * Find the list of interfaces, and pick
1708 			 * the first interface.
1709 			 */
1710 			if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
1711 			    devlist != NULL) {
1712 				device = strdup(devlist->name);
1713 				pcap_freealldevs(devlist);
1714 			}
1715 #else /* HAVE_PCAP_FINDALLDEVS */
1716 			/*
1717 			 * Use whatever interface pcap_lookupdev()
1718 			 * chooses.
1719 			 */
1720 			device = pcap_lookupdev(ebuf);
1721 #endif
1722 			if (device == NULL)
1723 				error("%s", ebuf);
1724 		}
1725 
1726 		/*
1727 		 * Try to open the interface with the specified name.
1728 		 */
1729 		pd = open_interface(device, ndo, ebuf);
1730 		if (pd == NULL) {
1731 			/*
1732 			 * That failed.  If we can get a list of
1733 			 * interfaces, and the interface name
1734 			 * is purely numeric, try to use it as
1735 			 * a 1-based index in the list of
1736 			 * interfaces.
1737 			 */
1738 #ifdef HAVE_PCAP_FINDALLDEVS
1739 			devnum = parse_interface_number(device);
1740 			if (devnum == -1) {
1741 				/*
1742 				 * It's not a number; just report
1743 				 * the open error and fail.
1744 				 */
1745 				error("%s", ebuf);
1746 			}
1747 
1748 			/*
1749 			 * OK, it's a number; try to find the
1750 			 * interface with that index, and try
1751 			 * to open it.
1752 			 *
1753 			 * find_interface_by_number() exits if it
1754 			 * couldn't be found.
1755 			 */
1756 			device = find_interface_by_number(devnum);
1757 			pd = open_interface(device, ndo, ebuf);
1758 			if (pd == NULL)
1759 				error("%s", ebuf);
1760 #else /* HAVE_PCAP_FINDALLDEVS */
1761 			/*
1762 			 * We can't get a list of interfaces; just
1763 			 * fail.
1764 			 */
1765 			error("%s", ebuf);
1766 #endif /* HAVE_PCAP_FINDALLDEVS */
1767 		}
1768 
1769 		/*
1770 		 * Let user own process after socket has been opened.
1771 		 */
1772 #ifndef _WIN32
1773 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1774 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1775 #endif /* _WIN32 */
1776 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1777 		if(Bflag != 0)
1778 			if(pcap_setbuff(pd, Bflag)==-1){
1779 				error("%s", pcap_geterr(pd));
1780 			}
1781 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1782 		if (Lflag)
1783 			show_dlts_and_exit(pd, device);
1784 		if (yflag_dlt >= 0) {
1785 #ifdef HAVE_PCAP_SET_DATALINK
1786 			if (pcap_set_datalink(pd, yflag_dlt) < 0)
1787 				error("%s", pcap_geterr(pd));
1788 #else
1789 			/*
1790 			 * We don't actually support changing the
1791 			 * data link type, so we only let them
1792 			 * set it to what it already is.
1793 			 */
1794 			if (yflag_dlt != pcap_datalink(pd)) {
1795 				error("%s is not one of the DLTs supported by this device\n",
1796 				      yflag_dlt_name);
1797 			}
1798 #endif
1799 			(void)fprintf(stderr, "%s: data link type %s\n",
1800 				      program_name, yflag_dlt_name);
1801 			(void)fflush(stderr);
1802 		}
1803 		i = pcap_snapshot(pd);
1804 		if (ndo->ndo_snaplen < i) {
1805 			warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1806 			ndo->ndo_snaplen = i;
1807 		}
1808                 if(ndo->ndo_fflag != 0) {
1809                         if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1810                                 warning("foreign (-f) flag used but: %s", ebuf);
1811                         }
1812                 }
1813 
1814 	}
1815 	if (infile)
1816 		cmdbuf = read_infile(infile);
1817 	else
1818 		cmdbuf = copy_argv(&argv[optind]);
1819 
1820 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1821 	pcap_set_optimizer_debug(dflag);
1822 #endif
1823 	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1824 		error("%s", pcap_geterr(pd));
1825 	if (dflag) {
1826 		bpf_dump(&fcode, dflag);
1827 		pcap_close(pd);
1828 		free(cmdbuf);
1829 		pcap_freecode(&fcode);
1830 		exit_tcpdump(0);
1831 	}
1832 
1833 #ifdef HAVE_CASPER
1834 	if (!ndo->ndo_nflag)
1835 		capdns = capdns_setup();
1836 #endif	/* HAVE_CASPER */
1837 
1838 	init_print(ndo, localnet, netmask, timezone_offset);
1839 
1840 #ifndef _WIN32
1841 	(void)setsignal(SIGPIPE, cleanup);
1842 	(void)setsignal(SIGTERM, cleanup);
1843 	(void)setsignal(SIGINT, cleanup);
1844 #endif /* _WIN32 */
1845 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1846 	(void)setsignal(SIGCHLD, child_cleanup);
1847 #endif
1848 	/* Cooperate with nohup(1) */
1849 #ifndef _WIN32
1850 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1851 		(void)setsignal(SIGHUP, oldhandler);
1852 #endif /* _WIN32 */
1853 
1854 #ifndef _WIN32
1855 	/*
1856 	 * If a user name was specified with "-Z", attempt to switch to
1857 	 * that user's UID.  This would probably be used with sudo,
1858 	 * to allow tcpdump to be run in a special restricted
1859 	 * account (if you just want to allow users to open capture
1860 	 * devices, and can't just give users that permission,
1861 	 * you'd make tcpdump set-UID or set-GID).
1862 	 *
1863 	 * Tcpdump doesn't necessarily write only to one savefile;
1864 	 * the general only way to allow a -Z instance to write to
1865 	 * savefiles as the user under whose UID it's run, rather
1866 	 * than as the user specified with -Z, would thus be to switch
1867 	 * to the original user ID before opening a capture file and
1868 	 * then switch back to the -Z user ID after opening the savefile.
1869 	 * Switching to the -Z user ID only after opening the first
1870 	 * savefile doesn't handle the general case.
1871 	 */
1872 
1873 	if (getuid() == 0 || geteuid() == 0) {
1874 #ifdef HAVE_LIBCAP_NG
1875 		/* Initialize capng */
1876 		capng_clear(CAPNG_SELECT_BOTH);
1877 		if (username) {
1878 			capng_updatev(
1879 				CAPNG_ADD,
1880 				CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1881 				CAP_SETUID,
1882 				CAP_SETGID,
1883 				-1);
1884 		}
1885 		if (chroot_dir) {
1886 			capng_update(
1887 				CAPNG_ADD,
1888 				CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1889 				CAP_SYS_CHROOT
1890 				);
1891 		}
1892 
1893 		if (WFileName) {
1894 			capng_update(
1895 				CAPNG_ADD,
1896 				CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1897 				CAP_DAC_OVERRIDE
1898 				);
1899 		}
1900 		capng_apply(CAPNG_SELECT_BOTH);
1901 #endif /* HAVE_LIBCAP_NG */
1902 		if (username || chroot_dir)
1903 			droproot(username, chroot_dir);
1904 
1905 	}
1906 #endif /* _WIN32 */
1907 
1908 	if (pcap_setfilter(pd, &fcode) < 0)
1909 		error("%s", pcap_geterr(pd));
1910 #ifdef HAVE_CAPSICUM
1911 	if (RFileName == NULL && VFileName == NULL) {
1912 		static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1913 
1914 		/*
1915 		 * The various libpcap devices use a combination of
1916 		 * read (bpf), ioctl (bpf, netmap), poll (netmap)
1917 		 * so we add the relevant access rights.
1918 		 */
1919 		cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
1920 		if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1921 		    errno != ENOSYS) {
1922 			error("unable to limit pcap descriptor");
1923 		}
1924 		if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1925 		    sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1926 			error("unable to limit ioctls on pcap descriptor");
1927 		}
1928 	}
1929 #endif
1930 	if (WFileName) {
1931 		pcap_dumper_t *p;
1932 		/* Do not exceed the default PATH_MAX for files. */
1933 		dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1934 
1935 		if (dumpinfo.CurrentFileName == NULL)
1936 			error("malloc of dumpinfo.CurrentFileName");
1937 
1938 		/* We do not need numbering for dumpfiles if Cflag isn't set. */
1939 		if (Cflag != 0)
1940 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1941 		else
1942 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1943 
1944 		p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1945 #ifdef HAVE_LIBCAP_NG
1946 		/* Give up CAP_DAC_OVERRIDE capability.
1947 		 * Only allow it to be restored if the -C or -G flag have been
1948 		 * set since we may need to create more files later on.
1949 		 */
1950 		capng_update(
1951 			CAPNG_DROP,
1952 			(Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1953 				| CAPNG_EFFECTIVE,
1954 			CAP_DAC_OVERRIDE
1955 			);
1956 		capng_apply(CAPNG_SELECT_BOTH);
1957 #endif /* HAVE_LIBCAP_NG */
1958 		if (p == NULL)
1959 			error("%s", pcap_geterr(pd));
1960 #ifdef HAVE_CAPSICUM
1961 		set_dumper_capsicum_rights(p);
1962 #endif
1963 		if (Cflag != 0 || Gflag != 0) {
1964 #ifdef HAVE_CAPSICUM
1965 			dumpinfo.WFileName = strdup(basename(WFileName));
1966 			if (dumpinfo.WFileName == NULL) {
1967 				error("Unable to allocate memory for file %s",
1968 				    WFileName);
1969 			}
1970 			dumpinfo.dirfd = open(dirname(WFileName),
1971 			    O_DIRECTORY | O_RDONLY);
1972 			if (dumpinfo.dirfd < 0) {
1973 				error("unable to open directory %s",
1974 				    dirname(WFileName));
1975 			}
1976 			cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1977 			    CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1978 			if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1979 			    errno != ENOSYS) {
1980 				error("unable to limit directory rights");
1981 			}
1982 			if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1983 			    errno != ENOSYS) {
1984 				error("unable to limit dump descriptor fcntls");
1985 			}
1986 #else	/* !HAVE_CAPSICUM */
1987 			dumpinfo.WFileName = WFileName;
1988 #endif
1989 			callback = dump_packet_and_trunc;
1990 			dumpinfo.pd = pd;
1991 			dumpinfo.p = p;
1992 			pcap_userdata = (u_char *)&dumpinfo;
1993 		} else {
1994 			callback = dump_packet;
1995 			pcap_userdata = (u_char *)p;
1996 		}
1997 #ifdef HAVE_PCAP_DUMP_FLUSH
1998 		if (Uflag)
1999 			pcap_dump_flush(p);
2000 #endif
2001 	} else {
2002 		dlt = pcap_datalink(pd);
2003 		ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2004 		callback = print_packet;
2005 		pcap_userdata = (u_char *)ndo;
2006 	}
2007 
2008 #ifdef SIGNAL_REQ_INFO
2009 	/*
2010 	 * We can't get statistics when reading from a file rather
2011 	 * than capturing from a device.
2012 	 */
2013 	if (RFileName == NULL)
2014 		(void)setsignal(SIGNAL_REQ_INFO, requestinfo);
2015 #endif
2016 
2017 	if (ndo->ndo_vflag > 0 && WFileName) {
2018 		/*
2019 		 * When capturing to a file, "-v" means tcpdump should,
2020 		 * every 10 seconds, "v"erbosely report the number of
2021 		 * packets captured.
2022 		 */
2023 #ifdef USE_WIN32_MM_TIMER
2024 		/* call verbose_stats_dump() each 1000 +/-100msec */
2025 		timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
2026 		setvbuf(stderr, NULL, _IONBF, 0);
2027 #elif defined(HAVE_ALARM)
2028 		(void)setsignal(SIGALRM, verbose_stats_dump);
2029 		alarm(1);
2030 #endif
2031 	}
2032 
2033 	if (RFileName == NULL) {
2034 		/*
2035 		 * Live capture (if -V was specified, we set RFileName
2036 		 * to a file from the -V file).  Print a message to
2037 		 * the standard error on UN*X.
2038 		 */
2039 		if (!ndo->ndo_vflag && !WFileName) {
2040 			(void)fprintf(stderr,
2041 			    "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
2042 			    program_name);
2043 		} else
2044 			(void)fprintf(stderr, "%s: ", program_name);
2045 		dlt = pcap_datalink(pd);
2046 		dlt_name = pcap_datalink_val_to_name(dlt);
2047 		if (dlt_name == NULL) {
2048 			(void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
2049 			    device, dlt, ndo->ndo_snaplen);
2050 		} else {
2051 			(void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2052 			    device, dlt_name,
2053 			    pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
2054 		}
2055 		(void)fflush(stderr);
2056 	}
2057 
2058 #ifdef HAVE_CAPSICUM
2059 	cansandbox = (VFileName == NULL && zflag == NULL);
2060 #ifdef HAVE_CASPER
2061 	cansandbox = (cansandbox && (ndo->ndo_nflag || capdns != NULL));
2062 #else
2063 	cansandbox = (cansandbox && ndo->ndo_nflag);
2064 #endif	/* HAVE_CASPER */
2065 	if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2066 		error("unable to enter the capability mode");
2067 #endif	/* HAVE_CAPSICUM */
2068 
2069 	do {
2070 		status = pcap_loop(pd, cnt, callback, pcap_userdata);
2071 		if (WFileName == NULL) {
2072 			/*
2073 			 * We're printing packets.  Flush the printed output,
2074 			 * so it doesn't get intermingled with error output.
2075 			 */
2076 			if (status == -2) {
2077 				/*
2078 				 * We got interrupted, so perhaps we didn't
2079 				 * manage to finish a line we were printing.
2080 				 * Print an extra newline, just in case.
2081 				 */
2082 				putchar('\n');
2083 			}
2084 			(void)fflush(stdout);
2085 		}
2086                 if (status == -2) {
2087 			/*
2088 			 * We got interrupted. If we are reading multiple
2089 			 * files (via -V) set these so that we stop.
2090 			 */
2091 			VFileName = NULL;
2092 			ret = NULL;
2093 		}
2094 		if (status == -1) {
2095 			/*
2096 			 * Error.  Report it.
2097 			 */
2098 			(void)fprintf(stderr, "%s: pcap_loop: %s\n",
2099 			    program_name, pcap_geterr(pd));
2100 		}
2101 		if (RFileName == NULL) {
2102 			/*
2103 			 * We're doing a live capture.  Report the capture
2104 			 * statistics.
2105 			 */
2106 			info(1);
2107 		}
2108 		pcap_close(pd);
2109 		if (VFileName != NULL) {
2110 			ret = get_next_file(VFile, VFileLine);
2111 			if (ret) {
2112 				int new_dlt;
2113 
2114 				RFileName = VFileLine;
2115 				pd = pcap_open_offline(RFileName, ebuf);
2116 				if (pd == NULL)
2117 					error("%s", ebuf);
2118 #ifdef HAVE_CAPSICUM
2119 				cap_rights_init(&rights, CAP_READ);
2120 				if (cap_rights_limit(fileno(pcap_file(pd)),
2121 				    &rights) < 0 && errno != ENOSYS) {
2122 					error("unable to limit pcap descriptor");
2123 				}
2124 #endif
2125 				new_dlt = pcap_datalink(pd);
2126 				if (new_dlt != dlt) {
2127 					/*
2128 					 * The new file has a different
2129 					 * link-layer header type from the
2130 					 * previous one.
2131 					 */
2132 					if (WFileName != NULL) {
2133 						/*
2134 						 * We're writing raw packets
2135 						 * that match the filter to
2136 						 * a pcap file.  pcap files
2137 						 * don't support multiple
2138 						 * different link-layer
2139 						 * header types, so we fail
2140 						 * here.
2141 						 */
2142 						error("%s: new dlt does not match original", RFileName);
2143 					}
2144 
2145 					/*
2146 					 * We're printing the decoded packets;
2147 					 * switch to the new DLT.
2148 					 *
2149 					 * To do that, we need to change
2150 					 * the printer, change the DLT name,
2151 					 * and recompile the filter with
2152 					 * the new DLT.
2153 					 */
2154 					dlt = new_dlt;
2155 					ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2156 					if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2157 						error("%s", pcap_geterr(pd));
2158 				}
2159 
2160 				/*
2161 				 * Set the filter on the new file.
2162 				 */
2163 				if (pcap_setfilter(pd, &fcode) < 0)
2164 					error("%s", pcap_geterr(pd));
2165 
2166 				/*
2167 				 * Report the new file.
2168 				 */
2169 				dlt_name = pcap_datalink_val_to_name(dlt);
2170 				if (dlt_name == NULL) {
2171 					fprintf(stderr, "reading from file %s, link-type %u\n",
2172 					    RFileName, dlt);
2173 				} else {
2174 					fprintf(stderr,
2175 					"reading from file %s, link-type %s (%s)\n",
2176 					    RFileName, dlt_name,
2177 					    pcap_datalink_val_to_description(dlt));
2178 				}
2179 			}
2180 		}
2181 	}
2182 	while (ret != NULL);
2183 
2184 	free(cmdbuf);
2185 	pcap_freecode(&fcode);
2186 	exit_tcpdump(status == -1 ? 1 : 0);
2187 }
2188 
2189 /* make a clean exit on interrupts */
2190 static RETSIGTYPE
2191 cleanup(int signo _U_)
2192 {
2193 #ifdef USE_WIN32_MM_TIMER
2194 	if (timer_id)
2195 		timeKillEvent(timer_id);
2196 	timer_id = 0;
2197 #elif defined(HAVE_ALARM)
2198 	alarm(0);
2199 #endif
2200 
2201 #ifdef HAVE_PCAP_BREAKLOOP
2202 	/*
2203 	 * We have "pcap_breakloop()"; use it, so that we do as little
2204 	 * as possible in the signal handler (it's probably not safe
2205 	 * to do anything with standard I/O streams in a signal handler -
2206 	 * the ANSI C standard doesn't say it is).
2207 	 */
2208 	pcap_breakloop(pd);
2209 #else
2210 	/*
2211 	 * We don't have "pcap_breakloop()"; this isn't safe, but
2212 	 * it's the best we can do.  Print the summary if we're
2213 	 * not reading from a savefile - i.e., if we're doing a
2214 	 * live capture - and exit.
2215 	 */
2216 	if (pd != NULL && pcap_file(pd) == NULL) {
2217 		/*
2218 		 * We got interrupted, so perhaps we didn't
2219 		 * manage to finish a line we were printing.
2220 		 * Print an extra newline, just in case.
2221 		 */
2222 		putchar('\n');
2223 		(void)fflush(stdout);
2224 		info(1);
2225 	}
2226 	exit_tcpdump(0);
2227 #endif
2228 }
2229 
2230 /*
2231   On windows, we do not use a fork, so we do not care less about
2232   waiting a child processes to die
2233  */
2234 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2235 static RETSIGTYPE
2236 child_cleanup(int signo _U_)
2237 {
2238   wait(NULL);
2239 }
2240 #endif /* HAVE_FORK && HAVE_VFORK */
2241 
2242 static void
2243 info(register int verbose)
2244 {
2245 	struct pcap_stat stats;
2246 
2247 	/*
2248 	 * Older versions of libpcap didn't set ps_ifdrop on some
2249 	 * platforms; initialize it to 0 to handle that.
2250 	 */
2251 	stats.ps_ifdrop = 0;
2252 	if (pcap_stats(pd, &stats) < 0) {
2253 		(void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2254 		infoprint = 0;
2255 		return;
2256 	}
2257 
2258 	if (!verbose)
2259 		fprintf(stderr, "%s: ", program_name);
2260 
2261 	(void)fprintf(stderr, "%u packet%s captured", packets_captured,
2262 	    PLURAL_SUFFIX(packets_captured));
2263 	if (!verbose)
2264 		fputs(", ", stderr);
2265 	else
2266 		putc('\n', stderr);
2267 	(void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
2268 	    PLURAL_SUFFIX(stats.ps_recv));
2269 	if (!verbose)
2270 		fputs(", ", stderr);
2271 	else
2272 		putc('\n', stderr);
2273 	(void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
2274 	    PLURAL_SUFFIX(stats.ps_drop));
2275 	if (stats.ps_ifdrop != 0) {
2276 		if (!verbose)
2277 			fputs(", ", stderr);
2278 		else
2279 			putc('\n', stderr);
2280 		(void)fprintf(stderr, "%u packet%s dropped by interface\n",
2281 		    stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
2282 	} else
2283 		putc('\n', stderr);
2284 	infoprint = 0;
2285 }
2286 
2287 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2288 #ifdef HAVE_FORK
2289 #define fork_subprocess() fork()
2290 #else
2291 #define fork_subprocess() vfork()
2292 #endif
2293 static void
2294 compress_savefile(const char *filename)
2295 {
2296 	pid_t child;
2297 
2298 	child = fork_subprocess();
2299 	if (child == -1) {
2300 		fprintf(stderr,
2301 			"compress_savefile: fork failed: %s\n",
2302 			pcap_strerror(errno));
2303 		return;
2304 	}
2305 	if (child != 0) {
2306 		/* Parent process. */
2307 		return;
2308 	}
2309 
2310 	/*
2311 	 * Child process.
2312 	 * Set to lowest priority so that this doesn't disturb the capture.
2313 	 */
2314 #ifdef NZERO
2315 	setpriority(PRIO_PROCESS, 0, NZERO - 1);
2316 #else
2317 	setpriority(PRIO_PROCESS, 0, 19);
2318 #endif
2319 	if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2320 		fprintf(stderr,
2321 			"compress_savefile: execlp(%s, %s) failed: %s\n",
2322 			zflag,
2323 			filename,
2324 			pcap_strerror(errno));
2325 #ifdef HAVE_FORK
2326 	exit(1);
2327 #else
2328 	_exit(1);
2329 #endif
2330 }
2331 #else  /* HAVE_FORK && HAVE_VFORK */
2332 static void
2333 compress_savefile(const char *filename)
2334 {
2335 	fprintf(stderr,
2336 		"compress_savefile failed. Functionality not implemented under your system\n");
2337 }
2338 #endif /* HAVE_FORK && HAVE_VFORK */
2339 
2340 static void
2341 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2342 {
2343 	struct dump_info *dump_info;
2344 
2345 	++packets_captured;
2346 
2347 	++infodelay;
2348 
2349 	dump_info = (struct dump_info *)user;
2350 
2351 	/*
2352 	 * XXX - this won't force the file to rotate on the specified time
2353 	 * boundary, but it will rotate on the first packet received after the
2354 	 * specified Gflag number of seconds. Note: if a Gflag time boundary
2355 	 * and a Cflag size boundary coincide, the time rotation will occur
2356 	 * first thereby cancelling the Cflag boundary (since the file should
2357 	 * be 0).
2358 	 */
2359 	if (Gflag != 0) {
2360 		/* Check if it is time to rotate */
2361 		time_t t;
2362 
2363 		/* Get the current time */
2364 		if ((t = time(NULL)) == (time_t)-1) {
2365 			error("dump_and_trunc_packet: can't get current_time: %s",
2366 			    pcap_strerror(errno));
2367 		}
2368 
2369 
2370 		/* If the time is greater than the specified window, rotate */
2371 		if (t - Gflag_time >= Gflag) {
2372 #ifdef HAVE_CAPSICUM
2373 			FILE *fp;
2374 			int fd;
2375 #endif
2376 
2377 			/* Update the Gflag_time */
2378 			Gflag_time = t;
2379 			/* Update Gflag_count */
2380 			Gflag_count++;
2381 			/*
2382 			 * Close the current file and open a new one.
2383 			 */
2384 			pcap_dump_close(dump_info->p);
2385 
2386 			/*
2387 			 * Compress the file we just closed, if the user asked for it
2388 			 */
2389 			if (zflag != NULL)
2390 				compress_savefile(dump_info->CurrentFileName);
2391 
2392 			/*
2393 			 * Check to see if we've exceeded the Wflag (when
2394 			 * not using Cflag).
2395 			 */
2396 			if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2397 				(void)fprintf(stderr, "Maximum file limit reached: %d\n",
2398 				    Wflag);
2399 				info(1);
2400 				exit_tcpdump(0);
2401 				/* NOTREACHED */
2402 			}
2403 			if (dump_info->CurrentFileName != NULL)
2404 				free(dump_info->CurrentFileName);
2405 			/* Allocate space for max filename + \0. */
2406 			dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2407 			if (dump_info->CurrentFileName == NULL)
2408 				error("dump_packet_and_trunc: malloc");
2409 			/*
2410 			 * Gflag was set otherwise we wouldn't be here. Reset the count
2411 			 * so multiple files would end with 1,2,3 in the filename.
2412 			 * The counting is handled with the -C flow after this.
2413 			 */
2414 			Cflag_count = 0;
2415 
2416 			/*
2417 			 * This is always the first file in the Cflag
2418 			 * rotation: e.g. 0
2419 			 * We also don't need numbering if Cflag is not set.
2420 			 */
2421 			if (Cflag != 0)
2422 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2423 				    WflagChars);
2424 			else
2425 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2426 
2427 #ifdef HAVE_LIBCAP_NG
2428 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2429 			capng_apply(CAPNG_SELECT_BOTH);
2430 #endif /* HAVE_LIBCAP_NG */
2431 #ifdef HAVE_CAPSICUM
2432 			fd = openat(dump_info->dirfd,
2433 			    dump_info->CurrentFileName,
2434 			    O_CREAT | O_WRONLY | O_TRUNC, 0644);
2435 			if (fd < 0) {
2436 				error("unable to open file %s",
2437 				    dump_info->CurrentFileName);
2438 			}
2439 			fp = fdopen(fd, "w");
2440 			if (fp == NULL) {
2441 				error("unable to fdopen file %s",
2442 				    dump_info->CurrentFileName);
2443 			}
2444 			dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2445 #else	/* !HAVE_CAPSICUM */
2446 			dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2447 #endif
2448 #ifdef HAVE_LIBCAP_NG
2449 			capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2450 			capng_apply(CAPNG_SELECT_BOTH);
2451 #endif /* HAVE_LIBCAP_NG */
2452 			if (dump_info->p == NULL)
2453 				error("%s", pcap_geterr(pd));
2454 #ifdef HAVE_CAPSICUM
2455 			set_dumper_capsicum_rights(dump_info->p);
2456 #endif
2457 		}
2458 	}
2459 
2460 	/*
2461 	 * XXX - this won't prevent capture files from getting
2462 	 * larger than Cflag - the last packet written to the
2463 	 * file could put it over Cflag.
2464 	 */
2465 	if (Cflag != 0) {
2466 		long size = pcap_dump_ftell(dump_info->p);
2467 
2468 		if (size == -1)
2469 			error("ftell fails on output file");
2470 		if (size > Cflag) {
2471 #ifdef HAVE_CAPSICUM
2472 			FILE *fp;
2473 			int fd;
2474 #endif
2475 
2476 			/*
2477 			 * Close the current file and open a new one.
2478 			 */
2479 			pcap_dump_close(dump_info->p);
2480 
2481 			/*
2482 			 * Compress the file we just closed, if the user
2483 			 * asked for it.
2484 			 */
2485 			if (zflag != NULL)
2486 				compress_savefile(dump_info->CurrentFileName);
2487 
2488 			Cflag_count++;
2489 			if (Wflag > 0) {
2490 				if (Cflag_count >= Wflag)
2491 					Cflag_count = 0;
2492 			}
2493 			if (dump_info->CurrentFileName != NULL)
2494 				free(dump_info->CurrentFileName);
2495 			dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2496 			if (dump_info->CurrentFileName == NULL)
2497 				error("dump_packet_and_trunc: malloc");
2498 			MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2499 #ifdef HAVE_LIBCAP_NG
2500 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2501 			capng_apply(CAPNG_SELECT_BOTH);
2502 #endif /* HAVE_LIBCAP_NG */
2503 #ifdef HAVE_CAPSICUM
2504 			fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2505 			    O_CREAT | O_WRONLY | O_TRUNC, 0644);
2506 			if (fd < 0) {
2507 				error("unable to open file %s",
2508 				    dump_info->CurrentFileName);
2509 			}
2510 			fp = fdopen(fd, "w");
2511 			if (fp == NULL) {
2512 				error("unable to fdopen file %s",
2513 				    dump_info->CurrentFileName);
2514 			}
2515 			dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2516 #else	/* !HAVE_CAPSICUM */
2517 			dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2518 #endif
2519 #ifdef HAVE_LIBCAP_NG
2520 			capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2521 			capng_apply(CAPNG_SELECT_BOTH);
2522 #endif /* HAVE_LIBCAP_NG */
2523 			if (dump_info->p == NULL)
2524 				error("%s", pcap_geterr(pd));
2525 #ifdef HAVE_CAPSICUM
2526 			set_dumper_capsicum_rights(dump_info->p);
2527 #endif
2528 		}
2529 	}
2530 
2531 	pcap_dump((u_char *)dump_info->p, h, sp);
2532 #ifdef HAVE_PCAP_DUMP_FLUSH
2533 	if (Uflag)
2534 		pcap_dump_flush(dump_info->p);
2535 #endif
2536 
2537 	--infodelay;
2538 	if (infoprint)
2539 		info(0);
2540 }
2541 
2542 static void
2543 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2544 {
2545 	++packets_captured;
2546 
2547 	++infodelay;
2548 
2549 	pcap_dump(user, h, sp);
2550 #ifdef HAVE_PCAP_DUMP_FLUSH
2551 	if (Uflag)
2552 		pcap_dump_flush((pcap_dumper_t *)user);
2553 #endif
2554 
2555 	--infodelay;
2556 	if (infoprint)
2557 		info(0);
2558 }
2559 
2560 static void
2561 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2562 {
2563 	++packets_captured;
2564 
2565 	++infodelay;
2566 
2567 	pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2568 
2569 	--infodelay;
2570 	if (infoprint)
2571 		info(0);
2572 }
2573 
2574 #ifdef _WIN32
2575 	/*
2576 	 * XXX - there should really be libpcap calls to get the version
2577 	 * number as a string (the string would be generated from #defines
2578 	 * at run time, so that it's not generated from string constants
2579 	 * in the library, as, on many UNIX systems, those constants would
2580 	 * be statically linked into the application executable image, and
2581 	 * would thus reflect the version of libpcap on the system on
2582 	 * which the application was *linked*, not the system on which it's
2583 	 * *running*.
2584 	 *
2585 	 * That routine should be documented, unlike the "version[]"
2586 	 * string, so that UNIX vendors providing their own libpcaps
2587 	 * don't omit it (as a couple of vendors have...).
2588 	 *
2589 	 * Packet.dll should perhaps also export a routine to return the
2590 	 * version number of the Packet.dll code, to supply the
2591 	 * "Wpcap_version" information on Windows.
2592 	 */
2593 	char WDversion[]="current-git.tcpdump.org";
2594 #if !defined(HAVE_GENERATED_VERSION)
2595 	char version[]="current-git.tcpdump.org";
2596 #endif
2597 	char pcap_version[]="current-git.tcpdump.org";
2598 	char Wpcap_version[]="3.1";
2599 #endif
2600 
2601 #ifdef SIGNAL_REQ_INFO
2602 RETSIGTYPE requestinfo(int signo _U_)
2603 {
2604 	if (infodelay)
2605 		++infoprint;
2606 	else
2607 		info(0);
2608 }
2609 #endif
2610 
2611 /*
2612  * Called once each second in verbose mode while dumping to file
2613  */
2614 #ifdef USE_WIN32_MM_TIMER
2615 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2616 				  DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2617 {
2618 	if (infodelay == 0)
2619 		fprintf(stderr, "Got %u\r", packets_captured);
2620 }
2621 #elif defined(HAVE_ALARM)
2622 static void verbose_stats_dump(int sig _U_)
2623 {
2624 	if (infodelay == 0)
2625 		fprintf(stderr, "Got %u\r", packets_captured);
2626 	alarm(1);
2627 }
2628 #endif
2629 
2630 USES_APPLE_DEPRECATED_API
2631 static void
2632 print_version(void)
2633 {
2634 	extern char version[];
2635 #ifndef HAVE_PCAP_LIB_VERSION
2636 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2637 	extern char pcap_version[];
2638 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2639 	static char pcap_version[] = "unknown";
2640 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2641 #endif /* HAVE_PCAP_LIB_VERSION */
2642 	const char *smi_version_string;
2643 
2644 #ifdef HAVE_PCAP_LIB_VERSION
2645 #ifdef _WIN32
2646 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2647 #else /* _WIN32 */
2648 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
2649 #endif /* _WIN32 */
2650 	(void)fprintf(stderr, "%s\n",pcap_lib_version());
2651 #else /* HAVE_PCAP_LIB_VERSION */
2652 #ifdef _WIN32
2653 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2654 	(void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2655 #else /* _WIN32 */
2656 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
2657 	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2658 #endif /* _WIN32 */
2659 #endif /* HAVE_PCAP_LIB_VERSION */
2660 
2661 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2662 	(void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2663 #endif
2664 
2665 	smi_version_string = nd_smi_version_string();
2666 	if (smi_version_string != NULL)
2667 		(void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2668 
2669 #if defined(__SANITIZE_ADDRESS__)
2670 	(void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n");
2671 #elif defined(__has_feature)
2672 #  if __has_feature(address_sanitizer)
2673 	(void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n");
2674 #  endif
2675 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2676 }
2677 USES_APPLE_RST
2678 
2679 static void
2680 print_usage(void)
2681 {
2682 	print_version();
2683 	(void)fprintf(stderr,
2684 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2685 	(void)fprintf(stderr,
2686 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2687 	(void)fprintf(stderr,
2688 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2689 #ifdef HAVE_PCAP_SETDIRECTION
2690 	(void)fprintf(stderr,
2691 "\t\t[ -Q in|out|inout ]\n");
2692 #endif
2693 	(void)fprintf(stderr,
2694 "\t\t[ -r file ] [ -s snaplen ] ");
2695 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2696 	(void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2697 	(void)fprintf(stderr,
2698 "\t\t");
2699 #endif
2700 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2701 	(void)fprintf(stderr, "[ --immediate-mode ] ");
2702 #endif
2703 	(void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2704 	(void)fprintf(stderr,
2705 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2706 	(void)fprintf(stderr,
2707 "\t\t[ -Z user ] [ expression ]\n");
2708 }
2709 /*
2710  * Local Variables:
2711  * c-style: whitesmith
2712  * c-basic-offset: 8
2713  * End:
2714  */
2715