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