xref: /original-bsd/sys/net/bpf.c (revision 68d9582f)
1 /*
2  * Copyright (c) 1990, 1991 Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from the Stanford/CMU enet packet filter,
6  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
7  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
8  * Berkeley Laboratory.
9  *
10  * %sccs.include.redist.c%
11  *
12  *      @(#)bpf.c	7.9 (Berkeley) 06/07/92
13  *
14  * static char rcsid[] =
15  * "$Header: bpf.c,v 1.33 91/10/27 21:21:58 mccanne Exp $";
16  */
17 
18 #include "bpfilter.h"
19 
20 #if NBPFILTER > 0
21 
22 #ifndef __GNUC__
23 #define inline
24 #else
25 #define inline __inline__
26 #endif
27 
28 #include <sys/param.h>
29 #include <sys/systm.h>
30 #include <sys/mbuf.h>
31 #include <sys/buf.h>
32 #include <sys/dir.h>
33 #include <sys/time.h>
34 #include <sys/proc.h>
35 #include <sys/user.h>
36 #include <sys/ioctl.h>
37 #include <sys/map.h>
38 
39 #include <sys/file.h>
40 #if defined(sparc) && BSD < 199103
41 #include <sys/stream.h>
42 #endif
43 #include <sys/tty.h>
44 #include <sys/uio.h>
45 
46 #include <sys/protosw.h>
47 #include <sys/socket.h>
48 #include <net/if.h>
49 
50 #include <net/bpf.h>
51 #include <net/bpfdesc.h>
52 
53 #include <sys/errno.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/if_ether.h>
57 #include <sys/kernel.h>
58 
59 /*
60  * Older BSDs don't have kernel malloc.
61  */
62 #if BSD < 199103
63 extern bcopy();
64 static caddr_t bpf_alloc();
65 #include <net/bpf_compat.h>
66 #define BPF_BUFSIZE (MCLBYTES-8)
67 #define UIOMOVE(cp, len, code, uio) uiomove(cp, len, code, uio)
68 #else
69 #define BPF_BUFSIZE 4096
70 #define UIOMOVE(cp, len, code, uio) uiomove(cp, len, uio)
71 #endif
72 
73 #define PRINET  26			/* interruptible */
74 
75 /*
76  * The default read buffer size is patchable.
77  */
78 int bpf_bufsize = BPF_BUFSIZE;
79 
80 /*
81  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
82  *  bpf_dtab holds the descriptors, indexed by minor device #
83  */
84 struct bpf_if	*bpf_iflist;
85 struct bpf_d	bpf_dtab[NBPFILTER];
86 
87 static void	bpf_ifname();
88 static void	catchpacket();
89 static void	bpf_freed();
90 static int	bpf_setif();
91 static int	bpf_initd();
92 static int	bpf_allocbufs();
93 
94 static int
95 bpf_movein(uio, linktype, mp, sockp)
96 	register struct uio *uio;
97 	int linktype;
98 	register struct mbuf **mp;
99 	register struct sockaddr *sockp;
100 {
101 	struct mbuf *m;
102 	int error;
103 	int len;
104 	int hlen;
105 
106 	/*
107 	 * Build a sockaddr based on the data link layer type.
108 	 * We do this at this level because the ethernet header
109 	 * is copied directly into the data field of the sockaddr.
110 	 * In the case of SLIP, there is no header and the packet
111 	 * is forwarded as is.
112 	 * Also, we are careful to leave room at the front of the mbuf
113 	 * for the link level header.
114 	 */
115 	switch (linktype) {
116 
117 	case DLT_SLIP:
118 		sockp->sa_family = AF_INET;
119 		hlen = 0;
120 		break;
121 
122 	case DLT_EN10MB:
123 		sockp->sa_family = AF_UNSPEC;
124 		/* XXX Would MAXLINKHDR be better? */
125 		hlen = sizeof(struct ether_header);
126 		break;
127 
128 	case DLT_FDDI:
129 		sockp->sa_family = AF_UNSPEC;
130 		/* XXX 4(FORMAC)+6(dst)+6(src)+3(LLC)+5(SNAP) */
131 		hlen = 24;
132 		break;
133 
134 	case DLT_NULL:
135 		sockp->sa_family = AF_UNSPEC;
136 		hlen = 0;
137 		break;
138 
139 	default:
140 		return (EIO);
141 	}
142 
143 	len = uio->uio_resid;
144 	if ((unsigned)len > MCLBYTES)
145 		return (EIO);
146 
147 	MGET(m, M_WAIT, MT_DATA);
148 	if (m == 0)
149 		return (ENOBUFS);
150 	if (len > MLEN) {
151 #if BSD >= 199103
152 		MCLGET(m, M_WAIT);
153 		if ((m->m_flags & M_EXT) == 0) {
154 #else
155 		MCLGET(m);
156 		if (m->m_len != MCLBYTES) {
157 #endif
158 			error = ENOBUFS;
159 			goto bad;
160 		}
161 	}
162 	m->m_len = len;
163 	*mp = m;
164 	/*
165 	 * Make room for link header.
166 	 */
167 	if (hlen != 0) {
168 		m->m_len -= hlen;
169 #if BSD >= 199103
170 		m->m_data += hlen; /* XXX */
171 #else
172 		m->m_off += hlen;
173 #endif
174 		error = UIOMOVE((caddr_t)sockp->sa_data, hlen, UIO_WRITE, uio);
175 		if (error)
176 			goto bad;
177 	}
178 	error = UIOMOVE(mtod(m, caddr_t), len - hlen, UIO_WRITE, uio);
179 	if (!error)
180 		return (0);
181  bad:
182 	m_freem(m);
183 	return (error);
184 }
185 
186 /*
187  * Attach file to the bpf interface, i.e. make d listen on bp.
188  * Must be called at splimp.
189  */
190 static void
191 bpf_attachd(d, bp)
192 	struct bpf_d *d;
193 	struct bpf_if *bp;
194 {
195 	/*
196 	 * Point d at bp, and add d to the interface's list of listeners.
197 	 * Finally, point the driver's bpf cookie at the interface so
198 	 * it will divert packets to bpf.
199 	 */
200 	d->bd_bif = bp;
201 	d->bd_next = bp->bif_dlist;
202 	bp->bif_dlist = d;
203 
204 	*bp->bif_driverp = bp;
205 }
206 
207 /*
208  * Detach a file from its interface.
209  */
210 static void
211 bpf_detachd(d)
212 	struct bpf_d *d;
213 {
214 	struct bpf_d **p;
215 	struct bpf_if *bp;
216 
217 	bp = d->bd_bif;
218 	/*
219 	 * Check if this descriptor had requested promiscuous mode.
220 	 * If so, turn it off.
221 	 */
222 	if (d->bd_promisc) {
223 		d->bd_promisc = 0;
224 		if (ifpromisc(bp->bif_ifp, 0))
225 			/*
226 			 * Something is really wrong if we were able to put
227 			 * the driver into promiscuous mode, but can't
228 			 * take it out.
229 			 */
230 			panic("bpf: ifpromisc failed");
231 	}
232 	/* Remove d from the interface's descriptor list. */
233 	p = &bp->bif_dlist;
234 	while (*p != d) {
235 		p = &(*p)->bd_next;
236 		if (*p == 0)
237 			panic("bpf_detachd: descriptor not in list");
238 	}
239 	*p = (*p)->bd_next;
240 	if (bp->bif_dlist == 0)
241 		/*
242 		 * Let the driver know that there are no more listeners.
243 		 */
244 		*d->bd_bif->bif_driverp = 0;
245 	d->bd_bif = 0;
246 }
247 
248 
249 /*
250  * Mark a descriptor free by making it point to itself.
251  * This is probably cheaper than marking with a constant since
252  * the address should be in a register anyway.
253  */
254 #define D_ISFREE(d) ((d) == (d)->bd_next)
255 #define D_MARKFREE(d) ((d)->bd_next = (d))
256 #define D_MARKUSED(d) ((d)->bd_next = 0)
257 
258 /*
259  * Open ethernet device.  Returns ENXIO for illegal minor device number,
260  * EBUSY if file is open by another process.
261  */
262 /* ARGSUSED */
263 int
264 bpfopen(dev, flag)
265 	dev_t dev;
266 	int flag;
267 {
268 	register struct bpf_d *d;
269 
270 	if (minor(dev) >= NBPFILTER)
271 		return (ENXIO);
272 	/*
273 	 * Each minor can be opened by only one process.  If the requested
274 	 * minor is in use, return EBUSY.
275 	 */
276 	d = &bpf_dtab[minor(dev)];
277 	if (!D_ISFREE(d))
278 		return (EBUSY);
279 
280 	/* Mark "free" and do most initialization. */
281 	bzero((char *)d, sizeof(*d));
282 	d->bd_bufsize = bpf_bufsize;
283 
284 	return (0);
285 }
286 
287 /*
288  * Close the descriptor by detaching it from its interface,
289  * deallocating its buffers, and marking it free.
290  */
291 /* ARGSUSED */
292 int
293 bpfclose(dev, flag)
294 	dev_t dev;
295 	int flag;
296 {
297 	register struct bpf_d *d = &bpf_dtab[minor(dev)];
298 	register int s;
299 
300 	s = splimp();
301 	if (d->bd_bif)
302 		bpf_detachd(d);
303 	splx(s);
304 	bpf_freed(d);
305 
306 	return (0);
307 }
308 
309 /*
310  * Support for SunOS, which does not have tsleep.
311  */
312 #if BSD < 199103
313 static
314 bpf_timeout(arg)
315 	caddr_t arg;
316 {
317 	struct bpf_d *d = (struct bpf_d *)arg;
318 	d->bd_timedout = 1;
319 	wakeup(arg);
320 }
321 
322 #define BPF_SLEEP(chan, pri, s, t) bpf_sleep((struct bpf_d *)chan)
323 
324 int
325 bpf_sleep(d)
326 	register struct bpf_d *d;
327 {
328 	register int rto = d->bd_rtout;
329 	register int st;
330 
331 	if (rto != 0) {
332 		d->bd_timedout = 0;
333 		timeout(bpf_timeout, (caddr_t)d, rto);
334 	}
335 	st = sleep((caddr_t)d, PRINET|PCATCH);
336 	if (rto != 0) {
337 		if (d->bd_timedout == 0)
338 			untimeout(bpf_timeout, (caddr_t)d);
339 		else if (st == 0)
340 			return EWOULDBLOCK;
341 	}
342 	return (st != 0) ? EINTR : 0;
343 }
344 #else
345 #define BPF_SLEEP tsleep
346 #endif
347 
348 /*
349  * Rotate the packet buffers in descriptor d.  Move the store buffer
350  * into the hold slot, and the free buffer into the store slot.
351  * Zero the length of the new store buffer.
352  */
353 #define ROTATE_BUFFERS(d) \
354 	(d)->bd_hbuf = (d)->bd_sbuf; \
355 	(d)->bd_hlen = (d)->bd_slen; \
356 	(d)->bd_sbuf = (d)->bd_fbuf; \
357 	(d)->bd_slen = 0; \
358 	(d)->bd_fbuf = 0;
359 /*
360  *  bpfread - read next chunk of packets from buffers
361  */
362 int
363 bpfread(dev, uio)
364 	dev_t dev;
365 	register struct uio *uio;
366 {
367 	register struct bpf_d *d = &bpf_dtab[minor(dev)];
368 	int error;
369 	int s;
370 
371 	/*
372 	 * Restrict application to use a buffer the same size as
373 	 * as kernel buffers.
374 	 */
375 	if (uio->uio_resid != d->bd_bufsize)
376 		return (EINVAL);
377 
378 	s = splimp();
379 	/*
380 	 * If the hold buffer is empty, then do a timed sleep, which
381 	 * ends when the timeout expires or when enough packets
382 	 * have arrived to fill the store buffer.
383 	 */
384 	while (d->bd_hbuf == 0) {
385 		if (d->bd_immediate && d->bd_slen != 0) {
386 			/*
387 			 * A packet(s) either arrived since the previous
388 			 * read or arrived while we were asleep.
389 			 * Rotate the buffers and return what's here.
390 			 */
391 			ROTATE_BUFFERS(d);
392 			break;
393 		}
394 		error = BPF_SLEEP((caddr_t)d, PRINET|PCATCH, "bpf",
395 				  d->bd_rtout);
396 		if (error == EINTR || error == ERESTART) {
397 			splx(s);
398 			return (error);
399 		}
400 		if (error == EWOULDBLOCK) {
401 			/*
402 			 * On a timeout, return what's in the buffer,
403 			 * which may be nothing.  If there is something
404 			 * in the store buffer, we can rotate the buffers.
405 			 */
406 			if (d->bd_hbuf)
407 				/*
408 				 * We filled up the buffer in between
409 				 * getting the timeout and arriving
410 				 * here, so we don't need to rotate.
411 				 */
412 				break;
413 
414 			if (d->bd_slen == 0) {
415 				splx(s);
416 				return (0);
417 			}
418 			ROTATE_BUFFERS(d);
419 			break;
420 		}
421 	}
422 	/*
423 	 * At this point, we know we have something in the hold slot.
424 	 */
425 	splx(s);
426 
427 	/*
428 	 * Move data from hold buffer into user space.
429 	 * We know the entire buffer is transferred since
430 	 * we checked above that the read buffer is bpf_bufsize bytes.
431 	 */
432 	error = UIOMOVE(d->bd_hbuf, d->bd_hlen, UIO_READ, uio);
433 
434 	s = splimp();
435 	d->bd_fbuf = d->bd_hbuf;
436 	d->bd_hbuf = 0;
437 	d->bd_hlen = 0;
438 	splx(s);
439 
440 	return (error);
441 }
442 
443 
444 /*
445  * If there are processes sleeping on this descriptor, wake them up.
446  */
447 static inline void
448 bpf_wakeup(d)
449 	register struct bpf_d *d;
450 {
451 	wakeup((caddr_t)d);
452 #if BSD >= 199103
453 	selwakeup(&d->bd_sel);
454 	/* XXX */
455 	d->bd_sel.si_pid = 0;
456 #else
457 	if (d->bd_selproc) {
458 		selwakeup(d->bd_selproc, (int)d->bd_selcoll);
459 		d->bd_selcoll = 0;
460 		d->bd_selproc = 0;
461 	}
462 #endif
463 }
464 
465 int
466 bpfwrite(dev, uio)
467 	dev_t dev;
468 	struct uio *uio;
469 {
470 	register struct bpf_d *d = &bpf_dtab[minor(dev)];
471 	struct ifnet *ifp;
472 	struct mbuf *m;
473 	int error, s;
474 	static struct sockaddr dst;
475 
476 	if (d->bd_bif == 0)
477 		return (ENXIO);
478 
479 	ifp = d->bd_bif->bif_ifp;
480 
481 	if (uio->uio_resid == 0)
482 		return (0);
483 	if (uio->uio_resid > ifp->if_mtu)
484 		return (EMSGSIZE);
485 
486 	error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, &m, &dst);
487 	if (error)
488 		return (error);
489 
490 	s = splnet();
491 #if BSD >= 199103
492 	error = (*ifp->if_output)(ifp, m, &dst, (struct rtentry *)0);
493 #else
494 	error = (*ifp->if_output)(ifp, m, &dst);
495 #endif
496 	splx(s);
497 	/*
498 	 * The driver frees the mbuf.
499 	 */
500 	return (error);
501 }
502 
503 /*
504  * Reset a descriptor by flushing its packet buffer and clearing the
505  * receive and drop counts.  Should be called at splimp.
506  */
507 static void
508 reset_d(d)
509 	struct bpf_d *d;
510 {
511 	if (d->bd_hbuf) {
512 		/* Free the hold buffer. */
513 		d->bd_fbuf = d->bd_hbuf;
514 		d->bd_hbuf = 0;
515 	}
516 	d->bd_slen = 0;
517 	d->bd_hlen = 0;
518 	d->bd_rcount = 0;
519 	d->bd_dcount = 0;
520 }
521 
522 /*
523  *  FIONREAD		Check for read packet available.
524  *  SIOCGIFADDR		Get interface address - convenient hook to driver.
525  *  BIOCGBLEN		Get buffer len [for read()].
526  *  BIOCSETF		Set ethernet read filter.
527  *  BIOCFLUSH		Flush read packet buffer.
528  *  BIOCPROMISC		Put interface into promiscuous mode.
529  *  BIOCGDLT		Get link layer type.
530  *  BIOCGETIF		Get interface name.
531  *  BIOCSETIF		Set interface.
532  *  BIOCSRTIMEOUT	Set read timeout.
533  *  BIOCGRTIMEOUT	Get read timeout.
534  *  BIOCGSTATS		Get packet stats.
535  *  BIOCIMMEDIATE	Set immediate mode.
536  *  BIOCVERSION		Get filter language version.
537  */
538 /* ARGSUSED */
539 int
540 bpfioctl(dev, cmd, addr, flag)
541 	dev_t dev;
542 	int cmd;
543 	caddr_t addr;
544 	int flag;
545 {
546 	register struct bpf_d *d = &bpf_dtab[minor(dev)];
547 	int s, error = 0;
548 
549 	switch (cmd) {
550 
551 	default:
552 		error = EINVAL;
553 		break;
554 
555 	/*
556 	 * Check for read packet available.
557 	 */
558 	case FIONREAD:
559 		{
560 			int n;
561 
562 			s = splimp();
563 			n = d->bd_slen;
564 			if (d->bd_hbuf)
565 				n += d->bd_hlen;
566 			splx(s);
567 
568 			*(int *)addr = n;
569 			break;
570 		}
571 
572 	case SIOCGIFADDR:
573 		{
574 			struct ifnet *ifp;
575 
576 			if (d->bd_bif == 0)
577 				error = EINVAL;
578 			else {
579 				ifp = d->bd_bif->bif_ifp;
580 				error = (*ifp->if_ioctl)(ifp, cmd, addr);
581 			}
582 			break;
583 		}
584 
585 	/*
586 	 * Get buffer len [for read()].
587 	 */
588 	case BIOCGBLEN:
589 		*(u_int *)addr = d->bd_bufsize;
590 		break;
591 
592 	/*
593 	 * Set buffer length.
594 	 */
595 	case BIOCSBLEN:
596 #if BSD < 199103
597 		error = EINVAL;
598 #else
599 		if (d->bd_bif != 0)
600 			error = EINVAL;
601 		else {
602 			register u_int size = *(u_int *)addr;
603 
604 			if (size > BPF_MAXBUFSIZE)
605 				*(u_int *)addr = size = BPF_MAXBUFSIZE;
606 			else if (size < BPF_MINBUFSIZE)
607 				*(u_int *)addr = size = BPF_MINBUFSIZE;
608 			d->bd_bufsize = size;
609 		}
610 #endif
611 		break;
612 
613 	/*
614 	 * Set link layer read filter.
615 	 */
616 	case BIOCSETF:
617 		error = bpf_setf(d, (struct bpf_program *)addr);
618 		break;
619 
620 	/*
621 	 * Flush read packet buffer.
622 	 */
623 	case BIOCFLUSH:
624 		s = splimp();
625 		reset_d(d);
626 		splx(s);
627 		break;
628 
629 	/*
630 	 * Put interface into promiscuous mode.
631 	 */
632 	case BIOCPROMISC:
633 		if (d->bd_bif == 0) {
634 			/*
635 			 * No interface attached yet.
636 			 */
637 			error = EINVAL;
638 			break;
639 		}
640 		s = splimp();
641 		if (d->bd_promisc == 0) {
642 			error = ifpromisc(d->bd_bif->bif_ifp, 1);
643 			if (error == 0)
644 				d->bd_promisc = 1;
645 		}
646 		splx(s);
647 		break;
648 
649 	/*
650 	 * Get device parameters.
651 	 */
652 	case BIOCGDLT:
653 		if (d->bd_bif == 0)
654 			error = EINVAL;
655 		else
656 			*(u_int *)addr = d->bd_bif->bif_dlt;
657 		break;
658 
659 	/*
660 	 * Set interface name.
661 	 */
662 	case BIOCGETIF:
663 		if (d->bd_bif == 0)
664 			error = EINVAL;
665 		else
666 			bpf_ifname(d->bd_bif->bif_ifp, (struct ifreq *)addr);
667 		break;
668 
669 	/*
670 	 * Set interface.
671 	 */
672 	case BIOCSETIF:
673 		error = bpf_setif(d, (struct ifreq *)addr);
674 		break;
675 
676 	/*
677 	 * Set read timeout.
678 	 */
679 	case BIOCSRTIMEOUT:
680 		{
681 			struct timeval *tv = (struct timeval *)addr;
682 			u_long msec;
683 
684 			/* Compute number of milliseconds. */
685 			msec = tv->tv_sec * 1000 + tv->tv_usec / 1000;
686 			/* Scale milliseconds to ticks.  Assume hard
687 			   clock has millisecond or greater resolution
688 			   (i.e. tick >= 1000).  For 10ms hardclock,
689 			   tick/1000 = 10, so rtout<-msec/10. */
690 			d->bd_rtout = msec / (tick / 1000);
691 			break;
692 		}
693 
694 	/*
695 	 * Get read timeout.
696 	 */
697 	case BIOCGRTIMEOUT:
698 		{
699 			struct timeval *tv = (struct timeval *)addr;
700 			u_long msec = d->bd_rtout;
701 
702 			msec *= tick / 1000;
703 			tv->tv_sec = msec / 1000;
704 			tv->tv_usec = msec % 1000;
705 			break;
706 		}
707 
708 	/*
709 	 * Get packet stats.
710 	 */
711 	case BIOCGSTATS:
712 		{
713 			struct bpf_stat *bs = (struct bpf_stat *)addr;
714 
715 			bs->bs_recv = d->bd_rcount;
716 			bs->bs_drop = d->bd_dcount;
717 			break;
718 		}
719 
720 	/*
721 	 * Set immediate mode.
722 	 */
723 	case BIOCIMMEDIATE:
724 		d->bd_immediate = *(u_int *)addr;
725 		break;
726 
727 	case BIOCVERSION:
728 		{
729 			struct bpf_version *bv = (struct bpf_version *)addr;
730 
731 			bv->bv_major = BPF_MAJOR_VERSION;
732 			bv->bv_minor = BPF_MINOR_VERSION;
733 			break;
734 		}
735 	}
736 	return (error);
737 }
738 
739 /*
740  * Set d's packet filter program to fp.  If this file already has a filter,
741  * free it and replace it.  Returns EINVAL for bogus requests.
742  */
743 int
744 bpf_setf(d, fp)
745 	struct bpf_d *d;
746 	struct bpf_program *fp;
747 {
748 	struct bpf_insn *fcode, *old;
749 	u_int flen, size;
750 	int s;
751 
752 	old = d->bd_filter;
753 	if (fp->bf_insns == 0) {
754 		if (fp->bf_len != 0)
755 			return (EINVAL);
756 		s = splimp();
757 		d->bd_filter = 0;
758 		reset_d(d);
759 		splx(s);
760 		if (old != 0)
761 			free((caddr_t)old, M_DEVBUF);
762 		return (0);
763 	}
764 	flen = fp->bf_len;
765 	if (flen > BPF_MAXINSNS)
766 		return (EINVAL);
767 
768 	size = flen * sizeof(*fp->bf_insns);
769 	fcode = (struct bpf_insn *)malloc(size, M_DEVBUF, M_WAITOK);
770 	if (copyin((caddr_t)fp->bf_insns, (caddr_t)fcode, size) == 0 &&
771 	    bpf_validate(fcode, (int)flen)) {
772 		s = splimp();
773 		d->bd_filter = fcode;
774 		reset_d(d);
775 		splx(s);
776 		if (old != 0)
777 			free((caddr_t)old, M_DEVBUF);
778 
779 		return (0);
780 	}
781 	free((caddr_t)fcode, M_DEVBUF);
782 	return (EINVAL);
783 }
784 
785 /*
786  * Detach a file from its current interface (if attached at all) and attach
787  * to the interface indicated by the name stored in ifr.
788  * Return an errno or 0.
789  */
790 static int
791 bpf_setif(d, ifr)
792 	struct bpf_d *d;
793 	struct ifreq *ifr;
794 {
795 	struct bpf_if *bp;
796 	char *cp;
797 	int unit, s, error;
798 
799 	/*
800 	 * Separate string into name part and unit number.  Put a null
801 	 * byte at the end of the name part, and compute the number.
802 	 * If the a unit number is unspecified, the default is 0,
803 	 * as initialized above.  XXX This should be common code.
804 	 */
805 	unit = 0;
806 	cp = ifr->ifr_name;
807 	cp[sizeof(ifr->ifr_name) - 1] = '\0';
808 	while (*cp++) {
809 		if (*cp >= '0' && *cp <= '9') {
810 			unit = *cp - '0';
811 			*cp++ = '\0';
812 			while (*cp)
813 				unit = 10 * unit + *cp++ - '0';
814 			break;
815 		}
816 	}
817 	/*
818 	 * Look through attached interfaces for the named one.
819 	 */
820 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
821 		struct ifnet *ifp = bp->bif_ifp;
822 
823 		if (ifp == 0 || unit != ifp->if_unit
824 		    || strcmp(ifp->if_name, ifr->ifr_name) != 0)
825 			continue;
826 		/*
827 		 * We found the requested interface.
828 		 * If it's not up, return an error.
829 		 * Allocate the packet buffers if we need to.
830 		 * If we're already attached to requested interface,
831 		 * just flush the buffer.
832 		 */
833 		if ((ifp->if_flags & IFF_UP) == 0)
834 			return (ENETDOWN);
835 
836 		if (d->bd_sbuf == 0) {
837 			error = bpf_allocbufs(d);
838 			if (error != 0)
839 				return (error);
840 		}
841 		s = splimp();
842 		if (bp != d->bd_bif) {
843 			if (d->bd_bif)
844 				/*
845 				 * Detach if attached to something else.
846 				 */
847 				bpf_detachd(d);
848 
849 			bpf_attachd(d, bp);
850 		}
851 		reset_d(d);
852 		splx(s);
853 		return (0);
854 	}
855 	/* Not found. */
856 	return (ENXIO);
857 }
858 
859 /*
860  * Convert an interface name plus unit number of an ifp to a single
861  * name which is returned in the ifr.
862  */
863 static void
864 bpf_ifname(ifp, ifr)
865 	struct ifnet *ifp;
866 	struct ifreq *ifr;
867 {
868 	char *s = ifp->if_name;
869 	char *d = ifr->ifr_name;
870 
871 	while (*d++ = *s++)
872 		continue;
873 	/* XXX Assume that unit number is less than 10. */
874 	*d++ = ifp->if_unit + '0';
875 	*d = '\0';
876 }
877 
878 /*
879  * The new select interface passes down the proc pointer; the old select
880  * stubs had to grab it out of the user struct.  This glue allows either case.
881  */
882 #if BSD >= 199103
883 #define bpf_select bpfselect
884 #else
885 int
886 bpfselect(dev, rw)
887 	register dev_t dev;
888 	int rw;
889 {
890 	return (bpf_select(dev, rw, u.u_procp));
891 }
892 #endif
893 
894 /*
895  * Support for select() system call
896  * Inspired by the code in tty.c for the same purpose.
897  *
898  * Return true iff the specific operation will not block indefinitely.
899  * Otherwise, return false but make a note that a selwakeup() must be done.
900  */
901 int
902 bpf_select(dev, rw, p)
903 	register dev_t dev;
904 	int rw;
905 	struct proc *p;
906 {
907 	register struct bpf_d *d;
908 	register int s;
909 
910 	if (rw != FREAD)
911 		return (0);
912 	/*
913 	 * An imitation of the FIONREAD ioctl code.
914 	 */
915 	d = &bpf_dtab[minor(dev)];
916 
917 	s = splimp();
918 	if (d->bd_hlen != 0 || (d->bd_immediate && d->bd_slen != 0)) {
919 		/*
920 		 * There is data waiting.
921 		 */
922 		splx(s);
923 		return (1);
924 	}
925 #if BSD >= 199103
926 	selrecord(p, &d->bd_sel);
927 #else
928 	/*
929 	 * No data ready.  If there's already a select() waiting on this
930 	 * minor device then this is a collision.  This shouldn't happen
931 	 * because minors really should not be shared, but if a process
932 	 * forks while one of these is open, it is possible that both
933 	 * processes could select on the same descriptor.
934 	 */
935 	if (d->bd_selproc && d->bd_selproc->p_wchan == (caddr_t)&selwait)
936 		d->bd_selcoll = 1;
937 	else
938 		d->bd_selproc = p;
939 #endif
940 	splx(s);
941 	return (0);
942 }
943 
944 /*
945  * Incoming linkage from device drivers.  Process the packet pkt, of length
946  * pktlen, which is stored in a contiguous buffer.  The packet is parsed
947  * by each process' filter, and if accepted, stashed into the corresponding
948  * buffer.
949  */
950 void
951 bpf_tap(arg, pkt, pktlen)
952 	caddr_t arg;
953 	register u_char *pkt;
954 	register u_int pktlen;
955 {
956 	struct bpf_if *bp;
957 	register struct bpf_d *d;
958 	register u_int slen;
959 	/*
960 	 * Note that the ipl does not have to be raised at this point.
961 	 * The only problem that could arise here is that if two different
962 	 * interfaces shared any data.  This is not the case.
963 	 */
964 	bp = (struct bpf_if *)arg;
965 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
966 		++d->bd_rcount;
967 		slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
968 		if (slen != 0)
969 			catchpacket(d, pkt, pktlen, slen, bcopy);
970 	}
971 }
972 
973 /*
974  * Copy data from an mbuf chain into a buffer.  This code is derived
975  * from m_copydata in sys/uipc_mbuf.c.
976  */
977 static void
978 bpf_mcopy(src, dst, len)
979 	u_char *src;
980 	u_char *dst;
981 	register int len;
982 {
983 	register struct mbuf *m = (struct mbuf *)src;
984 	register unsigned count;
985 
986 	while (len > 0) {
987 		if (m == 0)
988 			panic("bpf_mcopy");
989 		count = MIN(m->m_len, len);
990 		bcopy(mtod(m, caddr_t), (caddr_t)dst, count);
991 		m = m->m_next;
992 		dst += count;
993 		len -= count;
994 	}
995 }
996 
997 /*
998  * Incoming linkage from device drivers, when packet is in an mbuf chain.
999  */
1000 void
1001 bpf_mtap(arg, m)
1002 	caddr_t arg;
1003 	struct mbuf *m;
1004 {
1005 	struct bpf_if *bp = (struct bpf_if *)arg;
1006 	struct bpf_d *d;
1007 	u_int pktlen, slen;
1008 	struct mbuf *m0;
1009 
1010 	pktlen = 0;
1011 	for (m0 = m; m0 != 0; m0 = m0->m_next)
1012 		pktlen += m0->m_len;
1013 
1014 	for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1015 		++d->bd_rcount;
1016 		slen = bpf_filter(d->bd_filter, (u_char *)m, pktlen, 0);
1017 		if (slen != 0)
1018 			catchpacket(d, (u_char *)m, pktlen, slen, bpf_mcopy);
1019 	}
1020 }
1021 
1022 /*
1023  * Move the packet data from interface memory (pkt) into the
1024  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
1025  * otherwise 0.  "copy" is the routine called to do the actual data
1026  * transfer.  bcopy is passed in to copy contiguous chunks, while
1027  * bpf_mcopy is passed in to copy mbuf chains.  In the latter case,
1028  * pkt is really an mbuf.
1029  */
1030 static void
1031 catchpacket(d, pkt, pktlen, snaplen, cpfn)
1032 	register struct bpf_d *d;
1033 	register u_char *pkt;
1034 	register u_int pktlen, snaplen;
1035 	register void (*cpfn)();
1036 {
1037 	register struct bpf_hdr *hp;
1038 	register int totlen, curlen;
1039 	register int hdrlen = d->bd_bif->bif_hdrlen;
1040 	/*
1041 	 * Figure out how many bytes to move.  If the packet is
1042 	 * greater or equal to the snapshot length, transfer that
1043 	 * much.  Otherwise, transfer the whole packet (unless
1044 	 * we hit the buffer size limit).
1045 	 */
1046 	totlen = hdrlen + MIN(snaplen, pktlen);
1047 	if (totlen > d->bd_bufsize)
1048 		totlen = d->bd_bufsize;
1049 
1050 	/*
1051 	 * Round up the end of the previous packet to the next longword.
1052 	 */
1053 	curlen = BPF_WORDALIGN(d->bd_slen);
1054 	if (curlen + totlen > d->bd_bufsize) {
1055 		/*
1056 		 * This packet will overflow the storage buffer.
1057 		 * Rotate the buffers if we can, then wakeup any
1058 		 * pending reads.
1059 		 */
1060 		if (d->bd_fbuf == 0) {
1061 			/*
1062 			 * We haven't completed the previous read yet,
1063 			 * so drop the packet.
1064 			 */
1065 			++d->bd_dcount;
1066 			return;
1067 		}
1068 		ROTATE_BUFFERS(d);
1069 		bpf_wakeup(d);
1070 		curlen = 0;
1071 	}
1072 	else if (d->bd_immediate)
1073 		/*
1074 		 * Immediate mode is set.  A packet arrived so any
1075 		 * reads should be woken up.
1076 		 */
1077 		bpf_wakeup(d);
1078 
1079 	/*
1080 	 * Append the bpf header.
1081 	 */
1082 	hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1083 #if BSD >= 199103
1084 	microtime(&hp->bh_tstamp);
1085 #elif defined(sun)
1086 	uniqtime(&hp->bh_tstamp);
1087 #else
1088 	hp->bh_tstamp = time;
1089 #endif
1090 	hp->bh_datalen = pktlen;
1091 	hp->bh_hdrlen = hdrlen;
1092 	/*
1093 	 * Copy the packet data into the store buffer and update its length.
1094 	 */
1095 	(*cpfn)(pkt, (u_char *)hp + hdrlen, (hp->bh_caplen = totlen - hdrlen));
1096 	d->bd_slen = curlen + totlen;
1097 }
1098 
1099 /*
1100  * Initialize all nonzero fields of a descriptor.
1101  */
1102 static int
1103 bpf_allocbufs(d)
1104 	register struct bpf_d *d;
1105 {
1106 	d->bd_fbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_WAITOK);
1107 	if (d->bd_fbuf == 0)
1108 		return (ENOBUFS);
1109 
1110 	d->bd_sbuf = (caddr_t)malloc(d->bd_bufsize, M_DEVBUF, M_WAITOK);
1111 	if (d->bd_sbuf == 0) {
1112 		free(d->bd_fbuf, M_DEVBUF);
1113 		return (ENOBUFS);
1114 	}
1115 	d->bd_slen = 0;
1116 	d->bd_hlen = 0;
1117 	return (0);
1118 }
1119 
1120 /*
1121  * Free buffers currently in use by a descriptor.
1122  * Called on close.
1123  */
1124 static void
1125 bpf_freed(d)
1126 	register struct bpf_d *d;
1127 {
1128 	/*
1129 	 * We don't need to lock out interrupts since this descriptor has
1130 	 * been detached from its interface and it yet hasn't been marked
1131 	 * free.
1132 	 */
1133 	if (d->bd_sbuf != 0) {
1134 		free(d->bd_sbuf, M_DEVBUF);
1135 		if (d->bd_hbuf != 0)
1136 			free(d->bd_hbuf, M_DEVBUF);
1137 		if (d->bd_fbuf != 0)
1138 			free(d->bd_fbuf, M_DEVBUF);
1139 	}
1140 	if (d->bd_filter)
1141 		free((caddr_t)d->bd_filter, M_DEVBUF);
1142 
1143 	D_MARKFREE(d);
1144 }
1145 
1146 /*
1147  * Attach an interface to bpf.  driverp is a pointer to a (struct bpf_if *)
1148  * in the driver's softc; dlt is the link layer type; hdrlen is the fixed
1149  * size of the link header (variable length headers not yet supported).
1150  */
1151 void
1152 bpfattach(driverp, ifp, dlt, hdrlen)
1153 	caddr_t *driverp;
1154 	struct ifnet *ifp;
1155 	u_int dlt, hdrlen;
1156 {
1157 	struct bpf_if *bp;
1158 	int i;
1159 #if BSD < 199103
1160 	static struct bpf_if bpf_ifs[NBPFILTER];
1161 	static int bpfifno;
1162 
1163 	bp = (bpfifno < NBPFILTER) ? &bpf_ifs[bpfifno++] : 0;
1164 #else
1165 	bp = (struct bpf_if *)malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
1166 #endif
1167 	if (bp == 0)
1168 		panic("bpfattach");
1169 
1170 	bp->bif_dlist = 0;
1171 	bp->bif_driverp = (struct bpf_if **)driverp;
1172 	bp->bif_ifp = ifp;
1173 	bp->bif_dlt = dlt;
1174 
1175 	bp->bif_next = bpf_iflist;
1176 	bpf_iflist = bp;
1177 
1178 	*bp->bif_driverp = 0;
1179 
1180 	/*
1181 	 * Compute the length of the bpf header.  This is not necessarily
1182 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1183 	 * that the network layer header begins on a longword boundary (for
1184 	 * performance reasons and to alleviate alignment restrictions).
1185 	 */
1186 	bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1187 
1188 	/*
1189 	 * Mark all the descriptors free if this hasn't been done.
1190 	 */
1191 	if (!D_ISFREE(&bpf_dtab[0]))
1192 		for (i = 0; i < NBPFILTER; ++i)
1193 			D_MARKFREE(&bpf_dtab[i]);
1194 
1195 	printf("bpf: %s%d attached\n", ifp->if_name, ifp->if_unit);
1196 }
1197 
1198 #if BSD >= 199103
1199 /* XXX This routine belongs in net/if.c. */
1200 /*
1201  * Set/clear promiscuous mode on interface ifp based on the truth value
1202  * of pswitch.  The calls are reference counted so that only the first
1203  * "on" request actually has an effect, as does the final "off" request.
1204  * Results are undefined if the "off" and "on" requests are not matched.
1205  */
1206 int
1207 ifpromisc(ifp, pswitch)
1208 	struct ifnet *ifp;
1209 	int pswitch;
1210 {
1211 	struct ifreq ifr;
1212 	/*
1213 	 * If the device is not configured up, we cannot put it in
1214 	 * promiscuous mode.
1215 	 */
1216 	if ((ifp->if_flags & IFF_UP) == 0)
1217 		return (ENETDOWN);
1218 
1219 	if (pswitch) {
1220 		if (ifp->if_pcount++ != 0)
1221 			return (0);
1222 		ifp->if_flags |= IFF_PROMISC;
1223 	} else {
1224 		if (--ifp->if_pcount > 0)
1225 			return (0);
1226 		ifp->if_flags &= ~IFF_PROMISC;
1227 	}
1228 	ifr.ifr_flags = ifp->if_flags;
1229 	return ((*ifp->if_ioctl)(ifp, SIOCSIFFLAGS, (caddr_t)&ifr));
1230 }
1231 #endif
1232 
1233 #if BSD < 199103
1234 /*
1235  * Allocate some memory for bpf.  This is temporary SunOS support, and
1236  * is admittedly a hack.
1237  * If resources unavaiable, return 0.
1238  */
1239 static caddr_t
1240 bpf_alloc(size, canwait)
1241 	register int size;
1242 	register int canwait;
1243 {
1244 	register struct mbuf *m;
1245 
1246 	if ((unsigned)size > (MCLBYTES-8))
1247 		return 0;
1248 
1249 	MGET(m, canwait, MT_DATA);
1250 	if (m == 0)
1251 		return 0;
1252 	if ((unsigned)size > (MLEN-8)) {
1253 		MCLGET(m);
1254 		if (m->m_len != MCLBYTES) {
1255 			m_freem(m);
1256 			return 0;
1257 		}
1258 	}
1259 	*mtod(m, struct mbuf **) = m;
1260 	return mtod(m, caddr_t) + 8;
1261 }
1262 #endif
1263 #endif
1264