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