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