1/*
2 * Copyright (c) 1993, 1994, 1995, 1996, 1998
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 * $FreeBSD: releng/10.3/contrib/libpcap/pcap-bpf.c 251129 2013-05-30 08:02:00Z delphij $
22 */
23#ifndef lint
24static const char rcsid[] _U_ =
25    "@(#) $Header: /tcpdump/master/libpcap/pcap-bpf.c,v 1.116 2008-09-16 18:42:29 guy Exp $ (LBL)";
26#endif
27
28#ifdef HAVE_CONFIG_H
29#include "config.h"
30#endif
31
32#include <sys/param.h>			/* optionally get BSD define */
33#ifdef HAVE_ZEROCOPY_BPF
34#include <sys/mman.h>
35#endif
36#include <sys/socket.h>
37#include <time.h>
38/*
39 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
40 *
41 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
42 * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
43 * we could include <sys/sockio.h>, but if we're already including
44 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
45 * there's not much point in doing so.
46 *
47 * If we have <sys/ioccom.h>, we include it as well, to handle systems
48 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
49 * include <sys/ioctl.h>
50 */
51#include <sys/ioctl.h>
52#ifdef HAVE_SYS_IOCCOM_H
53#include <sys/ioccom.h>
54#endif
55#include <sys/utsname.h>
56
57#ifdef HAVE_ZEROCOPY_BPF
58#include <machine/atomic.h>
59#endif
60
61#include <net/if.h>
62
63#ifdef _AIX
64
65/*
66 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
67 * native OS version, as we need "struct bpf_config" from it.
68 */
69#define PCAP_DONT_INCLUDE_PCAP_BPF_H
70
71#include <sys/types.h>
72
73/*
74 * Prevent bpf.h from redefining the DLT_ values to their
75 * IFT_ values, as we're going to return the standard libpcap
76 * values, not IBM's non-standard IFT_ values.
77 */
78#undef _AIX
79#include <net/bpf.h>
80#define _AIX
81
82#include <net/if_types.h>		/* for IFT_ values */
83#include <sys/sysconfig.h>
84#include <sys/device.h>
85#include <sys/cfgodm.h>
86#include <cf.h>
87
88#ifdef __64BIT__
89#define domakedev makedev64
90#define getmajor major64
91#define bpf_hdr bpf_hdr32
92#else /* __64BIT__ */
93#define domakedev makedev
94#define getmajor major
95#endif /* __64BIT__ */
96
97#define BPF_NAME "bpf"
98#define BPF_MINORS 4
99#define DRIVER_PATH "/usr/lib/drivers"
100#define BPF_NODE "/dev/bpf"
101static int bpfloadedflag = 0;
102static int odmlockid = 0;
103
104static int bpf_load(char *errbuf);
105
106#else /* _AIX */
107
108#include <net/bpf.h>
109
110#endif /* _AIX */
111
112#include <ctype.h>
113#include <fcntl.h>
114#include <errno.h>
115#include <netdb.h>
116#include <stdio.h>
117#include <stdlib.h>
118#include <string.h>
119#include <unistd.h>
120
121#ifdef HAVE_NET_IF_MEDIA_H
122# include <net/if_media.h>
123#endif
124
125#include "pcap-int.h"
126
127#ifdef HAVE_OS_PROTO_H
128#include "os-proto.h"
129#endif
130
131#ifdef BIOCGDLTLIST
132# if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
133#define HAVE_BSD_IEEE80211
134# endif
135
136# if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
137static int find_802_11(struct bpf_dltlist *);
138
139#  ifdef HAVE_BSD_IEEE80211
140static int monitor_mode(pcap_t *, int);
141#  endif
142
143#  if defined(__APPLE__)
144static void remove_en(pcap_t *);
145static void remove_802_11(pcap_t *);
146#  endif
147
148# endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
149
150#endif /* BIOCGDLTLIST */
151
152#if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
153#include <zone.h>
154#endif
155
156/*
157 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
158 * don't get DLT_DOCSIS defined.
159 */
160#ifndef DLT_DOCSIS
161#define DLT_DOCSIS	143
162#endif
163
164/*
165 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
166 * defined, even though some of them are used by various Airport drivers.
167 */
168#ifndef DLT_PRISM_HEADER
169#define DLT_PRISM_HEADER	119
170#endif
171#ifndef DLT_AIRONET_HEADER
172#define DLT_AIRONET_HEADER	120
173#endif
174#ifndef DLT_IEEE802_11_RADIO
175#define DLT_IEEE802_11_RADIO	127
176#endif
177#ifndef DLT_IEEE802_11_RADIO_AVS
178#define DLT_IEEE802_11_RADIO_AVS 163
179#endif
180
181static int pcap_can_set_rfmon_bpf(pcap_t *p);
182static int pcap_activate_bpf(pcap_t *p);
183static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
184static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
185static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
186
187/*
188 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
189 * p->md.timeout so we don't call select(2) if the pcap handle is in non-
190 * blocking mode.  We preserve the timeout supplied by pcap_open functions
191 * to make sure it does not get clobbered if the pcap handle moves between
192 * blocking and non-blocking mode.
193 */
194static int
195pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
196{
197#ifdef HAVE_ZEROCOPY_BPF
198	if (p->md.zerocopy) {
199		/*
200		 * Use a negative value for the timeout to represent that the
201		 * pcap handle is in non-blocking mode.
202		 */
203		return (p->md.timeout < 0);
204	}
205#endif
206	return (pcap_getnonblock_fd(p, errbuf));
207}
208
209static int
210pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
211{
212#ifdef HAVE_ZEROCOPY_BPF
213	if (p->md.zerocopy) {
214		/*
215		 * Map each value to their corresponding negation to
216		 * preserve the timeout value provided with pcap_set_timeout.
217		 * (from pcap-linux.c).
218		 */
219		if (nonblock) {
220			if (p->md.timeout >= 0) {
221				/*
222				 * Indicate that we're switching to
223				 * non-blocking mode.
224				 */
225				p->md.timeout = ~p->md.timeout;
226			}
227		} else {
228			if (p->md.timeout < 0) {
229				p->md.timeout = ~p->md.timeout;
230			}
231		}
232		return (0);
233	}
234#endif
235	return (pcap_setnonblock_fd(p, nonblock, errbuf));
236}
237
238#ifdef HAVE_ZEROCOPY_BPF
239/*
240 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
241 * shared memory buffers.
242 *
243 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
244 * and set up p->buffer and cc to reflect one if available.  Notice that if
245 * there was no prior buffer, we select zbuf1 as this will be the first
246 * buffer filled for a fresh BPF session.
247 */
248static int
249pcap_next_zbuf_shm(pcap_t *p, int *cc)
250{
251	struct bpf_zbuf_header *bzh;
252
253	if (p->md.zbuffer == p->md.zbuf2 || p->md.zbuffer == NULL) {
254		bzh = (struct bpf_zbuf_header *)p->md.zbuf1;
255		if (bzh->bzh_user_gen !=
256		    atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
257			p->md.bzh = bzh;
258			p->md.zbuffer = (u_char *)p->md.zbuf1;
259			p->buffer = p->md.zbuffer + sizeof(*bzh);
260			*cc = bzh->bzh_kernel_len;
261			return (1);
262		}
263	} else if (p->md.zbuffer == p->md.zbuf1) {
264		bzh = (struct bpf_zbuf_header *)p->md.zbuf2;
265		if (bzh->bzh_user_gen !=
266		    atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
267			p->md.bzh = bzh;
268			p->md.zbuffer = (u_char *)p->md.zbuf2;
269  			p->buffer = p->md.zbuffer + sizeof(*bzh);
270			*cc = bzh->bzh_kernel_len;
271			return (1);
272		}
273	}
274	*cc = 0;
275	return (0);
276}
277
278/*
279 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
280 * select() for data or a timeout, and possibly force rotation of the buffer
281 * in the event we time out or are in immediate mode.  Invoke the shared
282 * memory check before doing system calls in order to avoid doing avoidable
283 * work.
284 */
285static int
286pcap_next_zbuf(pcap_t *p, int *cc)
287{
288	struct bpf_zbuf bz;
289	struct timeval tv;
290	struct timespec cur;
291	fd_set r_set;
292	int data, r;
293	int expire, tmout;
294
295#define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
296	/*
297	 * Start out by seeing whether anything is waiting by checking the
298	 * next shared memory buffer for data.
299	 */
300	data = pcap_next_zbuf_shm(p, cc);
301	if (data)
302		return (data);
303	/*
304	 * If a previous sleep was interrupted due to signal delivery, make
305	 * sure that the timeout gets adjusted accordingly.  This requires
306	 * that we analyze when the timeout should be been expired, and
307	 * subtract the current time from that.  If after this operation,
308	 * our timeout is less then or equal to zero, handle it like a
309	 * regular timeout.
310	 */
311	tmout = p->md.timeout;
312	if (tmout)
313		(void) clock_gettime(CLOCK_MONOTONIC, &cur);
314	if (p->md.interrupted && p->md.timeout) {
315		expire = TSTOMILLI(&p->md.firstsel) + p->md.timeout;
316		tmout = expire - TSTOMILLI(&cur);
317#undef TSTOMILLI
318		if (tmout <= 0) {
319			p->md.interrupted = 0;
320			data = pcap_next_zbuf_shm(p, cc);
321			if (data)
322				return (data);
323			if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
324				(void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
325				    "BIOCROTZBUF: %s", strerror(errno));
326				return (PCAP_ERROR);
327			}
328			return (pcap_next_zbuf_shm(p, cc));
329		}
330	}
331	/*
332	 * No data in the buffer, so must use select() to wait for data or
333	 * the next timeout.  Note that we only call select if the handle
334	 * is in blocking mode.
335	 */
336	if (p->md.timeout >= 0) {
337		FD_ZERO(&r_set);
338		FD_SET(p->fd, &r_set);
339		if (tmout != 0) {
340			tv.tv_sec = tmout / 1000;
341			tv.tv_usec = (tmout * 1000) % 1000000;
342		}
343		r = select(p->fd + 1, &r_set, NULL, NULL,
344		    p->md.timeout != 0 ? &tv : NULL);
345		if (r < 0 && errno == EINTR) {
346			if (!p->md.interrupted && p->md.timeout) {
347				p->md.interrupted = 1;
348				p->md.firstsel = cur;
349			}
350			return (0);
351		} else if (r < 0) {
352			(void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
353			    "select: %s", strerror(errno));
354			return (PCAP_ERROR);
355		}
356	}
357	p->md.interrupted = 0;
358	/*
359	 * Check again for data, which may exist now that we've either been
360	 * woken up as a result of data or timed out.  Try the "there's data"
361	 * case first since it doesn't require a system call.
362	 */
363	data = pcap_next_zbuf_shm(p, cc);
364	if (data)
365		return (data);
366	/*
367	 * Try forcing a buffer rotation to dislodge timed out or immediate
368	 * data.
369	 */
370	if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
371		(void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
372		    "BIOCROTZBUF: %s", strerror(errno));
373		return (PCAP_ERROR);
374	}
375	return (pcap_next_zbuf_shm(p, cc));
376}
377
378/*
379 * Notify kernel that we are done with the buffer.  We don't reset zbuffer so
380 * that we know which buffer to use next time around.
381 */
382static int
383pcap_ack_zbuf(pcap_t *p)
384{
385
386	atomic_store_rel_int(&p->md.bzh->bzh_user_gen,
387	    p->md.bzh->bzh_kernel_gen);
388	p->md.bzh = NULL;
389	p->buffer = NULL;
390	return (0);
391}
392#endif /* HAVE_ZEROCOPY_BPF */
393
394pcap_t *
395pcap_create_interface(const char *device, char *ebuf)
396{
397	pcap_t *p;
398
399	p = pcap_create_common(device, ebuf);
400	if (p == NULL)
401		return (NULL);
402
403	p->activate_op = pcap_activate_bpf;
404	p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
405	return (p);
406}
407
408/*
409 * On success, returns a file descriptor for a BPF device.
410 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
411 */
412static int
413bpf_open(pcap_t *p)
414{
415	int fd;
416#ifdef HAVE_CLONING_BPF
417	static const char device[] = "/dev/bpf";
418#else
419	int n = 0;
420	char device[sizeof "/dev/bpf0000000000"];
421#endif
422
423#ifdef _AIX
424	/*
425	 * Load the bpf driver, if it isn't already loaded,
426	 * and create the BPF device entries, if they don't
427	 * already exist.
428	 */
429	if (bpf_load(p->errbuf) == PCAP_ERROR)
430		return (PCAP_ERROR);
431#endif
432
433#ifdef HAVE_CLONING_BPF
434	if ((fd = open(device, O_RDWR)) == -1 &&
435	    (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
436		if (errno == EACCES)
437			fd = PCAP_ERROR_PERM_DENIED;
438		else
439			fd = PCAP_ERROR;
440		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
441		  "(cannot open device) %s: %s", device, pcap_strerror(errno));
442	}
443#else
444	/*
445	 * Go through all the minors and find one that isn't in use.
446	 */
447	do {
448		(void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
449		/*
450		 * Initially try a read/write open (to allow the inject
451		 * method to work).  If that fails due to permission
452		 * issues, fall back to read-only.  This allows a
453		 * non-root user to be granted specific access to pcap
454		 * capabilities via file permissions.
455		 *
456		 * XXX - we should have an API that has a flag that
457		 * controls whether to open read-only or read-write,
458		 * so that denial of permission to send (or inability
459		 * to send, if sending packets isn't supported on
460		 * the device in question) can be indicated at open
461		 * time.
462		 */
463		fd = open(device, O_RDWR);
464		if (fd == -1 && errno == EACCES)
465			fd = open(device, O_RDONLY);
466	} while (fd < 0 && errno == EBUSY);
467
468	/*
469	 * XXX better message for all minors used
470	 */
471	if (fd < 0) {
472		switch (errno) {
473
474		case ENOENT:
475			fd = PCAP_ERROR;
476			if (n == 1) {
477				/*
478				 * /dev/bpf0 doesn't exist, which
479				 * means we probably have no BPF
480				 * devices.
481				 */
482				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
483				    "(there are no BPF devices)");
484			} else {
485				/*
486				 * We got EBUSY on at least one
487				 * BPF device, so we have BPF
488				 * devices, but all the ones
489				 * that exist are busy.
490				 */
491				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
492				    "(all BPF devices are busy)");
493			}
494			break;
495
496		case EACCES:
497			/*
498			 * Got EACCES on the last device we tried,
499			 * and EBUSY on all devices before that,
500			 * if any.
501			 */
502			fd = PCAP_ERROR_PERM_DENIED;
503			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
504			    "(cannot open BPF device) %s: %s", device,
505			    pcap_strerror(errno));
506			break;
507
508		default:
509			/*
510			 * Some other problem.
511			 */
512			fd = PCAP_ERROR;
513			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
514			    "(cannot open BPF device) %s: %s", device,
515			    pcap_strerror(errno));
516			break;
517		}
518	}
519#endif
520
521	return (fd);
522}
523
524#ifdef BIOCGDLTLIST
525static int
526get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
527{
528	memset(bdlp, 0, sizeof(*bdlp));
529	if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
530		u_int i;
531		int is_ethernet;
532
533		bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
534		if (bdlp->bfl_list == NULL) {
535			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
536			    pcap_strerror(errno));
537			return (PCAP_ERROR);
538		}
539
540		if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
541			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
542			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
543			free(bdlp->bfl_list);
544			return (PCAP_ERROR);
545		}
546
547		/*
548		 * OK, for real Ethernet devices, add DLT_DOCSIS to the
549		 * list, so that an application can let you choose it,
550		 * in case you're capturing DOCSIS traffic that a Cisco
551		 * Cable Modem Termination System is putting out onto
552		 * an Ethernet (it doesn't put an Ethernet header onto
553		 * the wire, it puts raw DOCSIS frames out on the wire
554		 * inside the low-level Ethernet framing).
555		 *
556		 * A "real Ethernet device" is defined here as a device
557		 * that has a link-layer type of DLT_EN10MB and that has
558		 * no alternate link-layer types; that's done to exclude
559		 * 802.11 interfaces (which might or might not be the
560		 * right thing to do, but I suspect it is - Ethernet <->
561		 * 802.11 bridges would probably badly mishandle frames
562		 * that don't have Ethernet headers).
563		 *
564		 * On Solaris with BPF, Ethernet devices also offer
565		 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
566		 * treat it as an indication that the device isn't an
567		 * Ethernet.
568		 */
569		if (v == DLT_EN10MB) {
570			is_ethernet = 1;
571			for (i = 0; i < bdlp->bfl_len; i++) {
572				if (bdlp->bfl_list[i] != DLT_EN10MB
573#ifdef DLT_IPNET
574				    && bdlp->bfl_list[i] != DLT_IPNET
575#endif
576				    ) {
577					is_ethernet = 0;
578					break;
579				}
580			}
581			if (is_ethernet) {
582				/*
583				 * We reserved one more slot at the end of
584				 * the list.
585				 */
586				bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
587				bdlp->bfl_len++;
588			}
589		}
590	} else {
591		/*
592		 * EINVAL just means "we don't support this ioctl on
593		 * this device"; don't treat it as an error.
594		 */
595		if (errno != EINVAL) {
596			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
597			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
598			return (PCAP_ERROR);
599		}
600	}
601	return (0);
602}
603#endif
604
605static int
606pcap_can_set_rfmon_bpf(pcap_t *p)
607{
608#if defined(__APPLE__)
609	struct utsname osinfo;
610	struct ifreq ifr;
611	int fd;
612#ifdef BIOCGDLTLIST
613	struct bpf_dltlist bdl;
614#endif
615
616	/*
617	 * The joys of monitor mode on OS X.
618	 *
619	 * Prior to 10.4, it's not supported at all.
620	 *
621	 * In 10.4, if adapter enN supports monitor mode, there's a
622	 * wltN adapter corresponding to it; you open it, instead of
623	 * enN, to get monitor mode.  You get whatever link-layer
624	 * headers it supplies.
625	 *
626	 * In 10.5, and, we assume, later releases, if adapter enN
627	 * supports monitor mode, it offers, among its selectable
628	 * DLT_ values, values that let you get the 802.11 header;
629	 * selecting one of those values puts the adapter into monitor
630	 * mode (i.e., you can't get 802.11 headers except in monitor
631	 * mode, and you can't get Ethernet headers in monitor mode).
632	 */
633	if (uname(&osinfo) == -1) {
634		/*
635		 * Can't get the OS version; just say "no".
636		 */
637		return (0);
638	}
639	/*
640	 * We assume osinfo.sysname is "Darwin", because
641	 * __APPLE__ is defined.  We just check the version.
642	 */
643	if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
644		/*
645		 * 10.3 (Darwin 7.x) or earlier.
646		 * Monitor mode not supported.
647		 */
648		return (0);
649	}
650	if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
651		/*
652		 * 10.4 (Darwin 8.x).  s/en/wlt/, and check
653		 * whether the device exists.
654		 */
655		if (strncmp(p->opt.source, "en", 2) != 0) {
656			/*
657			 * Not an enN device; no monitor mode.
658			 */
659			return (0);
660		}
661		fd = socket(AF_INET, SOCK_DGRAM, 0);
662		if (fd == -1) {
663			(void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
664			    "socket: %s", pcap_strerror(errno));
665			return (PCAP_ERROR);
666		}
667		strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
668		strlcat(ifr.ifr_name, p->opt.source + 2, sizeof(ifr.ifr_name));
669		if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
670			/*
671			 * No such device?
672			 */
673			close(fd);
674			return (0);
675		}
676		close(fd);
677		return (1);
678	}
679
680#ifdef BIOCGDLTLIST
681	/*
682	 * Everything else is 10.5 or later; for those,
683	 * we just open the enN device, and check whether
684	 * we have any 802.11 devices.
685	 *
686	 * First, open a BPF device.
687	 */
688	fd = bpf_open(p);
689	if (fd < 0)
690		return (fd);	/* fd is the appropriate error code */
691
692	/*
693	 * Now bind to the device.
694	 */
695	(void)strncpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
696	if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
697		switch (errno) {
698
699		case ENXIO:
700			/*
701			 * There's no such device.
702			 */
703			close(fd);
704			return (PCAP_ERROR_NO_SUCH_DEVICE);
705
706		case ENETDOWN:
707			/*
708			 * Return a "network down" indication, so that
709			 * the application can report that rather than
710			 * saying we had a mysterious failure and
711			 * suggest that they report a problem to the
712			 * libpcap developers.
713			 */
714			close(fd);
715			return (PCAP_ERROR_IFACE_NOT_UP);
716
717		default:
718			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
719			    "BIOCSETIF: %s: %s",
720			    p->opt.source, pcap_strerror(errno));
721			close(fd);
722			return (PCAP_ERROR);
723		}
724	}
725
726	/*
727	 * We know the default link type -- now determine all the DLTs
728	 * this interface supports.  If this fails with EINVAL, it's
729	 * not fatal; we just don't get to use the feature later.
730	 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
731	 * as the default DLT for this adapter.)
732	 */
733	if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
734		close(fd);
735		return (PCAP_ERROR);
736	}
737	if (find_802_11(&bdl) != -1) {
738		/*
739		 * We have an 802.11 DLT, so we can set monitor mode.
740		 */
741		free(bdl.bfl_list);
742		close(fd);
743		return (1);
744	}
745	free(bdl.bfl_list);
746#endif /* BIOCGDLTLIST */
747	return (0);
748#elif defined(HAVE_BSD_IEEE80211)
749	int ret;
750
751	ret = monitor_mode(p, 0);
752	if (ret == PCAP_ERROR_RFMON_NOTSUP)
753		return (0);	/* not an error, just a "can't do" */
754	if (ret == 0)
755		return (1);	/* success */
756	return (ret);
757#else
758	return (0);
759#endif
760}
761
762static int
763pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
764{
765	struct bpf_stat s;
766
767	/*
768	 * "ps_recv" counts packets handed to the filter, not packets
769	 * that passed the filter.  This includes packets later dropped
770	 * because we ran out of buffer space.
771	 *
772	 * "ps_drop" counts packets dropped inside the BPF device
773	 * because we ran out of buffer space.  It doesn't count
774	 * packets dropped by the interface driver.  It counts
775	 * only packets that passed the filter.
776	 *
777	 * Both statistics include packets not yet read from the kernel
778	 * by libpcap, and thus not yet seen by the application.
779	 */
780	if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
781		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
782		    pcap_strerror(errno));
783		return (PCAP_ERROR);
784	}
785
786	ps->ps_recv = s.bs_recv;
787	ps->ps_drop = s.bs_drop;
788	ps->ps_ifdrop = 0;
789	return (0);
790}
791
792static int
793pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
794{
795	int cc;
796	int n = 0;
797	register u_char *bp, *ep;
798	u_char *datap;
799#ifdef PCAP_FDDIPAD
800	register int pad;
801#endif
802#ifdef HAVE_ZEROCOPY_BPF
803	int i;
804#endif
805
806 again:
807	/*
808	 * Has "pcap_breakloop()" been called?
809	 */
810	if (p->break_loop) {
811		/*
812		 * Yes - clear the flag that indicates that it
813		 * has, and return PCAP_ERROR_BREAK to indicate
814		 * that we were told to break out of the loop.
815		 */
816		p->break_loop = 0;
817		return (PCAP_ERROR_BREAK);
818	}
819	cc = p->cc;
820	if (p->cc == 0) {
821		/*
822		 * When reading without zero-copy from a file descriptor, we
823		 * use a single buffer and return a length of data in the
824		 * buffer.  With zero-copy, we update the p->buffer pointer
825		 * to point at whatever underlying buffer contains the next
826		 * data and update cc to reflect the data found in the
827		 * buffer.
828		 */
829#ifdef HAVE_ZEROCOPY_BPF
830		if (p->md.zerocopy) {
831			if (p->buffer != NULL)
832				pcap_ack_zbuf(p);
833			i = pcap_next_zbuf(p, &cc);
834			if (i == 0)
835				goto again;
836			if (i < 0)
837				return (PCAP_ERROR);
838		} else
839#endif
840		{
841			cc = read(p->fd, (char *)p->buffer, p->bufsize);
842		}
843		if (cc < 0) {
844			/* Don't choke when we get ptraced */
845			switch (errno) {
846
847			case EINTR:
848				goto again;
849
850#ifdef _AIX
851			case EFAULT:
852				/*
853				 * Sigh.  More AIX wonderfulness.
854				 *
855				 * For some unknown reason the uiomove()
856				 * operation in the bpf kernel extension
857				 * used to copy the buffer into user
858				 * space sometimes returns EFAULT. I have
859				 * no idea why this is the case given that
860				 * a kernel debugger shows the user buffer
861				 * is correct. This problem appears to
862				 * be mostly mitigated by the memset of
863				 * the buffer before it is first used.
864				 * Very strange.... Shaun Clowes
865				 *
866				 * In any case this means that we shouldn't
867				 * treat EFAULT as a fatal error; as we
868				 * don't have an API for returning
869				 * a "some packets were dropped since
870				 * the last packet you saw" indication,
871				 * we just ignore EFAULT and keep reading.
872				 */
873				goto again;
874#endif
875
876			case EWOULDBLOCK:
877				return (0);
878
879			case ENXIO:
880				/*
881				 * The device on which we're capturing
882				 * went away.
883				 *
884				 * XXX - we should really return
885				 * PCAP_ERROR_IFACE_NOT_UP, but
886				 * pcap_dispatch() etc. aren't
887				 * defined to retur that.
888				 */
889				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
890				    "The interface went down");
891				return (PCAP_ERROR);
892
893#if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
894			/*
895			 * Due to a SunOS bug, after 2^31 bytes, the kernel
896			 * file offset overflows and read fails with EINVAL.
897			 * The lseek() to 0 will fix things.
898			 */
899			case EINVAL:
900				if (lseek(p->fd, 0L, SEEK_CUR) +
901				    p->bufsize < 0) {
902					(void)lseek(p->fd, 0L, SEEK_SET);
903					goto again;
904				}
905				/* fall through */
906#endif
907			}
908			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
909			    pcap_strerror(errno));
910			return (PCAP_ERROR);
911		}
912		bp = p->buffer;
913	} else
914		bp = p->bp;
915
916	/*
917	 * Loop through each packet.
918	 */
919#define bhp ((struct bpf_hdr *)bp)
920	ep = bp + cc;
921#ifdef PCAP_FDDIPAD
922	pad = p->fddipad;
923#endif
924	while (bp < ep) {
925		register int caplen, hdrlen;
926
927		/*
928		 * Has "pcap_breakloop()" been called?
929		 * If so, return immediately - if we haven't read any
930		 * packets, clear the flag and return PCAP_ERROR_BREAK
931		 * to indicate that we were told to break out of the loop,
932		 * otherwise leave the flag set, so that the *next* call
933		 * will break out of the loop without having read any
934		 * packets, and return the number of packets we've
935		 * processed so far.
936		 */
937		if (p->break_loop) {
938			p->bp = bp;
939			p->cc = ep - bp;
940			/*
941			 * ep is set based on the return value of read(),
942			 * but read() from a BPF device doesn't necessarily
943			 * return a value that's a multiple of the alignment
944			 * value for BPF_WORDALIGN().  However, whenever we
945			 * increment bp, we round up the increment value by
946			 * a value rounded up by BPF_WORDALIGN(), so we
947			 * could increment bp past ep after processing the
948			 * last packet in the buffer.
949			 *
950			 * We treat ep < bp as an indication that this
951			 * happened, and just set p->cc to 0.
952			 */
953			if (p->cc < 0)
954				p->cc = 0;
955			if (n == 0) {
956				p->break_loop = 0;
957				return (PCAP_ERROR_BREAK);
958			} else
959				return (n);
960		}
961
962		caplen = bhp->bh_caplen;
963		hdrlen = bhp->bh_hdrlen;
964		datap = bp + hdrlen;
965		/*
966		 * Short-circuit evaluation: if using BPF filter
967		 * in kernel, no need to do it now - we already know
968		 * the packet passed the filter.
969		 *
970#ifdef PCAP_FDDIPAD
971		 * Note: the filter code was generated assuming
972		 * that p->fddipad was the amount of padding
973		 * before the header, as that's what's required
974		 * in the kernel, so we run the filter before
975		 * skipping that padding.
976#endif
977		 */
978		if (p->md.use_bpf ||
979		    bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
980			struct pcap_pkthdr pkthdr;
981
982			pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
983#ifdef _AIX
984			/*
985			 * AIX's BPF returns seconds/nanoseconds time
986			 * stamps, not seconds/microseconds time stamps.
987			 */
988			pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
989#else
990			pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
991#endif
992#ifdef PCAP_FDDIPAD
993			if (caplen > pad)
994				pkthdr.caplen = caplen - pad;
995			else
996				pkthdr.caplen = 0;
997			if (bhp->bh_datalen > pad)
998				pkthdr.len = bhp->bh_datalen - pad;
999			else
1000				pkthdr.len = 0;
1001			datap += pad;
1002#else
1003			pkthdr.caplen = caplen;
1004			pkthdr.len = bhp->bh_datalen;
1005#endif
1006			(*callback)(user, &pkthdr, datap);
1007			bp += BPF_WORDALIGN(caplen + hdrlen);
1008			if (++n >= cnt && cnt > 0) {
1009				p->bp = bp;
1010				p->cc = ep - bp;
1011				/*
1012				 * See comment above about p->cc < 0.
1013				 */
1014				if (p->cc < 0)
1015					p->cc = 0;
1016				return (n);
1017			}
1018		} else {
1019			/*
1020			 * Skip this packet.
1021			 */
1022			bp += BPF_WORDALIGN(caplen + hdrlen);
1023		}
1024	}
1025#undef bhp
1026	p->cc = 0;
1027	return (n);
1028}
1029
1030static int
1031pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1032{
1033	int ret;
1034
1035	ret = write(p->fd, buf, size);
1036#ifdef __APPLE__
1037	if (ret == -1 && errno == EAFNOSUPPORT) {
1038		/*
1039		 * In Mac OS X, there's a bug wherein setting the
1040		 * BIOCSHDRCMPLT flag causes writes to fail; see,
1041		 * for example:
1042		 *
1043		 *	http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1044		 *
1045		 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1046		 * assume it's due to that bug, and turn off that flag
1047		 * and try again.  If we succeed, it either means that
1048		 * somebody applied the fix from that URL, or other patches
1049		 * for that bug from
1050		 *
1051		 *	http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1052		 *
1053		 * and are running a Darwin kernel with those fixes, or
1054		 * that Apple fixed the problem in some OS X release.
1055		 */
1056		u_int spoof_eth_src = 0;
1057
1058		if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1059			(void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1060			    "send: can't turn off BIOCSHDRCMPLT: %s",
1061			    pcap_strerror(errno));
1062			return (PCAP_ERROR);
1063		}
1064
1065		/*
1066		 * Now try the write again.
1067		 */
1068		ret = write(p->fd, buf, size);
1069	}
1070#endif /* __APPLE__ */
1071	if (ret == -1) {
1072		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1073		    pcap_strerror(errno));
1074		return (PCAP_ERROR);
1075	}
1076	return (ret);
1077}
1078
1079#ifdef _AIX
1080static int
1081bpf_odminit(char *errbuf)
1082{
1083	char *errstr;
1084
1085	if (odm_initialize() == -1) {
1086		if (odm_err_msg(odmerrno, &errstr) == -1)
1087			errstr = "Unknown error";
1088		snprintf(errbuf, PCAP_ERRBUF_SIZE,
1089		    "bpf_load: odm_initialize failed: %s",
1090		    errstr);
1091		return (PCAP_ERROR);
1092	}
1093
1094	if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1095		if (odm_err_msg(odmerrno, &errstr) == -1)
1096			errstr = "Unknown error";
1097		snprintf(errbuf, PCAP_ERRBUF_SIZE,
1098		    "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1099		    errstr);
1100		(void)odm_terminate();
1101		return (PCAP_ERROR);
1102	}
1103
1104	return (0);
1105}
1106
1107static int
1108bpf_odmcleanup(char *errbuf)
1109{
1110	char *errstr;
1111
1112	if (odm_unlock(odmlockid) == -1) {
1113		if (errbuf != NULL) {
1114			if (odm_err_msg(odmerrno, &errstr) == -1)
1115				errstr = "Unknown error";
1116			snprintf(errbuf, PCAP_ERRBUF_SIZE,
1117			    "bpf_load: odm_unlock failed: %s",
1118			    errstr);
1119		}
1120		return (PCAP_ERROR);
1121	}
1122
1123	if (odm_terminate() == -1) {
1124		if (errbuf != NULL) {
1125			if (odm_err_msg(odmerrno, &errstr) == -1)
1126				errstr = "Unknown error";
1127			snprintf(errbuf, PCAP_ERRBUF_SIZE,
1128			    "bpf_load: odm_terminate failed: %s",
1129			    errstr);
1130		}
1131		return (PCAP_ERROR);
1132	}
1133
1134	return (0);
1135}
1136
1137static int
1138bpf_load(char *errbuf)
1139{
1140	long major;
1141	int *minors;
1142	int numminors, i, rc;
1143	char buf[1024];
1144	struct stat sbuf;
1145	struct bpf_config cfg_bpf;
1146	struct cfg_load cfg_ld;
1147	struct cfg_kmod cfg_km;
1148
1149	/*
1150	 * This is very very close to what happens in the real implementation
1151	 * but I've fixed some (unlikely) bug situations.
1152	 */
1153	if (bpfloadedflag)
1154		return (0);
1155
1156	if (bpf_odminit(errbuf) == PCAP_ERROR)
1157		return (PCAP_ERROR);
1158
1159	major = genmajor(BPF_NAME);
1160	if (major == -1) {
1161		snprintf(errbuf, PCAP_ERRBUF_SIZE,
1162		    "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1163		(void)bpf_odmcleanup(NULL);
1164		return (PCAP_ERROR);
1165	}
1166
1167	minors = getminor(major, &numminors, BPF_NAME);
1168	if (!minors) {
1169		minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1170		if (!minors) {
1171			snprintf(errbuf, PCAP_ERRBUF_SIZE,
1172			    "bpf_load: genminor failed: %s",
1173			    pcap_strerror(errno));
1174			(void)bpf_odmcleanup(NULL);
1175			return (PCAP_ERROR);
1176		}
1177	}
1178
1179	if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1180		return (PCAP_ERROR);
1181
1182	rc = stat(BPF_NODE "0", &sbuf);
1183	if (rc == -1 && errno != ENOENT) {
1184		snprintf(errbuf, PCAP_ERRBUF_SIZE,
1185		    "bpf_load: can't stat %s: %s",
1186		    BPF_NODE "0", pcap_strerror(errno));
1187		return (PCAP_ERROR);
1188	}
1189
1190	if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1191		for (i = 0; i < BPF_MINORS; i++) {
1192			sprintf(buf, "%s%d", BPF_NODE, i);
1193			unlink(buf);
1194			if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1195				snprintf(errbuf, PCAP_ERRBUF_SIZE,
1196				    "bpf_load: can't mknod %s: %s",
1197				    buf, pcap_strerror(errno));
1198				return (PCAP_ERROR);
1199			}
1200		}
1201	}
1202
1203	/* Check if the driver is loaded */
1204	memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1205	cfg_ld.path = buf;
1206	sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1207	if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1208	    (cfg_ld.kmid == 0)) {
1209		/* Driver isn't loaded, load it now */
1210		if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1211			snprintf(errbuf, PCAP_ERRBUF_SIZE,
1212			    "bpf_load: could not load driver: %s",
1213			    strerror(errno));
1214			return (PCAP_ERROR);
1215		}
1216	}
1217
1218	/* Configure the driver */
1219	cfg_km.cmd = CFG_INIT;
1220	cfg_km.kmid = cfg_ld.kmid;
1221	cfg_km.mdilen = sizeof(cfg_bpf);
1222	cfg_km.mdiptr = (void *)&cfg_bpf;
1223	for (i = 0; i < BPF_MINORS; i++) {
1224		cfg_bpf.devno = domakedev(major, i);
1225		if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1226			snprintf(errbuf, PCAP_ERRBUF_SIZE,
1227			    "bpf_load: could not configure driver: %s",
1228			    strerror(errno));
1229			return (PCAP_ERROR);
1230		}
1231	}
1232
1233	bpfloadedflag = 1;
1234
1235	return (0);
1236}
1237#endif
1238
1239/*
1240 * Turn off rfmon mode if necessary.
1241 */
1242static void
1243pcap_cleanup_bpf(pcap_t *p)
1244{
1245#ifdef HAVE_BSD_IEEE80211
1246	int sock;
1247	struct ifmediareq req;
1248	struct ifreq ifr;
1249#endif
1250
1251	if (p->md.must_do_on_close != 0) {
1252		/*
1253		 * There's something we have to do when closing this
1254		 * pcap_t.
1255		 */
1256#ifdef HAVE_BSD_IEEE80211
1257		if (p->md.must_do_on_close & MUST_CLEAR_RFMON) {
1258			/*
1259			 * We put the interface into rfmon mode;
1260			 * take it out of rfmon mode.
1261			 *
1262			 * XXX - if somebody else wants it in rfmon
1263			 * mode, this code cannot know that, so it'll take
1264			 * it out of rfmon mode.
1265			 */
1266			sock = socket(AF_INET, SOCK_DGRAM, 0);
1267			if (sock == -1) {
1268				fprintf(stderr,
1269				    "Can't restore interface flags (socket() failed: %s).\n"
1270				    "Please adjust manually.\n",
1271				    strerror(errno));
1272			} else {
1273				memset(&req, 0, sizeof(req));
1274				strncpy(req.ifm_name, p->md.device,
1275				    sizeof(req.ifm_name));
1276				if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1277					fprintf(stderr,
1278					    "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1279					    "Please adjust manually.\n",
1280					    strerror(errno));
1281				} else {
1282					if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1283						/*
1284						 * Rfmon mode is currently on;
1285						 * turn it off.
1286						 */
1287						memset(&ifr, 0, sizeof(ifr));
1288						(void)strncpy(ifr.ifr_name,
1289						    p->md.device,
1290						    sizeof(ifr.ifr_name));
1291						ifr.ifr_media =
1292						    req.ifm_current & ~IFM_IEEE80211_MONITOR;
1293						if (ioctl(sock, SIOCSIFMEDIA,
1294						    &ifr) == -1) {
1295							fprintf(stderr,
1296							    "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1297							    "Please adjust manually.\n",
1298							    strerror(errno));
1299						}
1300					}
1301				}
1302				close(sock);
1303			}
1304		}
1305#endif /* HAVE_BSD_IEEE80211 */
1306
1307		/*
1308		 * Take this pcap out of the list of pcaps for which we
1309		 * have to take the interface out of some mode.
1310		 */
1311		pcap_remove_from_pcaps_to_close(p);
1312		p->md.must_do_on_close = 0;
1313	}
1314
1315#ifdef HAVE_ZEROCOPY_BPF
1316	if (p->md.zerocopy) {
1317		/*
1318		 * Delete the mappings.  Note that p->buffer gets
1319		 * initialized to one of the mmapped regions in
1320		 * this case, so do not try and free it directly;
1321		 * null it out so that pcap_cleanup_live_common()
1322		 * doesn't try to free it.
1323		 */
1324		if (p->md.zbuf1 != MAP_FAILED && p->md.zbuf1 != NULL)
1325			(void) munmap(p->md.zbuf1, p->md.zbufsize);
1326		if (p->md.zbuf2 != MAP_FAILED && p->md.zbuf2 != NULL)
1327			(void) munmap(p->md.zbuf2, p->md.zbufsize);
1328		p->buffer = NULL;
1329		p->buffer = NULL;
1330	}
1331#endif
1332	if (p->md.device != NULL) {
1333		free(p->md.device);
1334		p->md.device = NULL;
1335	}
1336	pcap_cleanup_live_common(p);
1337}
1338
1339static int
1340check_setif_failure(pcap_t *p, int error)
1341{
1342#ifdef __APPLE__
1343	int fd;
1344	struct ifreq ifr;
1345	int err;
1346#endif
1347
1348	if (error == ENXIO) {
1349		/*
1350		 * No such device exists.
1351		 */
1352#ifdef __APPLE__
1353		if (p->opt.rfmon && strncmp(p->opt.source, "wlt", 3) == 0) {
1354			/*
1355			 * Monitor mode was requested, and we're trying
1356			 * to open a "wltN" device.  Assume that this
1357			 * is 10.4 and that we were asked to open an
1358			 * "enN" device; if that device exists, return
1359			 * "monitor mode not supported on the device".
1360			 */
1361			fd = socket(AF_INET, SOCK_DGRAM, 0);
1362			if (fd != -1) {
1363				strlcpy(ifr.ifr_name, "en",
1364				    sizeof(ifr.ifr_name));
1365				strlcat(ifr.ifr_name, p->opt.source + 3,
1366				    sizeof(ifr.ifr_name));
1367				if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1368					/*
1369					 * We assume this failed because
1370					 * the underlying device doesn't
1371					 * exist.
1372					 */
1373					err = PCAP_ERROR_NO_SUCH_DEVICE;
1374					snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1375					    "SIOCGIFFLAGS on %s failed: %s",
1376					    ifr.ifr_name, pcap_strerror(errno));
1377				} else {
1378					/*
1379					 * The underlying "enN" device
1380					 * exists, but there's no
1381					 * corresponding "wltN" device;
1382					 * that means that the "enN"
1383					 * device doesn't support
1384					 * monitor mode, probably because
1385					 * it's an Ethernet device rather
1386					 * than a wireless device.
1387					 */
1388					err = PCAP_ERROR_RFMON_NOTSUP;
1389				}
1390				close(fd);
1391			} else {
1392				/*
1393				 * We can't find out whether there's
1394				 * an underlying "enN" device, so
1395				 * just report "no such device".
1396				 */
1397				err = PCAP_ERROR_NO_SUCH_DEVICE;
1398				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1399				    "socket() failed: %s",
1400				    pcap_strerror(errno));
1401			}
1402			return (err);
1403		}
1404#endif
1405		/*
1406		 * No such device.
1407		 */
1408		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1409		    pcap_strerror(errno));
1410		return (PCAP_ERROR_NO_SUCH_DEVICE);
1411	} else if (errno == ENETDOWN) {
1412		/*
1413		 * Return a "network down" indication, so that
1414		 * the application can report that rather than
1415		 * saying we had a mysterious failure and
1416		 * suggest that they report a problem to the
1417		 * libpcap developers.
1418		 */
1419		return (PCAP_ERROR_IFACE_NOT_UP);
1420	} else {
1421		/*
1422		 * Some other error; fill in the error string, and
1423		 * return PCAP_ERROR.
1424		 */
1425		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1426		    p->opt.source, pcap_strerror(errno));
1427		return (PCAP_ERROR);
1428	}
1429}
1430
1431/*
1432 * Default capture buffer size.
1433 * 32K isn't very much for modern machines with fast networks; we
1434 * pick .5M, as that's the maximum on at least some systems with BPF.
1435 *
1436 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1437 * read failures under stress, so we leave it as 32K; yet another
1438 * place where AIX's BPF is broken.
1439 */
1440#ifdef _AIX
1441#define DEFAULT_BUFSIZE	32768
1442#else
1443#define DEFAULT_BUFSIZE	524288
1444#endif
1445
1446static int
1447pcap_activate_bpf(pcap_t *p)
1448{
1449	int status = 0;
1450	int fd;
1451#ifdef LIFNAMSIZ
1452	char *zonesep;
1453	struct lifreq ifr;
1454	char *ifrname = ifr.lifr_name;
1455	const size_t ifnamsiz = sizeof(ifr.lifr_name);
1456#else
1457	struct ifreq ifr;
1458	char *ifrname = ifr.ifr_name;
1459	const size_t ifnamsiz = sizeof(ifr.ifr_name);
1460#endif
1461	struct bpf_version bv;
1462#ifdef __APPLE__
1463	int sockfd;
1464	char *wltdev = NULL;
1465#endif
1466#ifdef BIOCGDLTLIST
1467	struct bpf_dltlist bdl;
1468#if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1469	int new_dlt;
1470#endif
1471#endif /* BIOCGDLTLIST */
1472#if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1473	u_int spoof_eth_src = 1;
1474#endif
1475	u_int v;
1476	struct bpf_insn total_insn;
1477	struct bpf_program total_prog;
1478	struct utsname osinfo;
1479
1480#ifdef HAVE_DAG_API
1481	if (strstr(device, "dag")) {
1482		return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
1483	}
1484#endif /* HAVE_DAG_API */
1485
1486#ifdef BIOCGDLTLIST
1487	memset(&bdl, 0, sizeof(bdl));
1488	int have_osinfo = 0;
1489#ifdef HAVE_ZEROCOPY_BPF
1490	struct bpf_zbuf bz;
1491	u_int bufmode, zbufmax;
1492#endif
1493
1494	fd = bpf_open(p);
1495	if (fd < 0) {
1496		status = fd;
1497		goto bad;
1498	}
1499
1500	p->fd = fd;
1501
1502	if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1503		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1504		    pcap_strerror(errno));
1505		status = PCAP_ERROR;
1506		goto bad;
1507	}
1508	if (bv.bv_major != BPF_MAJOR_VERSION ||
1509	    bv.bv_minor < BPF_MINOR_VERSION) {
1510		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1511		    "kernel bpf filter out of date");
1512		status = PCAP_ERROR;
1513		goto bad;
1514	}
1515
1516#if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1517	/*
1518	 * Check if the given source network device has a '/' separated
1519	 * zonename prefix string. The zonename prefixed source device
1520	 * can be used by libpcap consumers to capture network traffic
1521	 * in non-global zones from the global zone on Solaris 11 and
1522	 * above. If the zonename prefix is present then we strip the
1523	 * prefix and pass the zone ID as part of lifr_zoneid.
1524	 */
1525	if ((zonesep = strchr(p->opt.source, '/')) != NULL) {
1526		char zonename[ZONENAME_MAX];
1527		int  znamelen;
1528		char *lnamep;
1529
1530		znamelen = zonesep - p->opt.source;
1531		(void) strlcpy(zonename, p->opt.source, znamelen + 1);
1532		lnamep = strdup(zonesep + 1);
1533		ifr.lifr_zoneid = getzoneidbyname(zonename);
1534		free(p->opt.source);
1535		p->opt.source = lnamep;
1536	}
1537#endif
1538
1539	p->md.device = strdup(p->opt.source);
1540	if (p->md.device == NULL) {
1541		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1542		     pcap_strerror(errno));
1543		status = PCAP_ERROR;
1544		goto bad;
1545	}
1546
1547	/*
1548	 * Try finding a good size for the buffer; 32768 may be too
1549	 * big, so keep cutting it in half until we find a size
1550	 * that works, or run out of sizes to try.  If the default
1551	 * is larger, don't make it smaller.
1552	 *
1553	 * XXX - there should be a user-accessible hook to set the
1554	 * initial buffer size.
1555	 * Attempt to find out the version of the OS on which we're running.
1556	 */
1557	if (uname(&osinfo) == 0)
1558		have_osinfo = 1;
1559
1560#ifdef __APPLE__
1561	/*
1562	 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1563	 * of why we check the version number.
1564	 */
1565	if (p->opt.rfmon) {
1566		if (have_osinfo) {
1567			/*
1568			 * We assume osinfo.sysname is "Darwin", because
1569			 * __APPLE__ is defined.  We just check the version.
1570			 */
1571			if (osinfo.release[0] < '8' &&
1572			    osinfo.release[1] == '.') {
1573				/*
1574				 * 10.3 (Darwin 7.x) or earlier.
1575				 */
1576				status = PCAP_ERROR_RFMON_NOTSUP;
1577				goto bad;
1578			}
1579			if (osinfo.release[0] == '8' &&
1580			    osinfo.release[1] == '.') {
1581				/*
1582				 * 10.4 (Darwin 8.x).  s/en/wlt/
1583				 */
1584				if (strncmp(p->opt.source, "en", 2) != 0) {
1585					/*
1586					 * Not an enN device; check
1587					 * whether the device even exists.
1588					 */
1589					sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1590					if (sockfd != -1) {
1591						strlcpy(ifrname,
1592						    p->opt.source, ifnamsiz);
1593						if (ioctl(sockfd, SIOCGIFFLAGS,
1594						    (char *)&ifr) < 0) {
1595							/*
1596							 * We assume this
1597							 * failed because
1598							 * the underlying
1599							 * device doesn't
1600							 * exist.
1601							 */
1602							status = PCAP_ERROR_NO_SUCH_DEVICE;
1603							snprintf(p->errbuf,
1604							    PCAP_ERRBUF_SIZE,
1605							    "SIOCGIFFLAGS failed: %s",
1606							    pcap_strerror(errno));
1607						} else
1608							status = PCAP_ERROR_RFMON_NOTSUP;
1609						close(sockfd);
1610					} else {
1611						/*
1612						 * We can't find out whether
1613						 * the device exists, so just
1614						 * report "no such device".
1615						 */
1616						status = PCAP_ERROR_NO_SUCH_DEVICE;
1617						snprintf(p->errbuf,
1618						    PCAP_ERRBUF_SIZE,
1619						    "socket() failed: %s",
1620						    pcap_strerror(errno));
1621					}
1622					goto bad;
1623				}
1624				wltdev = malloc(strlen(p->opt.source) + 2);
1625				if (wltdev == NULL) {
1626					(void)snprintf(p->errbuf,
1627					    PCAP_ERRBUF_SIZE, "malloc: %s",
1628					    pcap_strerror(errno));
1629					status = PCAP_ERROR;
1630					goto bad;
1631				}
1632				strcpy(wltdev, "wlt");
1633				strcat(wltdev, p->opt.source + 2);
1634				free(p->opt.source);
1635				p->opt.source = wltdev;
1636			}
1637			/*
1638			 * Everything else is 10.5 or later; for those,
1639			 * we just open the enN device, and set the DLT.
1640			 */
1641		}
1642	}
1643#endif /* __APPLE__ */
1644#ifdef HAVE_ZEROCOPY_BPF
1645	/*
1646	 * If the BPF extension to set buffer mode is present, try setting
1647	 * the mode to zero-copy.  If that fails, use regular buffering.  If
1648	 * it succeeds but other setup fails, return an error to the user.
1649	 */
1650	bufmode = BPF_BUFMODE_ZBUF;
1651	if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1652		/*
1653		 * We have zerocopy BPF; use it.
1654		 */
1655		p->md.zerocopy = 1;
1656
1657		/*
1658		 * How to pick a buffer size: first, query the maximum buffer
1659		 * size supported by zero-copy.  This also lets us quickly
1660		 * determine whether the kernel generally supports zero-copy.
1661		 * Then, if a buffer size was specified, use that, otherwise
1662		 * query the default buffer size, which reflects kernel
1663		 * policy for a desired default.  Round to the nearest page
1664		 * size.
1665		 */
1666		if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1667			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1668			    pcap_strerror(errno));
1669			goto bad;
1670		}
1671
1672		if (p->opt.buffer_size != 0) {
1673			/*
1674			 * A buffer size was explicitly specified; use it.
1675			 */
1676			v = p->opt.buffer_size;
1677		} else {
1678			if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1679			    v < DEFAULT_BUFSIZE)
1680				v = DEFAULT_BUFSIZE;
1681		}
1682#ifndef roundup
1683#define roundup(x, y)   ((((x)+((y)-1))/(y))*(y))  /* to any y */
1684#endif
1685		p->md.zbufsize = roundup(v, getpagesize());
1686		if (p->md.zbufsize > zbufmax)
1687			p->md.zbufsize = zbufmax;
1688		p->md.zbuf1 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1689		    MAP_ANON, -1, 0);
1690		p->md.zbuf2 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1691		    MAP_ANON, -1, 0);
1692		if (p->md.zbuf1 == MAP_FAILED || p->md.zbuf2 == MAP_FAILED) {
1693			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1694			    pcap_strerror(errno));
1695			goto bad;
1696		}
1697		memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
1698		bz.bz_bufa = p->md.zbuf1;
1699		bz.bz_bufb = p->md.zbuf2;
1700		bz.bz_buflen = p->md.zbufsize;
1701		if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1702			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1703			    pcap_strerror(errno));
1704			goto bad;
1705		}
1706		(void)strncpy(ifrname, p->opt.source, ifnamsiz);
1707		if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1708			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1709			    p->opt.source, pcap_strerror(errno));
1710			goto bad;
1711		}
1712		v = p->md.zbufsize - sizeof(struct bpf_zbuf_header);
1713	} else
1714#endif
1715	{
1716		/*
1717		 * We don't have zerocopy BPF.
1718		 * Set the buffer size.
1719		 */
1720		if (p->opt.buffer_size != 0) {
1721			/*
1722			 * A buffer size was explicitly specified; use it.
1723			 */
1724			if (ioctl(fd, BIOCSBLEN,
1725			    (caddr_t)&p->opt.buffer_size) < 0) {
1726				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1727				    "BIOCSBLEN: %s: %s", p->opt.source,
1728				    pcap_strerror(errno));
1729				status = PCAP_ERROR;
1730				goto bad;
1731			}
1732
1733			/*
1734			 * Now bind to the device.
1735			 */
1736			(void)strncpy(ifrname, p->opt.source, ifnamsiz);
1737#ifdef BIOCSETLIF
1738			if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
1739#else
1740			if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
1741#endif
1742			{
1743				status = check_setif_failure(p, errno);
1744				goto bad;
1745			}
1746		} else {
1747			/*
1748			 * No buffer size was explicitly specified.
1749			 *
1750			 * Try finding a good size for the buffer;
1751			 * DEFAULT_BUFSIZE may be too big, so keep
1752			 * cutting it in half until we find a size
1753			 * that works, or run out of sizes to try.
1754			 * If the default is larger, don't make it smaller.
1755			 */
1756			if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1757			    v < DEFAULT_BUFSIZE)
1758				v = DEFAULT_BUFSIZE;
1759			for ( ; v != 0; v >>= 1) {
1760				/*
1761				 * Ignore the return value - this is because the
1762				 * call fails on BPF systems that don't have
1763				 * kernel malloc.  And if the call fails, it's
1764				 * no big deal, we just continue to use the
1765				 * standard buffer size.
1766				 */
1767				(void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
1768
1769				(void)strncpy(ifrname, p->opt.source, ifnamsiz);
1770#ifdef BIOCSETLIF
1771				if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
1772#else
1773				if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
1774#endif
1775					break;	/* that size worked; we're done */
1776
1777				if (errno != ENOBUFS) {
1778					status = check_setif_failure(p, errno);
1779					goto bad;
1780				}
1781			}
1782
1783			if (v == 0) {
1784				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1785				    "BIOCSBLEN: %s: No buffer size worked",
1786				    p->opt.source);
1787				status = PCAP_ERROR;
1788				goto bad;
1789			}
1790		}
1791	}
1792#endif
1793
1794	/* Get the data link layer type. */
1795	if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
1796		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
1797		    pcap_strerror(errno));
1798		status = PCAP_ERROR;
1799		goto bad;
1800	}
1801
1802#ifdef _AIX
1803	/*
1804	 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
1805	 */
1806	switch (v) {
1807
1808	case IFT_ETHER:
1809	case IFT_ISO88023:
1810		v = DLT_EN10MB;
1811		break;
1812
1813	case IFT_FDDI:
1814		v = DLT_FDDI;
1815		break;
1816
1817	case IFT_ISO88025:
1818		v = DLT_IEEE802;
1819		break;
1820
1821	case IFT_LOOP:
1822		v = DLT_NULL;
1823		break;
1824
1825	default:
1826		/*
1827		 * We don't know what to map this to yet.
1828		 */
1829		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
1830		    v);
1831		status = PCAP_ERROR;
1832		goto bad;
1833	}
1834#endif
1835#if _BSDI_VERSION - 0 >= 199510
1836	/* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
1837	switch (v) {
1838
1839	case DLT_SLIP:
1840		v = DLT_SLIP_BSDOS;
1841		break;
1842
1843	case DLT_PPP:
1844		v = DLT_PPP_BSDOS;
1845		break;
1846
1847	case 11:	/*DLT_FR*/
1848		v = DLT_FRELAY;
1849		break;
1850
1851	case 12:	/*DLT_C_HDLC*/
1852		v = DLT_CHDLC;
1853		break;
1854	}
1855#endif
1856
1857#ifdef BIOCGDLTLIST
1858	/*
1859	 * We know the default link type -- now determine all the DLTs
1860	 * this interface supports.  If this fails with EINVAL, it's
1861	 * not fatal; we just don't get to use the feature later.
1862	 */
1863	if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
1864		status = PCAP_ERROR;
1865		goto bad;
1866	}
1867	p->dlt_count = bdl.bfl_len;
1868	p->dlt_list = bdl.bfl_list;
1869
1870#ifdef __APPLE__
1871	/*
1872	 * Monitor mode fun, continued.
1873	 *
1874	 * For 10.5 and, we're assuming, later releases, as noted above,
1875	 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
1876	 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
1877	 * DLT_ value.  Choosing one of the 802.11 DLT_ values will turn
1878	 * monitor mode on.
1879	 *
1880	 * Therefore, if the user asked for monitor mode, we filter out
1881	 * the DLT_EN10MB value, as you can't get that in monitor mode,
1882	 * and, if the user didn't ask for monitor mode, we filter out
1883	 * the 802.11 DLT_ values, because selecting those will turn
1884	 * monitor mode on.  Then, for monitor mode, if an 802.11-plus-
1885	 * radio DLT_ value is offered, we try to select that, otherwise
1886	 * we try to select DLT_IEEE802_11.
1887	 */
1888	if (have_osinfo) {
1889		if (isdigit((unsigned)osinfo.release[0]) &&
1890		     (osinfo.release[0] == '9' ||
1891		     isdigit((unsigned)osinfo.release[1]))) {
1892			/*
1893			 * 10.5 (Darwin 9.x), or later.
1894			 */
1895			new_dlt = find_802_11(&bdl);
1896			if (new_dlt != -1) {
1897				/*
1898				 * We have at least one 802.11 DLT_ value,
1899				 * so this is an 802.11 interface.
1900				 * new_dlt is the best of the 802.11
1901				 * DLT_ values in the list.
1902				 */
1903				if (p->opt.rfmon) {
1904					/*
1905					 * Our caller wants monitor mode.
1906					 * Purge DLT_EN10MB from the list
1907					 * of link-layer types, as selecting
1908					 * it will keep monitor mode off.
1909					 */
1910					remove_en(p);
1911
1912					/*
1913					 * If the new mode we want isn't
1914					 * the default mode, attempt to
1915					 * select the new mode.
1916					 */
1917					if (new_dlt != v) {
1918						if (ioctl(p->fd, BIOCSDLT,
1919						    &new_dlt) != -1) {
1920							/*
1921							 * We succeeded;
1922							 * make this the
1923							 * new DLT_ value.
1924							 */
1925							v = new_dlt;
1926						}
1927					}
1928				} else {
1929					/*
1930					 * Our caller doesn't want
1931					 * monitor mode.  Unless this
1932					 * is being done by pcap_open_live(),
1933					 * purge the 802.11 link-layer types
1934					 * from the list, as selecting
1935					 * one of them will turn monitor
1936					 * mode on.
1937					 */
1938					if (!p->oldstyle)
1939						remove_802_11(p);
1940				}
1941			} else {
1942				if (p->opt.rfmon) {
1943					/*
1944					 * The caller requested monitor
1945					 * mode, but we have no 802.11
1946					 * link-layer types, so they
1947					 * can't have it.
1948					 */
1949					status = PCAP_ERROR_RFMON_NOTSUP;
1950					goto bad;
1951				}
1952			}
1953		}
1954	}
1955#elif defined(HAVE_BSD_IEEE80211)
1956	/*
1957	 * *BSD with the new 802.11 ioctls.
1958	 * Do we want monitor mode?
1959	 */
1960	if (p->opt.rfmon) {
1961		/*
1962		 * Try to put the interface into monitor mode.
1963		 */
1964		status = monitor_mode(p, 1);
1965		if (status != 0) {
1966			/*
1967			 * We failed.
1968			 */
1969			goto bad;
1970		}
1971
1972		/*
1973		 * We're in monitor mode.
1974		 * Try to find the best 802.11 DLT_ value and, if we
1975		 * succeed, try to switch to that mode if we're not
1976		 * already in that mode.
1977		 */
1978		new_dlt = find_802_11(&bdl);
1979		if (new_dlt != -1) {
1980			/*
1981			 * We have at least one 802.11 DLT_ value.
1982			 * new_dlt is the best of the 802.11
1983			 * DLT_ values in the list.
1984			 *
1985			 * If the new mode we want isn't the default mode,
1986			 * attempt to select the new mode.
1987			 */
1988			if (new_dlt != v) {
1989				if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
1990					/*
1991					 * We succeeded; make this the
1992					 * new DLT_ value.
1993					 */
1994					v = new_dlt;
1995				}
1996			}
1997		}
1998	}
1999#endif /* various platforms */
2000#endif /* BIOCGDLTLIST */
2001
2002	/*
2003	 * If this is an Ethernet device, and we don't have a DLT_ list,
2004	 * give it a list with DLT_EN10MB and DLT_DOCSIS.  (That'd give
2005	 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2006	 * do, but there's not much we can do about that without finding
2007	 * some other way of determining whether it's an Ethernet or 802.11
2008	 * device.)
2009	 */
2010	if (v == DLT_EN10MB && p->dlt_count == 0) {
2011		p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2012		/*
2013		 * If that fails, just leave the list empty.
2014		 */
2015		if (p->dlt_list != NULL) {
2016			p->dlt_list[0] = DLT_EN10MB;
2017			p->dlt_list[1] = DLT_DOCSIS;
2018			p->dlt_count = 2;
2019		}
2020	}
2021#ifdef PCAP_FDDIPAD
2022	if (v == DLT_FDDI)
2023		p->fddipad = PCAP_FDDIPAD;
2024	else
2025		p->fddipad = 0;
2026#endif
2027	p->linktype = v;
2028
2029#if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2030	/*
2031	 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2032	 * the link-layer source address isn't forcibly overwritten.
2033	 * (Should we ignore errors?  Should we do this only if
2034	 * we're open for writing?)
2035	 *
2036	 * XXX - I seem to remember some packet-sending bug in some
2037	 * BSDs - check CVS log for "bpf.c"?
2038	 */
2039	if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2040		(void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2041		    "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2042		status = PCAP_ERROR;
2043		goto bad;
2044	}
2045#endif
2046	/* set timeout */
2047#ifdef HAVE_ZEROCOPY_BPF
2048	if (p->md.timeout != 0 && !p->md.zerocopy) {
2049#else
2050	if (p->md.timeout) {
2051#endif
2052		/*
2053		 * XXX - is this seconds/nanoseconds in AIX?
2054		 * (Treating it as such doesn't fix the timeout
2055		 * problem described below.)
2056		 *
2057		 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2058		 * 64-bit userland - it takes, as an argument, a
2059		 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2060		 * and tv_usec, rather than a "struct timeval".
2061		 *
2062		 * If this platform defines "struct BPF_TIMEVAL",
2063		 * we check whether the structure size in BIOCSRTIMEOUT
2064		 * is that of a "struct timeval" and, if not, we use
2065		 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2066		 * (That way, if the bug is fixed in a future release,
2067		 * we will still do the right thing.)
2068		 */
2069		struct timeval to;
2070#ifdef HAVE_STRUCT_BPF_TIMEVAL
2071		struct BPF_TIMEVAL bpf_to;
2072
2073		if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2074			bpf_to.tv_sec = p->md.timeout / 1000;
2075			bpf_to.tv_usec = (p->md.timeout * 1000) % 1000000;
2076			if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2077				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2078				    "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2079				status = PCAP_ERROR;
2080				goto bad;
2081			}
2082		} else {
2083#endif
2084			to.tv_sec = p->md.timeout / 1000;
2085			to.tv_usec = (p->md.timeout * 1000) % 1000000;
2086			if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2087				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2088				    "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2089				status = PCAP_ERROR;
2090				goto bad;
2091			}
2092#ifdef HAVE_STRUCT_BPF_TIMEVAL
2093		}
2094#endif
2095	}
2096
2097#ifdef _AIX
2098#ifdef	BIOCIMMEDIATE
2099	/*
2100	 * Darren Reed notes that
2101	 *
2102	 *	On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2103	 *	timeout appears to be ignored and it waits until the buffer
2104	 *	is filled before returning.  The result of not having it
2105	 *	set is almost worse than useless if your BPF filter
2106	 *	is reducing things to only a few packets (i.e. one every
2107	 *	second or so).
2108	 *
2109	 * so we turn BIOCIMMEDIATE mode on if this is AIX.
2110	 *
2111	 * We don't turn it on for other platforms, as that means we
2112	 * get woken up for every packet, which may not be what we want;
2113	 * in the Winter 1993 USENIX paper on BPF, they say:
2114	 *
2115	 *	Since a process might want to look at every packet on a
2116	 *	network and the time between packets can be only a few
2117	 *	microseconds, it is not possible to do a read system call
2118	 *	per packet and BPF must collect the data from several
2119	 *	packets and return it as a unit when the monitoring
2120	 *	application does a read.
2121	 *
2122	 * which I infer is the reason for the timeout - it means we
2123	 * wait that amount of time, in the hopes that more packets
2124	 * will arrive and we'll get them all with one read.
2125	 *
2126	 * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
2127	 * BSDs) causes the timeout to be ignored.
2128	 *
2129	 * On the other hand, some platforms (e.g., Linux) don't support
2130	 * timeouts, they just hand stuff to you as soon as it arrives;
2131	 * if that doesn't cause a problem on those platforms, it may
2132	 * be OK to have BIOCIMMEDIATE mode on BSD as well.
2133	 *
2134	 * (Note, though, that applications may depend on the read
2135	 * completing, even if no packets have arrived, when the timeout
2136	 * expires, e.g. GUI applications that have to check for input
2137	 * while waiting for packets to arrive; a non-zero timeout
2138	 * prevents "select()" from working right on FreeBSD and
2139	 * possibly other BSDs, as the timer doesn't start until a
2140	 * "read()" is done, so the timer isn't in effect if the
2141	 * application is blocked on a "select()", and the "select()"
2142	 * doesn't get woken up for a BPF device until the buffer
2143	 * fills up.)
2144	 */
2145	v = 1;
2146	if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2147		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
2148		    pcap_strerror(errno));
2149		status = PCAP_ERROR;
2150		goto bad;
2151	}
2152#endif	/* BIOCIMMEDIATE */
2153#endif	/* _AIX */
2154
2155	if (p->opt.promisc) {
2156		/* set promiscuous mode, just warn if it fails */
2157		if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2158			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2159			    pcap_strerror(errno));
2160			status = PCAP_WARNING_PROMISC_NOTSUP;
2161		}
2162	}
2163
2164	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2165		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2166		    pcap_strerror(errno));
2167		status = PCAP_ERROR;
2168		goto bad;
2169	}
2170	p->bufsize = v;
2171#ifdef HAVE_ZEROCOPY_BPF
2172	if (!p->md.zerocopy) {
2173#endif
2174	p->buffer = (u_char *)malloc(p->bufsize);
2175	if (p->buffer == NULL) {
2176		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2177		    pcap_strerror(errno));
2178		status = PCAP_ERROR;
2179		goto bad;
2180	}
2181#ifdef _AIX
2182	/* For some strange reason this seems to prevent the EFAULT
2183	 * problems we have experienced from AIX BPF. */
2184	memset(p->buffer, 0x0, p->bufsize);
2185#endif
2186#ifdef HAVE_ZEROCOPY_BPF
2187	}
2188#endif
2189
2190	/*
2191	 * If there's no filter program installed, there's
2192	 * no indication to the kernel of what the snapshot
2193	 * length should be, so no snapshotting is done.
2194	 *
2195	 * Therefore, when we open the device, we install
2196	 * an "accept everything" filter with the specified
2197	 * snapshot length.
2198	 */
2199	total_insn.code = (u_short)(BPF_RET | BPF_K);
2200	total_insn.jt = 0;
2201	total_insn.jf = 0;
2202	total_insn.k = p->snapshot;
2203
2204	total_prog.bf_len = 1;
2205	total_prog.bf_insns = &total_insn;
2206	if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2207		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2208		    pcap_strerror(errno));
2209		status = PCAP_ERROR;
2210		goto bad;
2211	}
2212
2213	/*
2214	 * On most BPF platforms, either you can do a "select()" or
2215	 * "poll()" on a BPF file descriptor and it works correctly,
2216	 * or you can do it and it will return "readable" if the
2217	 * hold buffer is full but not if the timeout expires *and*
2218	 * a non-blocking read will, if the hold buffer is empty
2219	 * but the store buffer isn't empty, rotate the buffers
2220	 * and return what packets are available.
2221	 *
2222	 * In the latter case, the fact that a non-blocking read
2223	 * will give you the available packets means you can work
2224	 * around the failure of "select()" and "poll()" to wake up
2225	 * and return "readable" when the timeout expires by using
2226	 * the timeout as the "select()" or "poll()" timeout, putting
2227	 * the BPF descriptor into non-blocking mode, and read from
2228	 * it regardless of whether "select()" reports it as readable
2229	 * or not.
2230	 *
2231	 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2232	 * won't wake up and return "readable" if the timer expires
2233	 * and non-blocking reads return EWOULDBLOCK if the hold
2234	 * buffer is empty, even if the store buffer is non-empty.
2235	 *
2236	 * This means the workaround in question won't work.
2237	 *
2238	 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2239	 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2240	 * here".  On all other BPF platforms, we set it to the FD for
2241	 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2242	 * read will, if the hold buffer is empty and the store buffer
2243	 * isn't empty, rotate the buffers and return what packets are
2244	 * there (and in sufficiently recent versions of OpenBSD
2245	 * "select()" and "poll()" should work correctly).
2246	 *
2247	 * XXX - what about AIX?
2248	 */
2249	p->selectable_fd = p->fd;	/* assume select() works until we know otherwise */
2250	if (have_osinfo) {
2251		/*
2252		 * We can check what OS this is.
2253		 */
2254		if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2255			if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2256			     strncmp(osinfo.release, "4.4-", 4) == 0)
2257				p->selectable_fd = -1;
2258		}
2259	}
2260
2261	p->read_op = pcap_read_bpf;
2262	p->inject_op = pcap_inject_bpf;
2263	p->setfilter_op = pcap_setfilter_bpf;
2264	p->setdirection_op = pcap_setdirection_bpf;
2265	p->set_datalink_op = pcap_set_datalink_bpf;
2266	p->getnonblock_op = pcap_getnonblock_bpf;
2267	p->setnonblock_op = pcap_setnonblock_bpf;
2268	p->stats_op = pcap_stats_bpf;
2269	p->cleanup_op = pcap_cleanup_bpf;
2270
2271	return (status);
2272 bad:
2273 	pcap_cleanup_bpf(p);
2274	return (status);
2275}
2276
2277int
2278pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2279{
2280	return (0);
2281}
2282
2283#ifdef HAVE_BSD_IEEE80211
2284static int
2285monitor_mode(pcap_t *p, int set)
2286{
2287	int sock;
2288	struct ifmediareq req;
2289	int *media_list;
2290	int i;
2291	int can_do;
2292	struct ifreq ifr;
2293
2294	sock = socket(AF_INET, SOCK_DGRAM, 0);
2295	if (sock == -1) {
2296		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2297		    pcap_strerror(errno));
2298		return (PCAP_ERROR);
2299	}
2300
2301	memset(&req, 0, sizeof req);
2302	strncpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
2303
2304	/*
2305	 * Find out how many media types we have.
2306	 */
2307	if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2308		/*
2309		 * Can't get the media types.
2310		 */
2311		switch (errno) {
2312
2313		case ENXIO:
2314			/*
2315			 * There's no such device.
2316			 */
2317			close(sock);
2318			return (PCAP_ERROR_NO_SUCH_DEVICE);
2319
2320		case EINVAL:
2321			/*
2322			 * Interface doesn't support SIOC{G,S}IFMEDIA.
2323			 */
2324			close(sock);
2325			return (PCAP_ERROR_RFMON_NOTSUP);
2326
2327		default:
2328			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2329			    "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2330			close(sock);
2331			return (PCAP_ERROR);
2332		}
2333	}
2334	if (req.ifm_count == 0) {
2335		/*
2336		 * No media types.
2337		 */
2338		close(sock);
2339		return (PCAP_ERROR_RFMON_NOTSUP);
2340	}
2341
2342	/*
2343	 * Allocate a buffer to hold all the media types, and
2344	 * get the media types.
2345	 */
2346	media_list = malloc(req.ifm_count * sizeof(int));
2347	if (media_list == NULL) {
2348		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2349		    pcap_strerror(errno));
2350		close(sock);
2351		return (PCAP_ERROR);
2352	}
2353	req.ifm_ulist = media_list;
2354	if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2355		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2356		    pcap_strerror(errno));
2357		free(media_list);
2358		close(sock);
2359		return (PCAP_ERROR);
2360	}
2361
2362	/*
2363	 * Look for an 802.11 "automatic" media type.
2364	 * We assume that all 802.11 adapters have that media type,
2365	 * and that it will carry the monitor mode supported flag.
2366	 */
2367	can_do = 0;
2368	for (i = 0; i < req.ifm_count; i++) {
2369		if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2370		    && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2371			/* OK, does it do monitor mode? */
2372			if (media_list[i] & IFM_IEEE80211_MONITOR) {
2373				can_do = 1;
2374				break;
2375			}
2376		}
2377	}
2378	free(media_list);
2379	if (!can_do) {
2380		/*
2381		 * This adapter doesn't support monitor mode.
2382		 */
2383		close(sock);
2384		return (PCAP_ERROR_RFMON_NOTSUP);
2385	}
2386
2387	if (set) {
2388		/*
2389		 * Don't just check whether we can enable monitor mode,
2390		 * do so, if it's not already enabled.
2391		 */
2392		if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2393			/*
2394			 * Monitor mode isn't currently on, so turn it on,
2395			 * and remember that we should turn it off when the
2396			 * pcap_t is closed.
2397			 */
2398
2399			/*
2400			 * If we haven't already done so, arrange to have
2401			 * "pcap_close_all()" called when we exit.
2402			 */
2403			if (!pcap_do_addexit(p)) {
2404				/*
2405				 * "atexit()" failed; don't put the interface
2406				 * in monitor mode, just give up.
2407				 */
2408				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2409				     "atexit failed");
2410				close(sock);
2411				return (PCAP_ERROR);
2412			}
2413			memset(&ifr, 0, sizeof(ifr));
2414			(void)strncpy(ifr.ifr_name, p->opt.source,
2415			    sizeof(ifr.ifr_name));
2416			ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2417			if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2418				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2419				     "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2420				close(sock);
2421				return (PCAP_ERROR);
2422			}
2423
2424			p->md.must_do_on_close |= MUST_CLEAR_RFMON;
2425
2426			/*
2427			 * Add this to the list of pcaps to close when we exit.
2428			 */
2429			pcap_add_to_pcaps_to_close(p);
2430		}
2431	}
2432	return (0);
2433}
2434#endif /* HAVE_BSD_IEEE80211 */
2435
2436#if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2437/*
2438 * Check whether we have any 802.11 link-layer types; return the best
2439 * of the 802.11 link-layer types if we find one, and return -1
2440 * otherwise.
2441 *
2442 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2443 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2444 * headers are second-best; 802.11 with no radio information is
2445 * the least good.
2446 */
2447static int
2448find_802_11(struct bpf_dltlist *bdlp)
2449{
2450	int new_dlt;
2451	int i;
2452
2453	/*
2454	 * Scan the list of DLT_ values, looking for 802.11 values,
2455	 * and, if we find any, choose the best of them.
2456	 */
2457	new_dlt = -1;
2458	for (i = 0; i < bdlp->bfl_len; i++) {
2459		switch (bdlp->bfl_list[i]) {
2460
2461		case DLT_IEEE802_11:
2462			/*
2463			 * 802.11, but no radio.
2464			 *
2465			 * Offer this, and select it as the new mode
2466			 * unless we've already found an 802.11
2467			 * header with radio information.
2468			 */
2469			if (new_dlt == -1)
2470				new_dlt = bdlp->bfl_list[i];
2471			break;
2472
2473		case DLT_PRISM_HEADER:
2474		case DLT_AIRONET_HEADER:
2475		case DLT_IEEE802_11_RADIO_AVS:
2476			/*
2477			 * 802.11 with radio, but not radiotap.
2478			 *
2479			 * Offer this, and select it as the new mode
2480			 * unless we've already found the radiotap DLT_.
2481			 */
2482			if (new_dlt != DLT_IEEE802_11_RADIO)
2483				new_dlt = bdlp->bfl_list[i];
2484			break;
2485
2486		case DLT_IEEE802_11_RADIO:
2487			/*
2488			 * 802.11 with radiotap.
2489			 *
2490			 * Offer this, and select it as the new mode.
2491			 */
2492			new_dlt = bdlp->bfl_list[i];
2493			break;
2494
2495		default:
2496			/*
2497			 * Not 802.11.
2498			 */
2499			break;
2500		}
2501	}
2502
2503	return (new_dlt);
2504}
2505#endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2506
2507#if defined(__APPLE__) && defined(BIOCGDLTLIST)
2508/*
2509 * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2510 * and DLT_EN10MB isn't supported in monitor mode.
2511 */
2512static void
2513remove_en(pcap_t *p)
2514{
2515	int i, j;
2516
2517	/*
2518	 * Scan the list of DLT_ values and discard DLT_EN10MB.
2519	 */
2520	j = 0;
2521	for (i = 0; i < p->dlt_count; i++) {
2522		switch (p->dlt_list[i]) {
2523
2524		case DLT_EN10MB:
2525			/*
2526			 * Don't offer this one.
2527			 */
2528			continue;
2529
2530		default:
2531			/*
2532			 * Just copy this mode over.
2533			 */
2534			break;
2535		}
2536
2537		/*
2538		 * Copy this DLT_ value to its new position.
2539		 */
2540		p->dlt_list[j] = p->dlt_list[i];
2541		j++;
2542	}
2543
2544	/*
2545	 * Set the DLT_ count to the number of entries we copied.
2546	 */
2547	p->dlt_count = j;
2548}
2549
2550/*
2551 * Remove 802.11 link-layer types from the list of DLT_ values, as
2552 * we're not in monitor mode, and those DLT_ values will switch us
2553 * to monitor mode.
2554 */
2555static void
2556remove_802_11(pcap_t *p)
2557{
2558	int i, j;
2559
2560	/*
2561	 * Scan the list of DLT_ values and discard 802.11 values.
2562	 */
2563	j = 0;
2564	for (i = 0; i < p->dlt_count; i++) {
2565		switch (p->dlt_list[i]) {
2566
2567		case DLT_IEEE802_11:
2568		case DLT_PRISM_HEADER:
2569		case DLT_AIRONET_HEADER:
2570		case DLT_IEEE802_11_RADIO:
2571		case DLT_IEEE802_11_RADIO_AVS:
2572			/*
2573			 * 802.11.  Don't offer this one.
2574			 */
2575			continue;
2576
2577		default:
2578			/*
2579			 * Just copy this mode over.
2580			 */
2581			break;
2582		}
2583
2584		/*
2585		 * Copy this DLT_ value to its new position.
2586		 */
2587		p->dlt_list[j] = p->dlt_list[i];
2588		j++;
2589	}
2590
2591	/*
2592	 * Set the DLT_ count to the number of entries we copied.
2593	 */
2594	p->dlt_count = j;
2595}
2596#endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2597
2598static int
2599pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2600{
2601	/*
2602	 * Free any user-mode filter we might happen to have installed.
2603	 */
2604	pcap_freecode(&p->fcode);
2605
2606	/*
2607	 * Try to install the kernel filter.
2608	 */
2609	if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
2610		/*
2611		 * It worked.
2612		 */
2613		p->md.use_bpf = 1;	/* filtering in the kernel */
2614
2615		/*
2616		 * Discard any previously-received packets, as they might
2617		 * have passed whatever filter was formerly in effect, but
2618		 * might not pass this filter (BIOCSETF discards packets
2619		 * buffered in the kernel, so you can lose packets in any
2620		 * case).
2621		 */
2622		p->cc = 0;
2623		return (0);
2624	}
2625
2626	/*
2627	 * We failed.
2628	 *
2629	 * If it failed with EINVAL, that's probably because the program
2630	 * is invalid or too big.  Validate it ourselves; if we like it
2631	 * (we currently allow backward branches, to support protochain),
2632	 * run it in userland.  (There's no notion of "too big" for
2633	 * userland.)
2634	 *
2635	 * Otherwise, just give up.
2636	 * XXX - if the copy of the program into the kernel failed,
2637	 * we will get EINVAL rather than, say, EFAULT on at least
2638	 * some kernels.
2639	 */
2640	if (errno != EINVAL) {
2641		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2642		    pcap_strerror(errno));
2643		return (-1);
2644	}
2645
2646	/*
2647	 * install_bpf_program() validates the program.
2648	 *
2649	 * XXX - what if we already have a filter in the kernel?
2650	 */
2651	if (install_bpf_program(p, fp) < 0)
2652		return (-1);
2653	p->md.use_bpf = 0;	/* filtering in userland */
2654	return (0);
2655}
2656
2657/*
2658 * Set direction flag: Which packets do we accept on a forwarding
2659 * single device? IN, OUT or both?
2660 */
2661static int
2662pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
2663{
2664#if defined(BIOCSDIRECTION)
2665	u_int direction;
2666
2667	direction = (d == PCAP_D_IN) ? BPF_D_IN :
2668	    ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
2669	if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
2670		(void) snprintf(p->errbuf, sizeof(p->errbuf),
2671		    "Cannot set direction to %s: %s",
2672		        (d == PCAP_D_IN) ? "PCAP_D_IN" :
2673			((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
2674			strerror(errno));
2675		return (-1);
2676	}
2677	return (0);
2678#elif defined(BIOCSSEESENT)
2679	u_int seesent;
2680
2681	/*
2682	 * We don't support PCAP_D_OUT.
2683	 */
2684	if (d == PCAP_D_OUT) {
2685		snprintf(p->errbuf, sizeof(p->errbuf),
2686		    "Setting direction to PCAP_D_OUT is not supported on BPF");
2687		return -1;
2688	}
2689
2690	seesent = (d == PCAP_D_INOUT);
2691	if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
2692		(void) snprintf(p->errbuf, sizeof(p->errbuf),
2693		    "Cannot set direction to %s: %s",
2694		        (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
2695			strerror(errno));
2696		return (-1);
2697	}
2698	return (0);
2699#else
2700	(void) snprintf(p->errbuf, sizeof(p->errbuf),
2701	    "This system doesn't support BIOCSSEESENT, so the direction can't be set");
2702	return (-1);
2703#endif
2704}
2705
2706static int
2707pcap_set_datalink_bpf(pcap_t *p, int dlt)
2708{
2709#ifdef BIOCSDLT
2710	if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
2711		(void) snprintf(p->errbuf, sizeof(p->errbuf),
2712		    "Cannot set DLT %d: %s", dlt, strerror(errno));
2713		return (-1);
2714	}
2715#endif
2716	return (0);
2717}
2718