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