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