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