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