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