xref: /freebsd/contrib/tcpdump/tcpdump.c (revision 2d4dfaf5)
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 static const char rcsid[] _U_ =
33     "@(#) $Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.283 2008-09-25 21:45:50 guy Exp $ (LBL)";
34 #endif
35 
36 /* $FreeBSD$ */
37 
38 /*
39  * tcpdump - monitor tcp/ip traffic on an ethernet.
40  *
41  * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
42  * Mercilessly hacked and occasionally improved since then via the
43  * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
44  */
45 
46 #ifdef HAVE_CONFIG_H
47 #include "config.h"
48 #endif
49 
50 #include <tcpdump-stdinc.h>
51 
52 #ifdef WIN32
53 #include "getopt.h"
54 #include "w32_fzs.h"
55 extern int strcasecmp (const char *__s1, const char *__s2);
56 extern int SIZE_BUF;
57 #define off_t long
58 #define uint UINT
59 #endif /* WIN32 */
60 
61 #ifdef HAVE_SMI_H
62 #include <smi.h>
63 #endif
64 
65 #include <pcap.h>
66 #include <signal.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <limits.h>
71 #ifdef __FreeBSD__
72 #include <sys/capsicum.h>
73 #include <sys/ioccom.h>
74 #include <sys/types.h>
75 #include <sys/sysctl.h>
76 #include <net/bpf.h>
77 #include <fcntl.h>
78 #include <libgen.h>
79 #ifdef HAVE_LIBCAPSICUM
80 #include <libcapsicum.h>
81 #include <libcapsicum_dns.h>
82 #include <libcapsicum_service.h>
83 #include <nv.h>
84 #endif	/* HAVE_LIBCAPSICUM */
85 #endif	/* __FreeBSD__ */
86 #ifndef WIN32
87 #include <sys/wait.h>
88 #include <sys/resource.h>
89 #include <pwd.h>
90 #include <grp.h>
91 #include <errno.h>
92 #endif /* WIN32 */
93 
94 /* capabilities convinience library */
95 #ifdef HAVE_CAP_NG_H
96 #include <cap-ng.h>
97 #endif /* HAVE_CAP_NG_H */
98 
99 #include "netdissect.h"
100 #include "interface.h"
101 #include "addrtoname.h"
102 #include "machdep.h"
103 #include "setsignal.h"
104 #include "gmt2local.h"
105 #include "pcap-missing.h"
106 
107 #ifndef PATH_MAX
108 #define PATH_MAX 1024
109 #endif
110 
111 #ifdef SIGINFO
112 #define SIGNAL_REQ_INFO SIGINFO
113 #elif SIGUSR1
114 #define SIGNAL_REQ_INFO SIGUSR1
115 #endif
116 
117 netdissect_options Gndo;
118 netdissect_options *gndo = &Gndo;
119 
120 static int dflag;			/* print filter code */
121 static int Lflag;			/* list available data link types and exit */
122 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
123 static int Jflag;			/* list available time stamp types */
124 #endif
125 static char *zflag = NULL;		/* compress each savefile using a specified command (like gzip or bzip2) */
126 
127 static int infodelay;
128 static int infoprint;
129 
130 char *program_name;
131 
132 #ifdef HAVE_LIBCAPSICUM
133 cap_channel_t *capdns;
134 #endif
135 
136 int32_t thiszone;		/* seconds offset from gmt to local time */
137 
138 /* Forwards */
139 static RETSIGTYPE cleanup(int);
140 static RETSIGTYPE child_cleanup(int);
141 static void usage(void) __attribute__((noreturn));
142 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
143 
144 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
145 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
146 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
147 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
148 static void droproot(const char *, const char *);
149 static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
150      __attribute__ ((noreturn, format (printf, 2, 3)));
151 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
152 
153 #ifdef SIGNAL_REQ_INFO
154 RETSIGTYPE requestinfo(int);
155 #endif
156 
157 #if defined(USE_WIN32_MM_TIMER)
158   #include <MMsystem.h>
159   static UINT timer_id;
160   static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
161 #elif defined(HAVE_ALARM)
162   static void verbose_stats_dump(int sig);
163 #endif
164 
165 static void info(int);
166 static u_int packets_captured;
167 
168 struct printer {
169         if_printer f;
170 	int type;
171 };
172 
173 
174 struct ndo_printer {
175         if_ndo_printer f;
176 	int type;
177 };
178 
179 
180 static struct printer printers[] = {
181 	{ arcnet_if_print,	DLT_ARCNET },
182 #ifdef DLT_ARCNET_LINUX
183 	{ arcnet_linux_if_print, DLT_ARCNET_LINUX },
184 #endif
185 	{ token_if_print,	DLT_IEEE802 },
186 #ifdef DLT_LANE8023
187 	{ lane_if_print,        DLT_LANE8023 },
188 #endif
189 #ifdef DLT_CIP
190 	{ cip_if_print,         DLT_CIP },
191 #endif
192 #ifdef DLT_ATM_CLIP
193 	{ cip_if_print,		DLT_ATM_CLIP },
194 #endif
195 	{ sl_if_print,		DLT_SLIP },
196 #ifdef DLT_SLIP_BSDOS
197 	{ sl_bsdos_if_print,	DLT_SLIP_BSDOS },
198 #endif
199 	{ ppp_if_print,		DLT_PPP },
200 #ifdef DLT_PPP_WITHDIRECTION
201 	{ ppp_if_print,		DLT_PPP_WITHDIRECTION },
202 #endif
203 #ifdef DLT_PPP_BSDOS
204 	{ ppp_bsdos_if_print,	DLT_PPP_BSDOS },
205 #endif
206 	{ fddi_if_print,	DLT_FDDI },
207 	{ null_if_print,	DLT_NULL },
208 #ifdef DLT_LOOP
209 	{ null_if_print,	DLT_LOOP },
210 #endif
211 	{ raw_if_print,		DLT_RAW },
212 	{ atm_if_print,		DLT_ATM_RFC1483 },
213 #ifdef DLT_C_HDLC
214 	{ chdlc_if_print,	DLT_C_HDLC },
215 #endif
216 #ifdef DLT_HDLC
217 	{ chdlc_if_print,	DLT_HDLC },
218 #endif
219 #ifdef DLT_PPP_SERIAL
220 	{ ppp_hdlc_if_print,	DLT_PPP_SERIAL },
221 #endif
222 #ifdef DLT_PPP_ETHER
223 	{ pppoe_if_print,	DLT_PPP_ETHER },
224 #endif
225 #ifdef DLT_LINUX_SLL
226 	{ sll_if_print,		DLT_LINUX_SLL },
227 #endif
228 #ifdef DLT_IEEE802_11
229 	{ ieee802_11_if_print,	DLT_IEEE802_11},
230 #endif
231 #ifdef DLT_LTALK
232 	{ ltalk_if_print,	DLT_LTALK },
233 #endif
234 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
235 	{ pflog_if_print,	DLT_PFLOG },
236 #endif
237 #ifdef DLT_FR
238 	{ fr_if_print,		DLT_FR },
239 #endif
240 #ifdef DLT_FRELAY
241 	{ fr_if_print,		DLT_FRELAY },
242 #endif
243 #ifdef DLT_SUNATM
244 	{ sunatm_if_print,	DLT_SUNATM },
245 #endif
246 #ifdef DLT_IP_OVER_FC
247 	{ ipfc_if_print,	DLT_IP_OVER_FC },
248 #endif
249 #ifdef DLT_PRISM_HEADER
250 	{ prism_if_print,	DLT_PRISM_HEADER },
251 #endif
252 #ifdef DLT_IEEE802_11_RADIO
253 	{ ieee802_11_radio_if_print,	DLT_IEEE802_11_RADIO },
254 #endif
255 #ifdef DLT_ENC
256 	{ enc_if_print,		DLT_ENC },
257 #endif
258 #ifdef DLT_SYMANTEC_FIREWALL
259 	{ symantec_if_print,	DLT_SYMANTEC_FIREWALL },
260 #endif
261 #ifdef DLT_APPLE_IP_OVER_IEEE1394
262 	{ ap1394_if_print,	DLT_APPLE_IP_OVER_IEEE1394 },
263 #endif
264 #ifdef DLT_IEEE802_11_RADIO_AVS
265 	{ ieee802_11_radio_avs_if_print,	DLT_IEEE802_11_RADIO_AVS },
266 #endif
267 #ifdef DLT_JUNIPER_ATM1
268 	{ juniper_atm1_print,	DLT_JUNIPER_ATM1 },
269 #endif
270 #ifdef DLT_JUNIPER_ATM2
271 	{ juniper_atm2_print,	DLT_JUNIPER_ATM2 },
272 #endif
273 #ifdef DLT_JUNIPER_MFR
274 	{ juniper_mfr_print,	DLT_JUNIPER_MFR },
275 #endif
276 #ifdef DLT_JUNIPER_MLFR
277 	{ juniper_mlfr_print,	DLT_JUNIPER_MLFR },
278 #endif
279 #ifdef DLT_JUNIPER_MLPPP
280 	{ juniper_mlppp_print,	DLT_JUNIPER_MLPPP },
281 #endif
282 #ifdef DLT_JUNIPER_PPPOE
283 	{ juniper_pppoe_print,	DLT_JUNIPER_PPPOE },
284 #endif
285 #ifdef DLT_JUNIPER_PPPOE_ATM
286 	{ juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
287 #endif
288 #ifdef DLT_JUNIPER_GGSN
289 	{ juniper_ggsn_print,	DLT_JUNIPER_GGSN },
290 #endif
291 #ifdef DLT_JUNIPER_ES
292 	{ juniper_es_print,	DLT_JUNIPER_ES },
293 #endif
294 #ifdef DLT_JUNIPER_MONITOR
295 	{ juniper_monitor_print, DLT_JUNIPER_MONITOR },
296 #endif
297 #ifdef DLT_JUNIPER_SERVICES
298 	{ juniper_services_print, DLT_JUNIPER_SERVICES },
299 #endif
300 #ifdef DLT_JUNIPER_ETHER
301 	{ juniper_ether_print,	DLT_JUNIPER_ETHER },
302 #endif
303 #ifdef DLT_JUNIPER_PPP
304 	{ juniper_ppp_print,	DLT_JUNIPER_PPP },
305 #endif
306 #ifdef DLT_JUNIPER_FRELAY
307 	{ juniper_frelay_print,	DLT_JUNIPER_FRELAY },
308 #endif
309 #ifdef DLT_JUNIPER_CHDLC
310 	{ juniper_chdlc_print,	DLT_JUNIPER_CHDLC },
311 #endif
312 #ifdef DLT_MFR
313 	{ mfr_if_print,		DLT_MFR },
314 #endif
315 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
316 	{ bt_if_print,		DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
317 #endif
318 #ifdef HAVE_PCAP_USB_H
319 #ifdef DLT_USB_LINUX
320 	{ usb_linux_48_byte_print, DLT_USB_LINUX},
321 #endif /* DLT_USB_LINUX */
322 #ifdef DLT_USB_LINUX_MMAPPED
323 	{ usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
324 #endif /* DLT_USB_LINUX_MMAPPED */
325 #endif /* HAVE_PCAP_USB_H */
326 #ifdef DLT_IPV4
327 	{ raw_if_print,		DLT_IPV4 },
328 #endif
329 #ifdef DLT_IPV6
330 	{ raw_if_print,		DLT_IPV6 },
331 #endif
332 	{ NULL,			0 },
333 };
334 
335 static struct ndo_printer ndo_printers[] = {
336 	{ ether_if_print,	DLT_EN10MB },
337 #ifdef DLT_IPNET
338 	{ ipnet_if_print,	DLT_IPNET },
339 #endif
340 #ifdef DLT_IEEE802_15_4
341 	{ ieee802_15_4_if_print, DLT_IEEE802_15_4 },
342 #endif
343 #ifdef DLT_IEEE802_15_4_NOFCS
344 	{ ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
345 #endif
346 #ifdef DLT_PPI
347 	{ ppi_if_print,		DLT_PPI },
348 #endif
349 #ifdef DLT_NETANALYZER
350 	{ netanalyzer_if_print, DLT_NETANALYZER },
351 #endif
352 #ifdef DLT_NETANALYZER_TRANSPARENT
353 	{ netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
354 #endif
355 	{ NULL,			0 },
356 };
357 
358 if_printer
359 lookup_printer(int type)
360 {
361 	struct printer *p;
362 
363 	for (p = printers; p->f; ++p)
364 		if (type == p->type)
365 			return p->f;
366 
367 	return NULL;
368 	/* NOTREACHED */
369 }
370 
371 if_ndo_printer
372 lookup_ndo_printer(int type)
373 {
374 	struct ndo_printer *p;
375 
376 	for (p = ndo_printers; p->f; ++p)
377 		if (type == p->type)
378 			return p->f;
379 
380 	return NULL;
381 	/* NOTREACHED */
382 }
383 
384 static pcap_t *pd;
385 
386 static int supports_monitor_mode;
387 
388 extern int optind;
389 extern int opterr;
390 extern char *optarg;
391 
392 struct print_info {
393         netdissect_options *ndo;
394         union {
395                 if_printer     printer;
396                 if_ndo_printer ndo_printer;
397         } p;
398         int ndo_type;
399 };
400 
401 struct dump_info {
402 	char	*WFileName;
403 	char	*CurrentFileName;
404 	pcap_t	*pd;
405 	pcap_dumper_t *p;
406 #ifdef __FreeBSD__
407 	int	dirfd;
408 #endif
409 };
410 
411 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
412 static void
413 show_tstamp_types_and_exit(const char *device, pcap_t *pd)
414 {
415 	int n_tstamp_types;
416 	int *tstamp_types = 0;
417 	const char *tstamp_type_name;
418 	int i;
419 
420 	n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
421 	if (n_tstamp_types < 0)
422 		error("%s", pcap_geterr(pd));
423 
424 	if (n_tstamp_types == 0) {
425 		fprintf(stderr, "Time stamp type cannot be set for %s\n",
426 		    device);
427 		exit(0);
428 	}
429 	fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
430 	    device);
431 	for (i = 0; i < n_tstamp_types; i++) {
432 		tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
433 		if (tstamp_type_name != NULL) {
434 			(void) fprintf(stderr, "  %s (%s)\n", tstamp_type_name,
435 			    pcap_tstamp_type_val_to_description(tstamp_types[i]));
436 		} else {
437 			(void) fprintf(stderr, "  %d\n", tstamp_types[i]);
438 		}
439 	}
440 	pcap_free_tstamp_types(tstamp_types);
441 	exit(0);
442 }
443 #endif
444 
445 static void
446 show_dlts_and_exit(const char *device, pcap_t *pd)
447 {
448 	int n_dlts;
449 	int *dlts = 0;
450 	const char *dlt_name;
451 
452 	n_dlts = pcap_list_datalinks(pd, &dlts);
453 	if (n_dlts < 0)
454 		error("%s", pcap_geterr(pd));
455 	else if (n_dlts == 0 || !dlts)
456 		error("No data link types.");
457 
458 	/*
459 	 * If the interface is known to support monitor mode, indicate
460 	 * whether these are the data link types available when not in
461 	 * monitor mode, if -I wasn't specified, or when in monitor mode,
462 	 * when -I was specified (the link-layer types available in
463 	 * monitor mode might be different from the ones available when
464 	 * not in monitor mode).
465 	 */
466 	if (supports_monitor_mode)
467 		(void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
468 		    device,
469 		    Iflag ? "when in monitor mode" : "when not in monitor mode");
470 	else
471 		(void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
472 		    device);
473 
474 	while (--n_dlts >= 0) {
475 		dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
476 		if (dlt_name != NULL) {
477 			(void) fprintf(stderr, "  %s (%s)", dlt_name,
478 			    pcap_datalink_val_to_description(dlts[n_dlts]));
479 
480 			/*
481 			 * OK, does tcpdump handle that type?
482 			 */
483 			if (lookup_printer(dlts[n_dlts]) == NULL
484                             && lookup_ndo_printer(dlts[n_dlts]) == NULL)
485 				(void) fprintf(stderr, " (printing not supported)");
486 			fprintf(stderr, "\n");
487 		} else {
488 			(void) fprintf(stderr, "  DLT %d (printing not supported)\n",
489 			    dlts[n_dlts]);
490 		}
491 	}
492 #ifdef HAVE_PCAP_FREE_DATALINKS
493 	pcap_free_datalinks(dlts);
494 #endif
495 	exit(0);
496 }
497 
498 /*
499  * Set up flags that might or might not be supported depending on the
500  * version of libpcap we're using.
501  */
502 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
503 #define B_FLAG		"B:"
504 #define B_FLAG_USAGE	" [ -B size ]"
505 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
506 #define B_FLAG
507 #define B_FLAG_USAGE
508 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
509 
510 #ifdef HAVE_PCAP_CREATE
511 #define I_FLAG		"I"
512 #else /* HAVE_PCAP_CREATE */
513 #define I_FLAG
514 #endif /* HAVE_PCAP_CREATE */
515 
516 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
517 #define j_FLAG		"j:"
518 #define j_FLAG_USAGE	" [ -j tstamptype ]"
519 #define J_FLAG		"J"
520 #else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
521 #define j_FLAG
522 #define j_FLAG_USAGE
523 #define J_FLAG
524 #endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
525 
526 #ifdef HAVE_PCAP_FINDALLDEVS
527 #ifndef HAVE_PCAP_IF_T
528 #undef HAVE_PCAP_FINDALLDEVS
529 #endif
530 #endif
531 
532 #ifdef HAVE_PCAP_FINDALLDEVS
533 #define D_FLAG	"D"
534 #else
535 #define D_FLAG
536 #endif
537 
538 #ifdef HAVE_PCAP_DUMP_FLUSH
539 #define U_FLAG	"U"
540 #else
541 #define U_FLAG
542 #endif
543 
544 #ifndef WIN32
545 /* Drop root privileges and chroot if necessary */
546 static void
547 droproot(const char *username, const char *chroot_dir)
548 {
549 	struct passwd *pw = NULL;
550 
551 	if (chroot_dir && !username) {
552 		fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
553 		exit(1);
554 	}
555 
556 	pw = getpwnam(username);
557 	if (pw) {
558 		if (chroot_dir) {
559 			if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
560 				fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
561 				    chroot_dir, pcap_strerror(errno));
562 				exit(1);
563 			}
564 		}
565 #ifdef HAVE_CAP_NG_H
566 		int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
567 		if (ret < 0) {
568 			printf("error : ret %d\n", ret);
569 		}
570 		/* We don't need CAP_SETUID and CAP_SETGID */
571 		capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
572 		capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
573 		capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
574 		capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
575 		capng_apply(CAPNG_SELECT_BOTH);
576 
577 #else
578 		if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
579 		    setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
580 			fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
581 			    username,
582 			    (unsigned long)pw->pw_uid,
583 			    (unsigned long)pw->pw_gid,
584 			    pcap_strerror(errno));
585 			exit(1);
586 		}
587 #endif /* HAVE_CAP_NG_H */
588 	}
589 	else {
590 		fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
591 		    username);
592 		exit(1);
593 	}
594 }
595 #endif /* WIN32 */
596 
597 static int
598 getWflagChars(int x)
599 {
600 	int c = 0;
601 
602 	x -= 1;
603 	while (x > 0) {
604 		c += 1;
605 		x /= 10;
606 	}
607 
608 	return c;
609 }
610 
611 
612 static void
613 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
614 {
615         char *filename = malloc(PATH_MAX + 1);
616         if (filename == NULL)
617             error("Makefilename: malloc");
618 
619         /* Process with strftime if Gflag is set. */
620         if (Gflag != 0) {
621           struct tm *local_tm;
622 
623           /* Convert Gflag_time to a usable format */
624           if ((local_tm = localtime(&Gflag_time)) == NULL) {
625                   error("MakeTimedFilename: localtime");
626           }
627 
628           /* There's no good way to detect an error in strftime since a return
629            * value of 0 isn't necessarily failure.
630            */
631           strftime(filename, PATH_MAX, orig_name, local_tm);
632         } else {
633           strncpy(filename, orig_name, PATH_MAX);
634         }
635 
636 	if (cnt == 0 && max_chars == 0)
637 		strncpy(buffer, filename, PATH_MAX + 1);
638 	else
639 		if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
640                   /* Report an error if the filename is too large */
641                   error("too many output files or filename is too long (> %d)", PATH_MAX);
642         free(filename);
643 }
644 
645 static int tcpdump_printf(netdissect_options *ndo _U_,
646 			  const char *fmt, ...)
647 {
648 
649   va_list args;
650   int ret;
651 
652   va_start(args, fmt);
653   ret=vfprintf(stdout, fmt, args);
654   va_end(args);
655 
656   return ret;
657 }
658 
659 static struct print_info
660 get_print_info(int type)
661 {
662 	struct print_info printinfo;
663 
664 	printinfo.ndo_type = 1;
665 	printinfo.ndo = gndo;
666 	printinfo.p.ndo_printer = lookup_ndo_printer(type);
667 	if (printinfo.p.ndo_printer == NULL) {
668 		printinfo.p.printer = lookup_printer(type);
669 		printinfo.ndo_type = 0;
670 		if (printinfo.p.printer == NULL) {
671 			gndo->ndo_dltname = pcap_datalink_val_to_name(type);
672 			if (gndo->ndo_dltname != NULL)
673 				error("packet printing is not supported for link type %s: use -w",
674 				      gndo->ndo_dltname);
675 			else
676 				error("packet printing is not supported for link type %d: use -w", type);
677 		}
678 	}
679 	return (printinfo);
680 }
681 
682 static char *
683 get_next_file(FILE *VFile, char *ptr)
684 {
685 	char *ret;
686 
687 	ret = fgets(ptr, PATH_MAX, VFile);
688 	if (!ret)
689 		return NULL;
690 
691 	if (ptr[strlen(ptr) - 1] == '\n')
692 		ptr[strlen(ptr) - 1] = '\0';
693 
694 	return ret;
695 }
696 
697 #ifdef HAVE_LIBCAPSICUM
698 static cap_channel_t *
699 capdns_setup(void)
700 {
701 	cap_channel_t *capcas, *capdnsloc;
702 	const char *types[1];
703 	int families[2];
704 
705 	capcas = cap_init();
706 	if (capcas == NULL) {
707 		warning("unable to contact casperd");
708 		return (NULL);
709 	}
710 	capdnsloc = cap_service_open(capcas, "system.dns");
711 	/* Casper capability no longer needed. */
712 	cap_close(capcas);
713 	if (capdnsloc == NULL)
714 		error("unable to open system.dns service");
715 	/* Limit system.dns to reverse DNS lookups. */
716 	types[0] = "ADDR";
717 	if (cap_dns_type_limit(capdnsloc, types, 1) < 0)
718 		error("unable to limit access to system.dns service");
719 	families[0] = AF_INET;
720 	families[1] = AF_INET6;
721 	if (cap_dns_family_limit(capdnsloc, families, 2) < 0)
722 		error("unable to limit access to system.dns service");
723 
724 	return (capdnsloc);
725 }
726 #endif	/* HAVE_LIBCAPSICUM */
727 
728 int
729 main(int argc, char **argv)
730 {
731 	register int cnt, op, i;
732 	bpf_u_int32 localnet, netmask;
733 	register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName;
734 	pcap_handler callback;
735 	int type;
736 	int dlt;
737 	int new_dlt;
738 	const char *dlt_name;
739 	struct bpf_program fcode;
740 #ifndef WIN32
741 	RETSIGTYPE (*oldhandler)(int);
742 #endif
743 	struct print_info printinfo;
744 	struct dump_info dumpinfo;
745 	u_char *pcap_userdata;
746 	char ebuf[PCAP_ERRBUF_SIZE];
747 	char VFileLine[PATH_MAX + 1];
748 	char *username = NULL;
749 	char *chroot_dir = NULL;
750 	char *ret = NULL;
751 	char *end;
752 #ifdef HAVE_PCAP_FINDALLDEVS
753 	pcap_if_t *devpointer;
754 	int devnum;
755 #endif
756 	int status;
757 	FILE *VFile;
758 #ifdef __FreeBSD__
759 	cap_rights_t rights;
760 	int cansandbox;
761 #endif	/* __FreeBSD__ */
762 
763 #ifdef WIN32
764 	if(wsockinit() != 0) return 1;
765 #endif /* WIN32 */
766 
767 	jflag=-1;	/* not set */
768         gndo->ndo_Oflag=1;
769 	gndo->ndo_Rflag=1;
770 	gndo->ndo_dlt=-1;
771 	gndo->ndo_default_print=ndo_default_print;
772 	gndo->ndo_printf=tcpdump_printf;
773 	gndo->ndo_error=ndo_error;
774 	gndo->ndo_warning=ndo_warning;
775 	gndo->ndo_snaplen = DEFAULT_SNAPLEN;
776 
777 	cnt = -1;
778 	device = NULL;
779 	infile = NULL;
780 	RFileName = NULL;
781 	VFileName = NULL;
782 	VFile = NULL;
783 	WFileName = NULL;
784 	dlt = -1;
785 	if ((cp = strrchr(argv[0], '/')) != NULL)
786 		program_name = cp + 1;
787 	else
788 		program_name = argv[0];
789 
790 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
791 		error("%s", ebuf);
792 
793 #ifdef LIBSMI
794 	smiInit("tcpdump");
795 #endif
796 
797 	while (
798 	    (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:hHi:" I_FLAG j_FLAG J_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "V:vw:W:xXy:Yz:Z:")) != -1)
799 		switch (op) {
800 
801 		case 'a':
802 			/* compatibility for old -a */
803 			break;
804 
805 		case 'A':
806 			++Aflag;
807 			break;
808 
809 		case 'b':
810 			++bflag;
811 			break;
812 
813 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
814 		case 'B':
815 			Bflag = atoi(optarg)*1024;
816 			if (Bflag <= 0)
817 				error("invalid packet buffer size %s", optarg);
818 			break;
819 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
820 
821 		case 'c':
822 			cnt = atoi(optarg);
823 			if (cnt <= 0)
824 				error("invalid packet count %s", optarg);
825 			break;
826 
827 		case 'C':
828 			Cflag = atoi(optarg) * 1000000;
829 			if (Cflag < 0)
830 				error("invalid file size %s", optarg);
831 			break;
832 
833 		case 'd':
834 			++dflag;
835 			break;
836 
837 #ifdef HAVE_PCAP_FINDALLDEVS
838 		case 'D':
839 			if (pcap_findalldevs(&devpointer, ebuf) < 0)
840 				error("%s", ebuf);
841 			else {
842 				for (i = 0; devpointer != 0; i++) {
843 					printf("%d.%s", i+1, devpointer->name);
844 					if (devpointer->description != NULL)
845 						printf(" (%s)", devpointer->description);
846 					printf("\n");
847 					devpointer = devpointer->next;
848 				}
849 			}
850 			return 0;
851 #endif /* HAVE_PCAP_FINDALLDEVS */
852 
853 		case 'L':
854 			Lflag++;
855 			break;
856 
857 		case 'e':
858 			++eflag;
859 			break;
860 
861 		case 'E':
862 #ifndef HAVE_LIBCRYPTO
863 			warning("crypto code not compiled in");
864 #endif
865 			gndo->ndo_espsecret = optarg;
866 			break;
867 
868 		case 'f':
869 			++fflag;
870 			break;
871 
872 		case 'F':
873 			infile = optarg;
874 			break;
875 
876 		case 'G':
877 			Gflag = atoi(optarg);
878 			if (Gflag < 0)
879 				error("invalid number of seconds %s", optarg);
880 
881                         /* We will create one file initially. */
882                         Gflag_count = 0;
883 
884 			/* Grab the current time for rotation use. */
885 			if ((Gflag_time = time(NULL)) == (time_t)-1) {
886 				error("main: can't get current time: %s",
887 				    pcap_strerror(errno));
888 			}
889 			break;
890 
891 		case 'h':
892 			usage();
893 			break;
894 
895 		case 'H':
896 			++Hflag;
897 			break;
898 
899 		case 'i':
900 			if (optarg[0] == '0' && optarg[1] == 0)
901 				error("Invalid adapter index");
902 
903 #ifdef HAVE_PCAP_FINDALLDEVS
904 			/*
905 			 * If the argument is a number, treat it as
906 			 * an index into the list of adapters, as
907 			 * printed by "tcpdump -D".
908 			 *
909 			 * This should be OK on UNIX systems, as interfaces
910 			 * shouldn't have names that begin with digits.
911 			 * It can be useful on Windows, where more than
912 			 * one interface can have the same name.
913 			 */
914 			devnum = strtol(optarg, &end, 10);
915 			if (optarg != end && *end == '\0') {
916 				if (devnum < 0)
917 					error("Invalid adapter index");
918 
919 				if (pcap_findalldevs(&devpointer, ebuf) < 0)
920 					error("%s", ebuf);
921 				else {
922 					/*
923 					 * Look for the devnum-th entry
924 					 * in the list of devices
925 					 * (1-based).
926 					 */
927 					for (i = 0;
928 					    i < devnum-1 && devpointer != NULL;
929 					    i++, devpointer = devpointer->next)
930 						;
931 					if (devpointer == NULL)
932 						error("Invalid adapter index");
933 				}
934 				device = devpointer->name;
935 				break;
936 			}
937 #endif /* HAVE_PCAP_FINDALLDEVS */
938 			device = optarg;
939 			break;
940 
941 #ifdef HAVE_PCAP_CREATE
942 		case 'I':
943 			++Iflag;
944 			break;
945 #endif /* HAVE_PCAP_CREATE */
946 
947 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
948 		case 'j':
949 			jflag = pcap_tstamp_type_name_to_val(optarg);
950 			if (jflag < 0)
951 				error("invalid time stamp type %s", optarg);
952 			break;
953 
954 		case 'J':
955 			Jflag++;
956 			break;
957 #endif
958 
959 		case 'l':
960 #ifdef WIN32
961 			/*
962 			 * _IOLBF is the same as _IOFBF in Microsoft's C
963 			 * libraries; the only alternative they offer
964 			 * is _IONBF.
965 			 *
966 			 * XXX - this should really be checking for MSVC++,
967 			 * not WIN32, if, for example, MinGW has its own
968 			 * C library that is more UNIX-compatible.
969 			 */
970 			setvbuf(stdout, NULL, _IONBF, 0);
971 #else /* WIN32 */
972 #ifdef HAVE_SETLINEBUF
973 			setlinebuf(stdout);
974 #else
975 			setvbuf(stdout, NULL, _IOLBF, 0);
976 #endif
977 #endif /* WIN32 */
978 			break;
979 
980 		case 'K':
981 			++Kflag;
982 			break;
983 
984 		case 'm':
985 #ifdef LIBSMI
986 			if (smiLoadModule(optarg) == 0) {
987 				error("could not load MIB module %s", optarg);
988 			}
989 			sflag = 1;
990 #else
991 			(void)fprintf(stderr, "%s: ignoring option `-m %s' ",
992 				      program_name, optarg);
993 			(void)fprintf(stderr, "(no libsmi support)\n");
994 #endif
995 			break;
996 
997 		case 'M':
998 			/* TCP-MD5 shared secret */
999 #ifndef HAVE_LIBCRYPTO
1000 			warning("crypto code not compiled in");
1001 #endif
1002 			sigsecret = optarg;
1003 			break;
1004 
1005 		case 'n':
1006 			++nflag;
1007 			break;
1008 
1009 		case 'N':
1010 			++Nflag;
1011 			break;
1012 
1013 		case 'O':
1014 			Oflag = 0;
1015 			break;
1016 
1017 		case 'p':
1018 			++pflag;
1019 			break;
1020 
1021 		case 'q':
1022 			++qflag;
1023 			++suppress_default_print;
1024 			break;
1025 
1026 		case 'r':
1027 			RFileName = optarg;
1028 			break;
1029 
1030 		case 'R':
1031 			Rflag = 0;
1032 			break;
1033 
1034 		case 's':
1035 			snaplen = strtol(optarg, &end, 0);
1036 			if (optarg == end || *end != '\0'
1037 			    || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
1038 				error("invalid snaplen %s", optarg);
1039 			else if (snaplen == 0)
1040 				snaplen = MAXIMUM_SNAPLEN;
1041 			break;
1042 
1043 		case 'S':
1044 			++Sflag;
1045 			break;
1046 
1047 		case 't':
1048 			++tflag;
1049 			break;
1050 
1051 		case 'T':
1052 			if (strcasecmp(optarg, "vat") == 0)
1053 				packettype = PT_VAT;
1054 			else if (strcasecmp(optarg, "wb") == 0)
1055 				packettype = PT_WB;
1056 			else if (strcasecmp(optarg, "rpc") == 0)
1057 				packettype = PT_RPC;
1058 			else if (strcasecmp(optarg, "rtp") == 0)
1059 				packettype = PT_RTP;
1060 			else if (strcasecmp(optarg, "rtcp") == 0)
1061 				packettype = PT_RTCP;
1062 			else if (strcasecmp(optarg, "snmp") == 0)
1063 				packettype = PT_SNMP;
1064 			else if (strcasecmp(optarg, "cnfp") == 0)
1065 				packettype = PT_CNFP;
1066 			else if (strcasecmp(optarg, "tftp") == 0)
1067 				packettype = PT_TFTP;
1068 			else if (strcasecmp(optarg, "aodv") == 0)
1069 				packettype = PT_AODV;
1070 			else if (strcasecmp(optarg, "carp") == 0)
1071 				packettype = PT_CARP;
1072 			else if (strcasecmp(optarg, "radius") == 0)
1073 				packettype = PT_RADIUS;
1074 			else if (strcasecmp(optarg, "zmtp1") == 0)
1075 				packettype = PT_ZMTP1;
1076 			else if (strcasecmp(optarg, "vxlan") == 0)
1077 				packettype = PT_VXLAN;
1078 			else
1079 				error("unknown packet type `%s'", optarg);
1080 			break;
1081 
1082 		case 'u':
1083 			++uflag;
1084 			break;
1085 
1086 #ifdef HAVE_PCAP_DUMP_FLUSH
1087 		case 'U':
1088 			++Uflag;
1089 			break;
1090 #endif
1091 
1092 		case 'v':
1093 			++vflag;
1094 			break;
1095 
1096 		case 'V':
1097 			VFileName = optarg;
1098 			break;
1099 
1100 		case 'w':
1101 			WFileName = optarg;
1102 			break;
1103 
1104 		case 'W':
1105 			Wflag = atoi(optarg);
1106 			if (Wflag < 0)
1107 				error("invalid number of output files %s", optarg);
1108 			WflagChars = getWflagChars(Wflag);
1109 			break;
1110 
1111 		case 'x':
1112 			++xflag;
1113 			++suppress_default_print;
1114 			break;
1115 
1116 		case 'X':
1117 			++Xflag;
1118 			++suppress_default_print;
1119 			break;
1120 
1121 		case 'y':
1122 			gndo->ndo_dltname = optarg;
1123 			gndo->ndo_dlt =
1124 			  pcap_datalink_name_to_val(gndo->ndo_dltname);
1125 			if (gndo->ndo_dlt < 0)
1126 				error("invalid data link type %s", gndo->ndo_dltname);
1127 			break;
1128 
1129 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1130 		case 'Y':
1131 			{
1132 			/* Undocumented flag */
1133 #ifdef HAVE_PCAP_DEBUG
1134 			extern int pcap_debug;
1135 			pcap_debug = 1;
1136 #else
1137 			extern int yydebug;
1138 			yydebug = 1;
1139 #endif
1140 			}
1141 			break;
1142 #endif
1143 		case 'z':
1144 			if (optarg) {
1145 				zflag = strdup(optarg);
1146 			} else {
1147 				usage();
1148 				/* NOTREACHED */
1149 			}
1150 			break;
1151 
1152 		case 'Z':
1153 			if (optarg) {
1154 				username = strdup(optarg);
1155 			}
1156 			else {
1157 				usage();
1158 				/* NOTREACHED */
1159 			}
1160 			break;
1161 
1162 		default:
1163 			usage();
1164 			/* NOTREACHED */
1165 		}
1166 
1167 	switch (tflag) {
1168 
1169 	case 0: /* Default */
1170 	case 4: /* Default + Date*/
1171 		thiszone = gmt2local(0);
1172 		break;
1173 
1174 	case 1: /* No time stamp */
1175 	case 2: /* Unix timeval style */
1176 	case 3: /* Microseconds since previous packet */
1177         case 5: /* Microseconds since first packet */
1178 		break;
1179 
1180 	default: /* Not supported */
1181 		error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1182 		break;
1183 	}
1184 
1185 	if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1186 		error("-f can not be used with -V or -r");
1187 
1188 	if (VFileName != NULL && RFileName != NULL)
1189 		error("-V and -r are mutually exclusive.");
1190 
1191 #ifdef WITH_CHROOT
1192 	/* if run as root, prepare for chrooting */
1193 	if (getuid() == 0 || geteuid() == 0) {
1194 		/* future extensibility for cmd-line arguments */
1195 		if (!chroot_dir)
1196 			chroot_dir = WITH_CHROOT;
1197 	}
1198 #endif
1199 
1200 #ifdef WITH_USER
1201 	/* if run as root, prepare for dropping root privileges */
1202 	if (getuid() == 0 || geteuid() == 0) {
1203 		/* Run with '-Z root' to restore old behaviour */
1204 		if (!username)
1205 			username = WITH_USER;
1206 	}
1207 #endif
1208 
1209 	if (RFileName != NULL || VFileName != NULL) {
1210 		/*
1211 		 * If RFileName is non-null, it's the pathname of a
1212 		 * savefile to read.  If VFileName is non-null, it's
1213 		 * the pathname of a file containing a list of pathnames
1214 		 * (one per line) of savefiles to read.
1215 		 *
1216 		 * In either case, we're reading a savefile, not doing
1217 		 * a live capture.
1218 		 */
1219 #ifndef WIN32
1220 		/*
1221 		 * We don't need network access, so relinquish any set-UID
1222 		 * or set-GID privileges we have (if any).
1223 		 *
1224 		 * We do *not* want set-UID privileges when opening a
1225 		 * trace file, as that might let the user read other
1226 		 * people's trace files (especially if we're set-UID
1227 		 * root).
1228 		 */
1229 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1230 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1231 #endif /* WIN32 */
1232 		if (VFileName != NULL) {
1233 			if (VFileName[0] == '-' && VFileName[1] == '\0')
1234 				VFile = stdin;
1235 			else
1236 				VFile = fopen(VFileName, "r");
1237 
1238 			if (VFile == NULL)
1239 				error("Unable to open file: %s\n", strerror(errno));
1240 
1241 			ret = get_next_file(VFile, VFileLine);
1242 			if (!ret)
1243 				error("Nothing in %s\n", VFileName);
1244 			RFileName = VFileLine;
1245 		}
1246 
1247 		pd = pcap_open_offline(RFileName, ebuf);
1248 		if (pd == NULL)
1249 			error("%s", ebuf);
1250 #ifdef __FreeBSD__
1251 		cap_rights_init(&rights, CAP_READ);
1252 		if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 &&
1253 		    errno != ENOSYS) {
1254 			error("unable to limit pcap descriptor");
1255 		}
1256 #endif
1257 		dlt = pcap_datalink(pd);
1258 		dlt_name = pcap_datalink_val_to_name(dlt);
1259 		if (dlt_name == NULL) {
1260 			fprintf(stderr, "reading from file %s, link-type %u\n",
1261 			    RFileName, dlt);
1262 		} else {
1263 			fprintf(stderr,
1264 			    "reading from file %s, link-type %s (%s)\n",
1265 			    RFileName, dlt_name,
1266 			    pcap_datalink_val_to_description(dlt));
1267 		}
1268 		localnet = 0;
1269 		netmask = 0;
1270 	} else {
1271 		/*
1272 		 * We're doing a live capture.
1273 		 */
1274 		if (device == NULL) {
1275 			device = pcap_lookupdev(ebuf);
1276 			if (device == NULL)
1277 				error("%s", ebuf);
1278 		}
1279 #ifdef WIN32
1280 		/*
1281 		 * Print a message to the standard error on Windows.
1282 		 * XXX - why do it here, with a different message?
1283 		 */
1284 		if(strlen(device) == 1)	//we assume that an ASCII string is always longer than 1 char
1285 		{						//a Unicode string has a \0 as second byte (so strlen() is 1)
1286 			fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1287 		}
1288 		else
1289 		{
1290 			fprintf(stderr, "%s: listening on %s\n", program_name, device);
1291 		}
1292 
1293 		fflush(stderr);
1294 #endif /* WIN32 */
1295 #ifdef HAVE_PCAP_CREATE
1296 		pd = pcap_create(device, ebuf);
1297 		if (pd == NULL)
1298 			error("%s", ebuf);
1299 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1300 		if (Jflag)
1301 			show_tstamp_types_and_exit(device, pd);
1302 #endif
1303 		/*
1304 		 * Is this an interface that supports monitor mode?
1305 		 */
1306 		if (pcap_can_set_rfmon(pd) == 1)
1307 			supports_monitor_mode = 1;
1308 		else
1309 			supports_monitor_mode = 0;
1310 		status = pcap_set_snaplen(pd, snaplen);
1311 		if (status != 0)
1312 			error("%s: Can't set snapshot length: %s",
1313 			    device, pcap_statustostr(status));
1314 		status = pcap_set_promisc(pd, !pflag);
1315 		if (status != 0)
1316 			error("%s: Can't set promiscuous mode: %s",
1317 			    device, pcap_statustostr(status));
1318 		if (Iflag) {
1319 			status = pcap_set_rfmon(pd, 1);
1320 			if (status != 0)
1321 				error("%s: Can't set monitor mode: %s",
1322 				    device, pcap_statustostr(status));
1323 		}
1324 		status = pcap_set_timeout(pd, 1000);
1325 		if (status != 0)
1326 			error("%s: pcap_set_timeout failed: %s",
1327 			    device, pcap_statustostr(status));
1328 		if (Bflag != 0) {
1329 			status = pcap_set_buffer_size(pd, Bflag);
1330 			if (status != 0)
1331 				error("%s: Can't set buffer size: %s",
1332 				    device, pcap_statustostr(status));
1333 		}
1334 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1335                 if (jflag != -1) {
1336 			status = pcap_set_tstamp_type(pd, jflag);
1337 			if (status < 0)
1338 				error("%s: Can't set time stamp type: %s",
1339 			    	    device, pcap_statustostr(status));
1340 		}
1341 #endif
1342 		status = pcap_activate(pd);
1343 		if (status < 0) {
1344 			/*
1345 			 * pcap_activate() failed.
1346 			 */
1347 			cp = pcap_geterr(pd);
1348 			if (status == PCAP_ERROR)
1349 				error("%s", cp);
1350 			else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1351 			          status == PCAP_ERROR_PERM_DENIED) &&
1352 			         *cp != '\0')
1353 				error("%s: %s\n(%s)", device,
1354 				    pcap_statustostr(status), cp);
1355 #ifdef __FreeBSD__
1356 			else if (status == PCAP_ERROR_RFMON_NOTSUP &&
1357 			    strncmp(device, "wlan", 4) == 0) {
1358 				char parent[8], newdev[8];
1359 				char sysctl[32];
1360 				size_t s = sizeof(parent);
1361 
1362 				snprintf(sysctl, sizeof(sysctl),
1363 				    "net.wlan.%d.%%parent", atoi(device + 4));
1364 				sysctlbyname(sysctl, parent, &s, NULL, 0);
1365 				strlcpy(newdev, device, sizeof(newdev));
1366 				/* Suggest a new wlan device. */
1367 				newdev[strlen(newdev)-1]++;
1368 				error("%s is not a monitor mode VAP\n"
1369 				    "To create a new monitor mode VAP use:\n"
1370 				    "  ifconfig %s create wlandev %s wlanmode "
1371 				    "monitor\nand use %s as the tcpdump "
1372 				    "interface", device, newdev, parent,
1373 				    newdev);
1374 			}
1375 #endif
1376 			else
1377 				error("%s: %s", device,
1378 				    pcap_statustostr(status));
1379 		} else if (status > 0) {
1380 			/*
1381 			 * pcap_activate() succeeded, but it's warning us
1382 			 * of a problem it had.
1383 			 */
1384 			cp = pcap_geterr(pd);
1385 			if (status == PCAP_WARNING)
1386 				warning("%s", cp);
1387 			else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1388 			         *cp != '\0')
1389 				warning("%s: %s\n(%s)", device,
1390 				    pcap_statustostr(status), cp);
1391 			else
1392 				warning("%s: %s", device,
1393 				    pcap_statustostr(status));
1394 		}
1395 #else
1396 		*ebuf = '\0';
1397 		pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1398 		if (pd == NULL)
1399 			error("%s", ebuf);
1400 		else if (*ebuf)
1401 			warning("%s", ebuf);
1402 #endif /* HAVE_PCAP_CREATE */
1403 		/*
1404 		 * Let user own process after socket has been opened.
1405 		 */
1406 #ifndef WIN32
1407 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1408 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1409 #endif /* WIN32 */
1410 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1411 		if(Bflag != 0)
1412 			if(pcap_setbuff(pd, Bflag)==-1){
1413 				error("%s", pcap_geterr(pd));
1414 			}
1415 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1416 		if (Lflag)
1417 			show_dlts_and_exit(device, pd);
1418 		if (gndo->ndo_dlt >= 0) {
1419 #ifdef HAVE_PCAP_SET_DATALINK
1420 			if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1421 				error("%s", pcap_geterr(pd));
1422 #else
1423 			/*
1424 			 * We don't actually support changing the
1425 			 * data link type, so we only let them
1426 			 * set it to what it already is.
1427 			 */
1428 			if (gndo->ndo_dlt != pcap_datalink(pd)) {
1429 				error("%s is not one of the DLTs supported by this device\n",
1430 				      gndo->ndo_dltname);
1431 			}
1432 #endif
1433 			(void)fprintf(stderr, "%s: data link type %s\n",
1434 				      program_name, gndo->ndo_dltname);
1435 			(void)fflush(stderr);
1436 		}
1437 		i = pcap_snapshot(pd);
1438 		if (snaplen < i) {
1439 			warning("snaplen raised from %d to %d", snaplen, i);
1440 			snaplen = i;
1441 		}
1442 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1443 			localnet = 0;
1444 			netmask = 0;
1445 			warning("%s", ebuf);
1446 		}
1447 	}
1448 	if (infile)
1449 		cmdbuf = read_infile(infile);
1450 	else
1451 		cmdbuf = copy_argv(&argv[optind]);
1452 
1453 	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1454 		error("%s", pcap_geterr(pd));
1455 	if (dflag) {
1456 		bpf_dump(&fcode, dflag);
1457 		pcap_close(pd);
1458 		free(cmdbuf);
1459 		exit(0);
1460 	}
1461 
1462 #ifdef HAVE_LIBCAPSICUM
1463 	if (!nflag)
1464 		capdns = capdns_setup();
1465 #endif	/* HAVE_LIBCAPSICUM */
1466 
1467 	init_addrtoname(localnet, netmask);
1468         init_checksum();
1469 
1470 #ifndef WIN32
1471 	(void)setsignal(SIGPIPE, cleanup);
1472 	(void)setsignal(SIGTERM, cleanup);
1473 	(void)setsignal(SIGINT, cleanup);
1474 #endif /* WIN32 */
1475 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1476 	(void)setsignal(SIGCHLD, child_cleanup);
1477 #endif
1478 	/* Cooperate with nohup(1) */
1479 #ifndef WIN32
1480 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1481 		(void)setsignal(SIGHUP, oldhandler);
1482 #endif /* WIN32 */
1483 
1484 #ifndef WIN32
1485 	/*
1486 	 * If a user name was specified with "-Z", attempt to switch to
1487 	 * that user's UID.  This would probably be used with sudo,
1488 	 * to allow tcpdump to be run in a special restricted
1489 	 * account (if you just want to allow users to open capture
1490 	 * devices, and can't just give users that permission,
1491 	 * you'd make tcpdump set-UID or set-GID).
1492 	 *
1493 	 * Tcpdump doesn't necessarily write only to one savefile;
1494 	 * the general only way to allow a -Z instance to write to
1495 	 * savefiles as the user under whose UID it's run, rather
1496 	 * than as the user specified with -Z, would thus be to switch
1497 	 * to the original user ID before opening a capture file and
1498 	 * then switch back to the -Z user ID after opening the savefile.
1499 	 * Switching to the -Z user ID only after opening the first
1500 	 * savefile doesn't handle the general case.
1501 	 */
1502 
1503 #ifdef HAVE_CAP_NG_H
1504 	/* We are running as root and we will be writing to savefile */
1505 	if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1506 		if (username) {
1507 			/* Drop all capabilities from effective set */
1508 			capng_clear(CAPNG_EFFECTIVE);
1509 			/* Add capabilities we will need*/
1510 			capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1511 			capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1512 			capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1513 
1514 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1515 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1516 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1517 
1518 			capng_apply(CAPNG_SELECT_BOTH);
1519 		}
1520 	}
1521 #endif /* HAVE_CAP_NG_H */
1522 
1523 	if (getuid() == 0 || geteuid() == 0) {
1524 		if (username || chroot_dir)
1525 			droproot(username, chroot_dir);
1526 
1527 	}
1528 #endif /* WIN32 */
1529 
1530 	if (pcap_setfilter(pd, &fcode) < 0)
1531 		error("%s", pcap_geterr(pd));
1532 #ifdef __FreeBSD__
1533 	if (RFileName == NULL && VFileName == NULL) {
1534 		static const unsigned long cmds[] = { BIOCGSTATS };
1535 
1536 		/*
1537 		 * The various libpcap devices use a combination of
1538 		 * read (bpf), ioctl (bpf, netmap), poll (netmap).
1539 		 * Grant the relevant access rights, sorted by name.
1540 		 */
1541 		cap_rights_init(&rights, CAP_EVENT, CAP_IOCTL, CAP_READ);
1542 		if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 &&
1543 		    errno != ENOSYS) {
1544 			error("unable to limit pcap descriptor");
1545 		}
1546 		if (cap_ioctls_limit(pcap_fileno(pd), cmds,
1547 		    sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) {
1548 			error("unable to limit ioctls on pcap descriptor");
1549 		}
1550 	}
1551 #endif
1552 	if (WFileName) {
1553 		pcap_dumper_t *p;
1554 		/* Do not exceed the default PATH_MAX for files. */
1555 		dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1556 
1557 		if (dumpinfo.CurrentFileName == NULL)
1558 			error("malloc of dumpinfo.CurrentFileName");
1559 
1560 		/* We do not need numbering for dumpfiles if Cflag isn't set. */
1561 		if (Cflag != 0)
1562 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1563 		else
1564 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1565 
1566 		p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1567 #ifdef HAVE_CAP_NG_H
1568         /* Give up capabilities, clear Effective set */
1569         capng_clear(CAPNG_EFFECTIVE);
1570 #endif
1571 		if (p == NULL)
1572 			error("%s", pcap_geterr(pd));
1573 #ifdef __FreeBSD__
1574 		cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
1575 		if (cap_rights_limit(fileno(pcap_dump_file(p)), &rights) < 0 &&
1576 		    errno != ENOSYS) {
1577 			error("unable to limit dump descriptor");
1578 		}
1579 #endif
1580 		if (Cflag != 0 || Gflag != 0) {
1581 #ifdef __FreeBSD__
1582 			dumpinfo.WFileName = strdup(basename(WFileName));
1583 			dumpinfo.dirfd = open(dirname(WFileName),
1584 			    O_DIRECTORY | O_RDONLY);
1585 			if (dumpinfo.dirfd < 0) {
1586 				error("unable to open directory %s",
1587 				    dirname(WFileName));
1588 			}
1589 			cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL,
1590 			    CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE);
1591 			if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 &&
1592 			    errno != ENOSYS) {
1593 				error("unable to limit directory rights");
1594 			}
1595 #else	/* !__FreeBSD__ */
1596 			dumpinfo.WFileName = WFileName;
1597 #endif
1598 			callback = dump_packet_and_trunc;
1599 			dumpinfo.pd = pd;
1600 			dumpinfo.p = p;
1601 			pcap_userdata = (u_char *)&dumpinfo;
1602 		} else {
1603 			callback = dump_packet;
1604 			pcap_userdata = (u_char *)p;
1605 		}
1606 #ifdef HAVE_PCAP_DUMP_FLUSH
1607 		if (Uflag)
1608 			pcap_dump_flush(p);
1609 #endif
1610 	} else {
1611 		type = pcap_datalink(pd);
1612 		printinfo = get_print_info(type);
1613 		callback = print_packet;
1614 		pcap_userdata = (u_char *)&printinfo;
1615 	}
1616 
1617 #ifdef SIGNAL_REQ_INFO
1618 	/*
1619 	 * We can't get statistics when reading from a file rather
1620 	 * than capturing from a device.
1621 	 */
1622 	if (RFileName == NULL)
1623 		(void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1624 #endif
1625 
1626 	if (vflag > 0 && WFileName) {
1627 		/*
1628 		 * When capturing to a file, "-v" means tcpdump should,
1629 		 * every 10 secodns, "v"erbosely report the number of
1630 		 * packets captured.
1631 		 */
1632 #ifdef USE_WIN32_MM_TIMER
1633 		/* call verbose_stats_dump() each 1000 +/-100msec */
1634 		timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1635 		setvbuf(stderr, NULL, _IONBF, 0);
1636 #elif defined(HAVE_ALARM)
1637 		(void)setsignal(SIGALRM, verbose_stats_dump);
1638 		alarm(1);
1639 #endif
1640 	}
1641 
1642 #ifndef WIN32
1643 	if (RFileName == NULL) {
1644 		/*
1645 		 * Live capture (if -V was specified, we set RFileName
1646 		 * to a file from the -V file).  Print a message to
1647 		 * the standard error on UN*X.
1648 		 */
1649 		if (!vflag && !WFileName) {
1650 			(void)fprintf(stderr,
1651 			    "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1652 			    program_name);
1653 		} else
1654 			(void)fprintf(stderr, "%s: ", program_name);
1655 		dlt = pcap_datalink(pd);
1656 		dlt_name = pcap_datalink_val_to_name(dlt);
1657 		if (dlt_name == NULL) {
1658 			(void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1659 			    device, dlt, snaplen);
1660 		} else {
1661 			(void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1662 			    device, dlt_name,
1663 			    pcap_datalink_val_to_description(dlt), snaplen);
1664 		}
1665 		(void)fflush(stderr);
1666 	}
1667 #endif /* WIN32 */
1668 
1669 #ifdef __FreeBSD__
1670 	cansandbox = (VFileName == NULL && zflag == NULL);
1671 #ifdef HAVE_LIBCAPSICUM
1672 	cansandbox = (cansandbox && (nflag || capdns != NULL));
1673 #else
1674 	cansandbox = (cansandbox && nflag);
1675 #endif
1676 	if (cansandbox && cap_enter() < 0 && errno != ENOSYS)
1677 		error("unable to enter the capability mode");
1678 	if (cap_sandboxed())
1679 		fprintf(stderr, "capability mode sandbox enabled\n");
1680 #endif	/* __FreeBSD__ */
1681 
1682 	do {
1683 		status = pcap_loop(pd, cnt, callback, pcap_userdata);
1684 		if (WFileName == NULL) {
1685 			/*
1686 			 * We're printing packets.  Flush the printed output,
1687 			 * so it doesn't get intermingled with error output.
1688 			 */
1689 			if (status == -2) {
1690 				/*
1691 				 * We got interrupted, so perhaps we didn't
1692 				 * manage to finish a line we were printing.
1693 				 * Print an extra newline, just in case.
1694 				 */
1695 				putchar('\n');
1696 			}
1697 			(void)fflush(stdout);
1698 		}
1699 		if (status == -1) {
1700 			/*
1701 			 * Error.  Report it.
1702 			 */
1703 			(void)fprintf(stderr, "%s: pcap_loop: %s\n",
1704 			    program_name, pcap_geterr(pd));
1705 		}
1706 		if (RFileName == NULL) {
1707 			/*
1708 			 * We're doing a live capture.  Report the capture
1709 			 * statistics.
1710 			 */
1711 			info(1);
1712 		}
1713 		pcap_close(pd);
1714 		if (VFileName != NULL) {
1715 			ret = get_next_file(VFile, VFileLine);
1716 			if (ret) {
1717 				RFileName = VFileLine;
1718 				pd = pcap_open_offline(RFileName, ebuf);
1719 				if (pd == NULL)
1720 					error("%s", ebuf);
1721 #ifdef __FreeBSD__
1722 				cap_rights_init(&rights, CAP_READ);
1723 				if (cap_rights_limit(fileno(pcap_file(pd)),
1724 				    &rights) < 0 && errno != ENOSYS) {
1725 					error("unable to limit pcap descriptor");
1726 				}
1727 #endif
1728 				new_dlt = pcap_datalink(pd);
1729 				if (WFileName && new_dlt != dlt)
1730 					error("%s: new dlt does not match original", RFileName);
1731 				printinfo = get_print_info(new_dlt);
1732 				dlt_name = pcap_datalink_val_to_name(new_dlt);
1733 				if (dlt_name == NULL) {
1734 					fprintf(stderr, "reading from file %s, link-type %u\n",
1735 					RFileName, new_dlt);
1736 				} else {
1737 					fprintf(stderr,
1738 					"reading from file %s, link-type %s (%s)\n",
1739 					RFileName, dlt_name,
1740 					pcap_datalink_val_to_description(new_dlt));
1741 				}
1742 				if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1743 					error("%s", pcap_geterr(pd));
1744 				if (pcap_setfilter(pd, &fcode) < 0)
1745 					error("%s", pcap_geterr(pd));
1746 			}
1747 		}
1748 	}
1749 	while (ret != NULL);
1750 
1751 	free(cmdbuf);
1752 	exit(status == -1 ? 1 : 0);
1753 }
1754 
1755 /* make a clean exit on interrupts */
1756 static RETSIGTYPE
1757 cleanup(int signo _U_)
1758 {
1759 #ifdef USE_WIN32_MM_TIMER
1760 	if (timer_id)
1761 		timeKillEvent(timer_id);
1762 	timer_id = 0;
1763 #elif defined(HAVE_ALARM)
1764 	alarm(0);
1765 #endif
1766 
1767 #ifdef HAVE_PCAP_BREAKLOOP
1768 	/*
1769 	 * We have "pcap_breakloop()"; use it, so that we do as little
1770 	 * as possible in the signal handler (it's probably not safe
1771 	 * to do anything with standard I/O streams in a signal handler -
1772 	 * the ANSI C standard doesn't say it is).
1773 	 */
1774 	pcap_breakloop(pd);
1775 #else
1776 	/*
1777 	 * We don't have "pcap_breakloop()"; this isn't safe, but
1778 	 * it's the best we can do.  Print the summary if we're
1779 	 * not reading from a savefile - i.e., if we're doing a
1780 	 * live capture - and exit.
1781 	 */
1782 	if (pd != NULL && pcap_file(pd) == NULL) {
1783 		/*
1784 		 * We got interrupted, so perhaps we didn't
1785 		 * manage to finish a line we were printing.
1786 		 * Print an extra newline, just in case.
1787 		 */
1788 		putchar('\n');
1789 		(void)fflush(stdout);
1790 		info(1);
1791 	}
1792 	exit(0);
1793 #endif
1794 }
1795 
1796 /*
1797   On windows, we do not use a fork, so we do not care less about
1798   waiting a child processes to die
1799  */
1800 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1801 static RETSIGTYPE
1802 child_cleanup(int signo _U_)
1803 {
1804   wait(NULL);
1805 }
1806 #endif /* HAVE_FORK && HAVE_VFORK */
1807 
1808 static void
1809 info(register int verbose)
1810 {
1811 	struct pcap_stat stat;
1812 
1813 	/*
1814 	 * Older versions of libpcap didn't set ps_ifdrop on some
1815 	 * platforms; initialize it to 0 to handle that.
1816 	 */
1817 	stat.ps_ifdrop = 0;
1818 	if (pcap_stats(pd, &stat) < 0) {
1819 		(void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1820 		infoprint = 0;
1821 		return;
1822 	}
1823 
1824 	if (!verbose)
1825 		fprintf(stderr, "%s: ", program_name);
1826 
1827 	(void)fprintf(stderr, "%u packet%s captured", packets_captured,
1828 	    PLURAL_SUFFIX(packets_captured));
1829 	if (!verbose)
1830 		fputs(", ", stderr);
1831 	else
1832 		putc('\n', stderr);
1833 	(void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1834 	    PLURAL_SUFFIX(stat.ps_recv));
1835 	if (!verbose)
1836 		fputs(", ", stderr);
1837 	else
1838 		putc('\n', stderr);
1839 	(void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1840 	    PLURAL_SUFFIX(stat.ps_drop));
1841 	if (stat.ps_ifdrop != 0) {
1842 		if (!verbose)
1843 			fputs(", ", stderr);
1844 		else
1845 			putc('\n', stderr);
1846 		(void)fprintf(stderr, "%u packet%s dropped by interface\n",
1847 		    stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
1848 	} else
1849 		putc('\n', stderr);
1850 	infoprint = 0;
1851 }
1852 
1853 #if defined(HAVE_FORK) || defined(HAVE_VFORK)
1854 static void
1855 compress_savefile(const char *filename)
1856 {
1857 # ifdef HAVE_FORK
1858 	if (fork())
1859 # else
1860 	if (vfork())
1861 # endif
1862 		return;
1863 	/*
1864 	 * Set to lowest priority so that this doesn't disturb the capture
1865 	 */
1866 #ifdef NZERO
1867 	setpriority(PRIO_PROCESS, 0, NZERO - 1);
1868 #else
1869 	setpriority(PRIO_PROCESS, 0, 19);
1870 #endif
1871 	if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1872 		fprintf(stderr,
1873 			"compress_savefile:execlp(%s, %s): %s\n",
1874 			zflag,
1875 			filename,
1876 			strerror(errno));
1877 # ifdef HAVE_FORK
1878 	exit(1);
1879 # else
1880 	_exit(1);
1881 # endif
1882 }
1883 #else  /* HAVE_FORK && HAVE_VFORK */
1884 static void
1885 compress_savefile(const char *filename)
1886 {
1887 	fprintf(stderr,
1888 		"compress_savefile failed. Functionality not implemented under your system\n");
1889 }
1890 #endif /* HAVE_FORK && HAVE_VFORK */
1891 
1892 static void
1893 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1894 {
1895 	struct dump_info *dump_info;
1896 #ifdef __FreeBSD__
1897 	cap_rights_t rights;
1898 #endif
1899 
1900 	++packets_captured;
1901 
1902 	++infodelay;
1903 
1904 	dump_info = (struct dump_info *)user;
1905 
1906 	/*
1907 	 * XXX - this won't force the file to rotate on the specified time
1908 	 * boundary, but it will rotate on the first packet received after the
1909 	 * specified Gflag number of seconds. Note: if a Gflag time boundary
1910 	 * and a Cflag size boundary coincide, the time rotation will occur
1911 	 * first thereby cancelling the Cflag boundary (since the file should
1912 	 * be 0).
1913 	 */
1914 	if (Gflag != 0) {
1915 		/* Check if it is time to rotate */
1916 		time_t t;
1917 
1918 		/* Get the current time */
1919 		if ((t = time(NULL)) == (time_t)-1) {
1920 			error("dump_and_trunc_packet: can't get current_time: %s",
1921 			    pcap_strerror(errno));
1922 		}
1923 
1924 
1925 		/* If the time is greater than the specified window, rotate */
1926 		if (t - Gflag_time >= Gflag) {
1927 #ifdef __FreeBSD__
1928 			FILE *fp;
1929 			int fd;
1930 #endif
1931 
1932 			/* Update the Gflag_time */
1933 			Gflag_time = t;
1934 			/* Update Gflag_count */
1935 			Gflag_count++;
1936 			/*
1937 			 * Close the current file and open a new one.
1938 			 */
1939 			pcap_dump_close(dump_info->p);
1940 
1941 			/*
1942 			 * Compress the file we just closed, if the user asked for it
1943 			 */
1944 			if (zflag != NULL)
1945 				compress_savefile(dump_info->CurrentFileName);
1946 
1947 			/*
1948 			 * Check to see if we've exceeded the Wflag (when
1949 			 * not using Cflag).
1950 			 */
1951 			if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1952 				(void)fprintf(stderr, "Maximum file limit reached: %d\n",
1953 				    Wflag);
1954 				exit(0);
1955 				/* NOTREACHED */
1956 			}
1957 			if (dump_info->CurrentFileName != NULL)
1958 				free(dump_info->CurrentFileName);
1959 			/* Allocate space for max filename + \0. */
1960 			dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
1961 			if (dump_info->CurrentFileName == NULL)
1962 				error("dump_packet_and_trunc: malloc");
1963 			/*
1964 			 * This is always the first file in the Cflag
1965 			 * rotation: e.g. 0
1966 			 * We also don't need numbering if Cflag is not set.
1967 			 */
1968 			if (Cflag != 0)
1969 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1970 				    WflagChars);
1971 			else
1972 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1973 
1974 #ifdef HAVE_CAP_NG_H
1975 			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1976 			capng_apply(CAPNG_EFFECTIVE);
1977 #endif /* HAVE_CAP_NG_H */
1978 #ifdef __FreeBSD__
1979 			fd = openat(dump_info->dirfd,
1980 			    dump_info->CurrentFileName,
1981 			    O_CREAT | O_WRONLY | O_TRUNC, 0644);
1982 			if (fd < 0) {
1983 				error("unable to open file %s",
1984 				    dump_info->CurrentFileName);
1985 			}
1986 			fp = fdopen(fd, "w");
1987 			if (fp == NULL) {
1988 				error("unable to fdopen file %s",
1989 				    dump_info->CurrentFileName);
1990 			}
1991 			dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
1992 #else	/* !__FreeBSD__ */
1993 			dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1994 #endif
1995 #ifdef HAVE_CAP_NG_H
1996 			capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1997 			capng_apply(CAPNG_EFFECTIVE);
1998 #endif /* HAVE_CAP_NG_H */
1999 			if (dump_info->p == NULL)
2000 				error("%s", pcap_geterr(pd));
2001 #ifdef __FreeBSD__
2002 			cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2003 			if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2004 			    &rights) < 0 && errno != ENOSYS) {
2005 				error("unable to limit dump descriptor");
2006 			}
2007 #endif
2008 		}
2009 	}
2010 
2011 	/*
2012 	 * XXX - this won't prevent capture files from getting
2013 	 * larger than Cflag - the last packet written to the
2014 	 * file could put it over Cflag.
2015 	 */
2016 	if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
2017 #ifdef __FreeBSD__
2018 		FILE *fp;
2019 		int fd;
2020 #endif
2021 
2022 		/*
2023 		 * Close the current file and open a new one.
2024 		 */
2025 		pcap_dump_close(dump_info->p);
2026 
2027 		/*
2028 		 * Compress the file we just closed, if the user asked for it
2029 		 */
2030 		if (zflag != NULL)
2031 			compress_savefile(dump_info->CurrentFileName);
2032 
2033 		Cflag_count++;
2034 		if (Wflag > 0) {
2035 			if (Cflag_count >= Wflag)
2036 				Cflag_count = 0;
2037 		}
2038 		if (dump_info->CurrentFileName != NULL)
2039 			free(dump_info->CurrentFileName);
2040 		dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2041 		if (dump_info->CurrentFileName == NULL)
2042 			error("dump_packet_and_trunc: malloc");
2043 		MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2044 #ifdef __FreeBSD__
2045 		fd = openat(dump_info->dirfd, dump_info->CurrentFileName,
2046 		    O_CREAT | O_WRONLY | O_TRUNC, 0644);
2047 		if (fd < 0) {
2048 			error("unable to open file %s",
2049 			    dump_info->CurrentFileName);
2050 		}
2051 		fp = fdopen(fd, "w");
2052 		if (fp == NULL) {
2053 			error("unable to fdopen file %s",
2054 			    dump_info->CurrentFileName);
2055 		}
2056 		dump_info->p = pcap_dump_fopen(dump_info->pd, fp);
2057 #else	/* !__FreeBSD__ */
2058 		dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
2059 #endif
2060 		if (dump_info->p == NULL)
2061 			error("%s", pcap_geterr(pd));
2062 #ifdef __FreeBSD__
2063 		cap_rights_init(&rights, CAP_SEEK, CAP_WRITE);
2064 		if (cap_rights_limit(fileno(pcap_dump_file(dump_info->p)),
2065 		    &rights) < 0 && errno != ENOSYS) {
2066 			error("unable to limit dump descriptor");
2067 		}
2068 #endif
2069 	}
2070 
2071 	pcap_dump((u_char *)dump_info->p, h, sp);
2072 #ifdef HAVE_PCAP_DUMP_FLUSH
2073 	if (Uflag)
2074 		pcap_dump_flush(dump_info->p);
2075 #endif
2076 
2077 	--infodelay;
2078 	if (infoprint)
2079 		info(0);
2080 }
2081 
2082 static void
2083 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2084 {
2085 	++packets_captured;
2086 
2087 	++infodelay;
2088 
2089 	pcap_dump(user, h, sp);
2090 #ifdef HAVE_PCAP_DUMP_FLUSH
2091 	if (Uflag)
2092 		pcap_dump_flush((pcap_dumper_t *)user);
2093 #endif
2094 
2095 	--infodelay;
2096 	if (infoprint)
2097 		info(0);
2098 }
2099 
2100 static void
2101 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2102 {
2103 	struct print_info *print_info;
2104 	u_int hdrlen;
2105 
2106 	++packets_captured;
2107 
2108 	++infodelay;
2109 	ts_print(&h->ts);
2110 
2111 	print_info = (struct print_info *)user;
2112 
2113 	/*
2114 	 * Some printers want to check that they're not walking off the
2115 	 * end of the packet.
2116 	 * Rather than pass it all the way down, we set this global.
2117 	 */
2118 	snapend = sp + h->caplen;
2119 
2120         if(print_info->ndo_type) {
2121                 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2122         } else {
2123                 hdrlen = (*print_info->p.printer)(h, sp);
2124         }
2125 
2126 	if (Xflag) {
2127 		/*
2128 		 * Print the raw packet data in hex and ASCII.
2129 		 */
2130 		if (Xflag > 1) {
2131 			/*
2132 			 * Include the link-layer header.
2133 			 */
2134 			hex_and_ascii_print("\n\t", sp, h->caplen);
2135 		} else {
2136 			/*
2137 			 * Don't include the link-layer header - and if
2138 			 * we have nothing past the link-layer header,
2139 			 * print nothing.
2140 			 */
2141 			if (h->caplen > hdrlen)
2142 				hex_and_ascii_print("\n\t", sp + hdrlen,
2143 				    h->caplen - hdrlen);
2144 		}
2145 	} else if (xflag) {
2146 		/*
2147 		 * Print the raw packet data in hex.
2148 		 */
2149 		if (xflag > 1) {
2150 			/*
2151 			 * Include the link-layer header.
2152 			 */
2153 			hex_print("\n\t", sp, h->caplen);
2154 		} else {
2155 			/*
2156 			 * Don't include the link-layer header - and if
2157 			 * we have nothing past the link-layer header,
2158 			 * print nothing.
2159 			 */
2160 			if (h->caplen > hdrlen)
2161 				hex_print("\n\t", sp + hdrlen,
2162 				    h->caplen - hdrlen);
2163 		}
2164 	} else if (Aflag) {
2165 		/*
2166 		 * Print the raw packet data in ASCII.
2167 		 */
2168 		if (Aflag > 1) {
2169 			/*
2170 			 * Include the link-layer header.
2171 			 */
2172 			ascii_print(sp, h->caplen);
2173 		} else {
2174 			/*
2175 			 * Don't include the link-layer header - and if
2176 			 * we have nothing past the link-layer header,
2177 			 * print nothing.
2178 			 */
2179 			if (h->caplen > hdrlen)
2180 				ascii_print(sp + hdrlen, h->caplen - hdrlen);
2181 		}
2182 	}
2183 
2184 	putchar('\n');
2185 
2186 	--infodelay;
2187 	if (infoprint)
2188 		info(0);
2189 }
2190 
2191 #ifdef WIN32
2192 	/*
2193 	 * XXX - there should really be libpcap calls to get the version
2194 	 * number as a string (the string would be generated from #defines
2195 	 * at run time, so that it's not generated from string constants
2196 	 * in the library, as, on many UNIX systems, those constants would
2197 	 * be statically linked into the application executable image, and
2198 	 * would thus reflect the version of libpcap on the system on
2199 	 * which the application was *linked*, not the system on which it's
2200 	 * *running*.
2201 	 *
2202 	 * That routine should be documented, unlike the "version[]"
2203 	 * string, so that UNIX vendors providing their own libpcaps
2204 	 * don't omit it (as a couple of vendors have...).
2205 	 *
2206 	 * Packet.dll should perhaps also export a routine to return the
2207 	 * version number of the Packet.dll code, to supply the
2208 	 * "Wpcap_version" information on Windows.
2209 	 */
2210 	char WDversion[]="current-cvs.tcpdump.org";
2211 #if !defined(HAVE_GENERATED_VERSION)
2212 	char version[]="current-cvs.tcpdump.org";
2213 #endif
2214 	char pcap_version[]="current-cvs.tcpdump.org";
2215 	char Wpcap_version[]="3.1";
2216 #endif
2217 
2218 /*
2219  * By default, print the specified data out in hex and ASCII.
2220  */
2221 static void
2222 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
2223 {
2224 	hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
2225 }
2226 
2227 void
2228 default_print(const u_char *bp, u_int length)
2229 {
2230 	ndo_default_print(gndo, bp, length);
2231 }
2232 
2233 #ifdef SIGNAL_REQ_INFO
2234 RETSIGTYPE requestinfo(int signo _U_)
2235 {
2236 	if (infodelay)
2237 		++infoprint;
2238 	else
2239 		info(0);
2240 }
2241 #endif
2242 
2243 /*
2244  * Called once each second in verbose mode while dumping to file
2245  */
2246 #ifdef USE_WIN32_MM_TIMER
2247 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2248 				  DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2249 {
2250 	struct pcap_stat stat;
2251 
2252 	if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2253 		fprintf(stderr, "Got %u\r", packets_captured);
2254 }
2255 #elif defined(HAVE_ALARM)
2256 static void verbose_stats_dump(int sig _U_)
2257 {
2258 	struct pcap_stat stat;
2259 
2260 	if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
2261 		fprintf(stderr, "Got %u\r", packets_captured);
2262 	alarm(1);
2263 }
2264 #endif
2265 
2266 static void
2267 usage(void)
2268 {
2269 	extern char version[];
2270 #ifndef HAVE_PCAP_LIB_VERSION
2271 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
2272 	extern char pcap_version[];
2273 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2274 	static char pcap_version[] = "unknown";
2275 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
2276 #endif /* HAVE_PCAP_LIB_VERSION */
2277 
2278 #ifdef HAVE_PCAP_LIB_VERSION
2279 #ifdef WIN32
2280 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2281 #else /* WIN32 */
2282 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
2283 #endif /* WIN32 */
2284 	(void)fprintf(stderr, "%s\n",pcap_lib_version());
2285 #else /* HAVE_PCAP_LIB_VERSION */
2286 #ifdef WIN32
2287 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
2288 	(void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
2289 #else /* WIN32 */
2290 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
2291 	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
2292 #endif /* WIN32 */
2293 #endif /* HAVE_PCAP_LIB_VERSION */
2294 	(void)fprintf(stderr,
2295 "Usage: %s [-aAbd" D_FLAG "efhH" I_FLAG J_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
2296 	(void)fprintf(stderr,
2297 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
2298 	(void)fprintf(stderr,
2299 "\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
2300 	(void)fprintf(stderr,
2301 "\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -V file ] [ -w file ]\n");
2302 	(void)fprintf(stderr,
2303 "\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
2304 	(void)fprintf(stderr,
2305 "\t\t[ -Z user ] [ expression ]\n");
2306 	exit(1);
2307 }
2308 
2309 
2310 
2311 /* VARARGS */
2312 static void
2313 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
2314 {
2315 	va_list ap;
2316 
2317 	(void)fprintf(stderr, "%s: ", program_name);
2318 	va_start(ap, fmt);
2319 	(void)vfprintf(stderr, fmt, ap);
2320 	va_end(ap);
2321 	if (*fmt) {
2322 		fmt += strlen(fmt);
2323 		if (fmt[-1] != '\n')
2324 			(void)fputc('\n', stderr);
2325 	}
2326 	exit(1);
2327 	/* NOTREACHED */
2328 }
2329 
2330 /* VARARGS */
2331 static void
2332 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
2333 {
2334 	va_list ap;
2335 
2336 	(void)fprintf(stderr, "%s: WARNING: ", program_name);
2337 	va_start(ap, fmt);
2338 	(void)vfprintf(stderr, fmt, ap);
2339 	va_end(ap);
2340 	if (*fmt) {
2341 		fmt += strlen(fmt);
2342 		if (fmt[-1] != '\n')
2343 			(void)fputc('\n', stderr);
2344 	}
2345 }
2346