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