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