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