xref: /openbsd/lib/libpcap/pcap-bpf.c (revision a6445c1d)
1 /*	$OpenBSD: pcap-bpf.c,v 1.24 2014/10/16 20:08:21 deraadt Exp $	*/
2 
3 /*
4  * Copyright (c) 1993, 1994, 1995, 1996, 1998
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that: (1) source code distributions
9  * retain the above copyright notice and this paragraph in its entirety, (2)
10  * distributions including binary code include the above copyright notice and
11  * this paragraph in its entirety in the documentation or other materials
12  * provided with the distribution, and (3) all advertising materials mentioning
13  * features or use of this software display the following acknowledgement:
14  * ``This product includes software developed by the University of California,
15  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16  * the University nor the names of its contributors may be used to endorse
17  * or promote products derived from this software without specific prior
18  * written permission.
19  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22  */
23 
24 #include <sys/param.h>			/* optionally get BSD define */
25 #include <sys/time.h>
26 #include <sys/socket.h>
27 #include <sys/ioctl.h>
28 
29 #include <net/if.h>
30 
31 #include <ctype.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <netdb.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 
40 #include <net/if_media.h>
41 
42 #include "pcap-int.h"
43 
44 #ifdef HAVE_OS_PROTO_H
45 #include "os-proto.h"
46 #endif
47 
48 #include "gencode.h"
49 
50 static int find_802_11(struct bpf_dltlist *);
51 static int monitor_mode(pcap_t *, int);
52 
53 int
54 pcap_stats(pcap_t *p, struct pcap_stat *ps)
55 {
56 	struct bpf_stat s;
57 
58 	if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
59 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
60 		    pcap_strerror(errno));
61 		return (PCAP_ERROR);
62 	}
63 
64 	ps->ps_recv = s.bs_recv;
65 	ps->ps_drop = s.bs_drop;
66 	return (0);
67 }
68 
69 int
70 pcap_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
71 {
72 	int cc;
73 	int n = 0;
74 	register u_char *bp, *ep;
75 
76  again:
77 	/*
78 	 * Has "pcap_breakloop()" been called?
79 	 */
80 	if (p->break_loop) {
81 		/*
82 		 * Yes - clear the flag that indicates that it
83 		 * has, and return PCAP_ERROR_BREAK to indicate
84 		 * that we were told to break out of the loop.
85 		 */
86 		p->break_loop = 0;
87 		return (PCAP_ERROR_BREAK);
88 	}
89 
90 	cc = p->cc;
91 	if (p->cc == 0) {
92 		cc = read(p->fd, (char *)p->buffer, p->bufsize);
93 		if (cc < 0) {
94 			/* Don't choke when we get ptraced */
95 			switch (errno) {
96 
97 			case EINTR:
98 				goto again;
99 
100 			case EWOULDBLOCK:
101 				return (0);
102 
103 			case ENXIO:
104 				/*
105 				 * The device on which we're capturing
106 				 * went away.
107 				 *
108 				 * XXX - we should really return
109 				 * PCAP_ERROR_IFACE_NOT_UP, but
110 				 * pcap_dispatch() etc. aren't
111 				 * defined to return that.
112 				 */
113 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
114 				    "The interface went down");
115 				return (PCAP_ERROR);
116 
117 #if defined(sun) && !defined(BSD)
118 			/*
119 			 * Due to a SunOS bug, after 2^31 bytes, the kernel
120 			 * file offset overflows and read fails with EINVAL.
121 			 * The lseek() to 0 will fix things.
122 			 */
123 			case EINVAL:
124 				if (lseek(p->fd, 0L, SEEK_CUR) +
125 				    p->bufsize < 0) {
126 					(void)lseek(p->fd, 0L, SEEK_SET);
127 					goto again;
128 				}
129 				/* FALLTHROUGH */
130 #endif
131 			}
132 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
133 			    pcap_strerror(errno));
134 			return (PCAP_ERROR);
135 		}
136 		bp = p->buffer;
137 	} else
138 		bp = p->bp;
139 
140 	/*
141 	 * Loop through each packet.
142 	 */
143 #define bhp ((struct bpf_hdr *)bp)
144 	ep = bp + cc;
145 	while (bp < ep) {
146 		register int caplen, hdrlen;
147 
148 		/*
149 		 * Has "pcap_breakloop()" been called?
150 		 * If so, return immediately - if we haven't read any
151 		 * packets, clear the flag and return PCAP_ERROR_BREAK
152 		 * to indicate that we were told to break out of the loop,
153 		 * otherwise leave the flag set, so that the *next* call
154 		 * will break out of the loop without having read any
155 		 * packets, and return the number of packets we've
156 		 * processed so far.
157 		 */
158 		if (p->break_loop) {
159 			p->bp = bp;
160 			p->cc = ep - bp;
161 			/*
162 			 * ep is set based on the return value of read(),
163 			 * but read() from a BPF device doesn't necessarily
164 			 * return a value that's a multiple of the alignment
165 			 * value for BPF_WORDALIGN().  However, whenever we
166 			 * increment bp, we round up the increment value by
167 			 * a value rounded up by BPF_WORDALIGN(), so we
168 			 * could increment bp past ep after processing the
169 			 * last packet in the buffer.
170 			 *
171 			 * We treat ep < bp as an indication that this
172 			 * happened, and just set p->cc to 0.
173 			 */
174 			if (p->cc < 0)
175 				p->cc = 0;
176 			if (n == 0) {
177 				p->break_loop = 0;
178 				return (PCAP_ERROR_BREAK);
179 			} else
180 				return (n);
181 		}
182 
183 		caplen = bhp->bh_caplen;
184 		hdrlen = bhp->bh_hdrlen;
185 		/*
186 		 * XXX A bpf_hdr matches a pcap_pkthdr.
187 		 */
188 		(*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
189 		bp += BPF_WORDALIGN(caplen + hdrlen);
190 		if (++n >= cnt && cnt > 0) {
191 			p->bp = bp;
192 			p->cc = ep - bp;
193 			return (n);
194 		}
195 	}
196 #undef bhp
197 	p->cc = 0;
198 	return (n);
199 }
200 
201 int
202 pcap_inject(pcap_t *p, const void *buf, size_t len)
203 {
204 	return (write(p->fd, buf, len));
205 }
206 
207 int
208 pcap_sendpacket(pcap_t *p, const u_char *buf, int size)
209 {
210 	return (pcap_inject(p, buf, size) == -1 ? -1 : 0);
211 }
212 
213 /* ARGSUSED */
214 static __inline int
215 bpf_open(pcap_t *p)
216 {
217 	int fd;
218 	int n = 0;
219 	char device[sizeof "/dev/bpf0000000000"];
220 
221 	/*
222 	 * Go through all the minors and find one that isn't in use.
223 	 */
224 	do {
225 		(void)snprintf(device, sizeof device, "/dev/bpf%d", n++);
226 		fd = open(device, O_RDWR);
227 		if (fd < 0 && errno == EACCES)
228 			fd = open(device, O_RDONLY);
229 	} while (fd < 0 && errno == EBUSY);
230 
231 	/*
232 	 * XXX better message for all minors used
233 	 */
234 	if (fd < 0) {
235 		switch (errno) {
236 
237 		case ENOENT:
238 			fd = PCAP_ERROR;
239 			if (n == 1) {
240 				/*
241 				 * /dev/bpf0 doesn't exist, which
242 				 * means we probably have no BPF
243 				 * devices.
244 				 */
245 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
246 				    "(there are no BPF devices)");
247 			} else {
248 				/*
249 				 * We got EBUSY on at least one
250 				 * BPF device, so we have BPF
251 				 * devices, but all the ones
252 				 * that exist are busy.
253 				 */
254 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
255 				    "(all BPF devices are busy)");
256 			}
257 			break;
258 
259 		case EACCES:
260 			/*
261 			 * Got EACCES on the last device we tried,
262 			 * and EBUSY on all devices before that,
263 			 * if any.
264 			 */
265 			fd = PCAP_ERROR_PERM_DENIED;
266 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
267 			    "(cannot open BPF device) %s: %s", device,
268 			    pcap_strerror(errno));
269 			break;
270 
271 		default:
272 			/*
273 			 * Some other problem.
274 			 */
275 			fd = PCAP_ERROR;
276 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
277 			    "(cannot open BPF device) %s: %s", device,
278 			    pcap_strerror(errno));
279 			break;
280 		}
281 	}
282 
283 	return (fd);
284 }
285 
286 static int
287 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
288 {
289 	memset(bdlp, 0, sizeof(*bdlp));
290 	if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
291 		bdlp->bfl_list = (u_int *) calloc(bdlp->bfl_len + 1, sizeof(u_int));
292 		if (bdlp->bfl_list == NULL) {
293 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
294 			    pcap_strerror(errno));
295 			return (PCAP_ERROR);
296 		}
297 
298 		if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
299 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
300 			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
301 			free(bdlp->bfl_list);
302 			return (PCAP_ERROR);
303 		}
304 	} else {
305 		/*
306 		 * EINVAL just means "we don't support this ioctl on
307 		 * this device"; don't treat it as an error.
308 		 */
309 		if (errno != EINVAL) {
310 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
311 			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
312 			return (PCAP_ERROR);
313 		}
314 	}
315 	return (0);
316 }
317 
318 /*
319  * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
320  * a PCAP_ERROR value on an error.
321  */
322 int
323 pcap_can_set_rfmon(pcap_t *p)
324 {
325 #if defined(HAVE_BSD_IEEE80211)
326 	int ret;
327 
328 	ret = monitor_mode(p, 0);
329 	if (ret == PCAP_ERROR_RFMON_NOTSUP)
330 		return (0);	/* not an error, just a "can't do" */
331 	if (ret == 0)
332 		return (1);	/* success */
333 	return (ret);
334 #else
335 	return (0);
336 #endif
337 }
338 
339 static void
340 pcap_cleanup_bpf(pcap_t *p)
341 {
342 #ifdef HAVE_BSD_IEEE80211
343 	int sock;
344 	struct ifmediareq req;
345 	struct ifreq ifr;
346 #endif
347 
348 	if (p->md.must_do_on_close != 0) {
349 		/*
350 		 * There's something we have to do when closing this
351 		 * pcap_t.
352 		 */
353 #ifdef HAVE_BSD_IEEE80211
354 		if (p->md.must_do_on_close & MUST_CLEAR_RFMON) {
355 			/*
356 			 * We put the interface into rfmon mode;
357 			 * take it out of rfmon mode.
358 			 *
359 			 * XXX - if somebody else wants it in rfmon
360 			 * mode, this code cannot know that, so it'll take
361 			 * it out of rfmon mode.
362 			 */
363 			sock = socket(AF_INET, SOCK_DGRAM, 0);
364 			if (sock == -1) {
365 				fprintf(stderr,
366 				    "Can't restore interface flags (socket() failed: %s).\n"
367 				    "Please adjust manually.\n",
368 				    strerror(errno));
369 			} else {
370 				memset(&req, 0, sizeof(req));
371 				(void)strlcpy(req.ifm_name, p->opt.source,
372 				    sizeof(req.ifm_name));
373 				if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
374 					fprintf(stderr,
375 					    "Can't restore interface flags "
376 					    "(SIOCGIFMEDIA failed: %s).\n"
377 					    "Please adjust manually.\n",
378 					    strerror(errno));
379 				} else if (req.ifm_current & IFM_IEEE80211_MONITOR) {
380 					/*
381 					 * Rfmon mode is currently on;
382 					 * turn it off.
383 					 */
384 					memset(&ifr, 0, sizeof(ifr));
385 					(void)strlcpy(ifr.ifr_name,
386 					    p->opt.source,
387 					    sizeof(ifr.ifr_name));
388 					ifr.ifr_media =
389 					    req.ifm_current & ~IFM_IEEE80211_MONITOR;
390 					if (ioctl(sock, SIOCSIFMEDIA,
391 					    &ifr) == -1) {
392 						fprintf(stderr,
393 						    "Can't restore interface flags "
394 						    "(SIOCSIFMEDIA failed: %s).\n"
395 						    "Please adjust manually.\n",
396 						    strerror(errno));
397 					}
398 				}
399 				close(sock);
400 			}
401 		}
402 #endif /* HAVE_BSD_IEEE80211 */
403 
404 		/*
405 		 * Take this pcap out of the list of pcaps for which we
406 		 * have to take the interface out of some mode.
407 		 */
408 		pcap_remove_from_pcaps_to_close(p);
409 		p->md.must_do_on_close = 0;
410 	}
411 
412 	/*XXX*/
413 	if (p->fd >= 0) {
414 		close(p->fd);
415 		p->fd = -1;
416 	}
417 	if (p->sf.rfile != NULL) {
418 		(void)fclose(p->sf.rfile);
419 		if (p->sf.base != NULL)
420 			free(p->sf.base);
421 	} else if (p->buffer != NULL)
422 		free(p->buffer);
423 	pcap_freecode(&p->fcode);
424 	if (p->dlt_list != NULL) {
425 		free(p->dlt_list);
426 		p->dlt_list = NULL;
427 		p->dlt_count = 0;
428 	}
429 }
430 
431 void
432 pcap_close(pcap_t *p)
433 {
434 	if (p->opt.source != NULL)
435 		free(p->opt.source);
436 	pcap_cleanup_bpf(p);
437 	free(p);
438 }
439 
440 
441 static int
442 check_setif_failure(pcap_t *p, int error)
443 {
444 	if (error == ENXIO) {
445 		/*
446 		 * No such device.
447 		 */
448 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
449 		    pcap_strerror(errno));
450 		return (PCAP_ERROR_NO_SUCH_DEVICE);
451 	} else if (errno == ENETDOWN) {
452 		/*
453 		 * Return a "network down" indication, so that
454 		 * the application can report that rather than
455 		 * saying we had a mysterious failure and
456 		 * suggest that they report a problem to the
457 		 * libpcap developers.
458 		 */
459 		return (PCAP_ERROR_IFACE_NOT_UP);
460 	} else {
461 		/*
462 		 * Some other error; fill in the error string, and
463 		 * return PCAP_ERROR.
464 		 */
465 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
466 		    p->opt.source, pcap_strerror(errno));
467 		return (PCAP_ERROR);
468 	}
469 }
470 
471 int
472 pcap_activate(pcap_t *p)
473 {
474 	int status = 0;
475 	int fd;
476 	struct ifreq ifr;
477 	struct bpf_version bv;
478 	struct bpf_dltlist bdl;
479 	int new_dlt;
480 	u_int v;
481 
482 	fd = bpf_open(p);
483 	if (fd < 0) {
484 		status = fd;
485 		goto bad;
486 	}
487 
488 	p->fd = fd;
489 
490 	if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
491 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
492 		    pcap_strerror(errno));
493 		status = PCAP_ERROR;
494 		goto bad;
495 	}
496 	if (bv.bv_major != BPF_MAJOR_VERSION ||
497 	    bv.bv_minor < BPF_MINOR_VERSION) {
498 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
499 		    "kernel bpf filter out of date");
500 		status = PCAP_ERROR;
501 		goto bad;
502 	}
503 
504 #if 0
505 	/* Just use the kernel default */
506 	v = 32768;	/* XXX this should be a user-accessible hook */
507 	/* Ignore the return value - this is because the call fails on
508 	 * BPF systems that don't have kernel malloc.  And if the call
509 	 * fails, it's no big deal, we just continue to use the standard
510 	 * buffer size.
511 	 */
512 	(void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
513 #endif
514 
515 	/*
516 	 * Set the buffer size.
517 	 */
518 	if (p->opt.buffer_size != 0) {
519 		/*
520 		 * A buffer size was explicitly specified; use it.
521 		 */
522 		if (ioctl(fd, BIOCSBLEN,
523 		    (caddr_t)&p->opt.buffer_size) < 0) {
524 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
525 			    "BIOCSBLEN: %s: %s", p->opt.source,
526 			    pcap_strerror(errno));
527 			status = PCAP_ERROR;
528 			goto bad;
529 		}
530 	}
531 
532 	/*
533 	 * Now bind to the device.
534 	 */
535 	(void)strlcpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
536 	if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
537 		status = check_setif_failure(p, errno);
538 		goto bad;
539 	}
540 	/* Get the data link layer type. */
541 	if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
542 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
543 		    pcap_strerror(errno));
544 		status = PCAP_ERROR;
545 		goto bad;
546 	}
547 #if _BSDI_VERSION - 0 >= 199510
548 	/* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
549 	switch (v) {
550 
551 	case DLT_SLIP:
552 		v = DLT_SLIP_BSDOS;
553 		break;
554 
555 	case DLT_PPP:
556 		v = DLT_PPP_BSDOS;
557 		break;
558 
559 	case 11:	/*DLT_FR*/
560 		v = DLT_FRELAY;
561 		break;
562 
563 	case 12:	/*DLT_C_HDLC*/
564 		v = DLT_CHDLC;
565 		break;
566 	}
567 #endif
568 
569 	/*
570 	 * We know the default link type -- now determine all the DLTs
571 	 * this interface supports.  If this fails with EINVAL, it's
572 	 * not fatal; we just don't get to use the feature later.
573 	 */
574 	if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
575 		status = PCAP_ERROR;
576 		goto bad;
577 	}
578 	p->dlt_count = bdl.bfl_len;
579 	p->dlt_list = bdl.bfl_list;
580 
581 	/*
582 	 * *BSD with the new 802.11 ioctls.
583 	 * Do we want monitor mode?
584 	 */
585 	if (p->opt.rfmon) {
586 		/*
587 		 * Try to put the interface into monitor mode.
588 		 */
589 		status = monitor_mode(p, 1);
590 		if (status != 0) {
591 			/*
592 			 * We failed.
593 			 */
594 			goto bad;
595 		}
596 
597 		/*
598 		 * We're in monitor mode.
599 		 * Try to find the best 802.11 DLT_ value and, if we
600 		 * succeed, try to switch to that mode if we're not
601 		 * already in that mode.
602 		 */
603 		new_dlt = find_802_11(&bdl);
604 		if (new_dlt != -1) {
605 			/*
606 			 * We have at least one 802.11 DLT_ value.
607 			 * new_dlt is the best of the 802.11
608 			 * DLT_ values in the list.
609 			 *
610 			 * If the new mode we want isn't the default mode,
611 			 * attempt to select the new mode.
612 			 */
613 			if (new_dlt != v) {
614 				if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
615 					/*
616 					 * We succeeded; make this the
617 					 * new DLT_ value.
618 					 */
619 					v = new_dlt;
620 				}
621 			}
622 		}
623 	}
624 	p->linktype = v;
625 
626 	/* set timeout */
627 	if (p->md.timeout) {
628 		struct timeval to;
629 		to.tv_sec = p->md.timeout / 1000;
630 		to.tv_usec = (p->md.timeout * 1000) % 1000000;
631 		if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
632 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
633 			    "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
634 			status = PCAP_ERROR;
635 			goto bad;
636 		}
637 	}
638 
639 	if (p->opt.promisc) {
640 		/* set promiscuous mode, just warn if it fails */
641 		if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
642 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
643 			    pcap_strerror(errno));
644 			status = PCAP_WARNING_PROMISC_NOTSUP;
645 		}
646 	}
647 
648 	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
649 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
650 		    pcap_strerror(errno));
651 		status = PCAP_ERROR;
652 		goto bad;
653 	}
654 	p->bufsize = v;
655 	p->buffer = (u_char *)malloc(p->bufsize);
656 	if (p->buffer == NULL) {
657 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
658 		    pcap_strerror(errno));
659 		status = PCAP_ERROR;
660 		goto bad;
661 	}
662 
663 	if (status < 0)
664 		goto bad;
665 
666 	p->activated = 1;
667 
668 	return (status);
669  bad:
670 	pcap_cleanup_bpf(p);
671 
672 	if (p->errbuf[0] == '\0') {
673 		/*
674 		 * No error message supplied by the activate routine;
675 		 * for the benefit of programs that don't specially
676 		 * handle errors other than PCAP_ERROR, return the
677 		 * error message corresponding to the status.
678 		 */
679 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
680 		    pcap_statustostr(status));
681 	}
682 
683 	return (status);
684 }
685 
686 static int
687 monitor_mode(pcap_t *p, int set)
688 {
689 	int sock;
690 	struct ifmediareq req;
691 	int *media_list;
692 	int i;
693 	int can_do;
694 	struct ifreq ifr;
695 
696 	sock = socket(AF_INET, SOCK_DGRAM, 0);
697 	if (sock == -1) {
698 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
699 		    pcap_strerror(errno));
700 		return (PCAP_ERROR);
701 	}
702 
703 	memset(&req, 0, sizeof req);
704 	(void)strlcpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
705 
706 	/*
707 	 * Find out how many media types we have.
708 	 */
709 	if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
710 		/*
711 		 * Can't get the media types.
712 		 */
713 		switch (errno) {
714 
715 		case ENXIO:
716 			/*
717 			 * There's no such device.
718 			 */
719 			close(sock);
720 			return (PCAP_ERROR_NO_SUCH_DEVICE);
721 
722 		case EINVAL:
723 			/*
724 			 * Interface doesn't support SIOC{G,S}IFMEDIA.
725 			 */
726 			close(sock);
727 			return (PCAP_ERROR_RFMON_NOTSUP);
728 
729 		default:
730 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
731 			    "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
732 			close(sock);
733 			return (PCAP_ERROR);
734 		}
735 	}
736 	if (req.ifm_count == 0) {
737 		/*
738 		 * No media types.
739 		 */
740 		close(sock);
741 		return (PCAP_ERROR_RFMON_NOTSUP);
742 	}
743 
744 	/*
745 	 * Allocate a buffer to hold all the media types, and
746 	 * get the media types.
747 	 */
748 	media_list = (int *) calloc(req.ifm_count, sizeof(int));
749 	if (media_list == NULL) {
750 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
751 		    pcap_strerror(errno));
752 		close(sock);
753 		return (PCAP_ERROR);
754 	}
755 	req.ifm_ulist = media_list;
756 	if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
757 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
758 		    pcap_strerror(errno));
759 		free(media_list);
760 		close(sock);
761 		return (PCAP_ERROR);
762 	}
763 
764 	/*
765 	 * Look for an 802.11 "automatic" media type.
766 	 * We assume that all 802.11 adapters have that media type,
767 	 * and that it will carry the monitor mode supported flag.
768 	 */
769 	can_do = 0;
770 	for (i = 0; i < req.ifm_count; i++) {
771 		if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
772 		    && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
773 			/* OK, does it do monitor mode? */
774 			if (media_list[i] & IFM_IEEE80211_MONITOR) {
775 				can_do = 1;
776 				break;
777 			}
778 		}
779 	}
780 	free(media_list);
781 	if (!can_do) {
782 		/*
783 		 * This adapter doesn't support monitor mode.
784 		 */
785 		close(sock);
786 		return (PCAP_ERROR_RFMON_NOTSUP);
787 	}
788 
789 	if (set) {
790 		/*
791 		 * Don't just check whether we can enable monitor mode,
792 		 * do so, if it's not already enabled.
793 		 */
794 		if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
795 			/*
796 			 * Monitor mode isn't currently on, so turn it on,
797 			 * and remember that we should turn it off when the
798 			 * pcap_t is closed.
799 			 */
800 
801 			/*
802 			 * If we haven't already done so, arrange to have
803 			 * "pcap_close_all()" called when we exit.
804 			 */
805 			if (!pcap_do_addexit(p)) {
806 				/*
807 				 * "atexit()" failed; don't put the interface
808 				 * in monitor mode, just give up.
809 				 */
810 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
811 				     "atexit failed");
812 				close(sock);
813 				return (PCAP_ERROR);
814 			}
815 			memset(&ifr, 0, sizeof(ifr));
816 			(void)strlcpy(ifr.ifr_name, p->opt.source,
817 			    sizeof(ifr.ifr_name));
818 			ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
819 			if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
820 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
821 				     "SIOCSIFMEDIA: %s", pcap_strerror(errno));
822 				close(sock);
823 				return (PCAP_ERROR);
824 			}
825 
826 			p->md.must_do_on_close |= MUST_CLEAR_RFMON;
827 
828 			/*
829 			 * Add this to the list of pcaps to close when we exit.
830 			 */
831 			pcap_add_to_pcaps_to_close(p);
832 		}
833 	}
834 	return (0);
835 }
836 
837 /*
838  * Check whether we have any 802.11 link-layer types; return the best
839  * of the 802.11 link-layer types if we find one, and return -1
840  * otherwise.
841  *
842  * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
843  * best 802.11 link-layer type; any of the other 802.11-plus-radio
844  * headers are second-best; 802.11 with no radio information is
845  * the least good.
846  */
847 static int
848 find_802_11(struct bpf_dltlist *bdlp)
849 {
850 	int new_dlt;
851 	int i;
852 
853 	/*
854 	 * Scan the list of DLT_ values, looking for 802.11 values,
855 	 * and, if we find any, choose the best of them.
856 	 */
857 	new_dlt = -1;
858 	for (i = 0; i < bdlp->bfl_len; i++) {
859 		switch (bdlp->bfl_list[i]) {
860 
861 		case DLT_IEEE802_11:
862 			/*
863 			 * 802.11, but no radio.
864 			 *
865 			 * Offer this, and select it as the new mode
866 			 * unless we've already found an 802.11
867 			 * header with radio information.
868 			 */
869 			if (new_dlt == -1)
870 				new_dlt = bdlp->bfl_list[i];
871 			break;
872 
873 		case DLT_IEEE802_11_RADIO:
874 			/*
875 			 * 802.11 with radiotap.
876 			 *
877 			 * Offer this, and select it as the new mode.
878 			 */
879 			new_dlt = bdlp->bfl_list[i];
880 			break;
881 
882 		default:
883 			/*
884 			 * Not 802.11.
885 			 */
886 			break;
887 		}
888 	}
889 
890 	return (new_dlt);
891 }
892 
893 pcap_t *
894 pcap_create(const char *device, char *ebuf)
895 {
896 	pcap_t *p;
897 
898 	p = calloc(1, sizeof(*p));
899 	if (p == NULL) {
900 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
901 		    pcap_strerror(errno));
902 		return (NULL);
903 	}
904 	p->fd = -1;	/* not opened yet */
905 
906 	p->opt.source = strdup(device);
907 	if (p->opt.source == NULL) {
908 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
909 		    pcap_strerror(errno));
910 		free(p);
911 		return (NULL);
912 	}
913 
914 	/* put in some defaults*/
915 	pcap_set_timeout(p, 0);
916 	pcap_set_snaplen(p, 65535);	/* max packet size */
917 	p->opt.promisc = 0;
918 	p->opt.buffer_size = 0;
919 	return (p);
920 }
921 
922 pcap_t *
923 pcap_open_live(const char *source, int snaplen, int promisc, int to_ms,
924     char *errbuf)
925 {
926 	pcap_t *p;
927 	int status;
928 
929 	p = pcap_create(source, errbuf);
930 	if (p == NULL)
931 		return (NULL);
932 	status = pcap_set_snaplen(p, snaplen);
933 	if (status < 0)
934 		goto fail;
935 	status = pcap_set_promisc(p, promisc);
936 	if (status < 0)
937 		goto fail;
938 	status = pcap_set_timeout(p, to_ms);
939 	if (status < 0)
940 		goto fail;
941 	/*
942 	 * Mark this as opened with pcap_open_live(), so that, for
943 	 * example, we show the full list of DLT_ values, rather
944 	 * than just the ones that are compatible with capturing
945 	 * when not in monitor mode.  That allows existing applications
946 	 * to work the way they used to work, but allows new applications
947 	 * that know about the new open API to, for example, find out the
948 	 * DLT_ values that they can select without changing whether
949 	 * the adapter is in monitor mode or not.
950 	 */
951 	p->oldstyle = 1;
952 	status = pcap_activate(p);
953 	if (status < 0)
954 		goto fail;
955 	return (p);
956 fail:
957 	if (status == PCAP_ERROR)
958 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
959 		    p->errbuf);
960 	else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
961 	    status == PCAP_ERROR_PERM_DENIED ||
962 	    status == PCAP_ERROR_PROMISC_PERM_DENIED)
963 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", source,
964 		    pcap_statustostr(status), p->errbuf);
965 	else
966 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
967 		    pcap_statustostr(status));
968 	pcap_close(p);
969 	return (NULL);
970 }
971 
972 int
973 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
974 {
975 	/*
976 	 * It looks that BPF code generated by gen_protochain() is not
977 	 * compatible with some of kernel BPF code (for example BSD/OS 3.1).
978 	 * Take a safer side for now.
979 	 */
980 	if (no_optimize || (p->sf.rfile != NULL)){
981 		if (p->fcode.bf_insns != NULL)
982 			pcap_freecode(&p->fcode);
983 		p->fcode.bf_len = fp->bf_len;
984 		p->fcode.bf_insns = reallocarray(NULL,
985 		    fp->bf_len, sizeof(*fp->bf_insns));
986 		if (p->fcode.bf_insns == NULL) {
987 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
988 			    pcap_strerror(errno));
989 			return (-1);
990 		}
991 		memcpy(p->fcode.bf_insns, fp->bf_insns,
992 		    fp->bf_len * sizeof(*fp->bf_insns));
993 	} else if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) < 0) {
994 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
995 		    pcap_strerror(errno));
996 		return (-1);
997 	}
998 	return (0);
999 }
1000 
1001 int
1002 pcap_setdirection(pcap_t *p, pcap_direction_t d)
1003 {
1004 	u_int dirfilt;
1005 
1006 	switch (d) {
1007 	case PCAP_D_INOUT:
1008 		dirfilt = 0;
1009 		break;
1010 	case PCAP_D_IN:
1011 		dirfilt = BPF_DIRECTION_OUT;
1012 		break;
1013 	case PCAP_D_OUT:
1014 		dirfilt = BPF_DIRECTION_IN;
1015 		break;
1016 	default:
1017 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Invalid direction");
1018 		return (-1);
1019 	}
1020 	if (ioctl(p->fd, BIOCSDIRFILT, &dirfilt) < 0) {
1021 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSDIRFILT: %s",
1022 		    pcap_strerror(errno));
1023 		return (-1);
1024 	}
1025 	return (0);
1026 }
1027 
1028 int
1029 pcap_set_datalink(pcap_t *p, int dlt)
1030 {
1031 	int i;
1032 
1033 	if (p->dlt_count == 0) {
1034 		/*
1035 		 * We couldn't fetch the list of DLTs, or we don't
1036 		 * have a "set datalink" operation, which means
1037 		 * this platform doesn't support changing the
1038 		 * DLT for an interface.  Check whether the new
1039 		 * DLT is the one this interface supports.
1040 		 */
1041 		if (p->linktype != dlt)
1042 			goto unsupported;
1043 
1044 		/*
1045 		 * It is, so there's nothing we need to do here.
1046 		 */
1047 		return (0);
1048 	}
1049 	for (i = 0; i < p->dlt_count; i++)
1050 		if (p->dlt_list[i] == dlt)
1051 			break;
1052 	if (i >= p->dlt_count)
1053 		goto unsupported;
1054 	if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
1055 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
1056 		    "Cannot set DLT %d: %s", dlt, strerror(errno));
1057 		return (-1);
1058 	}
1059 	p->linktype = dlt;
1060 	return (0);
1061 
1062 unsupported:
1063 	(void) snprintf(p->errbuf, sizeof(p->errbuf),
1064 	    "DLT %d is not one of the DLTs supported by this device",
1065 	    dlt);
1066 	return (-1);
1067 }
1068 
1069