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