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