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