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