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