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