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