Home | History | Annotate | Line # | Download | only in net
bpf.c revision 1.61.4.3
      1 /*	$NetBSD: bpf.c,v 1.61.4.3 2001/10/01 12:47:31 fvdl Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1990, 1991, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from the Stanford/CMU enet packet filter,
      8  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
      9  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
     10  * Berkeley Laboratory.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	@(#)bpf.c	8.4 (Berkeley) 1/9/95
     41  * static char rcsid[] =
     42  * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
     43  */
     44 
     45 #include "bpfilter.h"
     46 
     47 #include <sys/param.h>
     48 #include <sys/systm.h>
     49 #include <sys/mbuf.h>
     50 #include <sys/buf.h>
     51 #include <sys/time.h>
     52 #include <sys/proc.h>
     53 #include <sys/user.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/map.h>
     56 #include <sys/conf.h>
     57 #include <sys/vnode.h>
     58 
     59 #include <miscfs/specfs/specdev.h>
     60 
     61 #include <sys/file.h>
     62 #include <sys/tty.h>
     63 #include <sys/uio.h>
     64 
     65 #include <sys/protosw.h>
     66 #include <sys/socket.h>
     67 #include <sys/errno.h>
     68 #include <sys/kernel.h>
     69 #include <sys/poll.h>
     70 
     71 #include <net/if.h>
     72 
     73 #include <net/bpf.h>
     74 #include <net/bpfdesc.h>
     75 
     76 #include <net/if_arc.h>
     77 #include <net/if_ether.h>
     78 
     79 #include <netinet/in.h>
     80 #include <netinet/if_inarp.h>
     81 
     82 #ifndef BPF_BUFSIZE
     83 # define BPF_BUFSIZE 8192		/* 4096 too small for FDDI frames */
     84 #endif
     85 
     86 #define PRINET  26			/* interruptible */
     87 
     88 /*
     89  * The default read buffer size is patchable.
     90  */
     91 int bpf_bufsize = BPF_BUFSIZE;
     92 
     93 /*
     94  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
     95  *  bpf_dtab holds the descriptors, indexed by minor device #
     96  */
     97 struct bpf_if	*bpf_iflist;
     98 struct bpf_d	bpf_dtab[NBPFILTER];
     99 
    100 static int	bpf_allocbufs __P((struct bpf_d *));
    101 static void	bpf_freed __P((struct bpf_d *));
    102 static void	bpf_ifname __P((struct ifnet *, struct ifreq *));
    103 static void	*bpf_mcpy __P((void *, const void *, size_t));
    104 static int	bpf_movein __P((struct uio *, int, int,
    105 			        struct mbuf **, struct sockaddr *));
    106 static void	bpf_attachd __P((struct bpf_d *, struct bpf_if *));
    107 static void	bpf_detachd __P((struct bpf_d *));
    108 static int	bpf_setif __P((struct bpf_d *, struct ifreq *));
    109 static __inline void
    110 		bpf_wakeup __P((struct bpf_d *));
    111 static void	catchpacket __P((struct bpf_d *, u_char *, u_int, u_int,
    112 				 void *(*)(void *, const void *, size_t)));
    113 static void	reset_d __P((struct bpf_d *));
    114 
    115 static int
    116 bpf_movein(uio, linktype, mtu, mp, sockp)
    117 	struct uio *uio;
    118 	int linktype;
    119 	int mtu;
    120 	struct mbuf **mp;
    121 	struct sockaddr *sockp;
    122 {
    123 	struct mbuf *m;
    124 	int error;
    125 	int len;
    126 	int hlen;
    127 	int align;
    128 
    129 	/*
    130 	 * Build a sockaddr based on the data link layer type.
    131 	 * We do this at this level because the ethernet header
    132 	 * is copied directly into the data field of the sockaddr.
    133 	 * In the case of SLIP, there is no header and the packet
    134 	 * is forwarded as is.
    135 	 * Also, we are careful to leave room at the front of the mbuf
    136 	 * for the link level header.
    137 	 */
    138 	switch (linktype) {
    139 
    140 	case DLT_SLIP:
    141 		sockp->sa_family = AF_INET;
    142 		hlen = 0;
    143 		align = 0;
    144 		break;
    145 
    146 	case DLT_PPP:
    147 		sockp->sa_family = AF_UNSPEC;
    148 		hlen = 0;
    149 		align = 0;
    150 		break;
    151 
    152 	case DLT_EN10MB:
    153 		sockp->sa_family = AF_UNSPEC;
    154 		/* XXX Would MAXLINKHDR be better? */
    155  		/* 6(dst)+6(src)+2(type) */
    156 		hlen = sizeof(struct ether_header);
    157 		align = 2;
    158 		break;
    159 
    160 	case DLT_ARCNET:
    161 		sockp->sa_family = AF_UNSPEC;
    162 		hlen = ARC_HDRLEN;
    163 		align = 5;
    164 		break;
    165 
    166 	case DLT_FDDI:
    167 		sockp->sa_family = AF_LINK;
    168 		/* XXX 4(FORMAC)+6(dst)+6(src) */
    169 		hlen = 16;
    170 		align = 0;
    171 		break;
    172 
    173 	case DLT_ECONET:
    174 		sockp->sa_family = AF_UNSPEC;
    175 		hlen = 6;
    176 		align = 2;
    177 		break;
    178 
    179 	case DLT_NULL:
    180 		sockp->sa_family = AF_UNSPEC;
    181 		hlen = 0;
    182 		align = 0;
    183 		break;
    184 
    185 	default:
    186 		return (EIO);
    187 	}
    188 
    189 	len = uio->uio_resid;
    190 	/*
    191 	 * If there aren't enough bytes for a link level header or the
    192 	 * packet length exceeds the interface mtu, return an error.
    193 	 */
    194 	if (len < hlen || len - hlen > mtu)
    195 		return (EMSGSIZE);
    196 
    197 	/*
    198 	 * XXX Avoid complicated buffer chaining ---
    199 	 * bail if it won't fit in a single mbuf.
    200 	 * (Take into account possible alignment bytes)
    201 	 */
    202 	if ((unsigned)len > MCLBYTES - align)
    203 		return (EIO);
    204 
    205 	MGETHDR(m, M_WAIT, MT_DATA);
    206 	if (m == 0)
    207 		return (ENOBUFS);
    208 	m->m_pkthdr.rcvif = 0;
    209 	m->m_pkthdr.len = len - hlen;
    210 	if (len > MHLEN - align) {
    211 		MCLGET(m, M_WAIT);
    212 		if ((m->m_flags & M_EXT) == 0) {
    213 			error = ENOBUFS;
    214 			goto bad;
    215 		}
    216 	}
    217 
    218 	/* Insure the data is properly aligned */
    219 	if (align > 0) {
    220 		m->m_data += align;
    221 		m->m_len -= align;
    222 	}
    223 
    224 	error = uiomove(mtod(m, caddr_t), len, uio);
    225 	if (error)
    226 		goto bad;
    227 	if (hlen != 0) {
    228 		memcpy(sockp->sa_data, mtod(m, caddr_t), hlen);
    229 		m->m_data += hlen; /* XXX */
    230 		len -= hlen;
    231 	}
    232 	m->m_len = len;
    233 	*mp = m;
    234 	return (0);
    235 
    236 bad:
    237 	m_freem(m);
    238 	return (error);
    239 }
    240 
    241 /*
    242  * Attach file to the bpf interface, i.e. make d listen on bp.
    243  * Must be called at splnet.
    244  */
    245 static void
    246 bpf_attachd(d, bp)
    247 	struct bpf_d *d;
    248 	struct bpf_if *bp;
    249 {
    250 	/*
    251 	 * Point d at bp, and add d to the interface's list of listeners.
    252 	 * Finally, point the driver's bpf cookie at the interface so
    253 	 * it will divert packets to bpf.
    254 	 */
    255 	d->bd_bif = bp;
    256 	d->bd_next = bp->bif_dlist;
    257 	bp->bif_dlist = d;
    258 
    259 	*bp->bif_driverp = bp;
    260 }
    261 
    262 /*
    263  * Detach a file from its interface.
    264  */
    265 static void
    266 bpf_detachd(d)
    267 	struct bpf_d *d;
    268 {
    269 	struct bpf_d **p;
    270 	struct bpf_if *bp;
    271 
    272 	bp = d->bd_bif;
    273 	/*
    274 	 * Check if this descriptor had requested promiscuous mode.
    275 	 * If so, turn it off.
    276 	 */
    277 	if (d->bd_promisc) {
    278 		int error;
    279 
    280 		d->bd_promisc = 0;
    281 		/*
    282 		 * Take device out of promiscuous mode.  Since we were
    283 		 * able to enter promiscuous mode, we should be able
    284 		 * to turn it off.  But we can get an error if
    285 		 * the interface was configured down, so only panic
    286 		 * if we don't get an unexpected error.
    287 		 */
    288   		error = ifpromisc(bp->bif_ifp, 0);
    289 		if (error && error != EINVAL)
    290 			panic("bpf: ifpromisc failed");
    291 	}
    292 	/* Remove d from the interface's descriptor list. */
    293 	p = &bp->bif_dlist;
    294 	while (*p != d) {
    295 		p = &(*p)->bd_next;
    296 		if (*p == 0)
    297 			panic("bpf_detachd: descriptor not in list");
    298 	}
    299 	*p = (*p)->bd_next;
    300 	if (bp->bif_dlist == 0)
    301 		/*
    302 		 * Let the driver know that there are no more listeners.
    303 		 */
    304 		*d->bd_bif->bif_driverp = 0;
    305 	d->bd_bif = 0;
    306 }
    307 
    308 
    309 /*
    310  * Mark a descriptor free by making it point to itself.
    311  * This is probably cheaper than marking with a constant since
    312  * the address should be in a register anyway.
    313  */
    314 #define D_ISFREE(d) ((d) == (d)->bd_next)
    315 #define D_MARKFREE(d) ((d)->bd_next = (d))
    316 #define D_MARKUSED(d) ((d)->bd_next = 0)
    317 
    318 /*
    319  * bpfilterattach() is called at boot time.
    320  */
    321 /* ARGSUSED */
    322 void
    323 bpfilterattach(n)
    324 	int n;
    325 {
    326 	int i;
    327 	/*
    328 	 * Mark all the descriptors free.
    329 	 */
    330 	for (i = 0; i < NBPFILTER; ++i)
    331 		D_MARKFREE(&bpf_dtab[i]);
    332 
    333 }
    334 
    335 /*
    336  * Open ethernet device.  Returns ENXIO for illegal minor device number,
    337  * EBUSY if file is open by another process.
    338  */
    339 /* ARGSUSED */
    340 int
    341 bpfopen(devvp, flag, mode, p)
    342 	struct vnode *devvp;
    343 	int flag;
    344 	int mode;
    345 	struct proc *p;
    346 {
    347 	struct bpf_d *d;
    348 	dev_t rdev;
    349 
    350 	rdev = vdev_rdev(devvp);
    351 
    352 	if (minor(rdev) >= NBPFILTER)
    353 		return (ENXIO);
    354 	/*
    355 	 * Each minor can be opened by only one process.  If the requested
    356 	 * minor is in use, return EBUSY.
    357 	 */
    358 	d = &bpf_dtab[minor(rdev)];
    359 	if (!D_ISFREE(d))
    360 		return (EBUSY);
    361 
    362 	/* Mark "free" and do most initialization. */
    363 	memset((char *)d, 0, sizeof(*d));
    364 	d->bd_bufsize = bpf_bufsize;
    365 
    366 	vdev_setprivdata(devvp, d);
    367 
    368 	return (0);
    369 }
    370 
    371 /*
    372  * Close the descriptor by detaching it from its interface,
    373  * deallocating its buffers, and marking it free.
    374  */
    375 /* ARGSUSED */
    376 int
    377 bpfclose(devvp, flag, mode, p)
    378 	struct vnode *devvp;
    379 	int flag;
    380 	int mode;
    381 	struct proc *p;
    382 {
    383 	struct bpf_d *d;
    384 	int s;
    385 
    386 	d = vdev_privdata(devvp);
    387 
    388 	s = splnet();
    389 	if (d->bd_bif)
    390 		bpf_detachd(d);
    391 	splx(s);
    392 	bpf_freed(d);
    393 
    394 	return (0);
    395 }
    396 
    397 /*
    398  * Rotate the packet buffers in descriptor d.  Move the store buffer
    399  * into the hold slot, and the free buffer into the store slot.
    400  * Zero the length of the new store buffer.
    401  */
    402 #define ROTATE_BUFFERS(d) \
    403 	(d)->bd_hbuf = (d)->bd_sbuf; \
    404 	(d)->bd_hlen = (d)->bd_slen; \
    405 	(d)->bd_sbuf = (d)->bd_fbuf; \
    406 	(d)->bd_slen = 0; \
    407 	(d)->bd_fbuf = 0;
    408 /*
    409  *  bpfread - read next chunk of packets from buffers
    410  */
    411 int
    412 bpfread(devvp, uio, ioflag)
    413 	struct vnode *devvp;
    414 	struct uio *uio;
    415 	int ioflag;
    416 {
    417 	struct bpf_d *d;
    418 	int error;
    419 	int s;
    420 
    421 	d = vdev_privdata(devvp);
    422 
    423 	/*
    424 	 * Restrict application to use a buffer the same size as
    425 	 * as kernel buffers.
    426 	 */
    427 	if (uio->uio_resid != d->bd_bufsize)
    428 		return (EINVAL);
    429 
    430 	s = splnet();
    431 	/*
    432 	 * If the hold buffer is empty, then do a timed sleep, which
    433 	 * ends when the timeout expires or when enough packets
    434 	 * have arrived to fill the store buffer.
    435 	 */
    436 	while (d->bd_hbuf == 0) {
    437 		if (d->bd_immediate) {
    438 			if (d->bd_slen == 0) {
    439 				splx(s);
    440 				return (EWOULDBLOCK);
    441 			}
    442 			/*
    443 			 * A packet(s) either arrived since the previous
    444 			 * read or arrived while we were asleep.
    445 			 * Rotate the buffers and return what's here.
    446 			 */
    447 			ROTATE_BUFFERS(d);
    448 			break;
    449 		}
    450 		if (d->bd_rtout != -1)
    451 			error = tsleep((caddr_t)d, PRINET|PCATCH, "bpf",
    452 					  d->bd_rtout);
    453 		else {
    454 			if (d->bd_rtout == -1) {
    455 				/* User requested non-blocking I/O */
    456 				error = EWOULDBLOCK;
    457 			} else
    458 				error = 0;
    459 		}
    460 		if (error == EINTR || error == ERESTART) {
    461 			splx(s);
    462 			return (error);
    463 		}
    464 		if (error == EWOULDBLOCK) {
    465 			/*
    466 			 * On a timeout, return what's in the buffer,
    467 			 * which may be nothing.  If there is something
    468 			 * in the store buffer, we can rotate the buffers.
    469 			 */
    470 			if (d->bd_hbuf)
    471 				/*
    472 				 * We filled up the buffer in between
    473 				 * getting the timeout and arriving
    474 				 * here, so we don't need to rotate.
    475 				 */
    476 				break;
    477 
    478 			if (d->bd_slen == 0) {
    479 				splx(s);
    480 				return (0);
    481 			}
    482 			ROTATE_BUFFERS(d);
    483 			break;
    484 		}
    485 		if (error != 0)
    486 			goto done;
    487 	}
    488 	/*
    489 	 * At this point, we know we have something in the hold slot.
    490 	 */
    491 	splx(s);
    492 
    493 	/*
    494 	 * Move data from hold buffer into user space.
    495 	 * We know the entire buffer is transferred since
    496 	 * we checked above that the read buffer is bpf_bufsize bytes.
    497 	 */
    498 	error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
    499 
    500 	s = splnet();
    501 	d->bd_fbuf = d->bd_hbuf;
    502 	d->bd_hbuf = 0;
    503 	d->bd_hlen = 0;
    504 done:
    505 	splx(s);
    506 	return (error);
    507 }
    508 
    509 
    510 /*
    511  * If there are processes sleeping on this descriptor, wake them up.
    512  */
    513 static __inline void
    514 bpf_wakeup(d)
    515 	struct bpf_d *d;
    516 {
    517 	struct proc *p;
    518 
    519 	wakeup((caddr_t)d);
    520 	if (d->bd_async) {
    521 		if (d->bd_pgid > 0)
    522 			gsignal (d->bd_pgid, SIGIO);
    523 		else if (d->bd_pgid && (p = pfind (-d->bd_pgid)) != NULL)
    524 			psignal (p, SIGIO);
    525 	}
    526 
    527 	selwakeup(&d->bd_sel);
    528 	/* XXX */
    529 	d->bd_sel.si_pid = 0;
    530 }
    531 
    532 int
    533 bpfwrite(devvp, uio, ioflag)
    534 	struct vnode *devvp;
    535 	struct uio *uio;
    536 	int ioflag;
    537 {
    538 	struct bpf_d *d;
    539 	struct ifnet *ifp;
    540 	struct mbuf *m;
    541 	int error, s;
    542 	static struct sockaddr_storage dst;
    543 
    544 	d = vdev_privdata(devvp);
    545 
    546 	if (d->bd_bif == 0)
    547 		return (ENXIO);
    548 
    549 	ifp = d->bd_bif->bif_ifp;
    550 
    551 	if (uio->uio_resid == 0)
    552 		return (0);
    553 
    554 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
    555 		(struct sockaddr *) &dst);
    556 	if (error)
    557 		return (error);
    558 
    559 	if (m->m_pkthdr.len > ifp->if_mtu)
    560 		return (EMSGSIZE);
    561 
    562 	if (d->bd_hdrcmplt)
    563 		dst.ss_family = pseudo_AF_HDRCMPLT;
    564 
    565 	s = splsoftnet();
    566 	error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
    567 	splx(s);
    568 	/*
    569 	 * The driver frees the mbuf.
    570 	 */
    571 	return (error);
    572 }
    573 
    574 /*
    575  * Reset a descriptor by flushing its packet buffer and clearing the
    576  * receive and drop counts.  Should be called at splnet.
    577  */
    578 static void
    579 reset_d(d)
    580 	struct bpf_d *d;
    581 {
    582 	if (d->bd_hbuf) {
    583 		/* Free the hold buffer. */
    584 		d->bd_fbuf = d->bd_hbuf;
    585 		d->bd_hbuf = 0;
    586 	}
    587 	d->bd_slen = 0;
    588 	d->bd_hlen = 0;
    589 	d->bd_rcount = 0;
    590 	d->bd_dcount = 0;
    591 }
    592 
    593 #ifdef BPF_KERN_FILTER
    594 extern struct bpf_insn *bpf_tcp_filter;
    595 extern struct bpf_insn *bpf_udp_filter;
    596 #endif
    597 
    598 /*
    599  *  FIONREAD		Check for read packet available.
    600  *  BIOCGBLEN		Get buffer len [for read()].
    601  *  BIOCSETF		Set ethernet read filter.
    602  *  BIOCFLUSH		Flush read packet buffer.
    603  *  BIOCPROMISC		Put interface into promiscuous mode.
    604  *  BIOCGDLT		Get link layer type.
    605  *  BIOCGETIF		Get interface name.
    606  *  BIOCSETIF		Set interface.
    607  *  BIOCSRTIMEOUT	Set read timeout.
    608  *  BIOCGRTIMEOUT	Get read timeout.
    609  *  BIOCGSTATS		Get packet stats.
    610  *  BIOCIMMEDIATE	Set immediate mode.
    611  *  BIOCVERSION		Get filter language version.
    612  *  BIOGHDRCMPLT	Get "header already complete" flag.
    613  *  BIOSHDRCMPLT	Set "header already complete" flag.
    614  */
    615 /* ARGSUSED */
    616 int
    617 bpfioctl(devvp, cmd, addr, flag, p)
    618 	struct vnode *devvp;
    619 	u_long cmd;
    620 	caddr_t addr;
    621 	int flag;
    622 	struct proc *p;
    623 {
    624 	struct bpf_d *d;
    625 	int s, error = 0;
    626 #ifdef BPF_KERN_FILTER
    627 	struct bpf_insn **p;
    628 #endif
    629 
    630 	d = vdev_privdata(devvp);
    631 
    632 	switch (cmd) {
    633 
    634 	default:
    635 		error = EINVAL;
    636 		break;
    637 
    638 	/*
    639 	 * Check for read packet available.
    640 	 */
    641 	case FIONREAD:
    642 		{
    643 			int n;
    644 
    645 			s = splnet();
    646 			n = d->bd_slen;
    647 			if (d->bd_hbuf)
    648 				n += d->bd_hlen;
    649 			splx(s);
    650 
    651 			*(int *)addr = n;
    652 			break;
    653 		}
    654 
    655 	/*
    656 	 * Get buffer len [for read()].
    657 	 */
    658 	case BIOCGBLEN:
    659 		*(u_int *)addr = d->bd_bufsize;
    660 		break;
    661 
    662 	/*
    663 	 * Set buffer length.
    664 	 */
    665 	case BIOCSBLEN:
    666 		if (d->bd_bif != 0)
    667 			error = EINVAL;
    668 		else {
    669 			u_int size = *(u_int *)addr;
    670 
    671 			if (size > BPF_MAXBUFSIZE)
    672 				*(u_int *)addr = size = BPF_MAXBUFSIZE;
    673 			else if (size < BPF_MINBUFSIZE)
    674 				*(u_int *)addr = size = BPF_MINBUFSIZE;
    675 			d->bd_bufsize = size;
    676 		}
    677 		break;
    678 
    679 	/*
    680 	 * Set link layer read filter.
    681 	 */
    682 	case BIOCSETF:
    683 		error = bpf_setf(d, (struct bpf_program *)addr);
    684 		break;
    685 
    686 #ifdef BPF_KERN_FILTER
    687 	/*
    688 	 * Set TCP or UDP reject filter.
    689 	 */
    690 	case BIOCSTCPF:
    691 	case BIOCSUDPF:
    692 		if (!suser()) {
    693 			error = EPERM;
    694 			break;
    695 		}
    696 
    697 		/* Validate and store filter */
    698 		error = bpf_setf(d, (struct bpf_program *)addr);
    699 
    700 		/* Free possible old filter */
    701 		if (cmd == BIOCSTCPF)
    702 			p = &bpf_tcp_filter;
    703 		else
    704 			p = &bpf_udp_filter;
    705 		if (*p != NULL)
    706 			free((caddr_t)*p, M_DEVBUF);
    707 
    708 		/* Steal new filter (noop if error) */
    709 		s = splnet();
    710 		*p = d->bd_filter;
    711 		d->bd_filter = NULL;
    712 		splx(s);
    713 		break;
    714 #endif
    715 
    716 	/*
    717 	 * Flush read packet buffer.
    718 	 */
    719 	case BIOCFLUSH:
    720 		s = splnet();
    721 		reset_d(d);
    722 		splx(s);
    723 		break;
    724 
    725 	/*
    726 	 * Put interface into promiscuous mode.
    727 	 */
    728 	case BIOCPROMISC:
    729 		if (d->bd_bif == 0) {
    730 			/*
    731 			 * No interface attached yet.
    732 			 */
    733 			error = EINVAL;
    734 			break;
    735 		}
    736 		s = splnet();
    737 		if (d->bd_promisc == 0) {
    738 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
    739 			if (error == 0)
    740 				d->bd_promisc = 1;
    741 		}
    742 		splx(s);
    743 		break;
    744 
    745 	/*
    746 	 * Get device parameters.
    747 	 */
    748 	case BIOCGDLT:
    749 		if (d->bd_bif == 0)
    750 			error = EINVAL;
    751 		else
    752 			*(u_int *)addr = d->bd_bif->bif_dlt;
    753 		break;
    754 
    755 	/*
    756 	 * Set interface name.
    757 	 */
    758 	case BIOCGETIF:
    759 		if (d->bd_bif == 0)
    760 			error = EINVAL;
    761 		else
    762 			bpf_ifname(d->bd_bif->bif_ifp, (struct ifreq *)addr);
    763 		break;
    764 
    765 	/*
    766 	 * Set interface.
    767 	 */
    768 	case BIOCSETIF:
    769 		error = bpf_setif(d, (struct ifreq *)addr);
    770 		break;
    771 
    772 	/*
    773 	 * Set read timeout.
    774 	 */
    775 	case BIOCSRTIMEOUT:
    776 		{
    777 			struct timeval *tv = (struct timeval *)addr;
    778 
    779 			/* Compute number of ticks. */
    780 			d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
    781 			if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
    782 				d->bd_rtout = 1;
    783 			break;
    784 		}
    785 
    786 	/*
    787 	 * Get read timeout.
    788 	 */
    789 	case BIOCGRTIMEOUT:
    790 		{
    791 			struct timeval *tv = (struct timeval *)addr;
    792 
    793 			tv->tv_sec = d->bd_rtout / hz;
    794 			tv->tv_usec = (d->bd_rtout % hz) * tick;
    795 			break;
    796 		}
    797 
    798 	/*
    799 	 * Get packet stats.
    800 	 */
    801 	case BIOCGSTATS:
    802 		{
    803 			struct bpf_stat *bs = (struct bpf_stat *)addr;
    804 
    805 			bs->bs_recv = d->bd_rcount;
    806 			bs->bs_drop = d->bd_dcount;
    807 			break;
    808 		}
    809 
    810 	/*
    811 	 * Set immediate mode.
    812 	 */
    813 	case BIOCIMMEDIATE:
    814 		d->bd_immediate = *(u_int *)addr;
    815 		break;
    816 
    817 	case BIOCVERSION:
    818 		{
    819 			struct bpf_version *bv = (struct bpf_version *)addr;
    820 
    821 			bv->bv_major = BPF_MAJOR_VERSION;
    822 			bv->bv_minor = BPF_MINOR_VERSION;
    823 			break;
    824 		}
    825 
    826 	case BIOCGHDRCMPLT:	/* get "header already complete" flag */
    827 		*(u_int *)addr = d->bd_hdrcmplt;
    828 		break;
    829 
    830 	case BIOCSHDRCMPLT:	/* set "header already complete" flag */
    831 		d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
    832 		break;
    833 
    834 	case FIONBIO:		/* Non-blocking I/O */
    835 		if (*(int *)addr)
    836 			d->bd_rtout = -1;
    837 		else
    838 			d->bd_rtout = 0;
    839 		break;
    840 
    841 	case FIOASYNC:		/* Send signal on receive packets */
    842 		d->bd_async = *(int *)addr;
    843 		break;
    844 
    845 	/*
    846 	 * N.B.  ioctl (FIOSETOWN) and fcntl (F_SETOWN) both end up doing
    847 	 * the equivalent of a TIOCSPGRP and hence end up here.  *However*
    848 	 * TIOCSPGRP's arg is a process group if it's positive and a process
    849 	 * id if it's negative.  This is exactly the opposite of what the
    850 	 * other two functions want!  Therefore there is code in ioctl and
    851 	 * fcntl to negate the arg before calling here.
    852 	 */
    853 	case TIOCSPGRP:		/* Process or group to send signals to */
    854 		d->bd_pgid = *(int *)addr;
    855 		break;
    856 
    857 	case TIOCGPGRP:
    858 		*(int *)addr = d->bd_pgid;
    859 		break;
    860 	}
    861 	return (error);
    862 }
    863 
    864 /*
    865  * Set d's packet filter program to fp.  If this file already has a filter,
    866  * free it and replace it.  Returns EINVAL for bogus requests.
    867  */
    868 int
    869 bpf_setf(d, fp)
    870 	struct bpf_d *d;
    871 	struct bpf_program *fp;
    872 {
    873 	struct bpf_insn *fcode, *old;
    874 	u_int flen, size;
    875 	int s;
    876 
    877 	old = d->bd_filter;
    878 	if (fp->bf_insns == 0) {
    879 		if (fp->bf_len != 0)
    880 			return (EINVAL);
    881 		s = splnet();
    882 		d->bd_filter = 0;
    883 		reset_d(d);
    884 		splx(s);
    885 		if (old != 0)
    886 			free((caddr_t)old, M_DEVBUF);
    887 		return (0);
    888 	}
    889 	flen = fp->bf_len;
    890 	if (flen > BPF_MAXINSNS)
    891 		return (EINVAL);
    892 
    893 	size = flen * sizeof(*fp->bf_insns);
    894 	fcode = (struct bpf_insn *)malloc(size, M_DEVBUF, M_WAITOK);
    895 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
    896 	    bpf_validate(fcode, (int)flen)) {
    897 		s = splnet();
    898 		d->bd_filter = fcode;
    899 		reset_d(d);
    900 		splx(s);
    901 		if (old != 0)
    902 			free((caddr_t)old, M_DEVBUF);
    903 
    904 		return (0);
    905 	}
    906 	free((caddr_t)fcode, M_DEVBUF);
    907 	return (EINVAL);
    908 }
    909 
    910 /*
    911  * Detach a file from its current interface (if attached at all) and attach
    912  * to the interface indicated by the name stored in ifr.
    913  * Return an errno or 0.
    914  */
    915 static int
    916 bpf_setif(d, ifr)
    917 	struct bpf_d *d;
    918 	struct ifreq *ifr;
    919 {
    920 	struct bpf_if *bp;
    921 	char *cp;
    922 	int unit_seen, i, s, error;
    923 
    924 	/*
    925 	 * Make sure the provided name has a unit number, and default
    926 	 * it to '0' if not specified.
    927 	 * XXX This is ugly ... do this differently?
    928 	 */
    929 	unit_seen = 0;
    930 	cp = ifr->ifr_name;
    931 	cp[sizeof(ifr->ifr_name) - 1] = '\0';	/* sanity */
    932 	while (*cp++)
    933 		if (*cp >= '0' && *cp <= '9')
    934 			unit_seen = 1;
    935 	if (!unit_seen) {
    936 		/* Make sure to leave room for the '\0'. */
    937 		for (i = 0; i < (IFNAMSIZ - 1); ++i) {
    938 			if ((ifr->ifr_name[i] >= 'a' &&
    939 			     ifr->ifr_name[i] <= 'z') ||
    940 			    (ifr->ifr_name[i] >= 'A' &&
    941 			     ifr->ifr_name[i] <= 'Z'))
    942 				continue;
    943 			ifr->ifr_name[i] = '0';
    944 		}
    945 	}
    946 
    947 	/*
    948 	 * Look through attached interfaces for the named one.
    949 	 */
    950 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
    951 		struct ifnet *ifp = bp->bif_ifp;
    952 
    953 		if (ifp == 0 ||
    954 		    strcmp(ifp->if_xname, ifr->ifr_name) != 0)
    955 			continue;
    956 		/*
    957 		 * We found the requested interface.
    958 		 * If it's not up, return an error.
    959 		 * Allocate the packet buffers if we need to.
    960 		 * If we're already attached to requested interface,
    961 		 * just flush the buffer.
    962 		 */
    963 		if ((ifp->if_flags & IFF_UP) == 0)
    964 			return (ENETDOWN);
    965 
    966 		if (d->bd_sbuf == 0) {
    967 			error = bpf_allocbufs(d);
    968 			if (error != 0)
    969 				return (error);
    970 		}
    971 		s = splnet();
    972 		if (bp != d->bd_bif) {
    973 			if (d->bd_bif)
    974 				/*
    975 				 * Detach if attached to something else.
    976 				 */
    977 				bpf_detachd(d);
    978 
    979 			bpf_attachd(d, bp);
    980 		}
    981 		reset_d(d);
    982 		splx(s);
    983 		return (0);
    984 	}
    985 	/* Not found. */
    986 	return (ENXIO);
    987 }
    988 
    989 /*
    990  * Copy the interface name to the ifreq.
    991  */
    992 static void
    993 bpf_ifname(ifp, ifr)
    994 	struct ifnet *ifp;
    995 	struct ifreq *ifr;
    996 {
    997 
    998 	memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
    999 }
   1000 
   1001 /*
   1002  * Support for poll() system call
   1003  *
   1004  * Return true iff the specific operation will not block indefinitely.
   1005  * Otherwise, return false but make a note that a selwakeup() must be done.
   1006  */
   1007 int
   1008 bpfpoll(devvp, events, p)
   1009 	struct vnode *devvp;
   1010 	int events;
   1011 	struct proc *p;
   1012 {
   1013 	struct bpf_d *d;
   1014 	int revents;
   1015 	int s;
   1016 
   1017 	revents = 0;
   1018 	d = vdev_privdata(devvp);
   1019 	s = splnet();
   1020 
   1021 	/*
   1022 	 * An imitation of the FIONREAD ioctl code.
   1023 	 */
   1024 	if (events & (POLLIN | POLLRDNORM)) {
   1025 		if (d->bd_hlen != 0 || (d->bd_immediate && d->bd_slen != 0))
   1026 			revents |= events & (POLLIN | POLLRDNORM);
   1027 		else
   1028 			selrecord(p, &d->bd_sel);
   1029 	}
   1030 
   1031 	splx(s);
   1032 	return (revents);
   1033 }
   1034 
   1035 /*
   1036  * Incoming linkage from device drivers.  Process the packet pkt, of length
   1037  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
   1038  * by each process' filter, and if accepted, stashed into the corresponding
   1039  * buffer.
   1040  */
   1041 void
   1042 bpf_tap(arg, pkt, pktlen)
   1043 	caddr_t arg;
   1044 	u_char *pkt;
   1045 	u_int pktlen;
   1046 {
   1047 	struct bpf_if *bp;
   1048 	struct bpf_d *d;
   1049 	u_int slen;
   1050 	/*
   1051 	 * Note that the ipl does not have to be raised at this point.
   1052 	 * The only problem that could arise here is that if two different
   1053 	 * interfaces shared any data.  This is not the case.
   1054 	 */
   1055 	bp = (struct bpf_if *)arg;
   1056 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1057 		++d->bd_rcount;
   1058 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
   1059 		if (slen != 0)
   1060 			catchpacket(d, pkt, pktlen, slen, memcpy);
   1061 	}
   1062 }
   1063 
   1064 /*
   1065  * Copy data from an mbuf chain into a buffer.  This code is derived
   1066  * from m_copydata in sys/uipc_mbuf.c.
   1067  */
   1068 static void *
   1069 bpf_mcpy(dst_arg, src_arg, len)
   1070 	void *dst_arg;
   1071 	const void *src_arg;
   1072 	size_t len;
   1073 {
   1074 	const struct mbuf *m;
   1075 	u_int count;
   1076 	u_char *dst;
   1077 
   1078 	m = src_arg;
   1079 	dst = dst_arg;
   1080 	while (len > 0) {
   1081 		if (m == 0)
   1082 			panic("bpf_mcpy");
   1083 		count = min(m->m_len, len);
   1084 		memcpy((caddr_t)dst, mtod(m, caddr_t), count);
   1085 		m = m->m_next;
   1086 		dst += count;
   1087 		len -= count;
   1088 	}
   1089 	return(dst_arg);
   1090 }
   1091 
   1092 /*
   1093  * Incoming linkage from device drivers, when packet is in an mbuf chain.
   1094  */
   1095 void
   1096 bpf_mtap(arg, m)
   1097 	caddr_t arg;
   1098 	struct mbuf *m;
   1099 {
   1100 	struct bpf_if *bp = (struct bpf_if *)arg;
   1101 	struct bpf_d *d;
   1102 	u_int pktlen, slen;
   1103 	struct mbuf *m0;
   1104 
   1105 	pktlen = 0;
   1106 	for (m0 = m; m0 != 0; m0 = m0->m_next)
   1107 		pktlen += m0->m_len;
   1108 
   1109 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
   1110 		++d->bd_rcount;
   1111 		slen = bpf_filter(d->bd_filter, (u_char *)m, pktlen, 0);
   1112 		if (slen != 0)
   1113 			catchpacket(d, (u_char *)m, pktlen, slen, bpf_mcpy);
   1114 	}
   1115 }
   1116 
   1117 /*
   1118  * Move the packet data from interface memory (pkt) into the
   1119  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
   1120  * otherwise 0.  "copy" is the routine called to do the actual data
   1121  * transfer.  memcpy is passed in to copy contiguous chunks, while
   1122  * bpf_mcpy is passed in to copy mbuf chains.  In the latter case,
   1123  * pkt is really an mbuf.
   1124  */
   1125 static void
   1126 catchpacket(d, pkt, pktlen, snaplen, cpfn)
   1127 	struct bpf_d *d;
   1128 	u_char *pkt;
   1129 	u_int pktlen, snaplen;
   1130 	void *(*cpfn) __P((void *, const void *, size_t));
   1131 {
   1132 	struct bpf_hdr *hp;
   1133 	int totlen, curlen;
   1134 	int hdrlen = d->bd_bif->bif_hdrlen;
   1135 	/*
   1136 	 * Figure out how many bytes to move.  If the packet is
   1137 	 * greater or equal to the snapshot length, transfer that
   1138 	 * much.  Otherwise, transfer the whole packet (unless
   1139 	 * we hit the buffer size limit).
   1140 	 */
   1141 	totlen = hdrlen + min(snaplen, pktlen);
   1142 	if (totlen > d->bd_bufsize)
   1143 		totlen = d->bd_bufsize;
   1144 
   1145 	/*
   1146 	 * Round up the end of the previous packet to the next longword.
   1147 	 */
   1148 	curlen = BPF_WORDALIGN(d->bd_slen);
   1149 	if (curlen + totlen > d->bd_bufsize) {
   1150 		/*
   1151 		 * This packet will overflow the storage buffer.
   1152 		 * Rotate the buffers if we can, then wakeup any
   1153 		 * pending reads.
   1154 		 */
   1155 		if (d->bd_fbuf == 0) {
   1156 			/*
   1157 			 * We haven't completed the previous read yet,
   1158 			 * so drop the packet.
   1159 			 */
   1160 			++d->bd_dcount;
   1161 			return;
   1162 		}
   1163 		ROTATE_BUFFERS(d);
   1164 		bpf_wakeup(d);
   1165 		curlen = 0;
   1166 	}
   1167 	else if (d->bd_immediate)
   1168 		/*
   1169 		 * Immediate mode is set.  A packet arrived so any
   1170 		 * reads should be woken up.
   1171 		 */
   1172 		bpf_wakeup(d);
   1173 
   1174 	/*
   1175 	 * Append the bpf header.
   1176 	 */
   1177 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
   1178 	microtime(&hp->bh_tstamp);
   1179 	hp->bh_datalen = pktlen;
   1180 	hp->bh_hdrlen = hdrlen;
   1181 	/*
   1182 	 * Copy the packet data into the store buffer and update its length.
   1183 	 */
   1184 	(*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
   1185 	d->bd_slen = curlen + totlen;
   1186 }
   1187 
   1188 /*
   1189  * Initialize all nonzero fields of a descriptor.
   1190  */
   1191 static int
   1192 bpf_allocbufs(d)
   1193 	struct bpf_d *d;
   1194 {
   1195 
   1196 	d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_WAITOK);
   1197 	d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_WAITOK);
   1198 	d->bd_slen = 0;
   1199 	d->bd_hlen = 0;
   1200 	return (0);
   1201 }
   1202 
   1203 /*
   1204  * Free buffers currently in use by a descriptor.
   1205  * Called on close.
   1206  */
   1207 static void
   1208 bpf_freed(d)
   1209 	struct bpf_d *d;
   1210 {
   1211 	/*
   1212 	 * We don't need to lock out interrupts since this descriptor has
   1213 	 * been detached from its interface and it yet hasn't been marked
   1214 	 * free.
   1215 	 */
   1216 	if (d->bd_sbuf != 0) {
   1217 		free(d->bd_sbuf, M_DEVBUF);
   1218 		if (d->bd_hbuf != 0)
   1219 			free(d->bd_hbuf, M_DEVBUF);
   1220 		if (d->bd_fbuf != 0)
   1221 			free(d->bd_fbuf, M_DEVBUF);
   1222 	}
   1223 	if (d->bd_filter)
   1224 		free((caddr_t)d->bd_filter, M_DEVBUF);
   1225 
   1226 	D_MARKFREE(d);
   1227 }
   1228 
   1229 /*
   1230  * Attach an interface to bpf.  dlt is the link layer type; hdrlen is the
   1231  * fixed size of the link header (variable length headers not yet supported).
   1232  */
   1233 void
   1234 bpfattach(ifp, dlt, hdrlen)
   1235 	struct ifnet *ifp;
   1236 	u_int dlt, hdrlen;
   1237 {
   1238 	struct bpf_if *bp;
   1239 	bp = (struct bpf_if *)malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
   1240 	if (bp == 0)
   1241 		panic("bpfattach");
   1242 
   1243 	bp->bif_dlist = 0;
   1244 	bp->bif_driverp = (struct bpf_if **)&ifp->if_bpf;
   1245 	bp->bif_ifp = ifp;
   1246 	bp->bif_dlt = dlt;
   1247 
   1248 	bp->bif_next = bpf_iflist;
   1249 	bpf_iflist = bp;
   1250 
   1251 	*bp->bif_driverp = 0;
   1252 
   1253 	/*
   1254 	 * Compute the length of the bpf header.  This is not necessarily
   1255 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1256 	 * that the network layer header begins on a longword boundary (for
   1257 	 * performance reasons and to alleviate alignment restrictions).
   1258 	 */
   1259 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1260 
   1261 #if 0
   1262 	printf("bpf: %s attached\n", ifp->if_xname);
   1263 #endif
   1264 }
   1265 
   1266 /*
   1267  * Remove an interface from bpf.
   1268  */
   1269 void
   1270 bpfdetach(ifp)
   1271 	struct ifnet *ifp;
   1272 {
   1273 	struct bpf_if *bp, **pbp;
   1274 	struct bpf_d *d;
   1275 	int i, s, cmaj;
   1276 
   1277 	/* locate the major number */
   1278 	for (cmaj = 0; cmaj <= nchrdev; cmaj++)
   1279 		if (cdevsw[cmaj].d_open == bpfopen)
   1280 			break;
   1281 
   1282 	/* Nuke the vnodes for any open instances */
   1283 	for (i = 0; i < NBPFILTER; ++i) {
   1284 		d = &bpf_dtab[i];
   1285 		if (!D_ISFREE(d) && d->bd_bif != NULL &&
   1286 		    d->bd_bif->bif_ifp == ifp) {
   1287 			/*
   1288 			 * Detach the descriptor from an interface now.
   1289 			 * It will be free'ed later by close routine.
   1290 			 */
   1291 			s = splnet();
   1292 			d->bd_promisc = 0;	/* we can't touch device. */
   1293 			bpf_detachd(d);
   1294 			splx(s);
   1295 			vdevgone(cmaj, i, i, VCHR);
   1296 		}
   1297 	}
   1298 
   1299 	for (bp = bpf_iflist, pbp = &bpf_iflist;
   1300 	     bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
   1301 		if (bp->bif_ifp == ifp) {
   1302 			*pbp = bp->bif_next;
   1303 			free(bp, M_DEVBUF);
   1304 			break;
   1305 		}
   1306 	}
   1307 }
   1308 
   1309 /*
   1310  * Change the data link type of a BPF instance.
   1311  */
   1312 void
   1313 bpf_change_type(ifp, dlt, hdrlen)
   1314 	struct ifnet *ifp;
   1315 	u_int dlt, hdrlen;
   1316 {
   1317 	struct bpf_if *bp;
   1318 
   1319 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
   1320 		if (bp->bif_driverp == (struct bpf_if **)&ifp->if_bpf)
   1321 			break;
   1322 	}
   1323 	if (bp == NULL)
   1324 		panic("bpf_change_type");
   1325 
   1326 	bp->bif_dlt = dlt;
   1327 
   1328 	/*
   1329 	 * Compute the length of the bpf header.  This is not necessarily
   1330 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
   1331 	 * that the network layer header begins on a longword boundary (for
   1332 	 * performance reasons and to alleviate alignment restrictions).
   1333 	 */
   1334 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
   1335 }
   1336