xref: /openbsd/lib/libpcap/pcap-bpf.c (revision 09467b48)
1 /*	$OpenBSD: pcap-bpf.c,v 1.37 2019/06/28 13:32:42 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) == -1) {
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 	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 == -1) {
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 		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 
219 	fd = open("/dev/bpf", O_RDWR);
220 	if (fd == -1 && errno == EACCES)
221 		fd = open("/dev/bpf", O_RDONLY);
222 
223 	if (fd == -1) {
224 		if (errno == EACCES)
225 			fd = PCAP_ERROR_PERM_DENIED;
226 		else
227 			fd = PCAP_ERROR;
228 
229 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
230 		    "(cannot open BPF device): %s",
231 		    pcap_strerror(errno));
232 	}
233 
234 	return (fd);
235 }
236 
237 static int
238 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
239 {
240 	memset(bdlp, 0, sizeof(*bdlp));
241 	if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
242 		bdlp->bfl_list = calloc(bdlp->bfl_len + 1, sizeof(u_int));
243 		if (bdlp->bfl_list == NULL) {
244 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
245 			    pcap_strerror(errno));
246 			return (PCAP_ERROR);
247 		}
248 
249 		if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == -1) {
250 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
251 			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
252 			free(bdlp->bfl_list);
253 			return (PCAP_ERROR);
254 		}
255 	} else {
256 		/*
257 		 * EINVAL just means "we don't support this ioctl on
258 		 * this device"; don't treat it as an error.
259 		 */
260 		if (errno != EINVAL) {
261 			(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
262 			    "BIOCGDLTLIST: %s", pcap_strerror(errno));
263 			return (PCAP_ERROR);
264 		}
265 	}
266 	return (0);
267 }
268 
269 /*
270  * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
271  * a PCAP_ERROR value on an error.
272  */
273 int
274 pcap_can_set_rfmon(pcap_t *p)
275 {
276 #if defined(HAVE_BSD_IEEE80211)
277 	int ret;
278 
279 	ret = monitor_mode(p, 0);
280 	if (ret == PCAP_ERROR_RFMON_NOTSUP)
281 		return (0);	/* not an error, just a "can't do" */
282 	if (ret == 0)
283 		return (1);	/* success */
284 	return (ret);
285 #else
286 	return (0);
287 #endif
288 }
289 
290 static void
291 pcap_cleanup_bpf(pcap_t *p)
292 {
293 #ifdef HAVE_BSD_IEEE80211
294 	int sock;
295 	struct ifmediareq req;
296 	struct ifreq ifr;
297 #endif
298 
299 	if (p->md.must_do_on_close != 0) {
300 		/*
301 		 * There's something we have to do when closing this
302 		 * pcap_t.
303 		 */
304 #ifdef HAVE_BSD_IEEE80211
305 		if (p->md.must_do_on_close & MUST_CLEAR_RFMON) {
306 			/*
307 			 * We put the interface into rfmon mode;
308 			 * take it out of rfmon mode.
309 			 *
310 			 * XXX - if somebody else wants it in rfmon
311 			 * mode, this code cannot know that, so it'll take
312 			 * it out of rfmon mode.
313 			 */
314 			sock = socket(AF_INET, SOCK_DGRAM, 0);
315 			if (sock == -1) {
316 				fprintf(stderr,
317 				    "Can't restore interface flags (socket() failed: %s).\n"
318 				    "Please adjust manually.\n",
319 				    strerror(errno));
320 			} else {
321 				memset(&req, 0, sizeof(req));
322 				(void)strlcpy(req.ifm_name, p->opt.source,
323 				    sizeof(req.ifm_name));
324 				if (ioctl(sock, SIOCGIFMEDIA, &req) == -1) {
325 					fprintf(stderr,
326 					    "Can't restore interface flags "
327 					    "(SIOCGIFMEDIA failed: %s).\n"
328 					    "Please adjust manually.\n",
329 					    strerror(errno));
330 				} else if (req.ifm_current & IFM_IEEE80211_MONITOR) {
331 					/*
332 					 * Rfmon mode is currently on;
333 					 * turn it off.
334 					 */
335 					memset(&ifr, 0, sizeof(ifr));
336 					(void)strlcpy(ifr.ifr_name,
337 					    p->opt.source,
338 					    sizeof(ifr.ifr_name));
339 					ifr.ifr_media =
340 					    req.ifm_current & ~IFM_IEEE80211_MONITOR;
341 					if (ioctl(sock, SIOCSIFMEDIA,
342 					    &ifr) == -1) {
343 						fprintf(stderr,
344 						    "Can't restore interface flags "
345 						    "(SIOCSIFMEDIA failed: %s).\n"
346 						    "Please adjust manually.\n",
347 						    strerror(errno));
348 					}
349 				}
350 				close(sock);
351 			}
352 		}
353 #endif /* HAVE_BSD_IEEE80211 */
354 
355 		/*
356 		 * Take this pcap out of the list of pcaps for which we
357 		 * have to take the interface out of some mode.
358 		 */
359 		pcap_remove_from_pcaps_to_close(p);
360 		p->md.must_do_on_close = 0;
361 	}
362 
363 	/*XXX*/
364 	if (p->fd >= 0) {
365 		close(p->fd);
366 		p->fd = -1;
367 	}
368 	if (p->sf.rfile != NULL) {
369 		(void)fclose(p->sf.rfile);
370 		free(p->sf.base);
371 	} else
372 		free(p->buffer);
373 
374 	pcap_freecode(&p->fcode);
375 	if (p->dlt_list != NULL) {
376 		free(p->dlt_list);
377 		p->dlt_list = NULL;
378 		p->dlt_count = 0;
379 	}
380 }
381 
382 void
383 pcap_close(pcap_t *p)
384 {
385 	pcap_cleanup_bpf(p);
386 	free(p->opt.source);
387 	free(p);
388 }
389 
390 
391 static int
392 check_setif_failure(pcap_t *p, int error)
393 {
394 	if (error == ENXIO) {
395 		/*
396 		 * No such device.
397 		 */
398 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
399 		    pcap_strerror(errno));
400 		return (PCAP_ERROR_NO_SUCH_DEVICE);
401 	} else if (errno == ENETDOWN) {
402 		/*
403 		 * Return a "network down" indication, so that
404 		 * the application can report that rather than
405 		 * saying we had a mysterious failure and
406 		 * suggest that they report a problem to the
407 		 * libpcap developers.
408 		 */
409 		return (PCAP_ERROR_IFACE_NOT_UP);
410 	} else {
411 		/*
412 		 * Some other error; fill in the error string, and
413 		 * return PCAP_ERROR.
414 		 */
415 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
416 		    p->opt.source, pcap_strerror(errno));
417 		return (PCAP_ERROR);
418 	}
419 }
420 
421 int
422 pcap_activate(pcap_t *p)
423 {
424 	int status = 0;
425 	int fd;
426 	struct ifreq ifr;
427 	struct bpf_version bv;
428 	struct bpf_dltlist bdl;
429 	int new_dlt;
430 	u_int v;
431 
432 	fd = bpf_open(p);
433 	if (fd < 0) {
434 		status = fd;
435 		goto bad;
436 	}
437 
438 	p->fd = fd;
439 
440 	if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) == -1) {
441 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
442 		    pcap_strerror(errno));
443 		status = PCAP_ERROR;
444 		goto bad;
445 	}
446 	if (bv.bv_major != BPF_MAJOR_VERSION ||
447 	    bv.bv_minor < BPF_MINOR_VERSION) {
448 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
449 		    "kernel bpf filter out of date");
450 		status = PCAP_ERROR;
451 		goto bad;
452 	}
453 
454 #if 0
455 	/* Just use the kernel default */
456 	v = 32768;	/* XXX this should be a user-accessible hook */
457 	/* Ignore the return value - this is because the call fails on
458 	 * BPF systems that don't have kernel malloc.  And if the call
459 	 * fails, it's no big deal, we just continue to use the standard
460 	 * buffer size.
461 	 */
462 	(void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
463 #endif
464 
465 	/*
466 	 * Set the buffer size.
467 	 */
468 	if (p->opt.buffer_size != 0) {
469 		/*
470 		 * A buffer size was explicitly specified; use it.
471 		 */
472 		if (ioctl(fd, BIOCSBLEN,
473 		    (caddr_t)&p->opt.buffer_size) == -1) {
474 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
475 			    "BIOCSBLEN: %s: %s", p->opt.source,
476 			    pcap_strerror(errno));
477 			status = PCAP_ERROR;
478 			goto bad;
479 		}
480 	}
481 
482 	/*
483 	 * Now bind to the device.
484 	 */
485 	(void)strlcpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
486 	if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) == -1) {
487 		status = check_setif_failure(p, errno);
488 		goto bad;
489 	}
490 	/* Get the data link layer type. */
491 	if (ioctl(fd, BIOCGDLT, (caddr_t)&v) == -1) {
492 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
493 		    pcap_strerror(errno));
494 		status = PCAP_ERROR;
495 		goto bad;
496 	}
497 
498 	/*
499 	 * We know the default link type -- now determine all the DLTs
500 	 * this interface supports.  If this fails with EINVAL, it's
501 	 * not fatal; we just don't get to use the feature later.
502 	 */
503 	if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
504 		status = PCAP_ERROR;
505 		goto bad;
506 	}
507 	p->dlt_count = bdl.bfl_len;
508 	p->dlt_list = bdl.bfl_list;
509 
510 	/*
511 	 * *BSD with the new 802.11 ioctls.
512 	 * Do we want monitor mode?
513 	 */
514 	if (p->opt.rfmon) {
515 		/*
516 		 * Try to put the interface into monitor mode.
517 		 */
518 		status = monitor_mode(p, 1);
519 		if (status != 0) {
520 			/*
521 			 * We failed.
522 			 */
523 			goto bad;
524 		}
525 
526 		/*
527 		 * We're in monitor mode.
528 		 * Try to find the best 802.11 DLT_ value and, if we
529 		 * succeed, try to switch to that mode if we're not
530 		 * already in that mode.
531 		 */
532 		new_dlt = find_802_11(&bdl);
533 		if (new_dlt != -1) {
534 			/*
535 			 * We have at least one 802.11 DLT_ value.
536 			 * new_dlt is the best of the 802.11
537 			 * DLT_ values in the list.
538 			 *
539 			 * If the new mode we want isn't the default mode,
540 			 * attempt to select the new mode.
541 			 */
542 			if (new_dlt != v) {
543 				if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
544 					/*
545 					 * We succeeded; make this the
546 					 * new DLT_ value.
547 					 */
548 					v = new_dlt;
549 				}
550 			}
551 		}
552 	}
553 	p->linktype = v;
554 
555 	/* set timeout */
556 	if (p->md.timeout) {
557 		struct timeval to;
558 		to.tv_sec = p->md.timeout / 1000;
559 		to.tv_usec = (p->md.timeout * 1000) % 1000000;
560 		if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) == -1) {
561 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
562 			    "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
563 			status = PCAP_ERROR;
564 			goto bad;
565 		}
566 	}
567 
568 	if (p->opt.immediate) {
569 		v = 1;
570 		if (ioctl(p->fd, BIOCIMMEDIATE, &v) == -1) {
571 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
572 			    "BIOCIMMEDIATE: %s", pcap_strerror(errno));
573 			status = PCAP_ERROR;
574 			goto bad;
575 		}
576 	}
577 
578 	if (p->opt.promisc) {
579 		/* set promiscuous mode, just warn if it fails */
580 		if (ioctl(p->fd, BIOCPROMISC, NULL) == -1) {
581 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
582 			    pcap_strerror(errno));
583 			status = PCAP_WARNING_PROMISC_NOTSUP;
584 		}
585 	}
586 
587 	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) == -1) {
588 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
589 		    pcap_strerror(errno));
590 		status = PCAP_ERROR;
591 		goto bad;
592 	}
593 	p->bufsize = v;
594 	p->buffer = malloc(p->bufsize);
595 	if (p->buffer == NULL) {
596 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
597 		    pcap_strerror(errno));
598 		status = PCAP_ERROR;
599 		goto bad;
600 	}
601 
602 	if (status < 0)
603 		goto bad;
604 
605 	p->activated = 1;
606 
607 	return (status);
608  bad:
609 	pcap_cleanup_bpf(p);
610 
611 	if (p->errbuf[0] == '\0') {
612 		/*
613 		 * No error message supplied by the activate routine;
614 		 * for the benefit of programs that don't specially
615 		 * handle errors other than PCAP_ERROR, return the
616 		 * error message corresponding to the status.
617 		 */
618 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
619 		    pcap_statustostr(status));
620 	}
621 
622 	return (status);
623 }
624 
625 static int
626 monitor_mode(pcap_t *p, int set)
627 {
628 	int sock;
629 	struct ifmediareq req;
630 	uint64_t *media_list;
631 	int i;
632 	int can_do;
633 	struct ifreq ifr;
634 
635 	sock = socket(AF_INET, SOCK_DGRAM, 0);
636 	if (sock == -1) {
637 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
638 		    pcap_strerror(errno));
639 		return (PCAP_ERROR);
640 	}
641 
642 	memset(&req, 0, sizeof req);
643 	(void)strlcpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
644 
645 	/*
646 	 * Find out how many media types we have.
647 	 */
648 	if (ioctl(sock, SIOCGIFMEDIA, &req) == -1) {
649 		/*
650 		 * Can't get the media types.
651 		 */
652 		switch (errno) {
653 
654 		case ENXIO:
655 			/*
656 			 * There's no such device.
657 			 */
658 			close(sock);
659 			return (PCAP_ERROR_NO_SUCH_DEVICE);
660 
661 		case EINVAL:
662 		case ENOTTY:
663 			/*
664 			 * Interface doesn't support SIOC{G,S}IFMEDIA.
665 			 */
666 			close(sock);
667 			return (PCAP_ERROR_RFMON_NOTSUP);
668 
669 		default:
670 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
671 			    "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
672 			close(sock);
673 			return (PCAP_ERROR);
674 		}
675 	}
676 	if (req.ifm_count == 0) {
677 		/*
678 		 * No media types.
679 		 */
680 		close(sock);
681 		return (PCAP_ERROR_RFMON_NOTSUP);
682 	}
683 
684 	/*
685 	 * Allocate a buffer to hold all the media types, and
686 	 * get the media types.
687 	 */
688 	media_list = calloc(req.ifm_count, sizeof(*media_list));
689 	if (media_list == NULL) {
690 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
691 		    pcap_strerror(errno));
692 		close(sock);
693 		return (PCAP_ERROR);
694 	}
695 	req.ifm_ulist = media_list;
696 	if (ioctl(sock, SIOCGIFMEDIA, &req) == -1) {
697 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
698 		    pcap_strerror(errno));
699 		free(media_list);
700 		close(sock);
701 		return (PCAP_ERROR);
702 	}
703 
704 	/*
705 	 * Look for an 802.11 "automatic" media type.
706 	 * We assume that all 802.11 adapters have that media type,
707 	 * and that it will carry the monitor mode supported flag.
708 	 */
709 	can_do = 0;
710 	for (i = 0; i < req.ifm_count; i++) {
711 		if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
712 		    && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
713 			/* OK, does it do monitor mode? */
714 			if (media_list[i] & IFM_IEEE80211_MONITOR) {
715 				can_do = 1;
716 				break;
717 			}
718 		}
719 	}
720 	free(media_list);
721 	if (!can_do) {
722 		/*
723 		 * This adapter doesn't support monitor mode.
724 		 */
725 		close(sock);
726 		return (PCAP_ERROR_RFMON_NOTSUP);
727 	}
728 
729 	if (set) {
730 		/*
731 		 * Don't just check whether we can enable monitor mode,
732 		 * do so, if it's not already enabled.
733 		 */
734 		if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
735 			/*
736 			 * Monitor mode isn't currently on, so turn it on,
737 			 * and remember that we should turn it off when the
738 			 * pcap_t is closed.
739 			 */
740 
741 			/*
742 			 * If we haven't already done so, arrange to have
743 			 * "pcap_close_all()" called when we exit.
744 			 */
745 			if (!pcap_do_addexit(p)) {
746 				/*
747 				 * "atexit()" failed; don't put the interface
748 				 * in monitor mode, just give up.
749 				 */
750 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
751 				     "atexit failed");
752 				close(sock);
753 				return (PCAP_ERROR);
754 			}
755 			memset(&ifr, 0, sizeof(ifr));
756 			(void)strlcpy(ifr.ifr_name, p->opt.source,
757 			    sizeof(ifr.ifr_name));
758 			ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
759 			if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
760 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
761 				     "SIOCSIFMEDIA: %s", pcap_strerror(errno));
762 				close(sock);
763 				return (PCAP_ERROR);
764 			}
765 
766 			p->md.must_do_on_close |= MUST_CLEAR_RFMON;
767 
768 			/*
769 			 * Add this to the list of pcaps to close when we exit.
770 			 */
771 			pcap_add_to_pcaps_to_close(p);
772 		}
773 	}
774 	return (0);
775 }
776 
777 /*
778  * Check whether we have any 802.11 link-layer types; return the best
779  * of the 802.11 link-layer types if we find one, and return -1
780  * otherwise.
781  *
782  * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
783  * best 802.11 link-layer type; any of the other 802.11-plus-radio
784  * headers are second-best; 802.11 with no radio information is
785  * the least good.
786  */
787 static int
788 find_802_11(struct bpf_dltlist *bdlp)
789 {
790 	int new_dlt;
791 	int i;
792 
793 	/*
794 	 * Scan the list of DLT_ values, looking for 802.11 values,
795 	 * and, if we find any, choose the best of them.
796 	 */
797 	new_dlt = -1;
798 	for (i = 0; i < bdlp->bfl_len; i++) {
799 		switch (bdlp->bfl_list[i]) {
800 
801 		case DLT_IEEE802_11:
802 			/*
803 			 * 802.11, but no radio.
804 			 *
805 			 * Offer this, and select it as the new mode
806 			 * unless we've already found an 802.11
807 			 * header with radio information.
808 			 */
809 			if (new_dlt == -1)
810 				new_dlt = bdlp->bfl_list[i];
811 			break;
812 
813 		case DLT_IEEE802_11_RADIO:
814 			/*
815 			 * 802.11 with radiotap.
816 			 *
817 			 * Offer this, and select it as the new mode.
818 			 */
819 			new_dlt = bdlp->bfl_list[i];
820 			break;
821 
822 		default:
823 			/*
824 			 * Not 802.11.
825 			 */
826 			break;
827 		}
828 	}
829 
830 	return (new_dlt);
831 }
832 
833 pcap_t *
834 pcap_create(const char *device, char *errbuf)
835 {
836 	pcap_t *p;
837 
838 	p = calloc(1, sizeof(*p));
839 	if (p == NULL) {
840 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
841 		    pcap_strerror(errno));
842 		return (NULL);
843 	}
844 	p->fd = -1;	/* not opened yet */
845 
846 	p->opt.source = strdup(device);
847 	if (p->opt.source == NULL) {
848 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
849 		    pcap_strerror(errno));
850 		free(p);
851 		return (NULL);
852 	}
853 
854 	/* put in some defaults*/
855 	pcap_set_timeout(p, 0);
856 	pcap_set_snaplen(p, 65535);	/* max packet size */
857 	p->opt.promisc = 0;
858 	p->opt.buffer_size = 0;
859 	p->opt.immediate = 0;
860 	return (p);
861 }
862 
863 pcap_t *
864 pcap_open_live(const char *source, int snaplen, int promisc, int to_ms,
865     char *errbuf)
866 {
867 	pcap_t *p;
868 	int status;
869 
870 	p = pcap_create(source, errbuf);
871 	if (p == NULL)
872 		return (NULL);
873 	status = pcap_set_snaplen(p, snaplen);
874 	if (status < 0)
875 		goto fail;
876 	status = pcap_set_promisc(p, promisc);
877 	if (status < 0)
878 		goto fail;
879 	status = pcap_set_timeout(p, to_ms);
880 	if (status < 0)
881 		goto fail;
882 	/*
883 	 * Mark this as opened with pcap_open_live(), so that, for
884 	 * example, we show the full list of DLT_ values, rather
885 	 * than just the ones that are compatible with capturing
886 	 * when not in monitor mode.  That allows existing applications
887 	 * to work the way they used to work, but allows new applications
888 	 * that know about the new open API to, for example, find out the
889 	 * DLT_ values that they can select without changing whether
890 	 * the adapter is in monitor mode or not.
891 	 */
892 	p->oldstyle = 1;
893 	status = pcap_activate(p);
894 	if (status < 0)
895 		goto fail;
896 	return (p);
897 fail:
898 	if (status == PCAP_ERROR)
899 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
900 		    p->errbuf);
901 	else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
902 	    status == PCAP_ERROR_PERM_DENIED ||
903 	    status == PCAP_ERROR_PROMISC_PERM_DENIED)
904 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", source,
905 		    pcap_statustostr(status), p->errbuf);
906 	else
907 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
908 		    pcap_statustostr(status));
909 	pcap_close(p);
910 	return (NULL);
911 }
912 
913 int
914 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
915 {
916 	/*
917 	 * It looks that BPF code generated by gen_protochain() is not
918 	 * compatible with some of kernel BPF code (for example BSD/OS 3.1).
919 	 * Take a safer side for now.
920 	 */
921 	if (no_optimize || (p->sf.rfile != NULL)){
922 		if (p->fcode.bf_insns != NULL)
923 			pcap_freecode(&p->fcode);
924 		p->fcode.bf_len = fp->bf_len;
925 		p->fcode.bf_insns = reallocarray(NULL,
926 		    fp->bf_len, sizeof(*fp->bf_insns));
927 		if (p->fcode.bf_insns == NULL) {
928 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
929 			    pcap_strerror(errno));
930 			return (-1);
931 		}
932 		memcpy(p->fcode.bf_insns, fp->bf_insns,
933 		    fp->bf_len * sizeof(*fp->bf_insns));
934 	} else if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == -1) {
935 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
936 		    pcap_strerror(errno));
937 		return (-1);
938 	}
939 	return (0);
940 }
941 
942 int
943 pcap_setdirection(pcap_t *p, pcap_direction_t d)
944 {
945 	u_int dirfilt;
946 
947 	switch (d) {
948 	case PCAP_D_INOUT:
949 		dirfilt = 0;
950 		break;
951 	case PCAP_D_IN:
952 		dirfilt = BPF_DIRECTION_OUT;
953 		break;
954 	case PCAP_D_OUT:
955 		dirfilt = BPF_DIRECTION_IN;
956 		break;
957 	default:
958 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Invalid direction");
959 		return (-1);
960 	}
961 	if (ioctl(p->fd, BIOCSDIRFILT, &dirfilt) == -1) {
962 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSDIRFILT: %s",
963 		    pcap_strerror(errno));
964 		return (-1);
965 	}
966 	return (0);
967 }
968 
969 int
970 pcap_set_datalink(pcap_t *p, int dlt)
971 {
972 	int i;
973 
974 	if (p->dlt_count == 0) {
975 		/*
976 		 * We couldn't fetch the list of DLTs, or we don't
977 		 * have a "set datalink" operation, which means
978 		 * this platform doesn't support changing the
979 		 * DLT for an interface.  Check whether the new
980 		 * DLT is the one this interface supports.
981 		 */
982 		if (p->linktype != dlt)
983 			goto unsupported;
984 
985 		/*
986 		 * It is, so there's nothing we need to do here.
987 		 */
988 		return (0);
989 	}
990 	for (i = 0; i < p->dlt_count; i++)
991 		if (p->dlt_list[i] == dlt)
992 			break;
993 	if (i >= p->dlt_count)
994 		goto unsupported;
995 	if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
996 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
997 		    "Cannot set DLT %d: %s", dlt, strerror(errno));
998 		return (-1);
999 	}
1000 	p->linktype = dlt;
1001 	return (0);
1002 
1003 unsupported:
1004 	(void) snprintf(p->errbuf, sizeof(p->errbuf),
1005 	    "DLT %d is not one of the DLTs supported by this device",
1006 	    dlt);
1007 	return (-1);
1008 }
1009 
1010