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