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