xref: /netbsd-src/external/bsd/tcpdump/dist/tcpdump.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
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.18 2019/10/01 16:06:16 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 				error("capng_change_id(): return %d\n", ret);
625 			else
626 				fprintf(stderr, "dropped privs to %s\n", username);
627 		}
628 #else
629 		if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
630 		    setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
631 			fprintf(stderr, "%s: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
632 				program_name, username,
633 				(unsigned long)pw->pw_uid,
634 				(unsigned long)pw->pw_gid,
635 				pcap_strerror(errno));
636 			exit_tcpdump(1);
637 		}
638 		else {
639 //			fprintf(stderr, "dropped privs to %s\n", username);
640 		}
641 #endif /* HAVE_LIBCAP_NG */
642 	}
643 	else {
644 		fprintf(stderr, "%s: Couldn't find user '%.32s'\n",
645 			program_name, username);
646 		exit_tcpdump(1);
647 	}
648 #ifdef HAVE_LIBCAP_NG
649 	/* We don't need CAP_SETUID, CAP_SETGID and CAP_SYS_CHROOT any more. */
650 	capng_updatev(
651 		CAPNG_DROP,
652 		CAPNG_EFFECTIVE | CAPNG_PERMITTED,
653 		CAP_SETUID,
654 		CAP_SETGID,
655 		CAP_SYS_CHROOT,
656 		-1);
657 	capng_apply(CAPNG_SELECT_BOTH);
658 #endif /* HAVE_LIBCAP_NG */
659 
660 }
661 #endif /* _WIN32 */
662 
663 static int
664 getWflagChars(int x)
665 {
666 	int c = 0;
667 
668 	x -= 1;
669 	while (x > 0) {
670 		c += 1;
671 		x /= 10;
672 	}
673 
674 	return c;
675 }
676 
677 
678 static void
679 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
680 {
681         char *filename = malloc(PATH_MAX + 1);
682         if (filename == NULL)
683             error("Makefilename: malloc");
684 
685         /* Process with strftime if Gflag is set. */
686         if (Gflag != 0) {
687           struct tm *local_tm;
688 
689           /* Convert Gflag_time to a usable format */
690           if ((local_tm = localtime(&Gflag_time)) == NULL) {
691                   error("MakeTimedFilename: localtime");
692           }
693 
694           /* There's no good way to detect an error in strftime since a return
695            * value of 0 isn't necessarily failure.
696            */
697           strftime(filename, PATH_MAX, orig_name, local_tm);
698         } else {
699           strncpy(filename, orig_name, PATH_MAX);
700         }
701 
702 	if (cnt == 0 && max_chars == 0)
703 		strncpy(buffer, filename, PATH_MAX + 1);
704 	else
705 		if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
706                   /* Report an error if the filename is too large */
707                   error("too many output files or filename is too long (> %d)", PATH_MAX);
708         free(filename);
709 }
710 
711 static char *
712 get_next_file(FILE *VFile, char *ptr)
713 {
714 	char *ret;
715 	size_t len;
716 
717 	ret = fgets(ptr, PATH_MAX, VFile);
718 	if (!ret)
719 		return NULL;
720 
721 	len = strlen (ptr);
722 	if (len > 0 && ptr[len - 1] == '\n')
723 		ptr[len - 1] = '\0';
724 
725 	return ret;
726 }
727 
728 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
729 static int
730 tstamp_precision_from_string(const char *precision)
731 {
732 	if (strncmp(precision, "nano", strlen("nano")) == 0)
733 		return PCAP_TSTAMP_PRECISION_NANO;
734 
735 	if (strncmp(precision, "micro", strlen("micro")) == 0)
736 		return PCAP_TSTAMP_PRECISION_MICRO;
737 
738 	return -EINVAL;
739 }
740 
741 static const char *
742 tstamp_precision_to_string(int precision)
743 {
744 	switch (precision) {
745 
746 	case PCAP_TSTAMP_PRECISION_MICRO:
747 		return "micro";
748 
749 	case PCAP_TSTAMP_PRECISION_NANO:
750 		return "nano";
751 
752 	default:
753 		return "unknown";
754 	}
755 }
756 #endif
757 
758 #ifdef HAVE_CAPSICUM
759 /*
760  * Ensure that, on a dump file's descriptor, we have all the rights
761  * necessary to make the standard I/O library work with an fdopen()ed
762  * FILE * from that descriptor.
763  *
764  * A long time ago, in a galaxy far far away, AT&T decided that, instead
765  * of providing separate APIs for getting and setting the FD_ flags on a
766  * descriptor, getting and setting the O_ flags on a descriptor, and
767  * locking files, they'd throw them all into a kitchen-sink fcntl() call
768  * along the lines of ioctl(), the fact that ioctl() operations are
769  * largely specific to particular character devices but fcntl() operations
770  * are either generic to all descriptors or generic to all descriptors for
771  * regular files nonwithstanding.
772  *
773  * The Capsicum people decided that fine-grained control of descriptor
774  * operations was required, so that you need to grant permission for
775  * reading, writing, seeking, and fcntl-ing.  The latter, courtesy of
776  * AT&T's decision, means that "fcntl-ing" isn't a thing, but a motley
777  * collection of things, so there are *individual* fcntls for which
778  * permission needs to be granted.
779  *
780  * The FreeBSD standard I/O people implemented some optimizations that
781  * requires that the standard I/O routines be able to determine whether
782  * the descriptor for the FILE * is open append-only or not; as that
783  * descriptor could have come from an open() rather than an fopen(),
784  * that requires that it be able to do an F_GETFL fcntl() to read
785  * the O_ flags.
786  *
787  * Tcpdump uses ftell() to determine how much data has been written
788  * to a file in order to, when used with -C, determine when it's time
789  * to rotate capture files.  ftell() therefore needs to do an lseek()
790  * to find out the file offset and must, thanks to the aforementioned
791  * optimization, also know whether the descriptor is open append-only
792  * or not.
793  *
794  * The net result of all the above is that we need to grant CAP_SEEK,
795  * CAP_WRITE, and CAP_FCNTL with the CAP_FCNTL_GETFL subcapability.
796  *
797  * Perhaps this is the universe's way of saying that either
798  *
799  *	1) there needs to be an fopenat() call and a pcap_dump_openat() call
800  *	   using it, so that Capsicum-capable tcpdump wouldn't need to do
801  *	   an fdopen()
802  *
803  * or
804  *
805  *	2) there needs to be a cap_fdopen() call in the FreeBSD standard
806  *	   I/O library that knows what rights are needed by the standard
807  *	   I/O library, based on the open mode, and assigns them, perhaps
808  *	   with an additional argument indicating, for example, whether
809  *	   seeking should be allowed, so that tcpdump doesn't need to know
810  *	   what the standard I/O library happens to require this week.
811  */
812 static void
813 set_dumper_capsicum_rights(pcap_dumper_t *p)
814 {
815 	int fd = fileno(pcap_dump_file(p));
816 	cap_rights_t rights;
817 
818 	cap_rights_init(&rights, CAP_SEEK, CAP_WRITE, CAP_FCNTL);
819 	if (cap_rights_limit(fd, &rights) < 0 && errno != ENOSYS) {
820 		error("unable to limit dump descriptor");
821 	}
822 	if (cap_fcntls_limit(fd, CAP_FCNTL_GETFL) < 0 && errno != ENOSYS) {
823 		error("unable to limit dump descriptor fcntls");
824 	}
825 }
826 #endif
827 
828 /*
829  * Copy arg vector into a new buffer, concatenating arguments with spaces.
830  */
831 static char *
832 copy_argv(register char **argv)
833 {
834 	register char **p;
835 	register u_int len = 0;
836 	char *buf;
837 	char *src, *dst;
838 
839 	p = argv;
840 	if (*p == NULL)
841 		return 0;
842 
843 	while (*p)
844 		len += strlen(*p++) + 1;
845 
846 	buf = (char *)malloc(len);
847 	if (buf == NULL)
848 		error("copy_argv: malloc");
849 
850 	p = argv;
851 	dst = buf;
852 	while ((src = *p++) != NULL) {
853 		while ((*dst++ = *src++) != '\0')
854 			;
855 		dst[-1] = ' ';
856 	}
857 	dst[-1] = '\0';
858 
859 	return buf;
860 }
861 
862 /*
863  * On Windows, we need to open the file in binary mode, so that
864  * we get all the bytes specified by the size we get from "fstat()".
865  * On UNIX, that's not necessary.  O_BINARY is defined on Windows;
866  * we define it as 0 if it's not defined, so it does nothing.
867  */
868 #ifndef O_BINARY
869 #define O_BINARY	0
870 #endif
871 
872 static char *
873 read_infile(char *fname)
874 {
875 	register int i, fd, cc;
876 	register char *cp;
877 	struct stat buf;
878 
879 	fd = open(fname, O_RDONLY|O_BINARY);
880 	if (fd < 0)
881 		error("can't open %s: %s", fname, pcap_strerror(errno));
882 
883 	if (fstat(fd, &buf) < 0)
884 		error("can't stat %s: %s", fname, pcap_strerror(errno));
885 
886 	cp = malloc((u_int)buf.st_size + 1);
887 	if (cp == NULL)
888 		error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
889 			fname, pcap_strerror(errno));
890 	cc = read(fd, cp, (u_int)buf.st_size);
891 	if (cc < 0)
892 		error("read %s: %s", fname, pcap_strerror(errno));
893 	if (cc != buf.st_size)
894 		error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
895 
896 	close(fd);
897 	/* replace "# comment" with spaces */
898 	for (i = 0; i < cc; i++) {
899 		if (cp[i] == '#')
900 			while (i < cc && cp[i] != '\n')
901 				cp[i++] = ' ';
902 	}
903 	cp[cc] = '\0';
904 	return (cp);
905 }
906 
907 #ifdef HAVE_PCAP_FINDALLDEVS
908 static long
909 parse_interface_number(const char *device)
910 {
911 	long devnum;
912 	char *end;
913 
914 	devnum = strtol(device, &end, 10);
915 	if (device != end && *end == '\0') {
916 		/*
917 		 * It's all-numeric, but is it a valid number?
918 		 */
919 		if (devnum <= 0) {
920 			/*
921 			 * No, it's not an ordinal.
922 			 */
923 			error("Invalid adapter index");
924 		}
925 		return (devnum);
926 	} else {
927 		/*
928 		 * It's not all-numeric; return -1, so our caller
929 		 * knows that.
930 		 */
931 		return (-1);
932 	}
933 }
934 
935 static char *
936 find_interface_by_number(long devnum)
937 {
938 	pcap_if_t *dev, *devlist;
939 	long i;
940 	char ebuf[PCAP_ERRBUF_SIZE];
941 	char *device;
942 
943 	if (pcap_findalldevs(&devlist, ebuf) < 0)
944 		error("%s", ebuf);
945 	/*
946 	 * Look for the devnum-th entry in the list of devices (1-based).
947 	 */
948 	for (i = 0, dev = devlist; i < devnum-1 && dev != NULL;
949 	    i++, dev = dev->next)
950 		;
951 	if (dev == NULL)
952 		error("Invalid adapter index");
953 	device = strdup(dev->name);
954 	pcap_freealldevs(devlist);
955 	return (device);
956 }
957 #endif
958 
959 static pcap_t *
960 open_interface(const char *device, netdissect_options *ndo, char *ebuf)
961 {
962 	pcap_t *pc;
963 #ifdef HAVE_PCAP_CREATE
964 	int status;
965 	char *cp;
966 #endif
967 
968 #ifdef HAVE_PCAP_CREATE
969 	pc = pcap_create(device, ebuf);
970 	if (pc == NULL) {
971 		/*
972 		 * If this failed with "No such device", that means
973 		 * the interface doesn't exist; return NULL, so that
974 		 * the caller can see whether the device name is
975 		 * actually an interface index.
976 		 */
977 		if (strstr(ebuf, "No such device") != NULL)
978 			return (NULL);
979 		error("%s", ebuf);
980 	}
981 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
982 	if (Jflag)
983 		show_tstamp_types_and_exit(pc, device);
984 #endif
985 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
986 	status = pcap_set_tstamp_precision(pc, ndo->ndo_tstamp_precision);
987 	if (status != 0)
988 		error("%s: Can't set %ssecond time stamp precision: %s",
989 			device,
990 			tstamp_precision_to_string(ndo->ndo_tstamp_precision),
991 			pcap_statustostr(status));
992 #endif
993 
994 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
995 	if (immediate_mode) {
996 		status = pcap_set_immediate_mode(pc, 1);
997 		if (status != 0)
998 			error("%s: Can't set immediate mode: %s",
999 			device,
1000 			pcap_statustostr(status));
1001 	}
1002 #endif
1003 	/*
1004 	 * Is this an interface that supports monitor mode?
1005 	 */
1006 	if (pcap_can_set_rfmon(pc) == 1)
1007 		supports_monitor_mode = 1;
1008 	else
1009 		supports_monitor_mode = 0;
1010 	status = pcap_set_snaplen(pc, ndo->ndo_snaplen);
1011 	if (status != 0)
1012 		error("%s: Can't set snapshot length: %s",
1013 		    device, pcap_statustostr(status));
1014 	status = pcap_set_promisc(pc, !pflag);
1015 	if (status != 0)
1016 		error("%s: Can't set promiscuous mode: %s",
1017 		    device, pcap_statustostr(status));
1018 	if (Iflag) {
1019 		status = pcap_set_rfmon(pc, 1);
1020 		if (status != 0)
1021 			error("%s: Can't set monitor mode: %s",
1022 			    device, pcap_statustostr(status));
1023 	}
1024 	status = pcap_set_timeout(pc, 1000);
1025 	if (status != 0)
1026 		error("%s: pcap_set_timeout failed: %s",
1027 		    device, pcap_statustostr(status));
1028 	if (Bflag != 0) {
1029 		status = pcap_set_buffer_size(pc, Bflag);
1030 		if (status != 0)
1031 			error("%s: Can't set buffer size: %s",
1032 			    device, pcap_statustostr(status));
1033 	}
1034 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1035 	if (jflag != -1) {
1036 		status = pcap_set_tstamp_type(pc, jflag);
1037 		if (status < 0)
1038 			error("%s: Can't set time stamp type: %s",
1039 		              device, pcap_statustostr(status));
1040 		else if (status > 0)
1041 			warning("When trying to set timestamp type '%s' on %s: %s",
1042 				pcap_tstamp_type_val_to_name(jflag), device,
1043 				pcap_statustostr(status));
1044 	}
1045 #endif
1046 	status = pcap_activate(pc);
1047 	if (status < 0) {
1048 		/*
1049 		 * pcap_activate() failed.
1050 		 */
1051 		cp = pcap_geterr(pc);
1052 		if (status == PCAP_ERROR)
1053 			error("%s", cp);
1054 		else if (status == PCAP_ERROR_NO_SUCH_DEVICE) {
1055 			/*
1056 			 * Return an error for our caller to handle.
1057 			 */
1058 			snprintf(ebuf, PCAP_ERRBUF_SIZE, "%s: %s\n(%s)",
1059 			    device, pcap_statustostr(status), cp);
1060 			pcap_close(pc);
1061 			return (NULL);
1062 		} else if (status == PCAP_ERROR_PERM_DENIED && *cp != '\0')
1063 			error("%s: %s\n(%s)", device,
1064 			    pcap_statustostr(status), cp);
1065 		else
1066 			error("%s: %s", device,
1067 			    pcap_statustostr(status));
1068 	} else if (status > 0) {
1069 		/*
1070 		 * pcap_activate() succeeded, but it's warning us
1071 		 * of a problem it had.
1072 		 */
1073 		cp = pcap_geterr(pc);
1074 		if (status == PCAP_WARNING)
1075 			warning("%s", cp);
1076 		else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1077 		         *cp != '\0')
1078 			warning("%s: %s\n(%s)", device,
1079 			    pcap_statustostr(status), cp);
1080 		else
1081 			warning("%s: %s", device,
1082 			    pcap_statustostr(status));
1083 	}
1084 #ifdef HAVE_PCAP_SETDIRECTION
1085 	if (Qflag != -1) {
1086 		status = pcap_setdirection(pc, Qflag);
1087 		if (status != 0)
1088 			error("%s: pcap_setdirection() failed: %s",
1089 			      device,  pcap_geterr(pc));
1090 		}
1091 #endif /* HAVE_PCAP_SETDIRECTION */
1092 #else /* HAVE_PCAP_CREATE */
1093 	*ebuf = '\0';
1094 	pc = pcap_open_live(device, ndo->ndo_snaplen, !pflag, 1000, ebuf);
1095 	if (pc == NULL) {
1096 		/*
1097 		 * If this failed with "No such device", that means
1098 		 * the interface doesn't exist; return NULL, so that
1099 		 * the caller can see whether the device name is
1100 		 * actually an interface index.
1101 		 */
1102 		if (strstr(ebuf, "No such device") != NULL)
1103 			return (NULL);
1104 		error("%s", ebuf);
1105 	}
1106 	if (*ebuf)
1107 		warning("%s", ebuf);
1108 #endif /* HAVE_PCAP_CREATE */
1109 
1110 	return (pc);
1111 }
1112 
1113 int
1114 main(int argc, char **argv)
1115 {
1116 	register int cnt, op, i;
1117 	bpf_u_int32 localnet =0 , netmask = 0;
1118 	int timezone_offset = 0;
1119 	register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
1120 	pcap_handler callback;
1121 	int dlt;
1122 	const char *dlt_name;
1123 	struct bpf_program fcode;
1124 #ifndef _WIN32
1125 	RETSIGTYPE (*oldhandler)(int);
1126 #endif
1127 	struct dump_info dumpinfo;
1128 	u_char *pcap_userdata;
1129 	char ebuf[PCAP_ERRBUF_SIZE];
1130 	char VFileLine[PATH_MAX + 1];
1131 	char *username = NULL;
1132 	char *chroot_dir = NULL;
1133 	char *ret = NULL;
1134 	char *end;
1135 #ifdef HAVE_PCAP_FINDALLDEVS
1136 	pcap_if_t *devlist;
1137 	long devnum;
1138 #endif
1139 	int status;
1140 	FILE *VFile;
1141 #ifdef HAVE_CAPSICUM
1142 	cap_rights_t rights;
1143 	int cansandbox;
1144 #endif	/* HAVE_CAPSICUM */
1145 	int Oflag = 1;			/* run filter code optimizer */
1146 	int yflag_dlt = -1;
1147 	const char *yflag_dlt_name = NULL;
1148 
1149 	netdissect_options Ndo;
1150 	netdissect_options *ndo = &Ndo;
1151 
1152 	/*
1153 	 * Initialize the netdissect code.
1154 	 */
1155 	if (nd_init(ebuf, sizeof ebuf) == -1)
1156 		error("%s", ebuf);
1157 
1158 	memset(ndo, 0, sizeof(*ndo));
1159 	ndo_set_function_pointers(ndo);
1160 	ndo->ndo_snaplen = DEFAULT_SNAPLEN;
1161 
1162 	cnt = -1;
1163 	device = NULL;
1164 	infile = NULL;
1165 	RFileName = NULL;
1166 	VFileName = NULL;
1167 	VFile = NULL;
1168 	WFileName = NULL;
1169 	dlt = -1;
1170 	if ((cp = strrchr(argv[0], '/')) != NULL)
1171 		ndo->program_name = program_name = cp + 1;
1172 	else
1173 		ndo->program_name = program_name = argv[0];
1174 
1175 #ifdef _WIN32
1176 	if (pcap_wsockinit() != 0)
1177 		error("Attempting to initialize Winsock failed");
1178 #endif /* _WIN32 */
1179 
1180 	/*
1181 	 * On platforms where the CPU doesn't support unaligned loads,
1182 	 * force unaligned accesses to abort with SIGBUS, rather than
1183 	 * being fixed up (slowly) by the OS kernel; on those platforms,
1184 	 * misaligned accesses are bugs, and we want tcpdump to crash so
1185 	 * that the bugs are reported.
1186 	 */
1187 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
1188 		error("%s", ebuf);
1189 
1190 	while (
1191 	    (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1)
1192 		switch (op) {
1193 
1194 		case 'a':
1195 			/* compatibility for old -a */
1196 			break;
1197 
1198 		case 'A':
1199 			++ndo->ndo_Aflag;
1200 			break;
1201 
1202 		case 'b':
1203 			++ndo->ndo_bflag;
1204 			break;
1205 
1206 #if defined(HAVE_PCAP_CREATE) || defined(_WIN32)
1207 		case 'B':
1208 			Bflag = atoi(optarg)*1024;
1209 			if (Bflag <= 0)
1210 				error("invalid packet buffer size %s", optarg);
1211 			break;
1212 #endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */
1213 
1214 		case 'c':
1215 			cnt = atoi(optarg);
1216 			if (cnt <= 0)
1217 				error("invalid packet count %s", optarg);
1218 			break;
1219 
1220 		case 'C':
1221 			Cflag = atoi(optarg) * 1000000;
1222 			if (Cflag <= 0)
1223 				error("invalid file size %s", optarg);
1224 			break;
1225 
1226 		case 'd':
1227 			++dflag;
1228 			break;
1229 
1230 		case 'D':
1231 			Dflag++;
1232 			break;
1233 
1234 		case 'L':
1235 			Lflag++;
1236 			break;
1237 
1238 		case 'e':
1239 			++ndo->ndo_eflag;
1240 			break;
1241 
1242 		case 'E':
1243 #ifndef HAVE_LIBCRYPTO
1244 			warning("crypto code not compiled in");
1245 #endif
1246 			ndo->ndo_espsecret = optarg;
1247 			break;
1248 
1249 		case 'f':
1250 			++ndo->ndo_fflag;
1251 			break;
1252 
1253 		case 'F':
1254 			infile = optarg;
1255 			break;
1256 
1257 		case 'G':
1258 			Gflag = atoi(optarg);
1259 			if (Gflag < 0)
1260 				error("invalid number of seconds %s", optarg);
1261 
1262                         /* We will create one file initially. */
1263                         Gflag_count = 0;
1264 
1265 			/* Grab the current time for rotation use. */
1266 			if ((Gflag_time = time(NULL)) == (time_t)-1) {
1267 				error("main: can't get current time: %s",
1268 				    pcap_strerror(errno));
1269 			}
1270 			break;
1271 
1272 		case 'h':
1273 			print_usage();
1274 			exit_tcpdump(0);
1275 			break;
1276 
1277 		case 'H':
1278 			++ndo->ndo_Hflag;
1279 			break;
1280 
1281 		case 'i':
1282 			device = optarg;
1283 			break;
1284 
1285 #ifdef HAVE_PCAP_CREATE
1286 		case 'I':
1287 			++Iflag;
1288 			break;
1289 #endif /* HAVE_PCAP_CREATE */
1290 
1291 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1292 		case 'j':
1293 			jflag = pcap_tstamp_type_name_to_val(optarg);
1294 			if (jflag < 0)
1295 				error("invalid time stamp type %s", optarg);
1296 			break;
1297 
1298 		case 'J':
1299 			Jflag++;
1300 			break;
1301 #endif
1302 
1303 		case 'l':
1304 #ifdef _WIN32
1305 			/*
1306 			 * _IOLBF is the same as _IOFBF in Microsoft's C
1307 			 * libraries; the only alternative they offer
1308 			 * is _IONBF.
1309 			 *
1310 			 * XXX - this should really be checking for MSVC++,
1311 			 * not _WIN32, if, for example, MinGW has its own
1312 			 * C library that is more UNIX-compatible.
1313 			 */
1314 			setvbuf(stdout, NULL, _IONBF, 0);
1315 #else /* _WIN32 */
1316 #ifdef HAVE_SETLINEBUF
1317 			setlinebuf(stdout);
1318 #else
1319 			setvbuf(stdout, NULL, _IOLBF, 0);
1320 #endif
1321 #endif /* _WIN32 */
1322 			break;
1323 
1324 		case 'K':
1325 			++ndo->ndo_Kflag;
1326 			break;
1327 
1328 		case 'm':
1329 			if (nd_have_smi_support()) {
1330 				if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1)
1331 					error("%s", ebuf);
1332 			} else {
1333 				(void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1334 					      program_name, optarg);
1335 				(void)fprintf(stderr, "(no libsmi support)\n");
1336 			}
1337 			break;
1338 
1339 		case 'M':
1340 			/* TCP-MD5 shared secret */
1341 #ifndef HAVE_LIBCRYPTO
1342 			warning("crypto code not compiled in");
1343 #endif
1344 			ndo->ndo_sigsecret = optarg;
1345 			break;
1346 
1347 		case 'n':
1348 			++ndo->ndo_nflag;
1349 			break;
1350 
1351 		case 'N':
1352 			++ndo->ndo_Nflag;
1353 			break;
1354 
1355 		case 'O':
1356 			Oflag = 0;
1357 			break;
1358 
1359 		case 'p':
1360 			++pflag;
1361 			break;
1362 
1363 		case 'q':
1364 			++ndo->ndo_qflag;
1365 			++ndo->ndo_suppress_default_print;
1366 			break;
1367 
1368 #ifdef HAVE_PCAP_SETDIRECTION
1369 		case 'Q':
1370 			if (ascii_strcasecmp(optarg, "in") == 0)
1371 				Qflag = PCAP_D_IN;
1372 			else if (ascii_strcasecmp(optarg, "out") == 0)
1373 				Qflag = PCAP_D_OUT;
1374 			else if (ascii_strcasecmp(optarg, "inout") == 0)
1375 				Qflag = PCAP_D_INOUT;
1376 			else
1377 				error("unknown capture direction `%s'", optarg);
1378 			break;
1379 #endif /* HAVE_PCAP_SETDIRECTION */
1380 
1381 		case 'r':
1382 			RFileName = optarg;
1383 			break;
1384 
1385 		case 's':
1386 			ndo->ndo_snaplen = strtol(optarg, &end, 0);
1387 			if (optarg == end || *end != '\0'
1388 			    || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1389 				error("invalid snaplen %s", optarg);
1390 			else if (ndo->ndo_snaplen == 0)
1391 				ndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1392 			break;
1393 
1394 		case 'S':
1395 			++ndo->ndo_Sflag;
1396 			break;
1397 
1398 		case 't':
1399 			++ndo->ndo_tflag;
1400 			break;
1401 
1402 		case 'T':
1403 			if (ascii_strcasecmp(optarg, "vat") == 0)
1404 				ndo->ndo_packettype = PT_VAT;
1405 			else if (ascii_strcasecmp(optarg, "wb") == 0)
1406 				ndo->ndo_packettype = PT_WB;
1407 			else if (ascii_strcasecmp(optarg, "rpc") == 0)
1408 				ndo->ndo_packettype = PT_RPC;
1409 			else if (ascii_strcasecmp(optarg, "rtp") == 0)
1410 				ndo->ndo_packettype = PT_RTP;
1411 			else if (ascii_strcasecmp(optarg, "rtcp") == 0)
1412 				ndo->ndo_packettype = PT_RTCP;
1413 			else if (ascii_strcasecmp(optarg, "snmp") == 0)
1414 				ndo->ndo_packettype = PT_SNMP;
1415 			else if (ascii_strcasecmp(optarg, "cnfp") == 0)
1416 				ndo->ndo_packettype = PT_CNFP;
1417 			else if (ascii_strcasecmp(optarg, "tftp") == 0)
1418 				ndo->ndo_packettype = PT_TFTP;
1419 			else if (ascii_strcasecmp(optarg, "aodv") == 0)
1420 				ndo->ndo_packettype = PT_AODV;
1421 			else if (ascii_strcasecmp(optarg, "carp") == 0)
1422 				ndo->ndo_packettype = PT_CARP;
1423 			else if (ascii_strcasecmp(optarg, "radius") == 0)
1424 				ndo->ndo_packettype = PT_RADIUS;
1425 			else if (ascii_strcasecmp(optarg, "zmtp1") == 0)
1426 				ndo->ndo_packettype = PT_ZMTP1;
1427 			else if (ascii_strcasecmp(optarg, "vxlan") == 0)
1428 				ndo->ndo_packettype = PT_VXLAN;
1429 			else if (ascii_strcasecmp(optarg, "pgm") == 0)
1430 				ndo->ndo_packettype = PT_PGM;
1431 			else if (ascii_strcasecmp(optarg, "pgm_zmtp1") == 0)
1432 				ndo->ndo_packettype = PT_PGM_ZMTP1;
1433 			else if (ascii_strcasecmp(optarg, "lmp") == 0)
1434 				ndo->ndo_packettype = PT_LMP;
1435 			else if (ascii_strcasecmp(optarg, "resp") == 0)
1436 				ndo->ndo_packettype = PT_RESP;
1437 			else
1438 				error("unknown packet type `%s'", optarg);
1439 			break;
1440 
1441 		case 'u':
1442 			++ndo->ndo_uflag;
1443 			break;
1444 
1445 #ifdef HAVE_PCAP_DUMP_FLUSH
1446 		case 'U':
1447 			++Uflag;
1448 			break;
1449 #endif
1450 
1451 		case 'v':
1452 			++ndo->ndo_vflag;
1453 			break;
1454 
1455 		case 'V':
1456 			VFileName = optarg;
1457 			break;
1458 
1459 		case 'w':
1460 			WFileName = optarg;
1461 			break;
1462 
1463 		case 'W':
1464 			Wflag = atoi(optarg);
1465 			if (Wflag <= 0)
1466 				error("invalid number of output files %s", optarg);
1467 			WflagChars = getWflagChars(Wflag);
1468 			break;
1469 
1470 		case 'x':
1471 			++ndo->ndo_xflag;
1472 			++ndo->ndo_suppress_default_print;
1473 			break;
1474 
1475 		case 'X':
1476 			++ndo->ndo_Xflag;
1477 			++ndo->ndo_suppress_default_print;
1478 			break;
1479 
1480 		case 'y':
1481 			yflag_dlt_name = optarg;
1482 			yflag_dlt =
1483 				pcap_datalink_name_to_val(yflag_dlt_name);
1484 			if (yflag_dlt < 0)
1485 				error("invalid data link type %s", yflag_dlt_name);
1486 			break;
1487 
1488 #ifdef HAVE_PCAP_SET_PARSER_DEBUG
1489 		case 'Y':
1490 			{
1491 			/* Undocumented flag */
1492 			pcap_set_parser_debug(1);
1493 			}
1494 			break;
1495 #endif
1496 		case 'z':
1497 			zflag = optarg;
1498 			break;
1499 
1500 		case 'Z':
1501 			username = optarg;
1502 			break;
1503 
1504 		case '#':
1505 			ndo->ndo_packet_number = 1;
1506 			break;
1507 
1508 		case OPTION_VERSION:
1509 			print_version();
1510 			exit_tcpdump(0);
1511 			break;
1512 
1513 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1514 		case OPTION_TSTAMP_PRECISION:
1515 			ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg);
1516 			if (ndo->ndo_tstamp_precision < 0)
1517 				error("unsupported time stamp precision");
1518 			break;
1519 #endif
1520 
1521 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1522 		case OPTION_IMMEDIATE_MODE:
1523 			immediate_mode = 1;
1524 			break;
1525 #endif
1526 
1527 		default:
1528 			print_usage();
1529 			exit_tcpdump(1);
1530 			/* NOTREACHED */
1531 		}
1532 
1533 #ifdef HAVE_PCAP_FINDALLDEVS
1534 	if (Dflag)
1535 		show_devices_and_exit();
1536 #endif
1537 
1538 	switch (ndo->ndo_tflag) {
1539 
1540 	case 0: /* Default */
1541 	case 4: /* Default + Date*/
1542 		timezone_offset = gmt2local(0);
1543 		break;
1544 
1545 	case 1: /* No time stamp */
1546 	case 2: /* Unix timeval style */
1547 	case 3: /* Microseconds since previous packet */
1548         case 5: /* Microseconds since first packet */
1549 		break;
1550 
1551 	default: /* Not supported */
1552 		error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1553 		break;
1554 	}
1555 
1556 	if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL))
1557 		error("-f can not be used with -V or -r");
1558 
1559 	if (VFileName != NULL && RFileName != NULL)
1560 		error("-V and -r are mutually exclusive.");
1561 
1562 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
1563 	/*
1564 	 * If we're printing dissected packets to the standard output
1565 	 * rather than saving raw packets to a file, and the standard
1566 	 * output is a terminal, use immediate mode, as the user's
1567 	 * probably expecting to see packets pop up immediately.
1568 	 */
1569 	if (WFileName == NULL && isatty(1))
1570 		immediate_mode = 1;
1571 #endif
1572 
1573 #ifdef WITH_CHROOT
1574 	/* if run as root, prepare for chrooting */
1575 	if (getuid() == 0 || geteuid() == 0) {
1576 		/* future extensibility for cmd-line arguments */
1577 		if (!chroot_dir)
1578 			chroot_dir = WITH_CHROOT;
1579 	}
1580 #endif
1581 
1582 #ifdef WITH_USER
1583 	/* if run as root, prepare for dropping root privileges */
1584 	if (getuid() == 0 || geteuid() == 0) {
1585 		/* Run with '-Z root' to restore old behaviour */
1586 		if (!username)
1587 			username = WITH_USER;
1588 	}
1589 #endif
1590 
1591 	if (RFileName != NULL || VFileName != NULL) {
1592 		/*
1593 		 * If RFileName is non-null, it's the pathname of a
1594 		 * savefile to read.  If VFileName is non-null, it's
1595 		 * the pathname of a file containing a list of pathnames
1596 		 * (one per line) of savefiles to read.
1597 		 *
1598 		 * In either case, we're reading a savefile, not doing
1599 		 * a live capture.
1600 		 */
1601 #ifndef _WIN32
1602 		/*
1603 		 * We don't need network access, so relinquish any set-UID
1604 		 * or set-GID privileges we have (if any).
1605 		 *
1606 		 * We do *not* want set-UID privileges when opening a
1607 		 * trace file, as that might let the user read other
1608 		 * people's trace files (especially if we're set-UID
1609 		 * root).
1610 		 */
1611 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1612 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1613 #endif /* _WIN32 */
1614 		if (VFileName != NULL) {
1615 			if (VFileName[0] == '-' && VFileName[1] == '\0')
1616 				VFile = stdin;
1617 			else
1618 				VFile = fopen(VFileName, "r");
1619 
1620 			if (VFile == NULL)
1621 				error("Unable to open file: %s\n", pcap_strerror(errno));
1622 
1623 			ret = get_next_file(VFile, VFileLine);
1624 			if (!ret)
1625 				error("Nothing in %s\n", VFileName);
1626 			RFileName = VFileLine;
1627 		}
1628 
1629 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
1630 		pd = pcap_open_offline_with_tstamp_precision(RFileName,
1631 		    ndo->ndo_tstamp_precision, ebuf);
1632 #else
1633 		pd = pcap_open_offline(RFileName, ebuf);
1634 #endif
1635 
1636 		if (pd == NULL)
1637 			error("%s", ebuf);
1638 #ifdef HAVE_CAPSICUM
1639 		cap_rights_init(&rights, CAP_READ);
1640 		if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1641 		    errno != ENOSYS) {
1642 			error("unable to limit pcap descriptor");
1643 		}
1644 #endif
1645 		dlt = pcap_datalink(pd);
1646 		dlt_name = pcap_datalink_val_to_name(dlt);
1647 		if (dlt_name == NULL) {
1648 			fprintf(stderr, "reading from file %s, link-type %u\n",
1649 			    RFileName, dlt);
1650 		} else {
1651 			fprintf(stderr,
1652 			    "reading from file %s, link-type %s (%s)\n",
1653 			    RFileName, dlt_name,
1654 			    pcap_datalink_val_to_description(dlt));
1655 		}
1656 	} else {
1657 		/*
1658 		 * We're doing a live capture.
1659 		 */
1660 		if (device == NULL) {
1661 			/*
1662 			 * No interface was specified.  Pick one.
1663 			 */
1664 #ifdef HAVE_PCAP_FINDALLDEVS
1665 			/*
1666 			 * Find the list of interfaces, and pick
1667 			 * the first interface.
1668 			 */
1669 			if (pcap_findalldevs(&devlist, ebuf) >= 0 &&
1670 			    devlist != NULL) {
1671 				device = strdup(devlist->name);
1672 				pcap_freealldevs(devlist);
1673 			}
1674 #else /* HAVE_PCAP_FINDALLDEVS */
1675 			/*
1676 			 * Use whatever interface pcap_lookupdev()
1677 			 * chooses.
1678 			 */
1679 			device = pcap_lookupdev(ebuf);
1680 #endif
1681 			if (device == NULL)
1682 				error("%s", ebuf);
1683 		}
1684 
1685 		/*
1686 		 * Try to open the interface with the specified name.
1687 		 */
1688 		pd = open_interface(device, ndo, ebuf);
1689 		if (pd == NULL) {
1690 			/*
1691 			 * That failed.  If we can get a list of
1692 			 * interfaces, and the interface name
1693 			 * is purely numeric, try to use it as
1694 			 * a 1-based index in the list of
1695 			 * interfaces.
1696 			 */
1697 #ifdef HAVE_PCAP_FINDALLDEVS
1698 			devnum = parse_interface_number(device);
1699 			if (devnum == -1) {
1700 				/*
1701 				 * It's not a number; just report
1702 				 * the open error and fail.
1703 				 */
1704 				error("%s", ebuf);
1705 			}
1706 
1707 			/*
1708 			 * OK, it's a number; try to find the
1709 			 * interface with that index, and try
1710 			 * to open it.
1711 			 *
1712 			 * find_interface_by_number() exits if it
1713 			 * couldn't be found.
1714 			 */
1715 			device = find_interface_by_number(devnum);
1716 			pd = open_interface(device, ndo, ebuf);
1717 			if (pd == NULL)
1718 				error("%s", ebuf);
1719 #else /* HAVE_PCAP_FINDALLDEVS */
1720 			/*
1721 			 * We can't get a list of interfaces; just
1722 			 * fail.
1723 			 */
1724 			error("%s", ebuf);
1725 #endif /* HAVE_PCAP_FINDALLDEVS */
1726 		}
1727 
1728 		/*
1729 		 * Let user own process after socket has been opened.
1730 		 */
1731 #ifndef _WIN32
1732 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1733 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1734 #endif /* _WIN32 */
1735 #if !defined(HAVE_PCAP_CREATE) && defined(_WIN32)
1736 		if(Bflag != 0)
1737 			if(pcap_setbuff(pd, Bflag)==-1){
1738 				error("%s", pcap_geterr(pd));
1739 			}
1740 #endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */
1741 		if (Lflag)
1742 			show_dlts_and_exit(pd, device);
1743 		if (yflag_dlt >= 0) {
1744 #ifdef HAVE_PCAP_SET_DATALINK
1745 			if (pcap_set_datalink(pd, yflag_dlt) < 0)
1746 				error("%s", pcap_geterr(pd));
1747 #else
1748 			/*
1749 			 * We don't actually support changing the
1750 			 * data link type, so we only let them
1751 			 * set it to what it already is.
1752 			 */
1753 			if (yflag_dlt != pcap_datalink(pd)) {
1754 				error("%s is not one of the DLTs supported by this device\n",
1755 				      yflag_dlt_name);
1756 			}
1757 #endif
1758 			(void)fprintf(stderr, "%s: data link type %s\n",
1759 				      program_name, yflag_dlt_name);
1760 			(void)fflush(stderr);
1761 		}
1762 		i = pcap_snapshot(pd);
1763 		if (ndo->ndo_snaplen < i) {
1764 			warning("snaplen raised from %d to %d", ndo->ndo_snaplen, i);
1765 			ndo->ndo_snaplen = i;
1766 		}
1767                 if(ndo->ndo_fflag != 0) {
1768                         if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1769                                 warning("foreign (-f) flag used but: %s", ebuf);
1770                         }
1771                 }
1772 
1773 	}
1774 	if (infile)
1775 		cmdbuf = read_infile(infile);
1776 	else
1777 		cmdbuf = copy_argv(&argv[optind]);
1778 
1779 #ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG
1780 	pcap_set_optimizer_debug(dflag);
1781 #endif
1782 	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1783 		error("%s", pcap_geterr(pd));
1784 	if (dflag) {
1785 		bpf_dump(&fcode, dflag);
1786 		pcap_close(pd);
1787 		free(cmdbuf);
1788 		pcap_freecode(&fcode);
1789 		exit_tcpdump(0);
1790 	}
1791 	init_print(ndo, localnet, netmask, timezone_offset);
1792 
1793 #ifndef _WIN32
1794 	(void)setsignal(SIGPIPE, cleanup);
1795 	(void)setsignal(SIGTERM, cleanup);
1796 	(void)setsignal(SIGINT, cleanup);
1797 #endif /* _WIN32 */
1798 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1799 	(void)setsignal(SIGCHLD, child_cleanup);
1800 #endif
1801 	/* Cooperate with nohup(1) */
1802 #ifndef _WIN32
1803 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1804 		(void)setsignal(SIGHUP, oldhandler);
1805 #endif /* _WIN32 */
1806 
1807 #ifndef _WIN32
1808 	/*
1809 	 * If a user name was specified with "-Z", attempt to switch to
1810 	 * that user's UID.  This would probably be used with sudo,
1811 	 * to allow tcpdump to be run in a special restricted
1812 	 * account (if you just want to allow users to open capture
1813 	 * devices, and can't just give users that permission,
1814 	 * you'd make tcpdump set-UID or set-GID).
1815 	 *
1816 	 * Tcpdump doesn't necessarily write only to one savefile;
1817 	 * the general only way to allow a -Z instance to write to
1818 	 * savefiles as the user under whose UID it's run, rather
1819 	 * than as the user specified with -Z, would thus be to switch
1820 	 * to the original user ID before opening a capture file and
1821 	 * then switch back to the -Z user ID after opening the savefile.
1822 	 * Switching to the -Z user ID only after opening the first
1823 	 * savefile doesn't handle the general case.
1824 	 */
1825 
1826 	if (getuid() == 0 || geteuid() == 0) {
1827 #ifdef HAVE_LIBCAP_NG
1828 		/* Initialize capng */
1829 		capng_clear(CAPNG_SELECT_BOTH);
1830 		if (username) {
1831 			capng_updatev(
1832 				CAPNG_ADD,
1833 				CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1834 				CAP_SETUID,
1835 				CAP_SETGID,
1836 				-1);
1837 		}
1838 		if (chroot_dir) {
1839 			capng_update(
1840 				CAPNG_ADD,
1841 				CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1842 				CAP_SYS_CHROOT
1843 				);
1844 		}
1845 
1846 		if (WFileName) {
1847 			capng_update(
1848 				CAPNG_ADD,
1849 				CAPNG_PERMITTED | CAPNG_EFFECTIVE,
1850 				CAP_DAC_OVERRIDE
1851 				);
1852 		}
1853 		capng_apply(CAPNG_SELECT_BOTH);
1854 #endif /* HAVE_LIBCAP_NG */
1855 		if (username || chroot_dir) {
1856 #ifndef HAVE_LIBCAP_NG
1857 			if (!WFileName)
1858 #endif
1859 			droproot(username, chroot_dir);
1860 		}
1861 	}
1862 #endif /* _WIN32 */
1863 
1864 	if (pcap_setfilter(pd, &fcode) < 0)
1865 		error("%s", pcap_geterr(pd));
1866 #ifdef HAVE_CAPSICUM
1867 	if (RFileName == NULL && VFileName == NULL) {
1868 		static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF };
1869 
1870 		/*
1871 		 * The various libpcap devices use a combination of
1872 		 * read (bpf), ioctl (bpf, netmap), poll (netmap)
1873 		 * so we add the relevant access rights.
1874 		 */
1875 		cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT);
1876 		if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1877 		    errno != ENOSYS) {
1878 			error("unable to limit pcap descriptor");
1879 		}
1880 		if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1881 		    sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1882 			error("unable to limit ioctls on pcap descriptor");
1883 		}
1884 	}
1885 #endif
1886 	if (WFileName) {
1887 		pcap_dumper_t *p;
1888 		/* Do not exceed the default PATH_MAX for files. */
1889 		dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1890 
1891 		if (dumpinfo.CurrentFileName == NULL)
1892 			error("malloc of dumpinfo.CurrentFileName");
1893 
1894 		/* We do not need numbering for dumpfiles if Cflag isn't set. */
1895 		if (Cflag != 0)
1896 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1897 		else
1898 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1899 
1900 		p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1901 #ifdef HAVE_LIBCAP_NG
1902 		/* Give up CAP_DAC_OVERRIDE capability.
1903 		 * Only allow it to be restored if the -C or -G flag have been
1904 		 * set since we may need to create more files later on.
1905 		 */
1906 		capng_update(
1907 			CAPNG_DROP,
1908 			(Cflag || Gflag ? 0 : CAPNG_PERMITTED)
1909 				| CAPNG_EFFECTIVE,
1910 			CAP_DAC_OVERRIDE
1911 			);
1912 		capng_apply(CAPNG_SELECT_BOTH);
1913 #endif /* HAVE_LIBCAP_NG */
1914 		if (p == NULL)
1915 			error("%s", pcap_geterr(pd));
1916 #ifdef HAVE_CAPSICUM
1917 		set_dumper_capsicum_rights(p);
1918 #endif
1919 		if (Cflag != 0 || Gflag != 0) {
1920 #ifdef HAVE_CAPSICUM
1921 			dumpinfo.WFileName = strdup(basename(WFileName));
1922 			if (dumpinfo.WFileName == NULL) {
1923 				error("Unable to allocate memory for file %s",
1924 				    WFileName);
1925 			}
1926 			dumpinfo.dirfd = open(dirname(WFileName),
1927 			    O_DIRECTORY | O_RDONLY);
1928 			if (dumpinfo.dirfd < 0) {
1929 				error("unable to open directory %s",
1930 				    dirname(WFileName));
1931 			}
1932 			cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1933 			    CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1934 			if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1935 			    errno != ENOSYS) {
1936 				error("unable to limit directory rights");
1937 			}
1938 			if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 &&
1939 			    errno != ENOSYS) {
1940 				error("unable to limit dump descriptor fcntls");
1941 			}
1942 #else	/* !HAVE_CAPSICUM */
1943 			dumpinfo.WFileName = WFileName;
1944 #endif
1945 			callback = dump_packet_and_trunc;
1946 			dumpinfo.pd = pd;
1947 			dumpinfo.p = p;
1948 			pcap_userdata = (u_char *)&dumpinfo;
1949 		} else {
1950 			callback = dump_packet;
1951 			pcap_userdata = (u_char *)p;
1952 		}
1953 #ifdef HAVE_PCAP_DUMP_FLUSH
1954 		if (Uflag)
1955 			pcap_dump_flush(p);
1956 #endif
1957 	} else {
1958 		dlt = pcap_datalink(pd);
1959 		ndo->ndo_if_printer = get_if_printer(ndo, dlt);
1960 		callback = print_packet;
1961 		pcap_userdata = (u_char *)ndo;
1962 	}
1963 
1964 #ifdef SIGNAL_REQ_INFO
1965 	/*
1966 	 * We can't get statistics when reading from a file rather
1967 	 * than capturing from a device.
1968 	 */
1969 	if (RFileName == NULL)
1970 		(void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1971 #endif
1972 
1973 	if (ndo->ndo_vflag > 0 && WFileName) {
1974 		/*
1975 		 * When capturing to a file, "-v" means tcpdump should,
1976 		 * every 10 seconds, "v"erbosely report the number of
1977 		 * packets captured.
1978 		 */
1979 #ifdef USE_WIN32_MM_TIMER
1980 		/* call verbose_stats_dump() each 1000 +/-100msec */
1981 		timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1982 		setvbuf(stderr, NULL, _IONBF, 0);
1983 #elif defined(HAVE_ALARM)
1984 		(void)setsignal(SIGALRM, verbose_stats_dump);
1985 		alarm(1);
1986 #endif
1987 	}
1988 
1989 	if (RFileName == NULL) {
1990 		/*
1991 		 * Live capture (if -V was specified, we set RFileName
1992 		 * to a file from the -V file).  Print a message to
1993 		 * the standard error on UN*X.
1994 		 */
1995 		if (!ndo->ndo_vflag && !WFileName) {
1996 			(void)fprintf(stderr,
1997 			    "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1998 			    program_name);
1999 		} else
2000 			(void)fprintf(stderr, "%s: ", program_name);
2001 		dlt = pcap_datalink(pd);
2002 		dlt_name = pcap_datalink_val_to_name(dlt);
2003 		if (dlt_name == NULL) {
2004 			(void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
2005 			    device, dlt, ndo->ndo_snaplen);
2006 		} else {
2007 			(void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
2008 			    device, dlt_name,
2009 			    pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen);
2010 		}
2011 		(void)fflush(stderr);
2012 	}
2013 
2014 	/*
2015 	 * If a user name was specified with "-Z", attempt to switch to
2016 	 * that user's UID.  This would probably be used with sudo,
2017 	 * to allow tcpdump to be run in a special restricted
2018 	 * account (if you just want to allow users to open capture
2019 	 * devices, and can't just give users that permission,
2020 	 * you'd make tcpdump set-UID or set-GID).
2021 	 *
2022 	 * Tcpdump doesn't necessarily write only to one savefile;
2023 	 * the general only way to allow a -Z instance to write to
2024 	 * savefiles as the user under whose UID it's run, rather
2025 	 * than as the user specified with -Z, would thus be to switch
2026 	 * to the original user ID before opening a capture file and
2027 	 * then switch back to the -Z user ID after opening the savefile.
2028 	 * Switching to the -Z user ID only after opening the first
2029 	 * savefile doesn't handle the general case.
2030 	 */
2031 	if (getuid() == 0 || geteuid() == 0) {
2032 		if (username || chroot_dir)
2033 			droproot(username, chroot_dir);
2034 	}
2035 
2036 #ifdef HAVE_CAPSICUM
2037 	cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL);
2038 	if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
2039 		error("unable to enter the capability mode");
2040 #endif	/* HAVE_CAPSICUM */
2041 
2042 	do {
2043 		status = pcap_loop(pd, cnt, callback, pcap_userdata);
2044 		if (WFileName == NULL) {
2045 			/*
2046 			 * We're printing packets.  Flush the printed output,
2047 			 * so it doesn't get intermingled with error output.
2048 			 */
2049 			if (status == -2) {
2050 				/*
2051 				 * We got interrupted, so perhaps we didn't
2052 				 * manage to finish a line we were printing.
2053 				 * Print an extra newline, just in case.
2054 				 */
2055 				putchar('\n');
2056 			}
2057 			(void)fflush(stdout);
2058 		}
2059                 if (status == -2) {
2060 			/*
2061 			 * We got interrupted. If we are reading multiple
2062 			 * files (via -V) set these so that we stop.
2063 			 */
2064 			VFileName = NULL;
2065 			ret = NULL;
2066 		}
2067 		if (status == -1) {
2068 			/*
2069 			 * Error.  Report it.
2070 			 */
2071 			(void)fprintf(stderr, "%s: pcap_loop: %s\n",
2072 			    program_name, pcap_geterr(pd));
2073 		}
2074 		if (RFileName == NULL) {
2075 			/*
2076 			 * We're doing a live capture.  Report the capture
2077 			 * statistics.
2078 			 */
2079 			info(1);
2080 		}
2081 		pcap_close(pd);
2082 		if (VFileName != NULL) {
2083 			ret = get_next_file(VFile, VFileLine);
2084 			if (ret) {
2085 				int new_dlt;
2086 
2087 				RFileName = VFileLine;
2088 				pd = pcap_open_offline(RFileName, ebuf);
2089 				if (pd == NULL)
2090 					error("%s", ebuf);
2091 #ifdef HAVE_CAPSICUM
2092 				cap_rights_init(&rights, CAP_READ);
2093 				if (cap_rights_limit(fileno(pcap_file(pd)),
2094 				    &rights) < 0 && errno != ENOSYS) {
2095 					error("unable to limit pcap descriptor");
2096 				}
2097 #endif
2098 				new_dlt = pcap_datalink(pd);
2099 				if (new_dlt != dlt) {
2100 					/*
2101 					 * The new file has a different
2102 					 * link-layer header type from the
2103 					 * previous one.
2104 					 */
2105 					if (WFileName != NULL) {
2106 						/*
2107 						 * We're writing raw packets
2108 						 * that match the filter to
2109 						 * a pcap file.  pcap files
2110 						 * don't support multiple
2111 						 * different link-layer
2112 						 * header types, so we fail
2113 						 * here.
2114 						 */
2115 						error("%s: new dlt does not match original", RFileName);
2116 					}
2117 
2118 					/*
2119 					 * We're printing the decoded packets;
2120 					 * switch to the new DLT.
2121 					 *
2122 					 * To do that, we need to change
2123 					 * the printer, change the DLT name,
2124 					 * and recompile the filter with
2125 					 * the new DLT.
2126 					 */
2127 					dlt = new_dlt;
2128 					ndo->ndo_if_printer = get_if_printer(ndo, dlt);
2129 					if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
2130 						error("%s", pcap_geterr(pd));
2131 				}
2132 
2133 				/*
2134 				 * Set the filter on the new file.
2135 				 */
2136 				if (pcap_setfilter(pd, &fcode) < 0)
2137 					error("%s", pcap_geterr(pd));
2138 
2139 				/*
2140 				 * Report the new file.
2141 				 */
2142 				dlt_name = pcap_datalink_val_to_name(dlt);
2143 				if (dlt_name == NULL) {
2144 					fprintf(stderr, "reading from file %s, link-type %u\n",
2145 					    RFileName, dlt);
2146 				} else {
2147 					fprintf(stderr,
2148 					"reading from file %s, link-type %s (%s)\n",
2149 					    RFileName, dlt_name,
2150 					    pcap_datalink_val_to_description(dlt));
2151 				}
2152 			}
2153 		}
2154 	}
2155 	while (ret != NULL);
2156 
2157 	free(cmdbuf);
2158 	pcap_freecode(&fcode);
2159 	exit_tcpdump(status == -1 ? 1 : 0);
2160 }
2161 
2162 /* make a clean exit on interrupts */
2163 static RETSIGTYPE
2164 cleanup(int signo _U_)
2165 {
2166 #ifdef USE_WIN32_MM_TIMER
2167 	if (timer_id)
2168 		timeKillEvent(timer_id);
2169 	timer_id = 0;
2170 #elif defined(HAVE_ALARM)
2171 	alarm(0);
2172 #endif
2173 
2174 #ifdef HAVE_PCAP_BREAKLOOP
2175 	/*
2176 	 * We have "pcap_breakloop()"; use it, so that we do as little
2177 	 * as possible in the signal handler (it's probably not safe
2178 	 * to do anything with standard I/O streams in a signal handler -
2179 	 * the ANSI C standard doesn't say it is).
2180 	 */
2181 	pcap_breakloop(pd);
2182 #else
2183 	/*
2184 	 * We don't have "pcap_breakloop()"; this isn't safe, but
2185 	 * it's the best we can do.  Print the summary if we're
2186 	 * not reading from a savefile - i.e., if we're doing a
2187 	 * live capture - and exit.
2188 	 */
2189 	if (pd != NULL && pcap_file(pd) == NULL) {
2190 		/*
2191 		 * We got interrupted, so perhaps we didn't
2192 		 * manage to finish a line we were printing.
2193 		 * Print an extra newline, just in case.
2194 		 */
2195 		putchar('\n');
2196 		(void)fflush(stdout);
2197 		info(1);
2198 	}
2199 	exit_tcpdump(0);
2200 #endif
2201 }
2202 
2203 /*
2204   On windows, we do not use a fork, so we do not care less about
2205   waiting a child processes to die
2206  */
2207 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2208 static RETSIGTYPE
2209 child_cleanup(int signo _U_)
2210 {
2211   wait(NULL);
2212 }
2213 #endif /* HAVE_FORK && HAVE_VFORK */
2214 
2215 static void
2216 info(register int verbose)
2217 {
2218 	struct pcap_stat stats;
2219 
2220 	/*
2221 	 * Older versions of libpcap didn't set ps_ifdrop on some
2222 	 * platforms; initialize it to 0 to handle that.
2223 	 */
2224 	stats.ps_ifdrop = 0;
2225 	if (pcap_stats(pd, &stats) < 0) {
2226 		(void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
2227 		infoprint = 0;
2228 		return;
2229 	}
2230 
2231 	if (!verbose)
2232 		fprintf(stderr, "%s: ", program_name);
2233 
2234 	(void)fprintf(stderr, "%u packet%s captured", packets_captured,
2235 	    PLURAL_SUFFIX(packets_captured));
2236 	if (!verbose)
2237 		fputs(", ", stderr);
2238 	else
2239 		putc('\n', stderr);
2240 	(void)fprintf(stderr, "%u packet%s received by filter", stats.ps_recv,
2241 	    PLURAL_SUFFIX(stats.ps_recv));
2242 	if (!verbose)
2243 		fputs(", ", stderr);
2244 	else
2245 		putc('\n', stderr);
2246 	(void)fprintf(stderr, "%u packet%s dropped by kernel", stats.ps_drop,
2247 	    PLURAL_SUFFIX(stats.ps_drop));
2248 	if (stats.ps_ifdrop != 0) {
2249 		if (!verbose)
2250 			fputs(", ", stderr);
2251 		else
2252 			putc('\n', stderr);
2253 		(void)fprintf(stderr, "%u packet%s dropped by interface\n",
2254 		    stats.ps_ifdrop, PLURAL_SUFFIX(stats.ps_ifdrop));
2255 	} else
2256 		putc('\n', stderr);
2257 	infoprint = 0;
2258 }
2259 
2260 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
2261 #ifdef HAVE_FORK
2262 #define fork_subprocess() fork()
2263 #else
2264 #define fork_subprocess() vfork()
2265 #endif
2266 static void
2267 compress_savefile(const char *filename)
2268 {
2269 	pid_t child;
2270 
2271 	child = fork_subprocess();
2272 	if (child == -1) {
2273 		fprintf(stderr,
2274 			"compress_savefile: fork failed: %s\n",
2275 			pcap_strerror(errno));
2276 		return;
2277 	}
2278 	if (child != 0) {
2279 		/* Parent process. */
2280 		return;
2281 	}
2282 
2283 	/*
2284 	 * Child process.
2285 	 * Set to lowest priority so that this doesn't disturb the capture.
2286 	 */
2287 #ifdef NZERO
2288 	setpriority(PRIO_PROCESS, 0, NZERO - 1);
2289 #else
2290 	setpriority(PRIO_PROCESS, 0, 19);
2291 #endif
2292 	if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2293 		fprintf(stderr,
2294 			"compress_savefile: execlp(%s, %s) failed: %s\n",
2295 			zflag,
2296 			filename,
2297 			pcap_strerror(errno));
2298 #ifdef HAVE_FORK
2299 	exit(1);
2300 #else
2301 	_exit(1);
2302 #endif
2303 }
2304 #else  /* HAVE_FORK && HAVE_VFORK */
2305 static void
2306 compress_savefile(const char *filename)
2307 {
2308 	fprintf(stderr,
2309 		"compress_savefile failed. Functionality not implemented under your system\n");
2310 }
2311 #endif /* HAVE_FORK && HAVE_VFORK */
2312 
2313 static void
2314 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2315 {
2316 	struct dump_info *dump_info;
2317 
2318 	++packets_captured;
2319 
2320 	++infodelay;
2321 
2322 	dump_info = (struct dump_info *)user;
2323 
2324 	/*
2325 	 * XXX - this won't force the file to rotate on the specified time
2326 	 * boundary, but it will rotate on the first packet received after the
2327 	 * specified Gflag number of seconds. Note: if a Gflag time boundary
2328 	 * and a Cflag size boundary coincide, the time rotation will occur
2329 	 * first thereby cancelling the Cflag boundary (since the file should
2330 	 * be 0).
2331 	 */
2332 	if (Gflag != 0) {
2333 		/* Check if it is time to rotate */
2334 		time_t t;
2335 
2336 		/* Get the current time */
2337 		if ((t = time(NULL)) == (time_t)-1) {
2338 			error("dump_and_trunc_packet: can't get current_time: %s",
2339 			    pcap_strerror(errno));
2340 		}
2341 
2342 
2343 		/* If the time is greater than the specified window, rotate */
2344 		if (t - Gflag_time >= Gflag) {
2345 #ifdef HAVE_CAPSICUM
2346 			FILE *fp;
2347 			int fd;
2348 #endif
2349 
2350 			/* Update the Gflag_time */
2351 			Gflag_time = t;
2352 			/* Update Gflag_count */
2353 			Gflag_count++;
2354 			/*
2355 			 * Close the current file and open a new one.
2356 			 */
2357 			pcap_dump_close(dump_info->p);
2358 
2359 			/*
2360 			 * Compress the file we just closed, if the user asked for it
2361 			 */
2362 			if (zflag != NULL)
2363 				compress_savefile(dump_info->CurrentFileName);
2364 
2365 			/*
2366 			 * Check to see if we've exceeded the Wflag (when
2367 			 * not using Cflag).
2368 			 */
2369 			if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2370 				(void)fprintf(stderr, "Maximum file limit reached: %d\n",
2371 				    Wflag);
2372 				info(1);
2373 				exit_tcpdump(0);
2374 				/* NOTREACHED */
2375 			}
2376 			if (dump_info->CurrentFileName != NULL)
2377 				free(dump_info->CurrentFileName);
2378 			/* Allocate space for max filename + \0. */
2379 			dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2380 			if (dump_info->CurrentFileName == NULL)
2381 				error("dump_packet_and_trunc: malloc");
2382 			/*
2383 			 * Gflag was set otherwise we wouldn't be here. Reset the count
2384 			 * so multiple files would end with 1,2,3 in the filename.
2385 			 * The counting is handled with the -C flow after this.
2386 			 */
2387 			Cflag_count = 0;
2388 
2389 			/*
2390 			 * This is always the first file in the Cflag
2391 			 * rotation: e.g. 0
2392 			 * We also don't need numbering if Cflag is not set.
2393 			 */
2394 			if (Cflag != 0)
2395 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2396 				    WflagChars);
2397 			else
2398 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2399 
2400 #ifdef HAVE_LIBCAP_NG
2401 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2402 			capng_apply(CAPNG_SELECT_BOTH);
2403 #endif /* HAVE_LIBCAP_NG */
2404 #ifdef HAVE_CAPSICUM
2405 			fd = openat(dump_info->dirfd,
2406 			    dump_info->CurrentFileName,
2407 			    O_CREAT | O_WRONLY | O_TRUNC, 0644);
2408 			if (fd < 0) {
2409 				error("unable to open file %s",
2410 				    dump_info->CurrentFileName);
2411 			}
2412 			fp = fdopen(fd, "w");
2413 			if (fp == NULL) {
2414 				error("unable to fdopen file %s",
2415 				    dump_info->CurrentFileName);
2416 			}
2417 			dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2418 #else	/* !HAVE_CAPSICUM */
2419 			dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2420 #endif
2421 #ifdef HAVE_LIBCAP_NG
2422 			capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2423 			capng_apply(CAPNG_SELECT_BOTH);
2424 #endif /* HAVE_LIBCAP_NG */
2425 			if (dump_info->p == NULL)
2426 				error("%s", pcap_geterr(pd));
2427 #ifdef HAVE_CAPSICUM
2428 			set_dumper_capsicum_rights(dump_info->p);
2429 #endif
2430 		}
2431 	}
2432 
2433 	/*
2434 	 * XXX - this won't prevent capture files from getting
2435 	 * larger than Cflag - the last packet written to the
2436 	 * file could put it over Cflag.
2437 	 */
2438 	if (Cflag != 0) {
2439 		long size = pcap_dump_ftell(dump_info->p);
2440 
2441 		if (size == -1)
2442 			error("ftell fails on output file");
2443 		if (size > Cflag) {
2444 #ifdef HAVE_CAPSICUM
2445 			FILE *fp;
2446 			int fd;
2447 #endif
2448 
2449 			/*
2450 			 * Close the current file and open a new one.
2451 			 */
2452 			pcap_dump_close(dump_info->p);
2453 
2454 			/*
2455 			 * Compress the file we just closed, if the user
2456 			 * asked for it.
2457 			 */
2458 			if (zflag != NULL)
2459 				compress_savefile(dump_info->CurrentFileName);
2460 
2461 			Cflag_count++;
2462 			if (Wflag > 0) {
2463 				if (Cflag_count >= Wflag)
2464 					Cflag_count = 0;
2465 			}
2466 			if (dump_info->CurrentFileName != NULL)
2467 				free(dump_info->CurrentFileName);
2468 			dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2469 			if (dump_info->CurrentFileName == NULL)
2470 				error("dump_packet_and_trunc: malloc");
2471 			MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2472 #ifdef HAVE_LIBCAP_NG
2473 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2474 			capng_apply(CAPNG_SELECT_BOTH);
2475 #endif /* HAVE_LIBCAP_NG */
2476 #ifdef HAVE_CAPSICUM
2477 			fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2478 			    O_CREAT | O_WRONLY | O_TRUNC, 0644);
2479 			if (fd < 0) {
2480 				error("unable to open file %s",
2481 				    dump_info->CurrentFileName);
2482 			}
2483 			fp = fdopen(fd, "w");
2484 			if (fp == NULL) {
2485 				error("unable to fdopen file %s",
2486 				    dump_info->CurrentFileName);
2487 			}
2488 			dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2489 #else	/* !HAVE_CAPSICUM */
2490 			dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2491 #endif
2492 #ifdef HAVE_LIBCAP_NG
2493 			capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2494 			capng_apply(CAPNG_SELECT_BOTH);
2495 #endif /* HAVE_LIBCAP_NG */
2496 			if (dump_info->p == NULL)
2497 				error("%s", pcap_geterr(pd));
2498 #ifdef HAVE_CAPSICUM
2499 			set_dumper_capsicum_rights(dump_info->p);
2500 #endif
2501 		}
2502 	}
2503 
2504 	pcap_dump((u_char *)dump_info->p, h, sp);
2505 #ifdef HAVE_PCAP_DUMP_FLUSH
2506 	if (Uflag)
2507 		pcap_dump_flush(dump_info->p);
2508 #endif
2509 
2510 	--infodelay;
2511 	if (infoprint)
2512 		info(0);
2513 }
2514 
2515 static void
2516 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2517 {
2518 	++packets_captured;
2519 
2520 	++infodelay;
2521 
2522 	pcap_dump(user, h, sp);
2523 #ifdef HAVE_PCAP_DUMP_FLUSH
2524 	if (Uflag)
2525 		pcap_dump_flush((pcap_dumper_t *)user);
2526 #endif
2527 
2528 	--infodelay;
2529 	if (infoprint)
2530 		info(0);
2531 }
2532 
2533 static void
2534 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2535 {
2536 	++packets_captured;
2537 
2538 	++infodelay;
2539 
2540 	pretty_print_packet((netdissect_options *)user, h, sp, packets_captured);
2541 
2542 	--infodelay;
2543 	if (infoprint)
2544 		info(0);
2545 }
2546 
2547 #ifdef _WIN32
2548 	/*
2549 	 * XXX - there should really be libpcap calls to get the version
2550 	 * number as a string (the string would be generated from #defines
2551 	 * at run time, so that it's not generated from string constants
2552 	 * in the library, as, on many UNIX systems, those constants would
2553 	 * be statically linked into the application executable image, and
2554 	 * would thus reflect the version of libpcap on the system on
2555 	 * which the application was *linked*, not the system on which it's
2556 	 * *running*.
2557 	 *
2558 	 * That routine should be documented, unlike the "version[]"
2559 	 * string, so that UNIX vendors providing their own libpcaps
2560 	 * don't omit it (as a couple of vendors have...).
2561 	 *
2562 	 * Packet.dll should perhaps also export a routine to return the
2563 	 * version number of the Packet.dll code, to supply the
2564 	 * "Wpcap_version" information on Windows.
2565 	 */
2566 	char WDversion[]="current-git.tcpdump.org";
2567 #if !defined(HAVE_GENERATED_VERSION)
2568 	char version[]="current-git.tcpdump.org";
2569 #endif
2570 	char pcap_version[]="current-git.tcpdump.org";
2571 	char Wpcap_version[]="3.1";
2572 #endif
2573 
2574 #ifdef SIGNAL_REQ_INFO
2575 RETSIGTYPE requestinfo(int signo _U_)
2576 {
2577 	if (infodelay)
2578 		++infoprint;
2579 	else
2580 		info(0);
2581 }
2582 #endif
2583 
2584 /*
2585  * Called once each second in verbose mode while dumping to file
2586  */
2587 #ifdef USE_WIN32_MM_TIMER
2588 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2589 				  DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2590 {
2591 	if (infodelay == 0)
2592 		fprintf(stderr, "Got %u\r", packets_captured);
2593 }
2594 #elif defined(HAVE_ALARM)
2595 static void verbose_stats_dump(int sig _U_)
2596 {
2597 	if (infodelay == 0)
2598 		fprintf(stderr, "Got %u\r", packets_captured);
2599 	alarm(1);
2600 }
2601 #endif
2602 
2603 USES_APPLE_DEPRECATED_API
2604 static void
2605 print_version(void)
2606 {
2607 	extern char version[];
2608 #ifndef HAVE_PCAP_LIB_VERSION
2609 #if defined(_WIN32) || defined(HAVE_PCAP_VERSION)
2610 	extern char pcap_version[];
2611 #else /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2612 	static char pcap_version[] = "unknown";
2613 #endif /* defined(_WIN32) || defined(HAVE_PCAP_VERSION) */
2614 #endif /* HAVE_PCAP_LIB_VERSION */
2615 	const char *smi_version_string;
2616 
2617 #ifdef HAVE_PCAP_LIB_VERSION
2618 #ifdef _WIN32
2619 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2620 #else /* _WIN32 */
2621 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
2622 #endif /* _WIN32 */
2623 	(void)fprintf(stderr, "%s\n",pcap_lib_version());
2624 #else /* HAVE_PCAP_LIB_VERSION */
2625 #ifdef _WIN32
2626 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2627 	(void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2628 #else /* _WIN32 */
2629 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
2630 	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2631 #endif /* _WIN32 */
2632 #endif /* HAVE_PCAP_LIB_VERSION */
2633 
2634 #if defined(HAVE_LIBCRYPTO) && defined(SSLEAY_VERSION)
2635 	(void)fprintf (stderr, "%s\n", SSLeay_version(SSLEAY_VERSION));
2636 #endif
2637 
2638 	smi_version_string = nd_smi_version_string();
2639 	if (smi_version_string != NULL)
2640 		(void)fprintf (stderr, "SMI-library: %s\n", smi_version_string);
2641 
2642 #if defined(__SANITIZE_ADDRESS__)
2643 	(void)fprintf (stderr, "Compiled with AddressSanitizer/GCC.\n");
2644 #elif defined(__has_feature)
2645 #  if __has_feature(address_sanitizer)
2646 	(void)fprintf (stderr, "Compiled with AddressSanitizer/CLang.\n");
2647 #  endif
2648 #endif /* __SANITIZE_ADDRESS__ or __has_feature */
2649 }
2650 USES_APPLE_RST
2651 
2652 static void
2653 print_usage(void)
2654 {
2655 	print_version();
2656 	(void)fprintf(stderr,
2657 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqStu" U_FLAG "vxX#]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2658 	(void)fprintf(stderr,
2659 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2660 	(void)fprintf(stderr,
2661 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ] [ --number ]\n");
2662 #ifdef HAVE_PCAP_SETDIRECTION
2663 	(void)fprintf(stderr,
2664 "\t\t[ -Q in|out|inout ]\n");
2665 #endif
2666 	(void)fprintf(stderr,
2667 "\t\t[ -r file ] [ -s snaplen ] ");
2668 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2669 	(void)fprintf(stderr, "[ --time-stamp-precision precision ]\n");
2670 	(void)fprintf(stderr,
2671 "\t\t");
2672 #endif
2673 #ifdef HAVE_PCAP_SET_IMMEDIATE_MODE
2674 	(void)fprintf(stderr, "[ --immediate-mode ] ");
2675 #endif
2676 	(void)fprintf(stderr, "[ -T type ] [ --version ] [ -V file ]\n");
2677 	(void)fprintf(stderr,
2678 "\t\t[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]\n");
2679 	(void)fprintf(stderr,
2680 "\t\t[ -Z user ] [ expression ]\n");
2681 }
2682 /*
2683  * Local Variables:
2684  * c-style: whitesmith
2685  * c-basic-offset: 8
2686  * End:
2687  */
2688