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