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