xref: /netbsd-src/external/bsd/tcpdump/dist/tcpdump.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  *
21  * Support for splitting captures into multiple files with a maximum
22  * file size:
23  *
24  * Copyright (c) 2001
25  *	Seth Webster <swebster@sst.ll.mit.edu>
26  */
27 
28 #include <sys/cdefs.h>
29 #ifndef lint
30 #if 0
31 static const char copyright[] _U_ =
32     "@(#) Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000\n\
33 The Regents of the University of California.  All rights reserved.\n";
34 static const char rcsid[] _U_ =
35     "@(#) Header: /tcpdump/master/tcpdump/tcpdump.c,v 1.283 2008-09-25 21:45:50 guy Exp (LBL)";
36 #else
37 __RCSID("$NetBSD: tcpdump.c,v 1.2 2010/12/05 05:11:31 christos Exp $");
38 #endif
39 #endif
40 
41 /*
42  * tcpdump - monitor tcp/ip traffic on an ethernet.
43  *
44  * First written in 1987 by Van Jacobson, Lawrence Berkeley Laboratory.
45  * Mercilessly hacked and occasionally improved since then via the
46  * combined efforts of Van, Steve McCanne and Craig Leres of LBL.
47  */
48 
49 #ifdef HAVE_CONFIG_H
50 #include "config.h"
51 #endif
52 
53 #include <tcpdump-stdinc.h>
54 
55 #ifdef WIN32
56 #include "getopt.h"
57 #include "w32_fzs.h"
58 extern int strcasecmp (const char *__s1, const char *__s2);
59 extern int SIZE_BUF;
60 #define off_t long
61 #define uint UINT
62 #endif /* WIN32 */
63 
64 #ifdef HAVE_SMI_H
65 #include <smi.h>
66 #endif
67 
68 #include <pcap.h>
69 #include <signal.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <limits.h>
74 #ifndef WIN32
75 #include <sys/wait.h>
76 #include <sys/resource.h>
77 #include <pwd.h>
78 #include <grp.h>
79 #include <errno.h>
80 #endif /* WIN32 */
81 
82 
83 #include "netdissect.h"
84 #include "interface.h"
85 #include "addrtoname.h"
86 #include "machdep.h"
87 #include "setsignal.h"
88 #include "gmt2local.h"
89 #include "pcap-missing.h"
90 
91 #ifndef NAME_MAX
92 #define NAME_MAX 255
93 #endif
94 
95 netdissect_options Gndo;
96 netdissect_options *gndo = &Gndo;
97 
98 static int dflag;			/* print filter code */
99 static int Lflag;			/* list available data link types and exit */
100 static char *zflag = NULL;		/* compress each savefile using a specified command (like gzip or bzip2) */
101 
102 static int infodelay;
103 static int infoprint;
104 
105 char *program_name;
106 
107 int32_t thiszone;		/* seconds offset from gmt to local time */
108 
109 /* Forwards */
110 static RETSIGTYPE cleanup(int);
111 static RETSIGTYPE child_cleanup(int);
112 static void usage(void) __attribute__((noreturn));
113 static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
114 
115 static void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
116 static void ndo_default_print(netdissect_options *, const u_char *, u_int);
117 static void dump_packet_and_trunc(u_char *, const struct pcap_pkthdr *, const u_char *);
118 static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
119 static void droproot(const char *, const char *);
120 static void ndo_error(netdissect_options *ndo, const char *fmt, ...);
121 static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
122 
123 #ifdef SIGINFO
124 RETSIGTYPE requestinfo(int);
125 #endif
126 
127 #if defined(USE_WIN32_MM_TIMER)
128   #include <MMsystem.h>
129   static UINT timer_id;
130   static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
131 #elif defined(HAVE_ALARM)
132   static void verbose_stats_dump(int sig);
133 #endif
134 
135 static void info(int);
136 static u_int packets_captured;
137 
138 typedef u_int (*if_printer)(const struct pcap_pkthdr *, const u_char *);
139 typedef u_int (*if_ndo_printer)(struct netdissect_options *ndo,
140                                 const struct pcap_pkthdr *, const u_char *);
141 
142 struct printer {
143         if_printer f;
144 	int type;
145 };
146 
147 
148 struct ndo_printer {
149         if_ndo_printer f;
150 	int type;
151 };
152 
153 
154 static struct printer printers[] = {
155 	{ arcnet_if_print,	DLT_ARCNET },
156 #ifdef DLT_ARCNET_LINUX
157 	{ arcnet_linux_if_print, DLT_ARCNET_LINUX },
158 #endif
159 	{ ether_if_print,	DLT_EN10MB },
160 	{ token_if_print,	DLT_IEEE802 },
161 #ifdef DLT_LANE8023
162 	{ lane_if_print,        DLT_LANE8023 },
163 #endif
164 #ifdef DLT_CIP
165 	{ cip_if_print,         DLT_CIP },
166 #endif
167 #ifdef DLT_ATM_CLIP
168 	{ cip_if_print,		DLT_ATM_CLIP },
169 #endif
170 	{ sl_if_print,		DLT_SLIP },
171 #ifdef DLT_SLIP_BSDOS
172 	{ sl_bsdos_if_print,	DLT_SLIP_BSDOS },
173 #endif
174 	{ ppp_if_print,		DLT_PPP },
175 #ifdef DLT_PPP_WITHDIRECTION
176 	{ ppp_if_print,		DLT_PPP_WITHDIRECTION },
177 #endif
178 #ifdef DLT_PPP_BSDOS
179 	{ ppp_bsdos_if_print,	DLT_PPP_BSDOS },
180 #endif
181 	{ fddi_if_print,	DLT_FDDI },
182 	{ null_if_print,	DLT_NULL },
183 #ifdef DLT_LOOP
184 	{ null_if_print,	DLT_LOOP },
185 #endif
186 	{ raw_if_print,		DLT_RAW },
187 	{ atm_if_print,		DLT_ATM_RFC1483 },
188 #ifdef DLT_C_HDLC
189 	{ chdlc_if_print,	DLT_C_HDLC },
190 #endif
191 #ifdef DLT_HDLC
192 	{ chdlc_if_print,	DLT_HDLC },
193 #endif
194 #ifdef DLT_PPP_SERIAL
195 	{ ppp_hdlc_if_print,	DLT_PPP_SERIAL },
196 #endif
197 #ifdef DLT_PPP_ETHER
198 	{ pppoe_if_print,	DLT_PPP_ETHER },
199 #endif
200 #ifdef DLT_LINUX_SLL
201 	{ sll_if_print,		DLT_LINUX_SLL },
202 #endif
203 #ifdef DLT_IEEE802_11
204 	{ ieee802_11_if_print,	DLT_IEEE802_11},
205 #endif
206 #ifdef DLT_LTALK
207 	{ ltalk_if_print,	DLT_LTALK },
208 #endif
209 #if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
210 	{ pflog_if_print,	DLT_PFLOG },
211 #endif
212 #ifdef DLT_PFSYNC
213 	{ pfsync_if_print,  DLT_PFSYNC },
214 #endif
215 #ifdef DLT_FR
216 	{ fr_if_print,		DLT_FR },
217 #endif
218 #ifdef DLT_FRELAY
219 	{ fr_if_print,		DLT_FRELAY },
220 #endif
221 #ifdef DLT_SUNATM
222 	{ sunatm_if_print,	DLT_SUNATM },
223 #endif
224 #ifdef DLT_IP_OVER_FC
225 	{ ipfc_if_print,	DLT_IP_OVER_FC },
226 #endif
227 #ifdef DLT_PRISM_HEADER
228 	{ prism_if_print,	DLT_PRISM_HEADER },
229 #endif
230 #ifdef DLT_IEEE802_11_RADIO
231 	{ ieee802_11_radio_if_print,	DLT_IEEE802_11_RADIO },
232 #endif
233 #ifdef DLT_ENC
234 	{ enc_if_print,		DLT_ENC },
235 #endif
236 #ifdef DLT_SYMANTEC_FIREWALL
237 	{ symantec_if_print,	DLT_SYMANTEC_FIREWALL },
238 #endif
239 #ifdef DLT_APPLE_IP_OVER_IEEE1394
240 	{ ap1394_if_print,	DLT_APPLE_IP_OVER_IEEE1394 },
241 #endif
242 #ifdef DLT_IEEE802_11_RADIO_AVS
243 	{ ieee802_11_radio_avs_if_print,	DLT_IEEE802_11_RADIO_AVS },
244 #endif
245 #ifdef DLT_JUNIPER_ATM1
246 	{ juniper_atm1_print,	DLT_JUNIPER_ATM1 },
247 #endif
248 #ifdef DLT_JUNIPER_ATM2
249 	{ juniper_atm2_print,	DLT_JUNIPER_ATM2 },
250 #endif
251 #ifdef DLT_JUNIPER_MFR
252 	{ juniper_mfr_print,	DLT_JUNIPER_MFR },
253 #endif
254 #ifdef DLT_JUNIPER_MLFR
255 	{ juniper_mlfr_print,	DLT_JUNIPER_MLFR },
256 #endif
257 #ifdef DLT_JUNIPER_MLPPP
258 	{ juniper_mlppp_print,	DLT_JUNIPER_MLPPP },
259 #endif
260 #ifdef DLT_JUNIPER_PPPOE
261 	{ juniper_pppoe_print,	DLT_JUNIPER_PPPOE },
262 #endif
263 #ifdef DLT_JUNIPER_PPPOE_ATM
264 	{ juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
265 #endif
266 #ifdef DLT_JUNIPER_GGSN
267 	{ juniper_ggsn_print,	DLT_JUNIPER_GGSN },
268 #endif
269 #ifdef DLT_JUNIPER_ES
270 	{ juniper_es_print,	DLT_JUNIPER_ES },
271 #endif
272 #ifdef DLT_JUNIPER_MONITOR
273 	{ juniper_monitor_print, DLT_JUNIPER_MONITOR },
274 #endif
275 #ifdef DLT_JUNIPER_SERVICES
276 	{ juniper_services_print, DLT_JUNIPER_SERVICES },
277 #endif
278 #ifdef DLT_JUNIPER_ETHER
279 	{ juniper_ether_print,	DLT_JUNIPER_ETHER },
280 #endif
281 #ifdef DLT_JUNIPER_PPP
282 	{ juniper_ppp_print,	DLT_JUNIPER_PPP },
283 #endif
284 #ifdef DLT_JUNIPER_FRELAY
285 	{ juniper_frelay_print,	DLT_JUNIPER_FRELAY },
286 #endif
287 #ifdef DLT_JUNIPER_CHDLC
288 	{ juniper_chdlc_print,	DLT_JUNIPER_CHDLC },
289 #endif
290 #ifdef DLT_MFR
291 	{ mfr_if_print,		DLT_MFR },
292 #endif
293 #if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
294 	{ bt_if_print,		DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
295 #endif
296 #ifdef HAVE_PCAP_USB_H
297 #ifdef DLT_USB_LINUX
298 	{ usb_linux_48_byte_print, DLT_USB_LINUX},
299 #endif /* DLT_USB_LINUX */
300 #ifdef DLT_USB_LINUX_MMAPPED
301 	{ usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
302 #endif /* DLT_USB_LINUX_MMAPPED */
303 #endif /* HAVE_PCAP_USB_H */
304 #ifdef DLT_IPV4
305 	{ raw_if_print,		DLT_IPV4 },
306 #endif
307 #ifdef DLT_IPV6
308 	{ raw_if_print,		DLT_IPV6 },
309 #endif
310 	{ NULL,			0 },
311 };
312 
313 static struct ndo_printer ndo_printers[] = {
314 #ifdef DLT_IPNET
315 	{ ipnet_if_print,	DLT_IPNET },
316 #endif
317 	{ NULL,			0 },
318 };
319 
320 static if_printer
321 lookup_printer(int type)
322 {
323 	struct printer *p;
324 
325 	for (p = printers; p->f; ++p)
326 		if (type == p->type)
327 			return p->f;
328 
329 	return NULL;
330 	/* NOTREACHED */
331 }
332 
333 static if_ndo_printer
334 lookup_ndo_printer(int type)
335 {
336 	struct ndo_printer *p;
337 
338 	for (p = ndo_printers; p->f; ++p)
339 		if (type == p->type)
340 			return p->f;
341 
342 	return NULL;
343 	/* NOTREACHED */
344 }
345 
346 static pcap_t *pd;
347 
348 static int supports_monitor_mode;
349 
350 extern int optind;
351 extern int opterr;
352 extern char *optarg;
353 
354 struct print_info {
355         netdissect_options *ndo;
356         union {
357                 if_printer     printer;
358                 if_ndo_printer ndo_printer;
359         } p;
360         int ndo_type;
361 };
362 
363 struct dump_info {
364 	char	*WFileName;
365 	char	*CurrentFileName;
366 	pcap_t	*pd;
367 	pcap_dumper_t *p;
368 };
369 
370 static void
371 show_dlts_and_exit(const char *device, pcap_t *pd)
372 {
373 	int n_dlts;
374 	int *dlts = 0;
375 	const char *dlt_name;
376 
377 	n_dlts = pcap_list_datalinks(pd, &dlts);
378 	if (n_dlts < 0)
379 		error("%s", pcap_geterr(pd));
380 	else if (n_dlts == 0 || !dlts)
381 		error("No data link types.");
382 
383 	/*
384 	 * If the interface is known to support monitor mode, indicate
385 	 * whether these are the data link types available when not in
386 	 * monitor mode, if -I wasn't specified, or when in monitor mode,
387 	 * when -I was specified (the link-layer types available in
388 	 * monitor mode might be different from the ones available when
389 	 * not in monitor mode).
390 	 */
391 	if (supports_monitor_mode)
392 		(void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
393 		    device,
394 		    Iflag ? "when in monitor mode" : "when not in monitor mode");
395 	else
396 		(void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
397 		    device);
398 
399 	while (--n_dlts >= 0) {
400 		dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
401 		if (dlt_name != NULL) {
402 			(void) fprintf(stderr, "  %s (%s)", dlt_name,
403 			    pcap_datalink_val_to_description(dlts[n_dlts]));
404 
405 			/*
406 			 * OK, does tcpdump handle that type?
407 			 */
408 			if (lookup_printer(dlts[n_dlts]) == NULL
409                             && lookup_ndo_printer(dlts[n_dlts]) == NULL)
410 				(void) fprintf(stderr, " (printing not supported)");
411 			putchar('\n');
412 		} else {
413 			(void) fprintf(stderr, "  DLT %d (printing not supported)\n",
414 			    dlts[n_dlts]);
415 		}
416 	}
417 	free(dlts);
418 	exit(0);
419 }
420 
421 /*
422  * Set up flags that might or might not be supported depending on the
423  * version of libpcap we're using.
424  */
425 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
426 #define B_FLAG		"B:"
427 #define B_FLAG_USAGE	" [ -B size ]"
428 #else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
429 #define B_FLAG
430 #define B_FLAG_USAGE
431 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
432 
433 #ifdef HAVE_PCAP_CREATE
434 #define I_FLAG		"I"
435 #else /* HAVE_PCAP_CREATE */
436 #define I_FLAG
437 #endif /* HAVE_PCAP_CREATE */
438 
439 #ifdef HAVE_PCAP_FINDALLDEVS
440 #ifndef HAVE_PCAP_IF_T
441 #undef HAVE_PCAP_FINDALLDEVS
442 #endif
443 #endif
444 
445 #ifdef HAVE_PCAP_FINDALLDEVS
446 #define D_FLAG	"D"
447 #else
448 #define D_FLAG
449 #endif
450 
451 #ifdef HAVE_PCAP_DUMP_FLUSH
452 #define U_FLAG	"U"
453 #else
454 #define U_FLAG
455 #endif
456 
457 #ifndef WIN32
458 /* Drop root privileges and chroot if necessary */
459 static void
460 droproot(const char *username, const char *chroot_dir)
461 {
462 	struct passwd *pw = NULL;
463 
464 	if (chroot_dir && !username) {
465 		fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
466 		exit(1);
467 	}
468 
469 	pw = getpwnam(username);
470 	if (pw) {
471 		if (chroot_dir) {
472 			if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
473 				fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
474 				    chroot_dir, pcap_strerror(errno));
475 				exit(1);
476 			}
477 		}
478 		if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
479 		    setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
480 			fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
481 			    username,
482 			    (unsigned long)pw->pw_uid,
483 			    (unsigned long)pw->pw_gid,
484 			    pcap_strerror(errno));
485 			exit(1);
486 		}
487 	}
488 	else {
489 		fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
490 		    username);
491 		exit(1);
492 	}
493 }
494 #endif /* WIN32 */
495 
496 static int
497 getWflagChars(int x)
498 {
499 	int c = 0;
500 
501 	x -= 1;
502 	while (x > 0) {
503 		c += 1;
504 		x /= 10;
505 	}
506 
507 	return c;
508 }
509 
510 
511 static void
512 MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
513 {
514         char *filename = malloc(NAME_MAX + 1);
515 
516         /* Process with strftime if Gflag is set. */
517         if (Gflag != 0) {
518           struct tm *local_tm;
519 
520           /* Convert Gflag_time to a usable format */
521           if ((local_tm = localtime(&Gflag_time)) == NULL) {
522                   error("MakeTimedFilename: localtime");
523           }
524 
525           /* There's no good way to detect an error in strftime since a return
526            * value of 0 isn't necessarily failure.
527            */
528           strftime(filename, NAME_MAX, orig_name, local_tm);
529         } else {
530           strncpy(filename, orig_name, NAME_MAX);
531         }
532 
533 	if (cnt == 0 && max_chars == 0)
534 		strncpy(buffer, filename, NAME_MAX + 1);
535 	else
536 		if (snprintf(buffer, NAME_MAX + 1, "%s%0*d", filename, max_chars, cnt) > NAME_MAX)
537                   /* Report an error if the filename is too large */
538                   error("too many output files or filename is too long (> %d)", NAME_MAX);
539         free(filename);
540 }
541 
542 static int tcpdump_printf(netdissect_options *ndo _U_,
543 			  const char *fmt, ...)
544 {
545 
546   va_list args;
547   int ret;
548 
549   va_start(args, fmt);
550   ret=vfprintf(stdout, fmt, args);
551   va_end(args);
552 
553   return ret;
554 }
555 
556 int
557 main(int argc, char **argv)
558 {
559 	register int cnt, op, i;
560 	bpf_u_int32 localnet, netmask;
561 	register char *cp, *infile, *cmdbuf, *device, *RFileName, *WFileName;
562 	pcap_handler callback;
563 	int type;
564 	struct bpf_program fcode;
565 #ifndef WIN32
566 	RETSIGTYPE (*oldhandler)(int);
567 #endif
568 	struct print_info printinfo;
569 	struct dump_info dumpinfo;
570 	u_char *pcap_userdata;
571 	char ebuf[PCAP_ERRBUF_SIZE];
572 	char *username = NULL;
573 	char *chroot_dir = NULL;
574 #ifdef HAVE_PCAP_FINDALLDEVS
575 	pcap_if_t *devpointer;
576 	int devnum;
577 #endif
578 	int status;
579 #ifdef WIN32
580 	if(wsockinit() != 0) return 1;
581 #endif /* WIN32 */
582 
583         gndo->ndo_Oflag=1;
584 	gndo->ndo_Rflag=1;
585 	gndo->ndo_dlt=-1;
586 	gndo->ndo_default_print=ndo_default_print;
587 	gndo->ndo_printf=tcpdump_printf;
588 	gndo->ndo_error=ndo_error;
589 	gndo->ndo_warning=ndo_warning;
590 	gndo->ndo_snaplen = DEFAULT_SNAPLEN;
591 
592 	cnt = -1;
593 	device = NULL;
594 	infile = NULL;
595 	RFileName = NULL;
596 	WFileName = NULL;
597 	if ((cp = strrchr(argv[0], '/')) != NULL)
598 		program_name = cp + 1;
599 	else
600 		program_name = argv[0];
601 
602 	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
603 		error("%s", ebuf);
604 
605 #ifdef LIBSMI
606 	smiInit("tcpdump");
607 #endif
608 
609 	opterr = 0;
610 	while (
611 	    (op = getopt(argc, argv, "aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:G:i:" I_FLAG "KlLm:M:nNOpqr:Rs:StT:u" U_FLAG "vw:W:xXy:Yz:Z:")) != -1)
612 		switch (op) {
613 
614 		case 'a':
615 			/* compatibility for old -a */
616 			break;
617 
618 		case 'A':
619 			++Aflag;
620 			break;
621 
622 		case 'b':
623 			++bflag;
624 			break;
625 
626 #if defined(HAVE_PCAP_CREATE) || defined(WIN32)
627 		case 'B':
628 			Bflag = atoi(optarg)*1024;
629 			if (Bflag <= 0)
630 				error("invalid packet buffer size %s", optarg);
631 			break;
632 #endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
633 
634 		case 'c':
635 			cnt = atoi(optarg);
636 			if (cnt <= 0)
637 				error("invalid packet count %s", optarg);
638 			break;
639 
640 		case 'C':
641 			Cflag = atoi(optarg) * 1000000;
642 			if (Cflag < 0)
643 				error("invalid file size %s", optarg);
644 			break;
645 
646 		case 'd':
647 			++dflag;
648 			break;
649 
650 #ifdef HAVE_PCAP_FINDALLDEVS
651 		case 'D':
652 			if (pcap_findalldevs(&devpointer, ebuf) < 0)
653 				error("%s", ebuf);
654 			else {
655 				for (i = 0; devpointer != 0; i++) {
656 					printf("%d.%s", i+1, devpointer->name);
657 					if (devpointer->description != NULL)
658 						printf(" (%s)", devpointer->description);
659 					printf("\n");
660 					devpointer = devpointer->next;
661 				}
662 			}
663 			return 0;
664 #endif /* HAVE_PCAP_FINDALLDEVS */
665 
666 		case 'L':
667 			Lflag++;
668 			break;
669 
670 		case 'e':
671 			++eflag;
672 			break;
673 
674 		case 'E':
675 #ifndef HAVE_LIBCRYPTO
676 			warning("crypto code not compiled in");
677 #endif
678 			gndo->ndo_espsecret = optarg;
679 			break;
680 
681 		case 'f':
682 			++fflag;
683 			break;
684 
685 		case 'F':
686 			infile = optarg;
687 			break;
688 
689 		case 'G':
690 			Gflag = atoi(optarg);
691 			if (Gflag < 0)
692 				error("invalid number of seconds %s", optarg);
693 
694                         /* We will create one file initially. */
695                         Gflag_count = 0;
696 
697 			/* Grab the current time for rotation use. */
698 			if ((Gflag_time = time(NULL)) == (time_t)-1) {
699 				error("main: can't get current time: %s",
700 				    pcap_strerror(errno));
701 			}
702 			break;
703 
704 		case 'i':
705 			if (optarg[0] == '0' && optarg[1] == 0)
706 				error("Invalid adapter index");
707 
708 #ifdef HAVE_PCAP_FINDALLDEVS
709 			/*
710 			 * If the argument is a number, treat it as
711 			 * an index into the list of adapters, as
712 			 * printed by "tcpdump -D".
713 			 *
714 			 * This should be OK on UNIX systems, as interfaces
715 			 * shouldn't have names that begin with digits.
716 			 * It can be useful on Windows, where more than
717 			 * one interface can have the same name.
718 			 */
719 			if ((devnum = atoi(optarg)) != 0) {
720 				if (devnum < 0)
721 					error("Invalid adapter index");
722 
723 				if (pcap_findalldevs(&devpointer, ebuf) < 0)
724 					error("%s", ebuf);
725 				else {
726 					/*
727 					 * Look for the devnum-th entry
728 					 * in the list of devices
729 					 * (1-based).
730 					 */
731 					for (i = 0;
732 					    i < devnum-1 && devpointer != NULL;
733 					    i++, devpointer = devpointer->next)
734 						;
735 					if (devpointer == NULL)
736 						error("Invalid adapter index");
737 				}
738 				device = devpointer->name;
739 				break;
740 			}
741 #endif /* HAVE_PCAP_FINDALLDEVS */
742 			device = optarg;
743 			break;
744 
745 #ifdef HAVE_PCAP_CREATE
746 		case 'I':
747 			++Iflag;
748 			break;
749 #endif /* HAVE_PCAP_CREATE */
750 
751 		case 'l':
752 #ifdef WIN32
753 			/*
754 			 * _IOLBF is the same as _IOFBF in Microsoft's C
755 			 * libraries; the only alternative they offer
756 			 * is _IONBF.
757 			 *
758 			 * XXX - this should really be checking for MSVC++,
759 			 * not WIN32, if, for example, MinGW has its own
760 			 * C library that is more UNIX-compatible.
761 			 */
762 			setvbuf(stdout, NULL, _IONBF, 0);
763 #else /* WIN32 */
764 #ifdef HAVE_SETLINEBUF
765 			setlinebuf(stdout);
766 #else
767 			setvbuf(stdout, NULL, _IOLBF, 0);
768 #endif
769 #endif /* WIN32 */
770 			break;
771 
772 		case 'K':
773 			++Kflag;
774 			break;
775 
776 		case 'm':
777 #ifdef LIBSMI
778 			if (smiLoadModule(optarg) == 0) {
779 				error("could not load MIB module %s", optarg);
780 			}
781 			sflag = 1;
782 #else
783 			(void)fprintf(stderr, "%s: ignoring option `-m %s' ",
784 				      program_name, optarg);
785 			(void)fprintf(stderr, "(no libsmi support)\n");
786 #endif
787 			break;
788 
789 		case 'M':
790 			/* TCP-MD5 shared secret */
791 #ifndef HAVE_LIBCRYPTO
792 			warning("crypto code not compiled in");
793 #endif
794 			sigsecret = optarg;
795 			break;
796 
797 		case 'n':
798 			++nflag;
799 			break;
800 
801 		case 'N':
802 			++Nflag;
803 			break;
804 
805 		case 'O':
806 			Oflag = 0;
807 			break;
808 
809 		case 'p':
810 			++pflag;
811 			break;
812 
813 		case 'q':
814 			++qflag;
815 			++suppress_default_print;
816 			break;
817 
818 		case 'r':
819 			RFileName = optarg;
820 			break;
821 
822 		case 'R':
823 			Rflag = 0;
824 			break;
825 
826 		case 's': {
827 			char *end;
828 
829 			snaplen = strtol(optarg, &end, 0);
830 			if (optarg == end || *end != '\0'
831 			    || snaplen < 0 || snaplen > MAXIMUM_SNAPLEN)
832 				error("invalid snaplen %s", optarg);
833 			else if (snaplen == 0)
834 				snaplen = MAXIMUM_SNAPLEN;
835 			break;
836 		}
837 
838 		case 'S':
839 			++Sflag;
840 			break;
841 
842 		case 't':
843 			++tflag;
844 			break;
845 
846 		case 'T':
847 			if (strcasecmp(optarg, "vat") == 0)
848 				packettype = PT_VAT;
849 			else if (strcasecmp(optarg, "wb") == 0)
850 				packettype = PT_WB;
851 			else if (strcasecmp(optarg, "rpc") == 0)
852 				packettype = PT_RPC;
853 			else if (strcasecmp(optarg, "rtp") == 0)
854 				packettype = PT_RTP;
855 			else if (strcasecmp(optarg, "rtcp") == 0)
856 				packettype = PT_RTCP;
857 			else if (strcasecmp(optarg, "snmp") == 0)
858 				packettype = PT_SNMP;
859 			else if (strcasecmp(optarg, "cnfp") == 0)
860 				packettype = PT_CNFP;
861 			else if (strcasecmp(optarg, "tftp") == 0)
862 				packettype = PT_TFTP;
863 			else if (strcasecmp(optarg, "aodv") == 0)
864 				packettype = PT_AODV;
865 			else
866 				error("unknown packet type `%s'", optarg);
867 			break;
868 
869 		case 'u':
870 			++uflag;
871 			break;
872 
873 #ifdef HAVE_PCAP_DUMP_FLUSH
874 		case 'U':
875 			++Uflag;
876 			break;
877 #endif
878 
879 		case 'v':
880 			++vflag;
881 			break;
882 
883 		case 'w':
884 			WFileName = optarg;
885 			break;
886 
887 		case 'W':
888 			Wflag = atoi(optarg);
889 			if (Wflag < 0)
890 				error("invalid number of output files %s", optarg);
891 			WflagChars = getWflagChars(Wflag);
892 			break;
893 
894 		case 'x':
895 			++xflag;
896 			++suppress_default_print;
897 			break;
898 
899 		case 'X':
900 			++Xflag;
901 			++suppress_default_print;
902 			break;
903 
904 		case 'y':
905 			gndo->ndo_dltname = optarg;
906 			gndo->ndo_dlt =
907 			  pcap_datalink_name_to_val(gndo->ndo_dltname);
908 			if (gndo->ndo_dlt < 0)
909 				error("invalid data link type %s", gndo->ndo_dltname);
910 			break;
911 
912 #if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
913 		case 'Y':
914 			{
915 			/* Undocumented flag */
916 #ifdef HAVE_PCAP_DEBUG
917 			extern int pcap_debug;
918 			pcap_debug = 1;
919 #else
920 			extern int yydebug;
921 			yydebug = 1;
922 #endif
923 			}
924 			break;
925 #endif
926 		case 'z':
927 			if (optarg) {
928 				zflag = strdup(optarg);
929 			} else {
930 				usage();
931 				/* NOTREACHED */
932 			}
933 			break;
934 
935 		case 'Z':
936 			if (optarg) {
937 				username = strdup(optarg);
938 			}
939 			else {
940 				usage();
941 				/* NOTREACHED */
942 			}
943 			break;
944 
945 		default:
946 			usage();
947 			/* NOTREACHED */
948 		}
949 
950 	switch (tflag) {
951 
952 	case 0: /* Default */
953 	case 4: /* Default + Date*/
954 		thiszone = gmt2local(0);
955 		break;
956 
957 	case 1: /* No time stamp */
958 	case 2: /* Unix timeval style */
959 	case 3: /* Microseconds since previous packet */
960         case 5: /* Microseconds since first packet */
961 		break;
962 
963 	default: /* Not supported */
964 		error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
965 		break;
966 	}
967 
968 #ifdef WITH_CHROOT
969 	/* if run as root, prepare for chrooting */
970 	if (getuid() == 0 || geteuid() == 0) {
971 		/* future extensibility for cmd-line arguments */
972 		if (!chroot_dir)
973 			chroot_dir = WITH_CHROOT;
974 	}
975 #endif
976 
977 #ifdef WITH_USER
978 	/* if run as root, prepare for dropping root privileges */
979 	if (getuid() == 0 || geteuid() == 0) {
980 		/* Run with '-Z root' to restore old behaviour */
981 		if (!username)
982 			username = WITH_USER;
983 	}
984 #endif
985 
986 	if (RFileName != NULL) {
987 		int dlt;
988 		const char *dlt_name;
989 
990 #ifndef WIN32
991 		/*
992 		 * We don't need network access, so relinquish any set-UID
993 		 * or set-GID privileges we have (if any).
994 		 *
995 		 * We do *not* want set-UID privileges when opening a
996 		 * trace file, as that might let the user read other
997 		 * people's trace files (especially if we're set-UID
998 		 * root).
999 		 */
1000 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1001 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1002 #endif /* WIN32 */
1003 		pd = pcap_open_offline(RFileName, ebuf);
1004 		if (pd == NULL)
1005 			error("%s", ebuf);
1006 		dlt = pcap_datalink(pd);
1007 		dlt_name = pcap_datalink_val_to_name(dlt);
1008 		if (dlt_name == NULL) {
1009 			fprintf(stderr, "reading from file %s, link-type %u\n",
1010 			    RFileName, dlt);
1011 		} else {
1012 			fprintf(stderr,
1013 			    "reading from file %s, link-type %s (%s)\n",
1014 			    RFileName, dlt_name,
1015 			    pcap_datalink_val_to_description(dlt));
1016 		}
1017 		localnet = 0;
1018 		netmask = 0;
1019 		if (fflag != 0)
1020 			error("-f and -r options are incompatible");
1021 	} else {
1022 		if (device == NULL) {
1023 			device = pcap_lookupdev(ebuf);
1024 			if (device == NULL)
1025 				error("%s", ebuf);
1026 		}
1027 #ifdef WIN32
1028 		if(strlen(device) == 1)	//we assume that an ASCII string is always longer than 1 char
1029 		{						//a Unicode string has a \0 as second byte (so strlen() is 1)
1030 			fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1031 		}
1032 		else
1033 		{
1034 			fprintf(stderr, "%s: listening on %s\n", program_name, device);
1035 		}
1036 
1037 		fflush(stderr);
1038 #endif /* WIN32 */
1039 #ifdef HAVE_PCAP_CREATE
1040 		pd = pcap_create(device, ebuf);
1041 		if (pd == NULL)
1042 			error("%s", ebuf);
1043 		/*
1044 		 * Is this an interface that supports monitor mode?
1045 		 */
1046 		if (pcap_can_set_rfmon(pd) == 1)
1047 			supports_monitor_mode = 1;
1048 		else
1049 			supports_monitor_mode = 0;
1050 		status = pcap_set_snaplen(pd, snaplen);
1051 		if (status != 0)
1052 			error("%s: pcap_set_snaplen failed: %s",
1053 			    device, pcap_statustostr(status));
1054 		status = pcap_set_promisc(pd, !pflag);
1055 		if (status != 0)
1056 			error("%s: pcap_set_promisc failed: %s",
1057 			    device, pcap_statustostr(status));
1058 		if (Iflag) {
1059 			status = pcap_set_rfmon(pd, 1);
1060 			if (status != 0)
1061 				error("%s: pcap_set_rfmon failed: %s",
1062 				    device, pcap_statustostr(status));
1063 		}
1064 		status = pcap_set_timeout(pd, 1000);
1065 		if (status != 0)
1066 			error("%s: pcap_set_timeout failed: %s",
1067 			    device, pcap_statustostr(status));
1068 		if (Bflag != 0) {
1069 			status = pcap_set_buffer_size(pd, Bflag);
1070 			if (status != 0)
1071 				error("%s: pcap_set_buffer_size failed: %s",
1072 				    device, pcap_statustostr(status));
1073 		}
1074 		status = pcap_activate(pd);
1075 		if (status < 0) {
1076 			/*
1077 			 * pcap_activate() failed.
1078 			 */
1079 			cp = pcap_geterr(pd);
1080 			if (status == PCAP_ERROR)
1081 				error("%s", cp);
1082 			else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1083 			          status == PCAP_ERROR_PERM_DENIED) &&
1084 			         *cp != '\0')
1085 				error("%s: %s\n(%s)", device,
1086 				    pcap_statustostr(status), cp);
1087 			else
1088 				error("%s: %s", device,
1089 				    pcap_statustostr(status));
1090 		} else if (status > 0) {
1091 			/*
1092 			 * pcap_activate() succeeded, but it's warning us
1093 			 * of a problem it had.
1094 			 */
1095 			cp = pcap_geterr(pd);
1096 			if (status == PCAP_WARNING)
1097 				warning("%s", cp);
1098 			else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1099 			         *cp != '\0')
1100 				warning("%s: %s\n(%s)", device,
1101 				    pcap_statustostr(status), cp);
1102 			else
1103 				warning("%s: %s", device,
1104 				    pcap_statustostr(status));
1105 		}
1106 #else
1107 		*ebuf = '\0';
1108 		pd = pcap_open_live(device, snaplen, !pflag, 1000, ebuf);
1109 		if (pd == NULL)
1110 			error("%s", ebuf);
1111 		else if (*ebuf)
1112 			warning("%s", ebuf);
1113 #endif /* HAVE_PCAP_CREATE */
1114 		/*
1115 		 * Let user own process after socket has been opened.
1116 		 */
1117 #ifndef WIN32
1118 		if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1119 			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1120 #endif /* WIN32 */
1121 #if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1122 		if(Bflag != 0)
1123 			if(pcap_setbuff(pd, Bflag)==-1){
1124 				error("%s", pcap_geterr(pd));
1125 			}
1126 #endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1127 		if (Lflag)
1128 			show_dlts_and_exit(device, pd);
1129 		if (gndo->ndo_dlt >= 0) {
1130 #ifdef HAVE_PCAP_SET_DATALINK
1131 			if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1132 				error("%s", pcap_geterr(pd));
1133 #else
1134 			/*
1135 			 * We don't actually support changing the
1136 			 * data link type, so we only let them
1137 			 * set it to what it already is.
1138 			 */
1139 			if (gndo->ndo_dlt != pcap_datalink(pd)) {
1140 				error("%s is not one of the DLTs supported by this device\n",
1141 				      gndo->ndo_dltname);
1142 			}
1143 #endif
1144 			(void)fprintf(stderr, "%s: data link type %s\n",
1145 				      program_name, gndo->ndo_dltname);
1146 			(void)fflush(stderr);
1147 		}
1148 		i = pcap_snapshot(pd);
1149 		if (snaplen < i) {
1150 			warning("snaplen raised from %d to %d", snaplen, i);
1151 			snaplen = i;
1152 		}
1153 		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1154 			localnet = 0;
1155 			netmask = 0;
1156 			warning("%s", ebuf);
1157 		}
1158 	}
1159 	if (infile)
1160 		cmdbuf = read_infile(infile);
1161 	else
1162 		cmdbuf = copy_argv(&argv[optind]);
1163 
1164 	if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0)
1165 		error("%s", pcap_geterr(pd));
1166 	free(cmdbuf);
1167 	if (dflag) {
1168 		bpf_dump(&fcode, dflag);
1169 		pcap_close(pd);
1170 		exit(0);
1171 	}
1172 	init_addrtoname(localnet, netmask);
1173         init_checksum();
1174 
1175 #ifndef WIN32
1176 	(void)setsignal(SIGPIPE, cleanup);
1177 	(void)setsignal(SIGTERM, cleanup);
1178 	(void)setsignal(SIGINT, cleanup);
1179 	(void)setsignal(SIGCHLD, child_cleanup);
1180 #endif /* WIN32 */
1181 	/* Cooperate with nohup(1) */
1182 #ifndef WIN32
1183 	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1184 		(void)setsignal(SIGHUP, oldhandler);
1185 #endif /* WIN32 */
1186 
1187 	if (pcap_setfilter(pd, &fcode) < 0)
1188 		error("%s", pcap_geterr(pd));
1189 	if (WFileName) {
1190 		pcap_dumper_t *p;
1191 		/* Do not exceed the default NAME_MAX for files. */
1192 		dumpinfo.CurrentFileName = (char *)malloc(NAME_MAX + 1);
1193 
1194 		if (dumpinfo.CurrentFileName == NULL)
1195 			error("malloc of dumpinfo.CurrentFileName");
1196 
1197 		/* We do not need numbering for dumpfiles if Cflag isn't set. */
1198 		if (Cflag != 0)
1199 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1200 		else
1201 		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1202 
1203 		p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1204 		if (p == NULL)
1205 			error("%s", pcap_geterr(pd));
1206 		if (Cflag != 0 || Gflag != 0) {
1207 			callback = dump_packet_and_trunc;
1208 			dumpinfo.WFileName = WFileName;
1209 			dumpinfo.pd = pd;
1210 			dumpinfo.p = p;
1211 			pcap_userdata = (u_char *)&dumpinfo;
1212 		} else {
1213 			callback = dump_packet;
1214 			pcap_userdata = (u_char *)p;
1215 		}
1216 	} else {
1217 		type = pcap_datalink(pd);
1218                 printinfo.ndo_type = 1;
1219                 printinfo.ndo = gndo;
1220 		printinfo.p.ndo_printer = lookup_ndo_printer(type);
1221                 if (printinfo.p.ndo_printer == NULL) {
1222                         printinfo.p.printer = lookup_printer(type);
1223                         printinfo.ndo_type = 0;
1224                         if (printinfo.p.printer == NULL) {
1225                                 gndo->ndo_dltname = pcap_datalink_val_to_name(type);
1226                                 if (gndo->ndo_dltname != NULL)
1227                                         error("packet printing is not supported for link type %s: use -w",
1228                                               gndo->ndo_dltname);
1229                                 else
1230                                         error("packet printing is not supported for link type %d: use -w", type);
1231                         }
1232                 }
1233 		callback = print_packet;
1234 		pcap_userdata = (u_char *)&printinfo;
1235 	}
1236 #ifndef WIN32
1237 	/*
1238 	 * We cannot do this earlier, because we want to be able to open
1239 	 * the file (if done) for writing before giving up permissions.
1240 	 */
1241 	if (getuid() == 0 || geteuid() == 0) {
1242 		if (username || chroot_dir)
1243 			droproot(username, chroot_dir);
1244 	}
1245 #endif /* WIN32 */
1246 #ifdef SIGINFO
1247 	/*
1248 	 * We can't get statistics when reading from a file rather
1249 	 * than capturing from a device.
1250 	 */
1251 	if (RFileName == NULL)
1252 		(void)setsignal(SIGINFO, requestinfo);
1253 #endif
1254 
1255 	if (vflag > 0 && WFileName) {
1256 		/*
1257 		 * When capturing to a file, "-v" means tcpdump should,
1258 		 * every 10 secodns, "v"erbosely report the number of
1259 		 * packets captured.
1260 		 */
1261 #ifdef USE_WIN32_MM_TIMER
1262 		/* call verbose_stats_dump() each 1000 +/-100msec */
1263 		timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1264 		setvbuf(stderr, NULL, _IONBF, 0);
1265 #elif defined(HAVE_ALARM)
1266 		(void)setsignal(SIGALRM, verbose_stats_dump);
1267 		alarm(1);
1268 #endif
1269 	}
1270 
1271 #ifndef WIN32
1272 	if (RFileName == NULL) {
1273 		int dlt;
1274 		const char *dlt_name;
1275 
1276 		if (!vflag && !WFileName) {
1277 			(void)fprintf(stderr,
1278 			    "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1279 			    program_name);
1280 		} else
1281 			(void)fprintf(stderr, "%s: ", program_name);
1282 		dlt = pcap_datalink(pd);
1283 		dlt_name = pcap_datalink_val_to_name(dlt);
1284 		if (dlt_name == NULL) {
1285 			(void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1286 			    device, dlt, snaplen);
1287 		} else {
1288 			(void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1289 			    device, dlt_name,
1290 			    pcap_datalink_val_to_description(dlt), snaplen);
1291 		}
1292 		(void)fflush(stderr);
1293 	}
1294 #endif /* WIN32 */
1295 	status = pcap_loop(pd, cnt, callback, pcap_userdata);
1296 	if (WFileName == NULL) {
1297 		/*
1298 		 * We're printing packets.  Flush the printed output,
1299 		 * so it doesn't get intermingled with error output.
1300 		 */
1301 		if (status == -2) {
1302 			/*
1303 			 * We got interrupted, so perhaps we didn't
1304 			 * manage to finish a line we were printing.
1305 			 * Print an extra newline, just in case.
1306 			 */
1307 			putchar('\n');
1308 		}
1309 		(void)fflush(stdout);
1310 	}
1311 	if (status == -1) {
1312 		/*
1313 		 * Error.  Report it.
1314 		 */
1315 		(void)fprintf(stderr, "%s: pcap_loop: %s\n",
1316 		    program_name, pcap_geterr(pd));
1317 	}
1318 	if (RFileName == NULL) {
1319 		/*
1320 		 * We're doing a live capture.  Report the capture
1321 		 * statistics.
1322 		 */
1323 		info(1);
1324 	}
1325 	pcap_close(pd);
1326 	exit(status == -1 ? 1 : 0);
1327 }
1328 
1329 /* make a clean exit on interrupts */
1330 static RETSIGTYPE
1331 cleanup(int signo _U_)
1332 {
1333 #ifdef USE_WIN32_MM_TIMER
1334 	if (timer_id)
1335 		timeKillEvent(timer_id);
1336 	timer_id = 0;
1337 #elif defined(HAVE_ALARM)
1338 	alarm(0);
1339 #endif
1340 
1341 #ifdef HAVE_PCAP_BREAKLOOP
1342 	/*
1343 	 * We have "pcap_breakloop()"; use it, so that we do as little
1344 	 * as possible in the signal handler (it's probably not safe
1345 	 * to do anything with standard I/O streams in a signal handler -
1346 	 * the ANSI C standard doesn't say it is).
1347 	 */
1348 	pcap_breakloop(pd);
1349 #else
1350 	/*
1351 	 * We don't have "pcap_breakloop()"; this isn't safe, but
1352 	 * it's the best we can do.  Print the summary if we're
1353 	 * not reading from a savefile - i.e., if we're doing a
1354 	 * live capture - and exit.
1355 	 */
1356 	if (pd != NULL && pcap_file(pd) == NULL) {
1357 		/*
1358 		 * We got interrupted, so perhaps we didn't
1359 		 * manage to finish a line we were printing.
1360 		 * Print an extra newline, just in case.
1361 		 */
1362 		putchar('\n');
1363 		(void)fflush(stdout);
1364 		info(1);
1365 	}
1366 	exit(0);
1367 #endif
1368 }
1369 
1370 /*
1371   On windows, we do not use a fork, so we do not care less about
1372   waiting a child processes to die
1373  */
1374 #ifndef WIN32
1375 static RETSIGTYPE
1376 child_cleanup(int signo _U_)
1377 {
1378   wait(NULL);
1379 }
1380 #endif /* WIN32 */
1381 
1382 static void
1383 info(register int verbose)
1384 {
1385 	struct pcap_stat stat;
1386 
1387 	/*
1388 	 * Older versions of libpcap didn't set ps_ifdrop on some
1389 	 * platforms; initialize it to 0 to handle that.
1390 	 */
1391 	stat.ps_ifdrop = 0;
1392 	if (pcap_stats(pd, &stat) < 0) {
1393 		(void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1394 		infoprint = 0;
1395 		return;
1396 	}
1397 
1398 	if (!verbose)
1399 		fprintf(stderr, "%s: ", program_name);
1400 
1401 	(void)fprintf(stderr, "%u packets captured", packets_captured);
1402 	if (!verbose)
1403 		fputs(", ", stderr);
1404 	else
1405 		putc('\n', stderr);
1406 	(void)fprintf(stderr, "%u packets received by filter", stat.ps_recv);
1407 	if (!verbose)
1408 		fputs(", ", stderr);
1409 	else
1410 		putc('\n', stderr);
1411 	(void)fprintf(stderr, "%u packets dropped by kernel", stat.ps_drop);
1412 	if (stat.ps_ifdrop != 0) {
1413 		if (!verbose)
1414 			fputs(", ", stderr);
1415 		else
1416 			putc('\n', stderr);
1417 		(void)fprintf(stderr, "%u packets dropped by interface\n",
1418 		    stat.ps_ifdrop);
1419 	} else
1420 		putc('\n', stderr);
1421 	infoprint = 0;
1422 }
1423 
1424 #ifndef WIN32
1425 static void
1426 compress_savefile(const char *filename)
1427 {
1428 	if (fork())
1429 		return;
1430 	/*
1431 	 * Set to lowest priority so that this doesn't disturb the capture
1432 	 */
1433 #ifdef NZERO
1434 	setpriority(PRIO_PROCESS, 0, NZERO - 1);
1435 #else
1436 	setpriority(PRIO_PROCESS, 0, 19);
1437 #endif
1438 	if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
1439 		fprintf(stderr,
1440 			"compress_savefile:execlp(%s, %s): %s\n",
1441 			zflag,
1442 			filename,
1443 			strerror(errno));
1444 }
1445 #else  /* WIN32 */
1446 static void
1447 compress_savefile(const char *filename)
1448 {
1449 	fprintf(stderr,
1450 		"compress_savefile failed. Functionality not implemented under windows\n");
1451 }
1452 #endif /* WIN32 */
1453 
1454 static void
1455 dump_packet_and_trunc(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1456 {
1457 	struct dump_info *dump_info;
1458 
1459 	++packets_captured;
1460 
1461 	++infodelay;
1462 
1463 	dump_info = (struct dump_info *)user;
1464 
1465 	/*
1466 	 * XXX - this won't force the file to rotate on the specified time
1467 	 * boundary, but it will rotate on the first packet received after the
1468 	 * specified Gflag number of seconds. Note: if a Gflag time boundary
1469 	 * and a Cflag size boundary coincide, the time rotation will occur
1470 	 * first thereby cancelling the Cflag boundary (since the file should
1471 	 * be 0).
1472 	 */
1473 	if (Gflag != 0) {
1474 		/* Check if it is time to rotate */
1475 		time_t t;
1476 
1477 		/* Get the current time */
1478 		if ((t = time(NULL)) == (time_t)-1) {
1479 			error("dump_and_trunc_packet: can't get current_time: %s",
1480 			    pcap_strerror(errno));
1481 		}
1482 
1483 
1484 		/* If the time is greater than the specified window, rotate */
1485 		if (t - Gflag_time >= Gflag) {
1486 			/* Update the Gflag_time */
1487 			Gflag_time = t;
1488 			/* Update Gflag_count */
1489 			Gflag_count++;
1490 			/*
1491 			 * Close the current file and open a new one.
1492 			 */
1493 			pcap_dump_close(dump_info->p);
1494 
1495 			/*
1496 			 * Compress the file we just closed, if the user asked for it
1497 			 */
1498 			if (zflag != NULL)
1499 				compress_savefile(dump_info->CurrentFileName);
1500 
1501 			/*
1502 			 * Check to see if we've exceeded the Wflag (when
1503 			 * not using Cflag).
1504 			 */
1505 			if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
1506 				(void)fprintf(stderr, "Maximum file limit reached: %d\n",
1507 				    Wflag);
1508 				exit(0);
1509 				/* NOTREACHED */
1510 			}
1511 			if (dump_info->CurrentFileName != NULL)
1512 				free(dump_info->CurrentFileName);
1513 			/* Allocate space for max filename + \0. */
1514 			dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1515 			if (dump_info->CurrentFileName == NULL)
1516 				error("dump_packet_and_trunc: malloc");
1517 			/*
1518 			 * This is always the first file in the Cflag
1519 			 * rotation: e.g. 0
1520 			 * We also don't need numbering if Cflag is not set.
1521 			 */
1522 			if (Cflag != 0)
1523 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
1524 				    WflagChars);
1525 			else
1526 				MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
1527 
1528 			dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1529 			if (dump_info->p == NULL)
1530 				error("%s", pcap_geterr(pd));
1531 		}
1532 	}
1533 
1534 	/*
1535 	 * XXX - this won't prevent capture files from getting
1536 	 * larger than Cflag - the last packet written to the
1537 	 * file could put it over Cflag.
1538 	 */
1539 	if (Cflag != 0 && pcap_dump_ftell(dump_info->p) > Cflag) {
1540 		/*
1541 		 * Close the current file and open a new one.
1542 		 */
1543 		pcap_dump_close(dump_info->p);
1544 
1545 		/*
1546 		 * Compress the file we just closed, if the user asked for it
1547 		 */
1548 		if (zflag != NULL)
1549 			compress_savefile(dump_info->CurrentFileName);
1550 
1551 		Cflag_count++;
1552 		if (Wflag > 0) {
1553 			if (Cflag_count >= Wflag)
1554 				Cflag_count = 0;
1555 		}
1556 		if (dump_info->CurrentFileName != NULL)
1557 			free(dump_info->CurrentFileName);
1558 		dump_info->CurrentFileName = (char *)malloc(NAME_MAX + 1);
1559 		if (dump_info->CurrentFileName == NULL)
1560 			error("dump_packet_and_trunc: malloc");
1561 		MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
1562 		dump_info->p = pcap_dump_open(dump_info->pd, dump_info->CurrentFileName);
1563 		if (dump_info->p == NULL)
1564 			error("%s", pcap_geterr(pd));
1565 	}
1566 
1567 	pcap_dump((u_char *)dump_info->p, h, sp);
1568 #ifdef HAVE_PCAP_DUMP_FLUSH
1569 	if (Uflag)
1570 		pcap_dump_flush(dump_info->p);
1571 #endif
1572 
1573 	--infodelay;
1574 	if (infoprint)
1575 		info(0);
1576 }
1577 
1578 static void
1579 dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1580 {
1581 	++packets_captured;
1582 
1583 	++infodelay;
1584 
1585 	pcap_dump(user, h, sp);
1586 #ifdef HAVE_PCAP_DUMP_FLUSH
1587 	if (Uflag)
1588 		pcap_dump_flush((pcap_dumper_t *)user);
1589 #endif
1590 
1591 	--infodelay;
1592 	if (infoprint)
1593 		info(0);
1594 }
1595 
1596 static void
1597 print_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
1598 {
1599 	struct print_info *print_info;
1600 	u_int hdrlen;
1601 
1602 	++packets_captured;
1603 
1604 	++infodelay;
1605 	ts_print(&h->ts);
1606 
1607 	print_info = (struct print_info *)user;
1608 
1609 	/*
1610 	 * Some printers want to check that they're not walking off the
1611 	 * end of the packet.
1612 	 * Rather than pass it all the way down, we set this global.
1613 	 */
1614 	snapend = sp + h->caplen;
1615 
1616         if(print_info->ndo_type) {
1617                 hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
1618         } else {
1619                 hdrlen = (*print_info->p.printer)(h, sp);
1620         }
1621 
1622 	if (Xflag) {
1623 		/*
1624 		 * Print the raw packet data in hex and ASCII.
1625 		 */
1626 		if (Xflag > 1) {
1627 			/*
1628 			 * Include the link-layer header.
1629 			 */
1630 			hex_and_ascii_print("\n\t", sp, h->caplen);
1631 		} else {
1632 			/*
1633 			 * Don't include the link-layer header - and if
1634 			 * we have nothing past the link-layer header,
1635 			 * print nothing.
1636 			 */
1637 			if (h->caplen > hdrlen)
1638 				hex_and_ascii_print("\n\t", sp + hdrlen,
1639 				    h->caplen - hdrlen);
1640 		}
1641 	} else if (xflag) {
1642 		/*
1643 		 * Print the raw packet data in hex.
1644 		 */
1645 		if (xflag > 1) {
1646 			/*
1647 			 * Include the link-layer header.
1648 			 */
1649 			hex_print("\n\t", sp, h->caplen);
1650 		} else {
1651 			/*
1652 			 * Don't include the link-layer header - and if
1653 			 * we have nothing past the link-layer header,
1654 			 * print nothing.
1655 			 */
1656 			if (h->caplen > hdrlen)
1657 				hex_print("\n\t", sp + hdrlen,
1658 				    h->caplen - hdrlen);
1659 		}
1660 	} else if (Aflag) {
1661 		/*
1662 		 * Print the raw packet data in ASCII.
1663 		 */
1664 		if (Aflag > 1) {
1665 			/*
1666 			 * Include the link-layer header.
1667 			 */
1668 			ascii_print(sp, h->caplen);
1669 		} else {
1670 			/*
1671 			 * Don't include the link-layer header - and if
1672 			 * we have nothing past the link-layer header,
1673 			 * print nothing.
1674 			 */
1675 			if (h->caplen > hdrlen)
1676 				ascii_print(sp + hdrlen, h->caplen - hdrlen);
1677 		}
1678 	}
1679 
1680 	putchar('\n');
1681 
1682 	--infodelay;
1683 	if (infoprint)
1684 		info(0);
1685 }
1686 
1687 #ifdef WIN32
1688 	/*
1689 	 * XXX - there should really be libpcap calls to get the version
1690 	 * number as a string (the string would be generated from #defines
1691 	 * at run time, so that it's not generated from string constants
1692 	 * in the library, as, on many UNIX systems, those constants would
1693 	 * be statically linked into the application executable image, and
1694 	 * would thus reflect the version of libpcap on the system on
1695 	 * which the application was *linked*, not the system on which it's
1696 	 * *running*.
1697 	 *
1698 	 * That routine should be documented, unlike the "version[]"
1699 	 * string, so that UNIX vendors providing their own libpcaps
1700 	 * don't omit it (as a couple of vendors have...).
1701 	 *
1702 	 * Packet.dll should perhaps also export a routine to return the
1703 	 * version number of the Packet.dll code, to supply the
1704 	 * "Wpcap_version" information on Windows.
1705 	 */
1706 	char WDversion[]="current-cvs.tcpdump.org";
1707 #if !defined(HAVE_GENERATED_VERSION)
1708 	char version[]="current-cvs.tcpdump.org";
1709 #endif
1710 	char pcap_version[]="current-cvs.tcpdump.org";
1711 	char Wpcap_version[]="3.1";
1712 #endif
1713 
1714 /*
1715  * By default, print the specified data out in hex and ASCII.
1716  */
1717 static void
1718 ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
1719 {
1720 	hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
1721 }
1722 
1723 void
1724 default_print(const u_char *bp, u_int length)
1725 {
1726 	ndo_default_print(gndo, bp, length);
1727 }
1728 
1729 #ifdef SIGINFO
1730 RETSIGTYPE requestinfo(int signo _U_)
1731 {
1732 	if (infodelay)
1733 		++infoprint;
1734 	else
1735 		info(0);
1736 }
1737 #endif
1738 
1739 /*
1740  * Called once each second in verbose mode while dumping to file
1741  */
1742 #ifdef USE_WIN32_MM_TIMER
1743 void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
1744 				  DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
1745 {
1746 	struct pcap_stat stat;
1747 
1748 	if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1749 		fprintf(stderr, "Got %u\r", packets_captured);
1750 }
1751 #elif defined(HAVE_ALARM)
1752 static void verbose_stats_dump(int sig _U_)
1753 {
1754 	struct pcap_stat stat;
1755 
1756 	if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
1757 		fprintf(stderr, "Got %u\r", packets_captured);
1758 	alarm(1);
1759 }
1760 #endif
1761 
1762 static void
1763 usage(void)
1764 {
1765 	extern char version[];
1766 #ifndef HAVE_PCAP_LIB_VERSION
1767 #if defined(WIN32) || defined(HAVE_PCAP_VERSION)
1768 	extern char pcap_version[];
1769 #else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1770 	static char pcap_version[] = "unknown";
1771 #endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
1772 #endif /* HAVE_PCAP_LIB_VERSION */
1773 
1774 #ifdef HAVE_PCAP_LIB_VERSION
1775 #ifdef WIN32
1776 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1777 #else /* WIN32 */
1778 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
1779 #endif /* WIN32 */
1780 	(void)fprintf(stderr, "%s\n",pcap_lib_version());
1781 #else /* HAVE_PCAP_LIB_VERSION */
1782 #ifdef WIN32
1783 	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
1784 	(void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
1785 #else /* WIN32 */
1786 	(void)fprintf(stderr, "%s version %s\n", program_name, version);
1787 	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
1788 #endif /* WIN32 */
1789 #endif /* HAVE_PCAP_LIB_VERSION */
1790 	(void)fprintf(stderr,
1791 "Usage: %s [-aAbd" D_FLAG "ef" I_FLAG "KlLnNOpqRStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
1792 	(void)fprintf(stderr,
1793 "\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
1794 	(void)fprintf(stderr,
1795 "\t\t[ -i interface ] [ -M secret ] [ -r file ]\n");
1796 	(void)fprintf(stderr,
1797 "\t\t[ -s snaplen ] [ -T type ] [ -w file ] [ -W filecount ]\n");
1798 	(void)fprintf(stderr,
1799 "\t\t[ -y datalinktype ] [ -z command ] [ -Z user ]\n");
1800 	(void)fprintf(stderr,
1801 "\t\t[ expression ]\n");
1802 	exit(1);
1803 }
1804 
1805 
1806 
1807 /* VARARGS */
1808 static void
1809 ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
1810 {
1811 	va_list ap;
1812 
1813 	(void)fprintf(stderr, "%s: ", program_name);
1814 	va_start(ap, fmt);
1815 	(void)vfprintf(stderr, fmt, ap);
1816 	va_end(ap);
1817 	if (*fmt) {
1818 		fmt += strlen(fmt);
1819 		if (fmt[-1] != '\n')
1820 			(void)fputc('\n', stderr);
1821 	}
1822 	exit(1);
1823 	/* NOTREACHED */
1824 }
1825 
1826 /* VARARGS */
1827 static void
1828 ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
1829 {
1830 	va_list ap;
1831 
1832 	(void)fprintf(stderr, "%s: WARNING: ", program_name);
1833 	va_start(ap, fmt);
1834 	(void)vfprintf(stderr, fmt, ap);
1835 	va_end(ap);
1836 	if (*fmt) {
1837 		fmt += strlen(fmt);
1838 		if (fmt[-1] != '\n')
1839 			(void)fputc('\n', stderr);
1840 	}
1841 }
1842