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#ifdef __APPLE__
64#define __APPLE_PCAP_NG_API
65#include <sys/ioctl.h>
66#include "pktmetadatafilter.h"
67#endif /* __APPLE__ */
68#include <pcap.h>
69#ifdef DLT_PKTAP
70#include <net/pktap.h>
71#include <net/iptap.h>
72#endif
73#ifdef DLT_PCAPNG
74#include <pcap/pcap-ng.h>
75#include <pcap/pcap-util.h>
76#endif
77#include <signal.h>
78#include <stdio.h>
79#include <stdlib.h>
80#include <string.h>
81#include <limits.h>
82#ifndef WIN32
83#include <sys/wait.h>
84#include <sys/resource.h>
85#include <pwd.h>
86#include <grp.h>
87#include <errno.h>
88#endif /* WIN32 */
89
90/* capabilities convinience library */
91#ifdef HAVE_CAP_NG_H
92#include <cap-ng.h>
93#endif /* HAVE_CAP_NG_H */
94
95#include "netdissect.h"
96#include "interface.h"
97#include "addrtoname.h"
98#include "machdep.h"
99#include "setsignal.h"
100#include "gmt2local.h"
101#include "pcap-missing.h"
102
103#ifndef PATH_MAX
104#define PATH_MAX 1024
105#endif
106
107#ifdef SIGINFO
108#define SIGNAL_REQ_INFO SIGINFO
109#elif SIGUSR1
110#define SIGNAL_REQ_INFO SIGUSR1
111#endif
112
113#ifndef MIN
114#define MIN(a,b) ((a)<(b)?(a):(b))
115#endif
116
117netdissect_options Gndo;
118netdissect_options *gndo = &Gndo;
119
120static int dflag;			/* print filter code */
121static int Lflag;			/* list available data link types and exit */
122#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
123static int Jflag;			/* list available time stamp types */
124#endif
125static char *zflag = NULL;		/* compress each savefile using a specified command (like gzip or bzip2) */
126
127static int infodelay;
128static int infoprint;
129
130char *filter_src_buf = NULL;
131
132char *program_name;
133
134int32_t thiszone;		/* seconds offset from gmt to local time */
135
136/* Forwards */
137static RETSIGTYPE cleanup(int);
138static RETSIGTYPE child_cleanup(int);
139static void usage(void) __attribute__((noreturn));
140static void show_dlts_and_exit(const char *device, pcap_t *pd) __attribute__((noreturn));
141
142static void print_callback(u_char *, const struct pcap_pkthdr *, const u_char *);
143static void ndo_default_print(netdissect_options *, const u_char *, u_int);
144static void dump_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
145static void droproot(const char *, const char *);
146static void ndo_error(netdissect_options *ndo, const char *fmt, ...)
147     __attribute__ ((noreturn, format (printf, 2, 3)));
148static void ndo_warning(netdissect_options *ndo, const char *fmt, ...);
149
150#ifdef __APPLE__
151
152node_t *pkt_meta_data_expression = NULL;
153
154char *open_special_device(char *);
155int pktap_filter_packet(pcap_t *, struct pcap_if_info *, const struct pcap_pkthdr *, const u_char *);
156
157#endif /* __APPLE__ */
158
159#ifdef SIGNAL_REQ_INFO
160RETSIGTYPE requestinfo(int);
161#endif
162
163#if defined(USE_WIN32_MM_TIMER)
164  #include <MMsystem.h>
165  static UINT timer_id;
166  static void CALLBACK verbose_stats_dump(UINT, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR);
167#elif defined(HAVE_ALARM)
168  static void verbose_stats_dump(int sig);
169#endif
170
171static void info(int);
172static u_long packets_captured;
173static u_long max_packet_cnt = -1;
174u_int packets_mtdt_fltr_drop = 0; /* Drops by metadata filter */
175
176struct printer {
177        if_printer f;
178	int type;
179};
180
181
182struct ndo_printer {
183        if_ndo_printer f;
184	int type;
185};
186
187
188static struct printer printers[] = {
189	{ arcnet_if_print,	DLT_ARCNET },
190#ifdef DLT_ARCNET_LINUX
191	{ arcnet_linux_if_print, DLT_ARCNET_LINUX },
192#endif
193	{ token_if_print,	DLT_IEEE802 },
194#ifdef DLT_LANE8023
195	{ lane_if_print,        DLT_LANE8023 },
196#endif
197#ifdef DLT_CIP
198	{ cip_if_print,         DLT_CIP },
199#endif
200#ifdef DLT_ATM_CLIP
201	{ cip_if_print,		DLT_ATM_CLIP },
202#endif
203	{ sl_if_print,		DLT_SLIP },
204#ifdef DLT_SLIP_BSDOS
205	{ sl_bsdos_if_print,	DLT_SLIP_BSDOS },
206#endif
207	{ ppp_if_print,		DLT_PPP },
208#ifdef DLT_PPP_WITHDIRECTION
209	{ ppp_if_print,		DLT_PPP_WITHDIRECTION },
210#endif
211#ifdef DLT_PPP_BSDOS
212	{ ppp_bsdos_if_print,	DLT_PPP_BSDOS },
213#endif
214	{ fddi_if_print,	DLT_FDDI },
215	{ null_if_print,	DLT_NULL },
216#ifdef DLT_LOOP
217	{ null_if_print,	DLT_LOOP },
218#endif
219	{ raw_if_print,		DLT_RAW },
220	{ atm_if_print,		DLT_ATM_RFC1483 },
221#ifdef DLT_C_HDLC
222	{ chdlc_if_print,	DLT_C_HDLC },
223#endif
224#ifdef DLT_HDLC
225	{ chdlc_if_print,	DLT_HDLC },
226#endif
227#ifdef DLT_PPP_SERIAL
228	{ ppp_hdlc_if_print,	DLT_PPP_SERIAL },
229#endif
230#ifdef DLT_PPP_ETHER
231	{ pppoe_if_print,	DLT_PPP_ETHER },
232#endif
233#ifdef DLT_LINUX_SLL
234	{ sll_if_print,		DLT_LINUX_SLL },
235#endif
236#ifdef DLT_IEEE802_11
237	{ ieee802_11_if_print,	DLT_IEEE802_11},
238#endif
239#ifdef DLT_LTALK
240	{ ltalk_if_print,	DLT_LTALK },
241#endif
242#if defined(DLT_PFLOG) && defined(HAVE_NET_PFVAR_H)
243	{ pflog_if_print,	DLT_PFLOG },
244#endif
245#ifdef DLT_FR
246	{ fr_if_print,		DLT_FR },
247#endif
248#ifdef DLT_FRELAY
249	{ fr_if_print,		DLT_FRELAY },
250#endif
251#ifdef DLT_SUNATM
252	{ sunatm_if_print,	DLT_SUNATM },
253#endif
254#ifdef DLT_IP_OVER_FC
255	{ ipfc_if_print,	DLT_IP_OVER_FC },
256#endif
257#ifdef DLT_PRISM_HEADER
258	{ prism_if_print,	DLT_PRISM_HEADER },
259#endif
260#ifdef DLT_IEEE802_11_RADIO
261	{ ieee802_11_radio_if_print,	DLT_IEEE802_11_RADIO },
262#endif
263#ifdef DLT_ENC
264	{ enc_if_print,		DLT_ENC },
265#endif
266#ifdef DLT_SYMANTEC_FIREWALL
267	{ symantec_if_print,	DLT_SYMANTEC_FIREWALL },
268#endif
269#ifdef DLT_APPLE_IP_OVER_IEEE1394
270	{ ap1394_if_print,	DLT_APPLE_IP_OVER_IEEE1394 },
271#endif
272#ifdef DLT_IEEE802_11_RADIO_AVS
273	{ ieee802_11_radio_avs_if_print,	DLT_IEEE802_11_RADIO_AVS },
274#endif
275#ifdef DLT_JUNIPER_ATM1
276	{ juniper_atm1_print,	DLT_JUNIPER_ATM1 },
277#endif
278#ifdef DLT_JUNIPER_ATM2
279	{ juniper_atm2_print,	DLT_JUNIPER_ATM2 },
280#endif
281#ifdef DLT_JUNIPER_MFR
282	{ juniper_mfr_print,	DLT_JUNIPER_MFR },
283#endif
284#ifdef DLT_JUNIPER_MLFR
285	{ juniper_mlfr_print,	DLT_JUNIPER_MLFR },
286#endif
287#ifdef DLT_JUNIPER_MLPPP
288	{ juniper_mlppp_print,	DLT_JUNIPER_MLPPP },
289#endif
290#ifdef DLT_JUNIPER_PPPOE
291	{ juniper_pppoe_print,	DLT_JUNIPER_PPPOE },
292#endif
293#ifdef DLT_JUNIPER_PPPOE_ATM
294	{ juniper_pppoe_atm_print, DLT_JUNIPER_PPPOE_ATM },
295#endif
296#ifdef DLT_JUNIPER_GGSN
297	{ juniper_ggsn_print,	DLT_JUNIPER_GGSN },
298#endif
299#ifdef DLT_JUNIPER_ES
300	{ juniper_es_print,	DLT_JUNIPER_ES },
301#endif
302#ifdef DLT_JUNIPER_MONITOR
303	{ juniper_monitor_print, DLT_JUNIPER_MONITOR },
304#endif
305#ifdef DLT_JUNIPER_SERVICES
306	{ juniper_services_print, DLT_JUNIPER_SERVICES },
307#endif
308#ifdef DLT_JUNIPER_ETHER
309	{ juniper_ether_print,	DLT_JUNIPER_ETHER },
310#endif
311#ifdef DLT_JUNIPER_PPP
312	{ juniper_ppp_print,	DLT_JUNIPER_PPP },
313#endif
314#ifdef DLT_JUNIPER_FRELAY
315	{ juniper_frelay_print,	DLT_JUNIPER_FRELAY },
316#endif
317#ifdef DLT_JUNIPER_CHDLC
318	{ juniper_chdlc_print,	DLT_JUNIPER_CHDLC },
319#endif
320#ifdef DLT_MFR
321	{ mfr_if_print,		DLT_MFR },
322#endif
323#if defined(DLT_BLUETOOTH_HCI_H4_WITH_PHDR) && defined(HAVE_PCAP_BLUETOOTH_H)
324	{ bt_if_print,		DLT_BLUETOOTH_HCI_H4_WITH_PHDR},
325#endif
326#ifdef HAVE_PCAP_USB_H
327#ifdef DLT_USB_LINUX
328	{ usb_linux_48_byte_print, DLT_USB_LINUX},
329#endif /* DLT_USB_LINUX */
330#ifdef DLT_USB_LINUX_MMAPPED
331	{ usb_linux_64_byte_print, DLT_USB_LINUX_MMAPPED},
332#endif /* DLT_USB_LINUX_MMAPPED */
333#endif /* HAVE_PCAP_USB_H */
334#ifdef DLT_IPV4
335	{ raw_if_print,		DLT_IPV4 },
336#endif
337#ifdef DLT_IPV6
338	{ raw_if_print,		DLT_IPV6 },
339#endif
340	{ NULL,			0 },
341};
342
343static struct ndo_printer ndo_printers[] = {
344	{ ether_if_print,	DLT_EN10MB },
345#ifdef DLT_IPNET
346	{ ipnet_if_print,	DLT_IPNET },
347#endif
348#ifdef DLT_IEEE802_15_4
349	{ ieee802_15_4_if_print, DLT_IEEE802_15_4 },
350#endif
351#ifdef DLT_IEEE802_15_4_NOFCS
352	{ ieee802_15_4_if_print, DLT_IEEE802_15_4_NOFCS },
353#endif
354#ifdef DLT_PPI
355	{ ppi_if_print,		DLT_PPI },
356#endif
357#ifdef DLT_NETANALYZER
358	{ netanalyzer_if_print, DLT_NETANALYZER },
359#endif
360#ifdef DLT_NETANALYZER_TRANSPARENT
361	{ netanalyzer_transparent_if_print, DLT_NETANALYZER_TRANSPARENT },
362#endif
363#ifdef DLT_PKTAP
364	{ pktap_if_print,		DLT_PKTAP },
365#endif
366#ifdef DLT_PCAPNG
367	{ pcapng_print,		DLT_PCAPNG },
368#endif
369	{ NULL,			0 },
370};
371
372if_printer
373lookup_printer(int type)
374{
375	struct printer *p;
376
377	for (p = printers; p->f; ++p)
378		if (type == p->type)
379			return p->f;
380
381	return NULL;
382	/* NOTREACHED */
383}
384
385if_ndo_printer
386lookup_ndo_printer(int type)
387{
388	struct ndo_printer *p;
389
390	for (p = ndo_printers; p->f; ++p)
391		if (type == p->type)
392			return p->f;
393
394	return NULL;
395	/* NOTREACHED */
396}
397
398/* packet capture handle to read packets from device or file */
399static pcap_t *pd;
400
401static int supports_monitor_mode;
402
403extern int optind;
404extern int opterr;
405extern char *optarg;
406
407struct print_info;
408typedef int (*print_handler_func_t)(struct print_info *, const struct pcap_pkthdr *,
409									const u_char *);
410struct print_info {
411	netdissect_options *ndo;
412	union {
413		if_printer     printer;
414		if_ndo_printer ndo_printer;
415	} p;
416	int ndo_type;
417	pcap_t *pcap;
418	print_handler_func_t printer_func;
419};
420
421static int print_packet(struct print_info *, const struct pcap_pkthdr *, const u_char *);
422static int print_pcap_ng_block(struct print_info *, const struct pcap_pkthdr *, const u_char *);
423#ifdef __APPLE__
424static int print_pktap_packet(struct print_info *, const struct pcap_pkthdr *, const u_char *);
425#endif
426
427struct dump_info;
428typedef int (*dump_handler_func_t)(struct dump_info *, const struct pcap_pkthdr *,
429							 const u_char *);
430struct dump_info {
431	char	*WFileName;
432	char	*CurrentFileName;
433	pcap_t	*pcap;
434	pcap_dumper_t *dumper;
435	dump_handler_func_t dumper_func;
436};
437
438int handle_pcap_dump(struct dump_info *, const struct pcap_pkthdr *, const u_char *);
439int handle_bpf_exthdr_dump(struct dump_info *, const struct pcap_pkthdr *, const u_char *);
440int handle_pcap_ng_dump(struct dump_info *, const struct pcap_pkthdr *, const u_char *);
441int handle_pktap_dump(struct dump_info *, const struct pcap_pkthdr *, const u_char *);
442
443
444#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
445static void
446show_tstamp_types_and_exit(const char *device, pcap_t *pd)
447{
448	int n_tstamp_types;
449	int *tstamp_types = 0;
450	const char *tstamp_type_name;
451	int i;
452
453	n_tstamp_types = pcap_list_tstamp_types(pd, &tstamp_types);
454	if (n_tstamp_types < 0)
455		error("%s", pcap_geterr(pd));
456
457	if (n_tstamp_types == 0) {
458		fprintf(stderr, "Time stamp type cannot be set for %s\n",
459		    device);
460		exit(0);
461	}
462	fprintf(stderr, "Time stamp types for %s (use option -j to set):\n",
463	    device);
464	for (i = 0; i < n_tstamp_types; i++) {
465		tstamp_type_name = pcap_tstamp_type_val_to_name(tstamp_types[i]);
466		if (tstamp_type_name != NULL) {
467			(void) fprintf(stderr, "  %s (%s)\n", tstamp_type_name,
468			    pcap_tstamp_type_val_to_description(tstamp_types[i]));
469		} else {
470			(void) fprintf(stderr, "  %d\n", tstamp_types[i]);
471		}
472	}
473	pcap_free_tstamp_types(tstamp_types);
474	exit(0);
475}
476#endif
477
478static void
479show_dlts_and_exit(const char *device, pcap_t *pd)
480{
481	int n_dlts;
482	int *dlts = 0;
483	const char *dlt_name;
484
485	n_dlts = pcap_list_datalinks(pd, &dlts);
486	if (n_dlts < 0)
487		error("%s", pcap_geterr(pd));
488	else if (n_dlts == 0 || !dlts)
489		error("No data link types.");
490
491	/*
492	 * If the interface is known to support monitor mode, indicate
493	 * whether these are the data link types available when not in
494	 * monitor mode, if -I wasn't specified, or when in monitor mode,
495	 * when -I was specified (the link-layer types available in
496	 * monitor mode might be different from the ones available when
497	 * not in monitor mode).
498	 */
499	if (supports_monitor_mode)
500		(void) fprintf(stderr, "Data link types for %s %s (use option -y to set):\n",
501		    device,
502		    Iflag ? "when in monitor mode" : "when not in monitor mode");
503	else
504		(void) fprintf(stderr, "Data link types for %s (use option -y to set):\n",
505		    device);
506
507	while (--n_dlts >= 0) {
508		dlt_name = pcap_datalink_val_to_name(dlts[n_dlts]);
509		if (dlt_name != NULL) {
510			(void) fprintf(stderr, "  %s (%s)", dlt_name,
511			    pcap_datalink_val_to_description(dlts[n_dlts]));
512
513			/*
514			 * OK, does tcpdump handle that type?
515			 */
516			if (lookup_printer(dlts[n_dlts]) == NULL
517                            && lookup_ndo_printer(dlts[n_dlts]) == NULL)
518				(void) fprintf(stderr, " (printing not supported)");
519			fprintf(stderr, "\n");
520		} else {
521			(void) fprintf(stderr, "  DLT %d (printing not supported)\n",
522			    dlts[n_dlts]);
523		}
524	}
525#ifdef HAVE_PCAP_FREE_DATALINKS
526	pcap_free_datalinks(dlts);
527#endif
528	exit(0);
529}
530
531/*
532 * Set up flags that might or might not be supported depending on the
533 * version of libpcap we're using.
534 */
535#if defined(HAVE_PCAP_CREATE) || defined(WIN32)
536#define B_FLAG		"B:"
537#define B_FLAG_USAGE	" [ -B size ]"
538#else /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
539#define B_FLAG
540#define B_FLAG_USAGE
541#endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
542
543#ifdef __APPLE__
544#define g_FLAG		"g"
545#define Q_FLAG		"Q:"
546#else
547#define g_FLAG
548#define Q_FLAG
549#endif
550
551#ifdef HAVE_PCAP_CREATE
552#define I_FLAG		"I"
553#else /* HAVE_PCAP_CREATE */
554#define I_FLAG
555#endif /* HAVE_PCAP_CREATE */
556
557#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
558#define j_FLAG		"j:"
559#define j_FLAG_USAGE	" [ -j tstamptype ]"
560#define J_FLAG		"J"
561#else /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
562#define j_FLAG
563#define j_FLAG_USAGE
564#define J_FLAG
565#endif /* PCAP_ERROR_TSTAMP_TYPE_NOTSUP */
566
567#ifdef HAVE_PCAP_FINDALLDEVS
568#ifndef HAVE_PCAP_IF_T
569#undef HAVE_PCAP_FINDALLDEVS
570#endif
571#endif
572
573#ifdef HAVE_PCAP_FINDALLDEVS
574#define D_FLAG	"D"
575#else
576#define D_FLAG
577#endif
578
579#ifdef HAVE_PCAP_DUMP_FLUSH
580#define U_FLAG	"U"
581#else
582#define U_FLAG
583#endif
584
585#ifndef WIN32
586/* Drop root privileges and chroot if necessary */
587static void
588droproot(const char *username, const char *chroot_dir)
589{
590	struct passwd *pw = NULL;
591
592	if (chroot_dir && !username) {
593		fprintf(stderr, "tcpdump: Chroot without dropping root is insecure\n");
594		exit(1);
595	}
596
597	pw = getpwnam(username);
598	if (pw) {
599		if (chroot_dir) {
600			if (chroot(chroot_dir) != 0 || chdir ("/") != 0) {
601				fprintf(stderr, "tcpdump: Couldn't chroot/chdir to '%.64s': %s\n",
602				    chroot_dir, pcap_strerror(errno));
603				exit(1);
604			}
605		}
606#ifdef HAVE_CAP_NG_H
607		int ret = capng_change_id(pw->pw_uid, pw->pw_gid, CAPNG_NO_FLAG);
608		if (ret < 0) {
609			printf("error : ret %d\n", ret);
610		}
611		/* We don't need CAP_SETUID and CAP_SETGID */
612		capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
613		capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_SETUID);
614		capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
615		capng_update(CAPNG_DROP, CAPNG_PERMITTED, CAP_SETUID);
616		capng_apply(CAPNG_SELECT_BOTH);
617
618#else
619		if (initgroups(pw->pw_name, pw->pw_gid) != 0 ||
620		    setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
621			fprintf(stderr, "tcpdump: Couldn't change to '%.32s' uid=%lu gid=%lu: %s\n",
622			    username,
623			    (unsigned long)pw->pw_uid,
624			    (unsigned long)pw->pw_gid,
625			    pcap_strerror(errno));
626			exit(1);
627		}
628#endif /* HAVE_CAP_NG_H */
629	}
630	else {
631		fprintf(stderr, "tcpdump: Couldn't find user '%.32s'\n",
632		    username);
633		exit(1);
634	}
635}
636#endif /* WIN32 */
637
638static int
639getWflagChars(int x)
640{
641	int c = 0;
642
643	x -= 1;
644	while (x > 0) {
645		c += 1;
646		x /= 10;
647	}
648
649	return c;
650}
651
652
653static void
654MakeFilename(char *buffer, char *orig_name, int cnt, int max_chars)
655{
656        char *filename = malloc(PATH_MAX + 1);
657        if (filename == NULL)
658            error("Makefilename: malloc");
659
660        /* Process with strftime if Gflag is set. */
661        if (Gflag != 0) {
662          struct tm *local_tm;
663
664          /* Convert Gflag_time to a usable format */
665          if ((local_tm = localtime(&Gflag_time)) == NULL) {
666                  error("MakeTimedFilename: localtime");
667          }
668
669          /* There's no good way to detect an error in strftime since a return
670           * value of 0 isn't necessarily failure.
671           */
672          strftime(filename, PATH_MAX, orig_name, local_tm);
673        } else {
674          strncpy(filename, orig_name, PATH_MAX);
675        }
676
677	if (cnt == 0 && max_chars == 0)
678		strncpy(buffer, filename, PATH_MAX + 1);
679	else
680		if (snprintf(buffer, PATH_MAX + 1, "%s%0*d", filename, max_chars, cnt) > PATH_MAX)
681                  /* Report an error if the filename is too large */
682                  error("too many output files or filename is too long (> %d)", PATH_MAX);
683        free(filename);
684}
685
686static int tcpdump_printf(netdissect_options *ndo _U_,
687			  const char *fmt, ...)
688{
689
690  va_list args;
691  int ret;
692
693  va_start(args, fmt);
694  ret=vfprintf(stdout, fmt, args);
695  va_end(args);
696
697  return ret;
698}
699
700static struct print_info
701get_print_info(int type)
702{
703	struct print_info printinfo;
704
705	printinfo.ndo_type = 1;
706	printinfo.ndo = gndo;
707	printinfo.p.ndo_printer = lookup_ndo_printer(type);
708	if (printinfo.p.ndo_printer == NULL) {
709		printinfo.p.printer = lookup_printer(type);
710		printinfo.ndo_type = 0;
711		if (printinfo.p.printer == NULL) {
712			gndo->ndo_dltname = pcap_datalink_val_to_name(type);
713			if (gndo->ndo_dltname != NULL)
714				error("packet printing is not supported for link type %s: use -w",
715				      gndo->ndo_dltname);
716			else
717				error("packet printing is not supported for link type %d: use -w", type);
718		}
719	}
720#ifdef DLT_PCAPNG
721	if (type == DLT_PCAPNG)
722		printinfo.printer_func = print_pcap_ng_block;
723	else
724#endif /* DLT_PCAPNG */
725#ifdef DLT_PKTAP
726	if (type == DLT_PKTAP)
727		printinfo.printer_func = print_pktap_packet;
728	else
729#endif /* DLT_PKTAP */
730		printinfo.printer_func = print_packet;
731
732	return (printinfo);
733}
734
735static char *
736get_next_file(FILE *VFile, char *ptr)
737{
738	char *ret;
739
740	ret = fgets(ptr, PATH_MAX, VFile);
741	if (!ret)
742		return NULL;
743
744	if (ptr[strlen(ptr) - 1] == '\n')
745		ptr[strlen(ptr) - 1] = '\0';
746
747	return ret;
748}
749
750int
751main(int argc, char **argv)
752{
753	register int op, i;
754	bpf_u_int32 localnet, netmask;
755	register char *cp, *infile, *device, *RFileName, *VFileName, *WFileName;
756	pcap_handler callback;
757	int dlt;
758	int new_dlt;
759	const char *dlt_name;
760	struct bpf_program fcode;
761#ifndef WIN32
762	RETSIGTYPE (*oldhandler)(int);
763#endif
764	struct print_info printinfo;
765	struct dump_info dumpinfo;
766	u_char *pcap_userdata;
767	char ebuf[PCAP_ERRBUF_SIZE];
768	char VFileLine[PATH_MAX + 1];
769	char *username = NULL;
770	char *chroot_dir = NULL;
771	char *ret = NULL;
772	char *end;
773#ifdef HAVE_PCAP_FINDALLDEVS
774	pcap_if_t *devpointer;
775	int devnum;
776#endif
777	int status;
778	FILE *VFile;
779#ifdef WIN32
780	if(wsockinit() != 0) return 1;
781#endif /* WIN32 */
782#ifdef __APPLE__
783	int on = 1;
784	int no_loopkupnet_warning = 0;
785#endif
786
787	jflag=-1;	/* not set */
788        gndo->ndo_Oflag=1;
789	gndo->ndo_Rflag=1;
790	gndo->ndo_dlt=-1;
791	gndo->ndo_default_print=ndo_default_print;
792	gndo->ndo_printf=tcpdump_printf;
793	gndo->ndo_error=ndo_error;
794	gndo->ndo_warning=ndo_warning;
795	gndo->ndo_snaplen = DEFAULT_SNAPLEN;
796
797	device = NULL;
798	infile = NULL;
799	RFileName = NULL;
800	VFileName = NULL;
801	VFile = NULL;
802	WFileName = NULL;
803	dlt = -1;
804	if ((cp = strrchr(argv[0], '/')) != NULL)
805		program_name = cp + 1;
806	else
807		program_name = argv[0];
808
809	if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0)
810		error("%s", ebuf);
811
812#ifdef LIBSMI
813	smiInit("tcpdump");
814#endif
815
816	while (
817	    (op = getopt(argc, argv, "@1aAb" B_FLAG "c:C:d" D_FLAG "eE:fF:" g_FLAG " G:hHi:" I_FLAG j_FLAG J_FLAG "kKlLm:M:nNoOpPq" Q_FLAG "r:Rs:StT:u" U_FLAG "vV:w:W:xXy:Yz:Z:")) != -1)
818		switch (op) {
819
820		case 'a':
821			/* compatibility for old -a */
822			break;
823
824		case 'A':
825			++Aflag;
826			break;
827
828		case 'b':
829			++bflag;
830			break;
831
832#if defined(HAVE_PCAP_CREATE) || defined(WIN32)
833		case 'B':
834			Bflag = atoi(optarg)*1024;
835			if (Bflag <= 0)
836				error("invalid packet buffer size %s", optarg);
837			break;
838#endif /* defined(HAVE_PCAP_CREATE) || defined(WIN32) */
839
840		case 'c':
841			max_packet_cnt = strtoul(optarg, NULL, 0);
842			break;
843
844		case 'C':
845			Cflag = atoi(optarg) * 1000000;
846			if (Cflag < 0)
847				error("invalid file size %s", optarg);
848			break;
849
850		case 'd':
851			++dflag;
852			break;
853
854#ifdef HAVE_PCAP_FINDALLDEVS
855		case 'D':
856			if (pcap_findalldevs(&devpointer, ebuf) < 0)
857				error("%s", ebuf);
858			else {
859				for (i = 0; devpointer != 0; i++) {
860					printf("%d.%s", i+1, devpointer->name);
861					if (devpointer->description != NULL)
862						printf(" (%s)", devpointer->description);
863					printf("\n");
864					devpointer = devpointer->next;
865				}
866			}
867			return 0;
868#endif /* HAVE_PCAP_FINDALLDEVS */
869
870		case 'e':
871			++eflag;
872			break;
873
874		case 'E':
875#ifndef HAVE_LIBCRYPTO
876			warning("crypto code not compiled in");
877#endif
878			gndo->ndo_espsecret = optarg;
879			break;
880
881		case 'f':
882			++fflag;
883			break;
884
885		case 'F':
886			infile = optarg;
887			break;
888
889#ifdef __APPLE__
890		case 'g':
891			gflag++;
892			break;
893#endif
894
895		case 'G':
896			Gflag = atoi(optarg);
897			if (Gflag < 0)
898				error("invalid number of seconds %s", optarg);
899
900                        /* We will create one file initially. */
901                        Gflag_count = 0;
902
903			/* Grab the current time for rotation use. */
904			if ((Gflag_time = time(NULL)) == (time_t)-1) {
905				error("main: can't get current time: %s",
906				    pcap_strerror(errno));
907			}
908			break;
909
910		case 'h':
911			usage();
912			break;
913
914		case 'H':
915			++Hflag;
916			break;
917
918		case 'i':
919			if (optarg[0] == '0' && optarg[1] == 0)
920				error("Invalid adapter index");
921
922#ifdef HAVE_PCAP_FINDALLDEVS
923			/*
924			 * If the argument is a number, treat it as
925			 * an index into the list of adapters, as
926			 * printed by "tcpdump -D".
927			 *
928			 * This should be OK on UNIX systems, as interfaces
929			 * shouldn't have names that begin with digits.
930			 * It can be useful on Windows, where more than
931			 * one interface can have the same name.
932			 */
933			devnum = strtol(optarg, &end, 10);
934			if (optarg != end && *end == '\0') {
935				if (devnum < 0)
936					error("Invalid adapter index");
937
938				if (pcap_findalldevs(&devpointer, ebuf) < 0)
939					error("%s", ebuf);
940				else {
941					/*
942					 * Look for the devnum-th entry
943					 * in the list of devices
944					 * (1-based).
945					 */
946					for (i = 0;
947					    i < devnum-1 && devpointer != NULL;
948					    i++, devpointer = devpointer->next)
949						;
950					if (devpointer == NULL)
951						error("Invalid adapter index");
952				}
953				device = devpointer->name;
954				break;
955			}
956#endif /* HAVE_PCAP_FINDALLDEVS */
957			device = optarg;
958			break;
959
960#ifdef HAVE_PCAP_CREATE
961		case 'I':
962			++Iflag;
963			break;
964#endif /* HAVE_PCAP_CREATE */
965
966#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
967		case 'j':
968			jflag = pcap_tstamp_type_name_to_val(optarg);
969			if (jflag < 0)
970				error("invalid time stamp type %s", optarg);
971			break;
972
973		case 'J':
974			Jflag++;
975			break;
976#endif
977
978		case 'L':
979			Lflag++;
980			break;
981
982		case 'l':
983#ifdef WIN32
984			/*
985			 * _IOLBF is the same as _IOFBF in Microsoft's C
986			 * libraries; the only alternative they offer
987			 * is _IONBF.
988			 *
989			 * XXX - this should really be checking for MSVC++,
990			 * not WIN32, if, for example, MinGW has its own
991			 * C library that is more UNIX-compatible.
992			 */
993			setvbuf(stdout, NULL, _IONBF, 0);
994#else /* WIN32 */
995#ifdef HAVE_SETLINEBUF
996			setlinebuf(stdout);
997#else
998			setvbuf(stdout, NULL, _IOLBF, 0);
999#endif
1000#endif /* WIN32 */
1001			break;
1002#ifdef __APPLE__
1003		case 'k': {
1004			const char *kstr;
1005			int ch;
1006			int val = 0;
1007
1008			if (optind >= argc || argv[optind][0] == '-') {
1009				kflag = PRMD_ALL;
1010				break;
1011			}
1012			kstr = argv[optind];
1013
1014			while ((ch = *kstr++) != 0) {
1015				if (ch == 'I')
1016					val |= PRMD_IF;
1017				else if (ch == 'P')
1018					val |= PRMD_PID;
1019				else if (ch == 'N')
1020					val |= PRMD_PNAME;
1021				else if (ch == 'S')
1022					val |= PRMD_SVC;
1023				else if (ch == 'D')
1024					val |= PRMD_DIR;
1025				else if (ch == 'C')
1026					val |= PRMD_COMMENT;
1027				else {
1028					/*
1029					 * Was most likely parsing a filter expression
1030					 * if we do not recognize the character
1031					 */
1032					if (val == 0)
1033						break;
1034					error("Invalid flag for option '-k'");
1035				}
1036			}
1037			if (val == 0)
1038				kflag = PRMD_ALL;
1039			else {
1040				kflag = val;
1041				optind++;
1042			}
1043			break;
1044		}
1045#endif
1046		case 'K':
1047			++Kflag;
1048			break;
1049
1050		case 'm':
1051#ifdef LIBSMI
1052			if (smiLoadModule(optarg) == 0) {
1053				error("could not load MIB module %s", optarg);
1054			}
1055			sflag = 1;
1056#else
1057			(void)fprintf(stderr, "%s: ignoring option `-m %s' ",
1058				      program_name, optarg);
1059			(void)fprintf(stderr, "(no libsmi support)\n");
1060#endif
1061			break;
1062
1063		case 'M':
1064			/* TCP-MD5 shared secret */
1065#ifndef HAVE_LIBCRYPTO
1066			warning("crypto code not compiled in");
1067#endif
1068			sigsecret = optarg;
1069			break;
1070
1071		case 'n':
1072			++nflag;
1073			break;
1074
1075		case 'N':
1076			++Nflag;
1077			break;
1078
1079		case 'o':
1080			++oflag;
1081			break;
1082
1083		case 'O':
1084			Oflag = 0;
1085			break;
1086
1087#ifdef __APPLE__
1088		case 'P':
1089			++Pflag;
1090#endif
1091
1092		case 'p':
1093			++pflag;
1094			break;
1095
1096		case 'q':
1097			++qflag;
1098			++suppress_default_print;
1099			break;
1100
1101#ifdef __APPLE__
1102		case 'Q': {
1103			pkt_meta_data_expression = parse_expression(optarg);
1104			if (pkt_meta_data_expression == NULL)
1105				error("invalid expression \"%s\"", optarg);
1106			break;
1107		}
1108#endif
1109		case 'r':
1110			RFileName = optarg;
1111			break;
1112
1113		case 'R':
1114			Rflag = 0;
1115			break;
1116
1117		case 's':
1118			gndo->ndo_snaplen = strtol(optarg, &end, 0);
1119			if (optarg == end || *end != '\0'
1120			    || gndo->ndo_snaplen < 0 || gndo->ndo_snaplen > MAXIMUM_SNAPLEN)
1121				error("invalid snaplen %s", optarg);
1122			else if (gndo->ndo_snaplen == 0)
1123				gndo->ndo_snaplen = MAXIMUM_SNAPLEN;
1124			break;
1125
1126		case 'S':
1127			++Sflag;
1128			break;
1129
1130		case 't': {
1131			unsigned long mode;
1132			const char *ptr;
1133			char *endptr;
1134
1135			if (optind >= argc || argv[optind][0] == '-') {
1136				++tflag;
1137				break;
1138			}
1139			ptr = argv[optind];
1140			mode = strtoul(ptr, &endptr, 0);
1141			if (*endptr != 0) {
1142				++tflag;
1143				break;
1144			}
1145			tflag = 1;
1146			switch (mode) {
1147				case 0:
1148					t0flag++;
1149					break;
1150				case 1:
1151					t1flag++;
1152					break;
1153				case 2:
1154					t2flag++;
1155					break;
1156				case 3:
1157					t3flag++;
1158					break;
1159				case 4:
1160					t4flag++;
1161					break;
1162				case 5:
1163					t5flag++;
1164					break;
1165				default:
1166					error("invalid timestamp mode %s", ptr);
1167					break;
1168			}
1169			optind++;
1170			break;
1171		}
1172		case 'T':
1173			if (strcasecmp(optarg, "vat") == 0)
1174				packettype = PT_VAT;
1175			else if (strcasecmp(optarg, "wb") == 0)
1176				packettype = PT_WB;
1177			else if (strcasecmp(optarg, "rpc") == 0)
1178				packettype = PT_RPC;
1179			else if (strcasecmp(optarg, "rtp") == 0)
1180				packettype = PT_RTP;
1181			else if (strcasecmp(optarg, "rtcp") == 0)
1182				packettype = PT_RTCP;
1183			else if (strcasecmp(optarg, "snmp") == 0)
1184				packettype = PT_SNMP;
1185			else if (strcasecmp(optarg, "cnfp") == 0)
1186				packettype = PT_CNFP;
1187			else if (strcasecmp(optarg, "tftp") == 0)
1188				packettype = PT_TFTP;
1189			else if (strcasecmp(optarg, "aodv") == 0)
1190				packettype = PT_AODV;
1191			else if (strcasecmp(optarg, "carp") == 0)
1192				packettype = PT_CARP;
1193			else if (strcasecmp(optarg, "radius") == 0)
1194				packettype = PT_RADIUS;
1195			else if (strcasecmp(optarg, "zmtp1") == 0)
1196				packettype = PT_ZMTP1;
1197			else if (strcasecmp(optarg, "vxlan") == 0)
1198				packettype = PT_VXLAN;
1199			else
1200				error("unknown packet type `%s'", optarg);
1201			break;
1202
1203		case 'u':
1204			++uflag;
1205			break;
1206
1207#ifdef HAVE_PCAP_DUMP_FLUSH
1208		case 'U':
1209			++Uflag;
1210			break;
1211#endif
1212
1213		case 'v':
1214			++vflag;
1215			break;
1216
1217		case 'V':
1218			VFileName = optarg;
1219			break;
1220
1221		case 'w':
1222			WFileName = optarg;
1223			break;
1224
1225		case 'W':
1226			Wflag = atoi(optarg);
1227			if (Wflag < 0)
1228				error("invalid number of output files %s", optarg);
1229			WflagChars = getWflagChars(Wflag);
1230			break;
1231
1232		case 'x':
1233			++xflag;
1234			++suppress_default_print;
1235			break;
1236
1237		case 'X':
1238			++Xflag;
1239			++suppress_default_print;
1240			break;
1241
1242		case 'y':
1243			gndo->ndo_dltname = optarg;
1244			gndo->ndo_dlt =
1245			  pcap_datalink_name_to_val(gndo->ndo_dltname);
1246			if (gndo->ndo_dlt < 0)
1247				error("invalid data link type %s", gndo->ndo_dltname);
1248			break;
1249
1250#if defined(HAVE_PCAP_DEBUG) || defined(HAVE_YYDEBUG)
1251		case 'Y':
1252			{
1253			/* Undocumented flag */
1254#ifdef HAVE_PCAP_DEBUG
1255			extern int pcap_debug;
1256			pcap_debug = 1;
1257#else
1258			extern int yydebug;
1259			yydebug = 1;
1260#endif
1261			}
1262			break;
1263#endif
1264		case 'z':
1265			if (optarg) {
1266				zflag = strdup(optarg);
1267			} else {
1268				usage();
1269				/* NOTREACHED */
1270			}
1271			break;
1272
1273		case 'Z':
1274			if (optarg) {
1275				username = strdup(optarg);
1276			}
1277			else {
1278				usage();
1279				/* NOTREACHED */
1280			}
1281			break;
1282
1283		default:
1284			usage();
1285			/* NOTREACHED */
1286		}
1287
1288	switch (tflag) {
1289
1290	case 0: /* Default */
1291	case 4: /* Default + Date*/
1292		thiszone = gmt2local(0);
1293		break;
1294
1295	case 1: /* No time stamp */
1296	case 2: /* Unix timeval style */
1297	case 3: /* Microseconds since previous packet */
1298	case 5: /* Microseconds since first packet */
1299		break;
1300
1301	default: /* Not supported */
1302		error("only -t, -tt, -ttt, -tttt and -ttttt are supported");
1303		break;
1304	}
1305
1306	if (t0flag || t4flag)
1307		thiszone = gmt2local(0);
1308
1309	if (fflag != 0 && (VFileName != NULL || RFileName != NULL))
1310		error("-f can not be used with -V or -r");
1311
1312	if (VFileName != NULL && RFileName != NULL)
1313		error("-V and -r are mutually exclusive.");
1314
1315#ifdef WITH_CHROOT
1316	/* if run as root, prepare for chrooting */
1317	if (getuid() == 0 || geteuid() == 0) {
1318		/* future extensibility for cmd-line arguments */
1319		if (!chroot_dir)
1320			chroot_dir = WITH_CHROOT;
1321	}
1322#endif
1323
1324#ifdef WITH_USER
1325	/* if run as root, prepare for dropping root privileges */
1326	if (getuid() == 0 || geteuid() == 0) {
1327		/* Run with '-Z root' to restore old behaviour */
1328		if (!username)
1329			username = WITH_USER;
1330	}
1331#endif
1332
1333	if (RFileName != NULL || VFileName != NULL) {
1334		/*
1335		 * If RFileName is non-null, it's the pathname of a
1336		 * savefile to read.  If VFileName is non-null, it's
1337		 * the pathname of a file containing a list of pathnames
1338		 * (one per line) of savefiles to read.
1339		 *
1340		 * In either case, we're reading a savefile, not doing
1341		 * a live capture.
1342		 */
1343#ifndef WIN32
1344		/*
1345		 * We don't need network access, so relinquish any set-UID
1346		 * or set-GID privileges we have (if any).
1347		 *
1348		 * We do *not* want set-UID privileges when opening a
1349		 * trace file, as that might let the user read other
1350		 * people's trace files (especially if we're set-UID
1351		 * root).
1352		 */
1353		if (setgid(getgid()) != 0 || setuid(getuid()) != 0 )
1354			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1355#endif /* WIN32 */
1356		if (VFileName != NULL) {
1357			if (VFileName[0] == '-' && VFileName[1] == '\0')
1358				VFile = stdin;
1359			else
1360				VFile = fopen(VFileName, "r");
1361
1362			if (VFile == NULL)
1363				error("Unable to open file: %s\n", strerror(errno));
1364
1365			ret = get_next_file(VFile, VFileLine);
1366			if (!ret)
1367				error("Nothing in %s\n", VFileName);
1368			RFileName = VFileLine;
1369		}
1370#if defined(__APPLE__) && defined(DLT_PCAPNG)
1371		pd = pcap_ng_open_offline(RFileName, ebuf);
1372		if (pd != NULL) {
1373			fprintf(stderr, "reading from PCAP-NG file %s\n",
1374					RFileName);
1375			/*
1376			 * The output file is also a pcap-ng file
1377			 */
1378			Pflag++;
1379		} else
1380#endif /* __APPLE__ && DLT_PCAPNG */
1381        {
1382			pd = pcap_open_offline(RFileName, ebuf);
1383			if (pd == NULL)
1384				error("%s", ebuf);
1385			dlt = pcap_datalink(pd);
1386			dlt_name = pcap_datalink_val_to_name(dlt);
1387			if (dlt_name == NULL) {
1388				fprintf(stderr, "reading from file %s, link-type %u\n",
1389					RFileName, dlt);
1390			} else {
1391				fprintf(stderr,
1392					"reading from file %s, link-type %s (%s)\n",
1393					RFileName, dlt_name,
1394					pcap_datalink_val_to_description(dlt));
1395			}
1396		}
1397		localnet = 0;
1398		netmask = 0;
1399	} else {
1400		/*
1401		 * We're doing a live capture.
1402		 */
1403#if defined(__APPLE__) && defined(DLT_PKTAP)
1404		/*
1405		 * By default use a pktap interface to tap on multiple physical interfaces
1406		 * The special device name "all" means to tap on all interfaces
1407		 */
1408		if (device == NULL)
1409			device = PKTAP_IFNAME;
1410		if (strncmp(device, PKTAP_IFNAME, strlen(PKTAP_IFNAME)) == 0 ||
1411			strncmp(device, IPTAP_IFNAME, strlen(IPTAP_IFNAME)) == 0 ||
1412			strcmp(device, "any") == 0 ||
1413			strcmp(device, "all") == 0) {
1414
1415			/* No need to attempt to use promiscuous mode */
1416			gndo->ndo_pflag = 1;
1417
1418			/* Suppress useless warnings */
1419			no_loopkupnet_warning = 1;
1420
1421            /* By default use PKTAP data link type */
1422            if (gndo->ndo_dltname == NULL) {
1423                gndo->ndo_dltname = "PKTAP";
1424                gndo->ndo_dlt = pcap_datalink_name_to_val(gndo->ndo_dltname);
1425                if (gndo->ndo_dlt < 0)
1426                    error("cannot use data link type %s", gndo->ndo_dltname);
1427            }
1428            /* Force PCAP-NG if capturing with metadata */
1429            if (gndo->ndo_dlt == DLT_PKTAP)
1430                Pflag++;
1431        }
1432#else /* __APPLE__ && DLT_PKTAP */
1433		if (device == NULL) {
1434			device = pcap_lookupdev(ebuf);
1435			if (device == NULL)
1436				error("%s", ebuf);
1437		}
1438#endif /* __APPLE__ && DLT_PCAPNG */
1439#ifdef WIN32
1440		/*
1441		 * Print a message to the standard error on Windows.
1442		 * XXX - why do it here, with a different message?
1443		 */
1444		if(strlen(device) == 1)	//we assume that an ASCII string is always longer than 1 char
1445		{						//a Unicode string has a \0 as second byte (so strlen() is 1)
1446			fprintf(stderr, "%s: listening on %ws\n", program_name, device);
1447		}
1448		else
1449		{
1450			fprintf(stderr, "%s: listening on %s\n", program_name, device);
1451		}
1452
1453		fflush(stderr);
1454#endif /* WIN32 */
1455#ifdef HAVE_PCAP_CREATE
1456		pd = pcap_create(device, ebuf);
1457		if (pd == NULL)
1458			error("%s", ebuf);
1459#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1460		if (Jflag)
1461			show_tstamp_types_and_exit(device, pd);
1462#endif
1463#if defined(__APPLE__) && defined(DLT_PKTAP)
1464		/*
1465		 * Must be called before pcap_activate()
1466		 */
1467		pcap_set_want_pktap(pd, 1);
1468#endif
1469		/*
1470		 * Is this an interface that supports monitor mode?
1471		 */
1472		if (pcap_can_set_rfmon(pd) == 1)
1473			supports_monitor_mode = 1;
1474		else
1475			supports_monitor_mode = 0;
1476		status = pcap_set_snaplen(pd, gndo->ndo_snaplen);
1477		if (status != 0)
1478			error("%s: Can't set snapshot length: %s",
1479			    device, pcap_statustostr(status));
1480		status = pcap_set_promisc(pd, !pflag);
1481		if (status != 0)
1482			error("%s: Can't set promiscuous mode: %s",
1483			    device, pcap_statustostr(status));
1484		if (Iflag) {
1485			status = pcap_set_rfmon(pd, 1);
1486			if (status != 0)
1487				error("%s: Can't set monitor mode: %s",
1488				    device, pcap_statustostr(status));
1489		}
1490		status = pcap_set_timeout(pd, 1000);
1491		if (status != 0)
1492			error("%s: pcap_set_timeout failed: %s",
1493			    device, pcap_statustostr(status));
1494		if (Bflag != 0) {
1495			status = pcap_set_buffer_size(pd, Bflag);
1496			if (status != 0)
1497				error("%s: Can't set buffer size: %s",
1498				    device, pcap_statustostr(status));
1499		}
1500#ifdef HAVE_PCAP_SET_TSTAMP_TYPE
1501                if (jflag != -1) {
1502			status = pcap_set_tstamp_type(pd, jflag);
1503			if (status < 0)
1504				error("%s: Can't set time stamp type: %s",
1505			    	    device, pcap_statustostr(status));
1506		}
1507#endif
1508		status = pcap_activate(pd);
1509		if (status < 0) {
1510			/*
1511			 * pcap_activate() failed.
1512			 */
1513			cp = pcap_geterr(pd);
1514			if (status == PCAP_ERROR)
1515				error("%s", cp);
1516			else if ((status == PCAP_ERROR_NO_SUCH_DEVICE ||
1517			          status == PCAP_ERROR_PERM_DENIED) &&
1518			         *cp != '\0')
1519				error("%s: %s\n(%s)", device,
1520				    pcap_statustostr(status), cp);
1521			else
1522				error("%s: %s", device,
1523				    pcap_statustostr(status));
1524		} else if (status > 0) {
1525			/*
1526			 * pcap_activate() succeeded, but it's warning us
1527			 * of a problem it had.
1528			 */
1529			cp = pcap_geterr(pd);
1530			if (status == PCAP_WARNING)
1531				warning("%s", cp);
1532			else if (status == PCAP_WARNING_PROMISC_NOTSUP &&
1533			         *cp != '\0')
1534				warning("%s: %s\n(%s)", device,
1535				    pcap_statustostr(status), cp);
1536			else
1537				warning("%s: %s", device,
1538				    pcap_statustostr(status));
1539		}
1540#else
1541		*ebuf = '\0';
1542		pd = pcap_open_live(device, gndo->ndo_snaplen, !pflag, 1000, ebuf);
1543		if (pd == NULL)
1544			error("%s", ebuf);
1545		else if (*ebuf)
1546			warning("%s", ebuf);
1547#endif /* HAVE_PCAP_CREATE */
1548
1549		/*
1550		 * Let user own process after socket has been opened.
1551		 */
1552#ifndef WIN32
1553		if (setgid(getgid()) != 0 || setuid(getuid()) != 0)
1554			fprintf(stderr, "Warning: setgid/setuid failed !\n");
1555#endif /* WIN32 */
1556#if !defined(HAVE_PCAP_CREATE) && defined(WIN32)
1557		if(Bflag != 0)
1558			if(pcap_setbuff(pd, Bflag)==-1){
1559				error("%s", pcap_geterr(pd));
1560			}
1561#endif /* !defined(HAVE_PCAP_CREATE) && defined(WIN32) */
1562		if (Lflag)
1563			show_dlts_and_exit(device, pd);
1564		if (gndo->ndo_dlt >= 0) {
1565#ifdef HAVE_PCAP_SET_DATALINK
1566			if (pcap_set_datalink(pd, gndo->ndo_dlt) < 0)
1567				error("%s", pcap_geterr(pd));
1568#else
1569			/*
1570			 * We don't actually support changing the
1571			 * data link type, so we only let them
1572			 * set it to what it already is.
1573			 */
1574			if (gndo->ndo_dlt != pcap_datalink(pd)) {
1575				error("%s is not one of the DLTs supported by this device\n",
1576				      gndo->ndo_dltname);
1577			}
1578#endif
1579			(void)fprintf(stderr, "%s: data link type %s\n",
1580				      program_name, gndo->ndo_dltname);
1581			(void)fflush(stderr);
1582		}
1583#ifdef __APPLE__
1584#ifdef DLT_PKTAP
1585		/*
1586		 * Use packet metadata from one source only: DLT_PKTAP
1587		 * supersedes the BPF extended header mechamisn
1588		 */
1589		if (pcap_datalink(pd) != DLT_PKTAP)
1590#endif /* DLT_PKTAP */
1591			if ((kflag || Pflag) && pcap_apple_set_exthdr(pd, on) == -1)
1592				warning("%s", pcap_geterr(pd));
1593#endif /* __APPLE__ */
1594		i = pcap_snapshot(pd);
1595		if (gndo->ndo_snaplen < i) {
1596			warning("snaplen raised from %d to %d", gndo->ndo_snaplen, i);
1597			gndo->ndo_snaplen = i;
1598		}
1599		if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) {
1600			localnet = 0;
1601			netmask = 0;
1602#if __APPLE__
1603			if (!no_loopkupnet_warning)
1604				warning("%s", ebuf);
1605#else
1606			warning("%s", ebuf);
1607#endif /* __APPLE__ */
1608		}
1609	}
1610	if (infile)
1611		filter_src_buf = read_infile(infile);
1612	else
1613		filter_src_buf = copy_argv(&argv[optind]);
1614
1615#if defined(DLT_PCAPNG) && defined(DLT_PKTAP)
1616	/*
1617	 * For PKTAP and PCAPNG the filter expression is compiled
1618	 * whenever a new interface is discovered
1619	 */
1620	dlt = pcap_datalink(pd);
1621	if (dlt == DLT_PCAPNG || dlt == DLT_PKTAP) {
1622		if (pcap_set_filter_info(pd, filter_src_buf, Oflag, netmask) < 0)
1623			error("%s", pcap_geterr(pd));
1624	} else
1625#endif /* DLT_PCAPNG && DLT_PKTAP */
1626		if (pcap_compile(pd, &fcode, filter_src_buf, Oflag, netmask) < 0)
1627			error("%s", pcap_geterr(pd));
1628
1629	if (dflag) {
1630		bpf_dump(&fcode, dflag);
1631		pcap_close(pd);
1632		exit(0);
1633	}
1634	init_addrtoname(localnet, netmask);
1635        init_checksum();
1636
1637#ifndef WIN32
1638	(void)setsignal(SIGPIPE, cleanup);
1639	(void)setsignal(SIGTERM, cleanup);
1640	(void)setsignal(SIGINT, cleanup);
1641#endif /* WIN32 */
1642#ifdef __APPLE__
1643    /*
1644     * The default action for SIGQUIT is to create a core dump and that is
1645     * generating a lot of useless crash tracer reports.
1646     */
1647	(void)setsignal(SIGQUIT, cleanup);
1648	(void)setsignal(SIGABRT, cleanup);
1649#endif /* __APPLE__ */
1650#if defined(HAVE_FORK) || defined(HAVE_VFORK)
1651	(void)setsignal(SIGCHLD, child_cleanup);
1652#endif
1653	/* Cooperate with nohup(1) */
1654#ifndef WIN32
1655	if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL)
1656		(void)setsignal(SIGHUP, oldhandler);
1657#endif /* WIN32 */
1658
1659#ifndef WIN32
1660	/*
1661	 * If a user name was specified with "-Z", attempt to switch to
1662	 * that user's UID.  This would probably be used with sudo,
1663	 * to allow tcpdump to be run in a special restricted
1664	 * account (if you just want to allow users to open capture
1665	 * devices, and can't just give users that permission,
1666	 * you'd make tcpdump set-UID or set-GID).
1667	 *
1668	 * Tcpdump doesn't necessarily write only to one savefile;
1669	 * the general only way to allow a -Z instance to write to
1670	 * savefiles as the user under whose UID it's run, rather
1671	 * than as the user specified with -Z, would thus be to switch
1672	 * to the original user ID before opening a capture file and
1673	 * then switch back to the -Z user ID after opening the savefile.
1674	 * Switching to the -Z user ID only after opening the first
1675	 * savefile doesn't handle the general case.
1676	 */
1677
1678#ifdef HAVE_CAP_NG_H
1679	/* We are running as root and we will be writing to savefile */
1680	if ((getuid() == 0 || geteuid() == 0) && WFileName) {
1681		if (username) {
1682			/* Drop all capabilities from effective set */
1683			capng_clear(CAPNG_EFFECTIVE);
1684			/* Add capabilities we will need*/
1685			capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETUID);
1686			capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_SETGID);
1687			capng_update(CAPNG_ADD, CAPNG_PERMITTED, CAP_DAC_OVERRIDE);
1688
1689			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETUID);
1690			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_SETGID);
1691			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
1692
1693			capng_apply(CAPNG_SELECT_BOTH);
1694		}
1695	}
1696#endif /* HAVE_CAP_NG_H */
1697
1698	if (getuid() == 0 || geteuid() == 0) {
1699		if (username || chroot_dir)
1700			droproot(username, chroot_dir);
1701	}
1702#endif /* WIN32 */
1703
1704#if defined(DLT_PCAPNG) && defined(DLT_PKTAP)
1705	dlt = pcap_datalink(pd);
1706	if (dlt != DLT_PCAPNG && dlt != DLT_PKTAP)
1707#endif /* DLT_PCAPNG && DLT_PKTAP */
1708		if (pcap_setfilter(pd, &fcode) < 0)
1709			error("%s", pcap_geterr(pd));
1710
1711	if (WFileName) {
1712		pcap_dumper_t *p;
1713		/* Do not exceed the default PATH_MAX for files. */
1714		dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1);
1715
1716		if (dumpinfo.CurrentFileName == NULL)
1717			error("malloc of dumpinfo.CurrentFileName");
1718
1719		/* We do not need numbering for dumpfiles if Cflag isn't set. */
1720		if (Cflag != 0)
1721		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars);
1722		else
1723		  MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0);
1724
1725#ifdef __APPLE__
1726		if (Pflag)
1727			p = pcap_ng_dump_open(pd, dumpinfo.CurrentFileName);
1728		else
1729#endif /* __APPLE__ */
1730			p = pcap_dump_open(pd, dumpinfo.CurrentFileName);
1731#ifdef HAVE_CAP_NG_H
1732        /* Give up capabilities, clear Effective set */
1733        capng_clear(CAPNG_EFFECTIVE);
1734#endif
1735		if (p == NULL)
1736			error("%s", pcap_geterr(pd));
1737
1738		if (Cflag != 0 || Gflag != 0)
1739			dumpinfo.WFileName = WFileName;
1740
1741		callback = dump_packet;
1742		dumpinfo.pcap = pd;
1743		dumpinfo.dumper = p;
1744#if defined(DLT_PCAPNG) && defined(DLT_PKTAP)
1745		if (dlt == DLT_PKTAP)
1746			dumpinfo.dumper_func = handle_pktap_dump;
1747		else if (dlt == DLT_PCAPNG)
1748			dumpinfo.dumper_func = handle_pcap_ng_dump;
1749		else
1750#endif /* DLT_PCAPNG && DLT_PKTAP */
1751#ifdef __APPLE__
1752		if (Pflag)
1753			dumpinfo.dumper_func = handle_bpf_exthdr_dump;
1754		else
1755#endif /* __APPLE__ */
1756			dumpinfo.dumper_func = handle_pcap_dump;
1757		pcap_userdata = (u_char *)&dumpinfo;
1758
1759#ifdef HAVE_PCAP_DUMP_FLUSH
1760		if (Uflag)
1761			pcap_dump_flush(p);
1762#endif
1763	} else {
1764		dlt = pcap_datalink(pd);
1765		printinfo = get_print_info(dlt);
1766		printinfo.pcap = pd;
1767		callback = print_callback;
1768		pcap_userdata = (u_char *)&printinfo;
1769		gndo->ndo_pcap = pd;
1770	}
1771
1772#ifdef SIGNAL_REQ_INFO
1773	/*
1774	 * We can't get statistics when reading from a file rather
1775	 * than capturing from a device.
1776	 */
1777	if (RFileName == NULL)
1778		(void)setsignal(SIGNAL_REQ_INFO, requestinfo);
1779#endif
1780
1781	if (vflag > 0 && WFileName) {
1782		/*
1783		 * When capturing to a file, "-v" means tcpdump should,
1784		 * every 10 seconds, "v"erbosely report the number of
1785		 * packets captured.
1786		 */
1787#ifdef USE_WIN32_MM_TIMER
1788		/* call verbose_stats_dump() each 1000 +/-100msec */
1789		timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC);
1790		setvbuf(stderr, NULL, _IONBF, 0);
1791#elif defined(HAVE_ALARM)
1792		(void)setsignal(SIGALRM, verbose_stats_dump);
1793		alarm(1);
1794#endif
1795	}
1796
1797#ifndef WIN32
1798	if (RFileName == NULL) {
1799		/*
1800		 * Live capture (if -V was specified, we set RFileName
1801		 * to a file from the -V file).  Print a message to
1802		 * the standard error on UN*X.
1803		 */
1804		if (!vflag && !WFileName) {
1805			(void)fprintf(stderr,
1806			    "%s: verbose output suppressed, use -v or -vv for full protocol decode\n",
1807			    program_name);
1808		} else
1809			(void)fprintf(stderr, "%s: ", program_name);
1810		dlt = pcap_datalink(pd);
1811		dlt_name = pcap_datalink_val_to_name(dlt);
1812		if (dlt_name == NULL) {
1813			(void)fprintf(stderr, "listening on %s, link-type %u, capture size %u bytes\n",
1814			    device, dlt, gndo->ndo_snaplen);
1815		} else {
1816			(void)fprintf(stderr, "listening on %s, link-type %s (%s), capture size %u bytes\n",
1817			    device, dlt_name,
1818			    pcap_datalink_val_to_description(dlt), gndo->ndo_snaplen);
1819		}
1820		(void)fflush(stderr);
1821	}
1822#endif /* WIN32 */
1823	do {
1824		status = pcap_loop(pd, -1, callback, pcap_userdata);
1825		if (WFileName == NULL) {
1826			/*
1827			 * We're printing packets.  Flush the printed output,
1828			 * so it doesn't get intermingled with error output.
1829			 */
1830			if (status == -2) {
1831				/*
1832				 * We got interrupted, so perhaps we didn't
1833				 * manage to finish a line we were printing.
1834				 * Print an extra newline, just in case.
1835				 */
1836				putchar('\n');
1837			}
1838			(void)fflush(stdout);
1839		}
1840		if (status == -1) {
1841			/*
1842			 * Error.  Report it.
1843			 */
1844			(void)fprintf(stderr, "%s: pcap_loop: %s\n",
1845			    program_name, pcap_geterr(pd));
1846		}
1847		if (RFileName == NULL) {
1848			/*
1849			 * We're doing a live capture.  Report the capture
1850			 * statistics.
1851			 */
1852			info(1);
1853		}
1854		pcap_close(pd);
1855		if (VFileName != NULL) {
1856			ret = get_next_file(VFile, VFileLine);
1857			if (ret) {
1858				RFileName = VFileLine;
1859#if defined(__APPLE__) && defined(DLT_PCAPNG)
1860				pd = pcap_ng_open_offline(RFileName, ebuf);
1861				if (pd != NULL) {
1862					fprintf(stderr, "reading from PCAP-NG file %s\n",
1863							RFileName);
1864				} else
1865#endif /* __APPLE__ && DLT_PCAPNG */
1866				pd = pcap_open_offline(RFileName, ebuf);
1867				if (pd == NULL)
1868					error("%s", ebuf);
1869				new_dlt = pcap_datalink(pd);
1870				if (WFileName && new_dlt != dlt)
1871					error("%s: new dlt does not match original", RFileName);
1872				dlt_name = pcap_datalink_val_to_name(new_dlt);
1873				if (dlt_name == NULL) {
1874					fprintf(stderr, "reading from file %s, link-type %u\n",
1875					RFileName, new_dlt);
1876				} else {
1877					fprintf(stderr,
1878					"reading from file %s, link-type %s (%s)\n",
1879					RFileName, dlt_name,
1880					pcap_datalink_val_to_description(new_dlt));
1881				}
1882				gndo->ndo_pcap = pd;
1883				if (WFileName)
1884					dumpinfo.pcap = pd;
1885				else
1886					printinfo.pcap = pd;
1887#if defined(DLT_PCAPNG) && defined(DLT_PKTAP)
1888				if (new_dlt == DLT_PCAPNG || new_dlt == DLT_PKTAP) {
1889					if (pcap_set_filter_info(pd, filter_src_buf, Oflag, netmask) < 0)
1890						error("%s", pcap_geterr(pd));
1891				} else {
1892#endif /* DLT_PCAPNG && DLT_PKTAP */
1893				if (pcap_compile(pd, &fcode, filter_src_buf, Oflag, netmask) < 0)
1894					error("%s", pcap_geterr(pd));
1895				if (pcap_setfilter(pd, &fcode) < 0)
1896					error("%s", pcap_geterr(pd));
1897#if defined(DLT_PCAPNG) && defined(DLT_PKTAP)
1898				}
1899#endif /* DLT_PCAPNG && DLT_PKTAP */
1900			}
1901		}
1902	} while (ret != NULL);
1903
1904	if (WFileName != NULL) {
1905		if (Pflag)
1906			pcap_ng_dump_close(dumpinfo.dumper);
1907		else
1908			pcap_dump_close(dumpinfo.dumper);
1909	}
1910	exit(status == -1 ? 1 : 0);
1911}
1912
1913/* make a clean exit on interrupts */
1914static RETSIGTYPE
1915cleanup(int signo _U_)
1916{
1917#ifdef USE_WIN32_MM_TIMER
1918	if (timer_id)
1919		timeKillEvent(timer_id);
1920	timer_id = 0;
1921#elif defined(HAVE_ALARM)
1922	alarm(0);
1923#endif
1924
1925#ifdef HAVE_PCAP_BREAKLOOP
1926	/*
1927	 * We have "pcap_breakloop()"; use it, so that we do as little
1928	 * as possible in the signal handler (it's probably not safe
1929	 * to do anything with standard I/O streams in a signal handler -
1930	 * the ANSI C standard doesn't say it is).
1931	 */
1932	pcap_breakloop(pd);
1933#else
1934	/*
1935	 * We don't have "pcap_breakloop()"; this isn't safe, but
1936	 * it's the best we can do.  Print the summary if we're
1937	 * not reading from a savefile - i.e., if we're doing a
1938	 * live capture - and exit.
1939	 */
1940	if (pd != NULL && pcap_file(pd) == NULL) {
1941		/*
1942		 * We got interrupted, so perhaps we didn't
1943		 * manage to finish a line we were printing.
1944		 * Print an extra newline, just in case.
1945		 */
1946		putchar('\n');
1947		(void)fflush(stdout);
1948		info(1);
1949	}
1950	exit(0);
1951#endif
1952}
1953
1954/*
1955  On windows, we do not use a fork, so we do not care less about
1956  waiting a child processes to die
1957 */
1958#if defined(HAVE_FORK) || defined(HAVE_VFORK)
1959static RETSIGTYPE
1960child_cleanup(int signo _U_)
1961{
1962  wait(NULL);
1963}
1964#endif /* HAVE_FORK && HAVE_VFORK */
1965
1966static void
1967info(register int verbose)
1968{
1969	struct pcap_stat stat;
1970
1971	/*
1972	 * Older versions of libpcap didn't set ps_ifdrop on some
1973	 * platforms; initialize it to 0 to handle that.
1974	 */
1975	stat.ps_ifdrop = 0;
1976	if (pcap_stats(pd, &stat) < 0) {
1977		(void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd));
1978		infoprint = 0;
1979		return;
1980	}
1981
1982	if (!verbose)
1983		fprintf(stderr, "%s: ", program_name);
1984
1985	(void)fprintf(stderr, "%lu packet%s captured", packets_captured,
1986	    PLURAL_SUFFIX(packets_captured));
1987	if (!verbose)
1988		fputs(", ", stderr);
1989	else
1990		putc('\n', stderr);
1991	(void)fprintf(stderr, "%u packet%s received by filter", stat.ps_recv,
1992	    PLURAL_SUFFIX(stat.ps_recv));
1993	if (!verbose)
1994		fputs(", ", stderr);
1995	else
1996		putc('\n', stderr);
1997	(void)fprintf(stderr, "%u packet%s dropped by kernel", stat.ps_drop,
1998	    PLURAL_SUFFIX(stat.ps_drop));
1999	if (packets_mtdt_fltr_drop != 0) {
2000		if (!verbose)
2001			fputs(", ", stderr);
2002		else
2003			putc('\n', stderr);
2004		(void)fprintf(stderr, "%u drop%s by metadata filter", packets_mtdt_fltr_drop,
2005					  PLURAL_SUFFIX(packets_mtdt_fltr_drop));
2006	}
2007	if (stat.ps_ifdrop != 0) {
2008		if (!verbose)
2009			fputs(", ", stderr);
2010		else
2011			putc('\n', stderr);
2012		(void)fprintf(stderr, "%u packet%s dropped by interface\n",
2013		    stat.ps_ifdrop, PLURAL_SUFFIX(stat.ps_ifdrop));
2014	} else
2015		putc('\n', stderr);
2016	infoprint = 0;
2017}
2018
2019#if defined(HAVE_FORK) || defined(HAVE_VFORK)
2020static void
2021compress_savefile(const char *filename)
2022{
2023# ifdef HAVE_FORK
2024	if (fork())
2025# else
2026	if (vfork())
2027# endif
2028		return;
2029	/*
2030	 * Set to lowest priority so that this doesn't disturb the capture
2031	 */
2032#ifdef NZERO
2033	setpriority(PRIO_PROCESS, 0, NZERO - 1);
2034#else
2035	setpriority(PRIO_PROCESS, 0, 19);
2036#endif
2037	if (execlp(zflag, zflag, filename, (char *)NULL) == -1)
2038		fprintf(stderr,
2039			"compress_savefile:execlp(%s, %s): %s\n",
2040			zflag,
2041			filename,
2042			strerror(errno));
2043# ifdef HAVE_FORK
2044	exit(1);
2045# else
2046	_exit(1);
2047# endif
2048}
2049#else  /* HAVE_FORK && HAVE_VFORK */
2050static void
2051compress_savefile(const char *filename)
2052{
2053	fprintf(stderr,
2054		"compress_savefile failed. Functionality not implemented under your system\n");
2055}
2056#endif /* HAVE_FORK && HAVE_VFORK */
2057
2058static void
2059dump_packet(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2060{
2061	struct dump_info *dump_info;
2062
2063	++infodelay;
2064
2065	dump_info = (struct dump_info *)user;
2066
2067	if (dump_info->WFileName && (Cflag != 0 || Gflag != 0)) {
2068		/*
2069		 * XXX - this won't force the file to rotate on the specified time
2070		 * boundary, but it will rotate on the first packet received after the
2071		 * specified Gflag number of seconds. Note: if a Gflag time boundary
2072		 * and a Cflag size boundary coincide, the time rotation will occur
2073		 * first thereby cancelling the Cflag boundary (since the file should
2074		 * be 0).
2075		 */
2076		if (Gflag != 0) {
2077			/* Check if it is time to rotate */
2078			time_t t;
2079
2080			/* Get the current time */
2081			if ((t = time(NULL)) == (time_t)-1) {
2082				error("dump_and_trunc_packet: can't get current_time: %s",
2083					  pcap_strerror(errno));
2084			}
2085
2086
2087			/* If the time is greater than the specified window, rotate */
2088			if (t - Gflag_time >= Gflag) {
2089				/* Update the Gflag_time */
2090				Gflag_time = t;
2091				/* Update Gflag_count */
2092				Gflag_count++;
2093				/*
2094				 * Close the current file and open a new one.
2095				 */
2096				if (Pflag)
2097					pcap_ng_dump_close(dump_info->dumper);
2098				else
2099					pcap_dump_close(dump_info->dumper);
2100
2101				/*
2102				 * Compress the file we just closed, if the user asked for it
2103				 */
2104				if (zflag != NULL)
2105					compress_savefile(dump_info->CurrentFileName);
2106
2107				/*
2108				 * Check to see if we've exceeded the Wflag (when
2109				 * not using Cflag).
2110				 */
2111				if (Cflag == 0 && Wflag > 0 && Gflag_count >= Wflag) {
2112					(void)fprintf(stderr, "Maximum file limit reached: %d\n",
2113								  Wflag);
2114					exit(0);
2115					/* NOTREACHED */
2116				}
2117				if (dump_info->CurrentFileName != NULL)
2118					free(dump_info->CurrentFileName);
2119				/* Allocate space for max filename + \0. */
2120				dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2121				if (dump_info->CurrentFileName == NULL)
2122					error("dump_packet_and_trunc: malloc");
2123				/*
2124				 * This is always the first file in the Cflag
2125				 * rotation: e.g. 0
2126				 * We also don't need numbering if Cflag is not set.
2127				 */
2128				if (Cflag != 0)
2129					MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0,
2130								 WflagChars);
2131				else
2132					MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, 0, 0);
2133
2134				if (Pflag)
2135					dump_info->dumper = pcap_ng_dump_open(dump_info->pcap, dump_info->CurrentFileName);
2136				else
2137					dump_info->dumper = pcap_dump_open(dump_info->pcap, dump_info->CurrentFileName);
2138				if (dump_info->dumper == NULL)
2139					error("%s", pcap_geterr(pd));
2140			}
2141		}
2142
2143		/*
2144		 * XXX - this won't prevent capture files from getting
2145		 * larger than Cflag - the last packet written to the
2146		 * file could put it over Cflag.
2147		 */
2148		if (Cflag != 0 && pcap_dump_ftell(dump_info->dumper) > Cflag) {
2149			/*
2150			 * Close the current file and open a new one.
2151			 */
2152			if (Pflag)
2153				pcap_ng_dump_close(dump_info->dumper);
2154			else
2155				pcap_dump_close(dump_info->dumper);
2156
2157			/*
2158			 * Compress the file we just closed, if the user asked for it
2159			 */
2160			if (zflag != NULL)
2161				compress_savefile(dump_info->CurrentFileName);
2162
2163			Cflag_count++;
2164			if (Wflag > 0) {
2165				if (Cflag_count >= Wflag)
2166					Cflag_count = 0;
2167			}
2168			if (dump_info->CurrentFileName != NULL)
2169				free(dump_info->CurrentFileName);
2170			dump_info->CurrentFileName = (char *)malloc(PATH_MAX + 1);
2171			if (dump_info->CurrentFileName == NULL)
2172				error("dump_packet_and_trunc: malloc");
2173			MakeFilename(dump_info->CurrentFileName, dump_info->WFileName, Cflag_count, WflagChars);
2174
2175#ifdef HAVE_CAP_NG_H
2176			capng_update(CAPNG_ADD, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2177			capng_apply(CAPNG_EFFECTIVE);
2178#endif /* HAVE_CAP_NG_H */
2179
2180			if (Pflag)
2181				dump_info->dumper = pcap_ng_dump_open(dump_info->pcap, dump_info->CurrentFileName);
2182			else
2183				dump_info->dumper = pcap_dump_open(dump_info->pcap, dump_info->CurrentFileName);
2184
2185#ifdef HAVE_CAP_NG_H
2186			capng_update(CAPNG_DROP, CAPNG_EFFECTIVE, CAP_DAC_OVERRIDE);
2187			capng_apply(CAPNG_EFFECTIVE);
2188#endif /* HAVE_CAP_NG_H */
2189
2190			if (dump_info->dumper == NULL)
2191				error("%s", pcap_geterr(pd));
2192		}
2193	}
2194
2195	if (dump_info->dumper_func(dump_info, h, sp) == 1)
2196		packets_captured++;
2197
2198#ifdef HAVE_PCAP_DUMP_FLUSH
2199	if (Uflag)
2200		pcap_dump_flush(dump_info->dumper);
2201#endif
2202
2203	--infodelay;
2204	if (infoprint)
2205		info(0);
2206
2207 	if (packets_captured >= max_packet_cnt)
2208		pcap_breakloop(dump_info->pcap);
2209}
2210
2211char *
2212svc2str(uint32_t svc)
2213{
2214	static char svcstr[10];
2215
2216	switch (svc) {
2217		case SO_TC_BK_SYS:
2218			return "BK_SYS";
2219		case SO_TC_BK:
2220			return "BK";
2221		case SO_TC_BE:
2222			return "BE";
2223		case SO_TC_RD:
2224			return "RD";
2225		case SO_TC_OAM:
2226			return "OAM";
2227		case SO_TC_AV:
2228			return "AV";
2229		case SO_TC_RV:
2230			return "RV";
2231		case SO_TC_VI:
2232			return "VI";
2233		case SO_TC_VO:
2234			return "VO";
2235		case SO_TC_CTL:
2236			return "CTL";
2237		default:
2238			snprintf(svcstr, sizeof(svcstr), "%u", svc);
2239			return svcstr;
2240	}
2241}
2242
2243int
2244handle_pcap_dump(struct dump_info *dump_info, const struct pcap_pkthdr *h,
2245				   const u_char *sp)
2246{
2247	pcap_dump((u_char *)dump_info->dumper, h, sp);
2248
2249	return (1);
2250}
2251
2252int
2253handle_bpf_exthdr_dump(struct dump_info *dump_info, const struct pcap_pkthdr *h,
2254					const u_char *sp)
2255{
2256	pcap_ng_dump((u_char *)dump_info->dumper, h, sp);
2257
2258	return (1);
2259}
2260
2261int
2262handle_pcap_ng_dump(struct dump_info *dump_info, const struct pcap_pkthdr *h,
2263					const u_char *sp)
2264{
2265	static pcapng_block_t block = NULL;
2266	struct pcap_if_info *if_info = NULL;
2267	uint32_t if_id;
2268	u_short pack_flags_code = 0;
2269	u_char *pkt_data;
2270	struct pcap_proc_info *proc_info = NULL;
2271	struct pcap_proc_info *e_proc_info = NULL;
2272	uint32_t pkt_svc = -1;
2273	uint32_t packet_flags = 0;
2274	struct pcapng_option_info option_info;
2275	int result = 0;
2276
2277	if (block == NULL) {
2278		block = pcap_ng_block_alloc(65536);
2279		if (block == NULL) {
2280			error("%s: pcap_ng_block_alloc() no memory", __func__);
2281		}
2282	}
2283
2284	if (pcap_ng_block_init_with_raw_block(block, dump_info->pcap, (u_char *)sp)) {
2285		warning("%s: pcap_ng_block_init_with_raw_block() ", __func__);
2286		goto done;
2287	}
2288
2289	switch (pcap_ng_block_get_type(block)) {
2290		case PCAPNG_BT_SHB: {
2291			pcap_clear_if_infos(dump_info->pcap);
2292
2293			pcap_ng_dump_block(dump_info->dumper, block);
2294
2295			goto done;
2296		}
2297		case PCAPNG_BT_IDB: {
2298			struct pcapng_interface_description_fields *idbp =
2299			pcap_ng_get_interface_description_fields(block);
2300			const char *ifname = "";
2301
2302			if (pcap_ng_block_get_option(block, PCAPNG_IF_NAME, &option_info) == 1)
2303				ifname = (const char *)option_info.value;
2304
2305			if_info = pcap_add_if_info(dump_info->pcap, ifname, -1, idbp->linktype, idbp->snaplen);
2306			if (if_info == NULL)
2307				error("%s: cannot allocate memory", __func__);
2308
2309			pcap_ng_dump_block(dump_info->dumper, block);
2310
2311			goto done;
2312		}
2313		case PCAPNG_BT_PIB: {
2314			struct pcapng_process_information_fields *pibp =
2315			pcap_ng_get_process_information_fields(block);
2316			const char *procname = "";
2317
2318			if (pcap_ng_block_get_option(block, PCAPNG_PIB_NAME, &option_info) == 1)
2319				procname = option_info.value;
2320
2321			(void) pcap_add_proc_info(dump_info->pcap, pibp->process_id, procname);
2322
2323			pcap_ng_dump_block(dump_info->dumper, block);
2324
2325			goto done;
2326		}
2327		case PCAPNG_BT_EPB: {
2328			struct pcapng_enhanced_packet_fields *epbp = pcap_ng_get_enhanced_packet_fields(block);
2329
2330			if (pcap_ng_block_get_option(block, PCAPNG_EPB_PIB_INDEX, &option_info) == 1) {
2331				uint32_t pibindex;
2332
2333				if (option_info.length != 4) {
2334					error("%s: pib index option length %u != 4", __func__, option_info.length);
2335					abort();
2336				}
2337				pibindex = *(uint32_t *)(option_info.value);
2338				if (pcap_is_swapped(dump_info->pcap))
2339					pibindex = SWAPLONG(pibindex);
2340
2341				proc_info = pcap_find_proc_info_by_index(dump_info->pcap, pibindex);
2342			}
2343			if (pcap_ng_block_get_option(block, PCAPNG_EPB_E_PIB_INDEX, &option_info) == 1) {
2344				uint32_t pibindex;
2345
2346				if (option_info.length != 4) {
2347					error("%s: e_pib index option length %u != 4", __func__, option_info.length);
2348					abort();
2349				}
2350				pibindex = *(uint32_t *)(option_info.value);
2351				if (pcap_is_swapped(dump_info->pcap))
2352					pibindex = SWAPLONG(pibindex);
2353
2354				e_proc_info = pcap_find_proc_info_by_index(dump_info->pcap, pibindex);
2355			}
2356			if (pcap_ng_block_get_option(block, PCAPNG_EPB_SVC, &option_info) == 1) {
2357				if (option_info.length != 4) {
2358					error("%s: svc option length %u != 4", __func__, option_info.length);
2359					abort();
2360				}
2361				pkt_svc = *(uint32_t *)(option_info.value);
2362				if (pcap_is_swapped(dump_info->pcap))
2363					pkt_svc = SWAPLONG(pkt_svc);
2364			}
2365
2366			if_id = epbp->interface_id;
2367
2368			pack_flags_code = PCAPNG_EPB_FLAGS;
2369
2370			break;
2371		}
2372		case PCAPNG_BT_SPB: {
2373
2374			if_id = 0;
2375
2376			pack_flags_code = PCAPNG_PACK_FLAGS;
2377
2378			break;
2379		}
2380		case PCAPNG_BT_PB: {
2381			struct pcapng_packet_fields *pbp = pcap_ng_get_packet_fields(block);
2382
2383			if_id = pbp->interface_id;
2384
2385			break;
2386		}
2387		default:
2388			goto done;
2389	}
2390
2391	/*
2392	 * Here we have a packet
2393	 */
2394	pkt_data = pcap_ng_block_packet_get_data_ptr(block);
2395
2396	if_info = pcap_find_if_info_by_id(dump_info->pcap, if_id);
2397	if (if_info == NULL) {
2398		error("%s: unknown interface id %u", __func__, if_id);
2399		abort();
2400	}
2401
2402	/*
2403	 * Evaluate the per-interface BPF filter expression
2404	 */
2405	if (if_info->if_filter_program.bf_insns != NULL &&
2406		pcap_offline_filter(&if_info->if_filter_program, h, pkt_data) == 0)
2407		goto done;
2408
2409	if (pcap_ng_block_get_option(block, pack_flags_code, &option_info) == 1) {
2410		if (option_info.length != 4) {
2411			error("%s: pack_flags option length %u != 4", __func__, option_info.length);
2412			abort();
2413		}
2414		bcopy(option_info.value, &packet_flags, sizeof(packet_flags));
2415
2416		if (pcap_is_swapped(dump_info->pcap))
2417			packet_flags = SWAPLONG(packet_flags);
2418	}
2419
2420	/*
2421	 * Evaluate the packet metadata expression
2422	 */
2423	if (pkt_meta_data_expression != NULL) {
2424		struct pkt_meta_data pmd;
2425
2426		pmd.itf = &if_info->if_name[0];
2427		pmd.proc = (proc_info != NULL) ? proc_info->proc_name : "";
2428		pmd.eproc = (e_proc_info != NULL) ? e_proc_info->proc_name : "";
2429		pmd.pid = (proc_info != NULL) ? proc_info->proc_pid : -1;
2430		pmd.epid = (e_proc_info != NULL) ? e_proc_info->proc_pid : -1;
2431		pmd.svc = (pkt_svc != -1) ? svc2str(pkt_svc) : "";
2432		pmd.dir =  (packet_flags & 3) == 2 ? "out" :
2433		(packet_flags & 3) == 1 ? "in" : "";
2434
2435		if (evaluate_expression(pkt_meta_data_expression, &pmd) == 0) {
2436			packets_mtdt_fltr_drop++;
2437			goto done;
2438		}
2439	}
2440
2441	pcap_ng_dump_block(dump_info->dumper, block);
2442
2443	result = 1;
2444
2445done:
2446	return (result);
2447}
2448
2449int
2450handle_pktap_dump(struct dump_info *dump_info, const struct pcap_pkthdr *h,
2451				  const u_char *sp)
2452{
2453	if (pktap_filter_packet(dump_info->pcap, NULL, h, sp) == 0)
2454		return (0);
2455
2456	if (pcap_ng_dump_pktap(dump_info->pcap, dump_info->dumper, h, sp) == 0)
2457		return (0);
2458
2459	return (1);
2460}
2461
2462static void
2463print_callback(u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
2464{
2465	struct print_info *print_info = (struct print_info *)user;
2466
2467	++infodelay;
2468
2469	print_info->printer_func(print_info, h, sp);
2470
2471	--infodelay;
2472	if (infoprint)
2473		info(0);
2474
2475	if (packets_captured >= max_packet_cnt)
2476		pcap_breakloop(print_info->pcap);
2477}
2478
2479static void
2480print_raw_packet_data(const struct pcap_pkthdr *h, const u_char *sp, u_int hdrlen)
2481{
2482	if (Xflag) {
2483		/*
2484		 * Print the raw packet data in hex and ASCII.
2485		 */
2486		if (Xflag > 1) {
2487			/*
2488			 * Include the link-layer header.
2489			 */
2490			hex_and_ascii_print("\n\t", sp, h->caplen);
2491		} else {
2492			/*
2493			 * Don't include the link-layer header - and if
2494			 * we have nothing past the link-layer header,
2495			 * print nothing.
2496			 */
2497			if (h->caplen > hdrlen)
2498				hex_and_ascii_print("\n\t", sp + hdrlen,
2499									h->caplen - hdrlen);
2500		}
2501	} else if (xflag) {
2502		/*
2503		 * Print the raw packet data in hex.
2504		 */
2505		if (xflag > 1) {
2506			/*
2507			 * Include the link-layer header.
2508			 */
2509			hex_print("\n\t", sp, h->caplen);
2510		} else {
2511			/*
2512			 * Don't include the link-layer header - and if
2513			 * we have nothing past the link-layer header,
2514			 * print nothing.
2515			 */
2516			if (h->caplen > hdrlen)
2517				hex_print("\n\t", sp + hdrlen,
2518						  h->caplen - hdrlen);
2519		}
2520	} else if (Aflag) {
2521		/*
2522		 * Print the raw packet data in ASCII.
2523		 */
2524		if (Aflag > 1) {
2525			/*
2526			 * Include the link-layer header.
2527			 */
2528			ascii_print(sp, h->caplen);
2529		} else {
2530			/*
2531			 * Don't include the link-layer header - and if
2532			 * we have nothing past the link-layer header,
2533			 * print nothing.
2534			 */
2535			if (h->caplen > hdrlen)
2536				ascii_print(sp + hdrlen, h->caplen - hdrlen);
2537		}
2538	}
2539}
2540
2541static int
2542print_packet(struct print_info *print_info, const struct pcap_pkthdr *h, const u_char *sp)
2543{
2544	u_int hdrlen;
2545
2546	packets_captured++;
2547
2548	if (oflag)
2549		printf("%5lu ", packets_captured);
2550
2551	ts_print(&h->ts);
2552#ifdef __APPLE__
2553	if (kflag && h->comment[0])
2554		printf("%s ", h->comment);
2555#endif
2556
2557	/*
2558	 * Some printers want to check that they're not walking off the
2559	 * end of the packet.
2560	 * Rather than pass it all the way down, we set this global.
2561	 */
2562	snapend = sp + h->caplen;
2563
2564	if(print_info->ndo_type) {
2565		hdrlen = (*print_info->p.ndo_printer)(print_info->ndo, h, sp);
2566	} else {
2567		hdrlen = (*print_info->p.printer)(h, sp);
2568	}
2569
2570	print_raw_packet_data(h, sp, hdrlen);
2571
2572	putchar('\n');
2573
2574	return (1);
2575}
2576
2577#ifdef __APPLE__
2578static int
2579print_pktap_packet(struct print_info *print_info, const struct pcap_pkthdr *h, const u_char *sp)
2580{
2581	if (pktap_filter_packet(print_info->pcap, NULL, h, sp) == 0)
2582		return (0);
2583
2584	print_packet(print_info, h, sp);
2585
2586	return (1);
2587}
2588
2589#ifdef DLT_PCAPNG
2590
2591static int
2592print_pcap_ng_block(struct print_info *print_info, const struct pcap_pkthdr *h, const u_char *sp)
2593{
2594	pcapng_block_t block;
2595	struct pcap_if_info *if_info = NULL;
2596	uint32_t if_id;
2597	if_ndo_printer ndo_printer;
2598	if_printer printer;
2599	u_short pack_flags_code = 0;
2600	u_char *pkt_data;
2601	netdissect_options *ndo = print_info->ndo;
2602	u_int hdrlen = 0;
2603	struct pcap_proc_info *proc_info = NULL;
2604	struct pcap_proc_info *e_proc_info = NULL;
2605	uint32_t pkt_svc = -1;
2606	uint32_t packet_flags = 0;
2607    struct pcapng_option_info option_info;
2608	int result = 0;
2609
2610	block = pcap_ng_block_alloc_with_raw_block(print_info->pcap, (u_char *)sp);
2611	if (block == NULL) {
2612		warning("%s: unknown PCAP-NG block type", __func__);
2613		goto done;
2614	}
2615
2616	switch (pcap_ng_block_get_type(block)) {
2617		case PCAPNG_BT_SHB: {
2618			struct pcapng_section_header_fields *shbp = pcap_ng_get_section_header_fields(block);
2619
2620			pcap_clear_if_infos(print_info->pcap);
2621			if (vflag) {
2622				printf("Section Header Block version %u.%u",
2623					   shbp->major_version, shbp->minor_version);
2624				if (shbp->section_length == (u_int64_t)-1)
2625					printf(", section_length: -1");
2626				else
2627					printf(", section_length: %llu", shbp->section_length);
2628
2629				if (pcap_ng_block_get_option(block, PCAPNG_SHB_HARDWARE, &option_info) == 1)
2630					printf(", hardware: %s", (const char *)option_info.value);
2631
2632				if (pcap_ng_block_get_option(block, PCAPNG_SHB_OS, &option_info) == 1)
2633					printf(", OS: %s", (const char *)option_info.value);
2634
2635				if (pcap_ng_block_get_option(block, PCAPNG_SHB_USERAPPL, &option_info) == 1)
2636					printf(", app: %s", (const char *)option_info.value);
2637
2638				printf("\n");
2639			}
2640			goto done;
2641		}
2642		case PCAPNG_BT_IDB: {
2643			struct pcapng_interface_description_fields *idbp =
2644				pcap_ng_get_interface_description_fields(block);
2645			const char *ifname = "";
2646
2647            if (pcap_ng_block_get_option(block, PCAPNG_IF_NAME, &option_info) == 1)
2648                ifname = (const char *)option_info.value;
2649
2650			if_info = pcap_add_if_info(print_info->pcap, ifname, -1, idbp->linktype, idbp->snaplen);
2651			if (if_info == NULL)
2652				error("%s: cannot allocate memory", __func__);
2653
2654			if (vflag)
2655				printf("Interface Description Block id: %d name: %s linktype: %u snaplen: %u\n",
2656					   if_info->if_id, if_info->if_name, if_info->if_linktype,
2657					   if_info->if_snaplen);
2658
2659			goto done;
2660		}
2661		case PCAPNG_BT_PIB: {
2662			struct pcapng_process_information_fields *pibp =
2663				pcap_ng_get_process_information_fields(block);
2664			const char *procname = "";
2665
2666            if (pcap_ng_block_get_option(block, PCAPNG_PIB_NAME, &option_info) == 1)
2667                procname = option_info.value;
2668
2669			proc_info = pcap_add_proc_info(print_info->pcap, pibp->process_id, procname);
2670
2671			if (vflag)
2672				printf("Process Information Block pid: %u proc_name: %s\n",
2673					   proc_info->proc_pid, proc_info->proc_name);
2674			goto done;
2675		}
2676		case PCAPNG_BT_EPB: {
2677			struct pcapng_enhanced_packet_fields *epbp = pcap_ng_get_enhanced_packet_fields(block);
2678
2679            if (pcap_ng_block_get_option(block, PCAPNG_EPB_PIB_INDEX, &option_info) == 1) {
2680				uint32_t pibindex;
2681
2682                if (option_info.length != 4) {
2683                    error("%s: pib index option length %u != 4", __func__, option_info.length);
2684                    abort();
2685                }
2686				pibindex = *(uint32_t *)(option_info.value);
2687                if (pcap_is_swapped(print_info->pcap))
2688					pibindex = SWAPLONG(pibindex);
2689
2690				proc_info = pcap_find_proc_info_by_index(print_info->pcap, pibindex);
2691			}
2692            if (pcap_ng_block_get_option(block, PCAPNG_EPB_E_PIB_INDEX, &option_info) == 1) {
2693				uint32_t pibindex;
2694
2695                if (option_info.length != 4) {
2696                    error("%s: e_pib index option length %u != 4", __func__, option_info.length);
2697                    abort();
2698                }
2699				pibindex = *(uint32_t *)(option_info.value);
2700                if (pcap_is_swapped(print_info->pcap))
2701					pibindex = SWAPLONG(pibindex);
2702
2703				e_proc_info = pcap_find_proc_info_by_index(print_info->pcap, pibindex);
2704			}
2705            if (pcap_ng_block_get_option(block, PCAPNG_EPB_SVC, &option_info) == 1) {
2706                if (option_info.length != 4) {
2707                    error("%s: svc option length %u != 4", __func__, option_info.length);
2708                    abort();
2709                }
2710				pkt_svc = *(uint32_t *)(option_info.value);
2711				if (pcap_is_swapped(print_info->pcap))
2712					pkt_svc = SWAPLONG(pkt_svc);
2713			}
2714
2715			if_id = epbp->interface_id;
2716
2717			pack_flags_code = PCAPNG_EPB_FLAGS;
2718
2719			break;
2720		}
2721		case PCAPNG_BT_SPB: {
2722
2723			if_id = 0;
2724
2725			pack_flags_code = PCAPNG_PACK_FLAGS;
2726
2727			break;
2728		}
2729		case PCAPNG_BT_PB: {
2730			struct pcapng_packet_fields *pbp = pcap_ng_get_packet_fields(block);
2731
2732			if_id = pbp->interface_id;
2733
2734			break;
2735		}
2736		default:
2737			goto done;
2738	}
2739
2740	/*
2741	 * Here we have a packet
2742	 */
2743	pkt_data = pcap_ng_block_packet_get_data_ptr(block);
2744
2745	if_info = pcap_find_if_info_by_id(print_info->pcap, if_id);
2746	if (if_info == NULL) {
2747		error("%s: unknown interface id %u", __func__, if_id);
2748		abort();
2749	}
2750
2751	/*
2752	 * Evaluate the per-interface BPF filter expression
2753	 */
2754	if (if_info->if_filter_program.bf_insns != NULL &&
2755		pcap_offline_filter(&if_info->if_filter_program, h, pkt_data) == 0)
2756		goto done;
2757
2758    if (pcap_ng_block_get_option(block, pack_flags_code, &option_info) == 1) {
2759		if (option_info.length != 4) {
2760			error("%s: pack_flags option length %u != 4", __func__, option_info.length);
2761			abort();
2762		}
2763        bcopy(option_info.value, &packet_flags, sizeof(packet_flags));
2764
2765		if (pcap_is_swapped(print_info->pcap))
2766			packet_flags = SWAPLONG(packet_flags);
2767	}
2768
2769	/*
2770	 * Evaluate the packet metadata expression
2771	 */
2772	if (pkt_meta_data_expression != NULL) {
2773		struct pkt_meta_data pmd;
2774
2775		pmd.itf = &if_info->if_name[0];
2776		pmd.proc = (proc_info != NULL) ? proc_info->proc_name : "";
2777		pmd.eproc = (e_proc_info != NULL) ? e_proc_info->proc_name : "";
2778		pmd.pid = (proc_info != NULL) ? proc_info->proc_pid : -1;
2779		pmd.epid = (e_proc_info != NULL) ? e_proc_info->proc_pid : -1;
2780		pmd.svc = (pkt_svc != -1) ? svc2str(pkt_svc) : "";
2781		pmd.dir =  (packet_flags & 3) == 2 ? "out" :
2782			(packet_flags & 3) == 1 ? "in" : "";
2783
2784		if (evaluate_expression(pkt_meta_data_expression, &pmd) == 0) {
2785			packets_mtdt_fltr_drop++;
2786			goto done;
2787		}
2788	}
2789
2790	packets_captured++;
2791
2792	if (oflag)
2793		printf("%5lu ", packets_captured);
2794
2795	ts_print(&h->ts);
2796
2797	/*
2798	 * Packet metadata
2799	 */
2800	if (kflag != PRMD_NONE) {
2801		const char *prsep = "";
2802
2803		ND_PRINT((ndo, "("));
2804
2805		/*
2806		 * Interface name
2807		 */
2808		if (kflag & PRMD_IF) {
2809			if (if_info->if_name && if_info->if_name[0] != 0)
2810				ND_PRINT((ndo, "%s", if_info->if_name));
2811			else
2812				ND_PRINT((ndo, "%d", if_id));
2813			prsep = ", ";
2814		}
2815
2816		/*
2817		 * Process name and/or process ID
2818		 */
2819		if (proc_info != NULL) {
2820			switch ((kflag & (PRMD_PNAME |PRMD_PID))) {
2821				case (PRMD_PNAME | PRMD_PID):
2822					ND_PRINT((ndo, "%sproc %s:%u",
2823							  prsep,
2824							  proc_info->proc_name ,
2825							  proc_info->proc_pid));
2826					prsep = ", ";
2827					if (e_proc_info != NULL) {
2828						ND_PRINT((ndo, "%seproc %s:%u",
2829								  prsep,
2830								  e_proc_info->proc_name ,
2831								  e_proc_info->proc_pid));
2832						prsep = ", ";
2833					}
2834					break;
2835				case PRMD_PNAME:
2836					ND_PRINT((ndo, "%sproc %s",
2837							  prsep,
2838							  proc_info->proc_name));
2839					prsep = ", ";
2840					if (e_proc_info != NULL) {
2841						ND_PRINT((ndo, "%seproc %s",
2842								  prsep,
2843								  e_proc_info->proc_name));
2844					}
2845					break;
2846
2847				case PRMD_PID:
2848					ND_PRINT((ndo, "%sproc %u",
2849							  prsep,
2850							  proc_info->proc_pid));
2851					prsep = ", ";
2852					if (e_proc_info != NULL) {
2853						ND_PRINT((ndo, "%seproc %u",
2854								  prsep,
2855								  e_proc_info->proc_pid));
2856					}
2857					break;
2858
2859				default:
2860					break;
2861			}
2862		}
2863
2864		/*
2865		 * Service class
2866		 */
2867		if ((kflag & PRMD_SVC) && pkt_svc != -1) {
2868			ND_PRINT((ndo, "%ssvc %s",
2869					  prsep,
2870					  svc2str(pkt_svc)));
2871			prsep = ", ";
2872		}
2873
2874		/*
2875		 * Direction
2876		 */
2877		if ((kflag & PRMD_DIR) && (packet_flags & 3)) {
2878			if ((packet_flags & 2) == 2)
2879				ND_PRINT((ndo, "%sout",
2880						  prsep));
2881			else if ((packet_flags & 1) == 1)
2882				ND_PRINT((ndo, "%sin",
2883						  prsep));
2884			prsep = ", ";
2885		}
2886
2887		/*
2888		 * Comment
2889		 */
2890		if (kflag & PRMD_COMMENT) {
2891            if (pcap_ng_block_get_option(block, PCAPNG_OPT_COMMENT, &option_info) == 1) {
2892				if (option_info.value != NULL) {
2893					const char *str_comment = (const char *)option_info.value;
2894
2895					if (str_comment && *str_comment != 0) {
2896						ND_PRINT((ndo, "%s%s",
2897								  prsep,
2898								  str_comment));
2899						prsep = ", ";
2900					}
2901				}
2902			}
2903        }
2904
2905		ND_PRINT((ndo, ") "));
2906	}
2907
2908	/*
2909	 * Some printers want to check that they're not walking off the
2910	 * end of the packet.
2911	 * Rather than pass it all the way down, we set this global.
2912	 */
2913	snapend = pkt_data + h->caplen;
2914
2915	if ((printer = lookup_printer(if_info->if_linktype)) != NULL) {
2916		hdrlen = printer(h, pkt_data);
2917	} else if ((ndo_printer = lookup_ndo_printer(if_info->if_linktype)) != NULL) {
2918		hdrlen = ndo_printer(ndo, h, pkt_data);
2919	} else {
2920		if (!ndo->ndo_suppress_default_print)
2921			ndo->ndo_default_print(ndo, pkt_data, h->caplen);
2922	}
2923	print_raw_packet_data(h, pkt_data, hdrlen);
2924
2925	putchar('\n');
2926
2927	result = 1;
2928
2929done:
2930	if (block != NULL)
2931		pcap_ng_free_block(block);
2932
2933	return (result);
2934}
2935
2936#endif /* DLT_PCAPNG */
2937#endif /* __APPLE__ */
2938
2939#ifdef WIN32
2940	/*
2941	 * XXX - there should really be libpcap calls to get the version
2942	 * number as a string (the string would be generated from #defines
2943	 * at run time, so that it's not generated from string constants
2944	 * in the library, as, on many UNIX systems, those constants would
2945	 * be statically linked into the application executable image, and
2946	 * would thus reflect the version of libpcap on the system on
2947	 * which the application was *linked*, not the system on which it's
2948	 * *running*.
2949	 *
2950	 * That routine should be documented, unlike the "version[]"
2951	 * string, so that UNIX vendors providing their own libpcaps
2952	 * don't omit it (as a couple of vendors have...).
2953	 *
2954	 * Packet.dll should perhaps also export a routine to return the
2955	 * version number of the Packet.dll code, to supply the
2956	 * "Wpcap_version" information on Windows.
2957	 */
2958	char WDversion[]="current-cvs.tcpdump.org";
2959#if !defined(HAVE_GENERATED_VERSION)
2960	char version[]="current-cvs.tcpdump.org";
2961#endif
2962	char pcap_version[]="current-cvs.tcpdump.org";
2963	char Wpcap_version[]="3.1";
2964#endif
2965
2966/*
2967 * By default, print the specified data out in hex and ASCII.
2968 */
2969static void
2970ndo_default_print(netdissect_options *ndo _U_, const u_char *bp, u_int length)
2971{
2972	hex_and_ascii_print("\n\t", bp, length); /* pass on lf and identation string */
2973}
2974
2975void
2976default_print(const u_char *bp, u_int length)
2977{
2978	ndo_default_print(gndo, bp, length);
2979}
2980
2981#ifdef SIGNAL_REQ_INFO
2982RETSIGTYPE requestinfo(int signo _U_)
2983{
2984	if (infodelay)
2985		++infoprint;
2986	else
2987		info(0);
2988}
2989#endif
2990
2991/*
2992 * Called once each second in verbose mode while dumping to file
2993 */
2994#ifdef USE_WIN32_MM_TIMER
2995void CALLBACK verbose_stats_dump (UINT timer_id _U_, UINT msg _U_, DWORD_PTR arg _U_,
2996				  DWORD_PTR dw1 _U_, DWORD_PTR dw2 _U_)
2997{
2998	struct pcap_stat stat;
2999
3000	if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
3001		fprintf(stderr, "Got %u\r", packets_captured);
3002}
3003#elif defined(HAVE_ALARM)
3004static void verbose_stats_dump(int sig _U_)
3005{
3006	struct pcap_stat stat;
3007
3008	if (infodelay == 0 && pcap_stats(pd, &stat) >= 0)
3009		fprintf(stderr, "Got %lu\r", packets_captured);
3010	alarm(1);
3011}
3012#endif
3013
3014static void
3015usage(void)
3016{
3017	extern char version[];
3018#ifndef HAVE_PCAP_LIB_VERSION
3019#if defined(WIN32) || defined(HAVE_PCAP_VERSION)
3020	extern char pcap_version[];
3021#else /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
3022	static char pcap_version[] = "unknown";
3023#endif /* defined(WIN32) || defined(HAVE_PCAP_VERSION) */
3024#endif /* HAVE_PCAP_LIB_VERSION */
3025
3026#ifdef HAVE_PCAP_LIB_VERSION
3027#ifdef WIN32
3028	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
3029#else /* WIN32 */
3030	(void)fprintf(stderr, "%s version %s\n", program_name, version);
3031#endif /* WIN32 */
3032	(void)fprintf(stderr, "%s\n",pcap_lib_version());
3033#else /* HAVE_PCAP_LIB_VERSION */
3034#ifdef WIN32
3035	(void)fprintf(stderr, "%s version %s, based on tcpdump version %s\n", program_name, WDversion, version);
3036	(void)fprintf(stderr, "WinPcap version %s, based on libpcap version %s\n",Wpcap_version, pcap_version);
3037#else /* WIN32 */
3038	(void)fprintf(stderr, "%s version %s\n", program_name, version);
3039	(void)fprintf(stderr, "libpcap version %s\n", pcap_version);
3040#endif /* WIN32 */
3041#endif /* HAVE_PCAP_LIB_VERSION */
3042	(void)fprintf(stderr,
3043"Usage: %s [-aAbd" D_FLAG "efhH" g_FLAG I_FLAG J_FLAG "kKlLnNOpPq" Q_FLAG "RStu" U_FLAG "vxX]" B_FLAG_USAGE " [ -c count ]\n", program_name);
3044	(void)fprintf(stderr,
3045"\t\t[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]\n");
3046	(void)fprintf(stderr,
3047"\t\t[ -i interface ]" j_FLAG_USAGE " [ -M secret ]\n");
3048#if __APPLE__
3049	(void)fprintf(stderr,
3050"\t\t[ -Q metadata-filter-expression ]\n");
3051#endif /* __APPLE__ */
3052	(void)fprintf(stderr,
3053"\t\t[ -r file ] [ -s snaplen ] [ -T type ] [ -w file ]\n");
3054	(void)fprintf(stderr,
3055"\t\t[ -W filecount ] [ -y datalinktype ] [ -z command ]\n");
3056	(void)fprintf(stderr,
3057"\t\t[ -Z user ] [ expression ]\n");
3058	exit(1);
3059}
3060
3061/* VARARGS */
3062static void
3063ndo_error(netdissect_options *ndo _U_, const char *fmt, ...)
3064{
3065	va_list ap;
3066
3067	(void)fprintf(stderr, "%s: ", program_name);
3068	va_start(ap, fmt);
3069	(void)vfprintf(stderr, fmt, ap);
3070	va_end(ap);
3071	if (*fmt) {
3072		fmt += strlen(fmt);
3073		if (fmt[-1] != '\n')
3074			(void)fputc('\n', stderr);
3075	}
3076	exit(1);
3077	/* NOTREACHED */
3078}
3079
3080/* VARARGS */
3081static void
3082ndo_warning(netdissect_options *ndo _U_, const char *fmt, ...)
3083{
3084	va_list ap;
3085
3086	(void)fprintf(stderr, "%s: WARNING: ", program_name);
3087	va_start(ap, fmt);
3088	(void)vfprintf(stderr, fmt, ap);
3089	va_end(ap);
3090	if (*fmt) {
3091		fmt += strlen(fmt);
3092		if (fmt[-1] != '\n')
3093			(void)fputc('\n', stderr);
3094	}
3095}
3096