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