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