bpf.c revision 1.151 1 /* $NetBSD: bpf.c,v 1.151 2010/01/15 22:16:46 pooka 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. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)bpf.c 8.4 (Berkeley) 1/9/95
37 * static char rcsid[] =
38 * "Header: bpf.c,v 1.67 96/09/26 22:00:52 leres Exp ";
39 */
40
41 #include <sys/cdefs.h>
42 __KERNEL_RCSID(0, "$NetBSD: bpf.c,v 1.151 2010/01/15 22:16:46 pooka Exp $");
43
44 #if defined(_KERNEL_OPT)
45 #include "opt_bpf.h"
46 #include "sl.h"
47 #include "strip.h"
48 #endif
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/mbuf.h>
53 #include <sys/buf.h>
54 #include <sys/time.h>
55 #include <sys/proc.h>
56 #include <sys/ioctl.h>
57 #include <sys/conf.h>
58 #include <sys/vnode.h>
59 #include <sys/queue.h>
60 #include <sys/stat.h>
61
62 #include <sys/file.h>
63 #include <sys/filedesc.h>
64 #include <sys/tty.h>
65 #include <sys/uio.h>
66
67 #include <sys/protosw.h>
68 #include <sys/socket.h>
69 #include <sys/errno.h>
70 #include <sys/kernel.h>
71 #include <sys/poll.h>
72 #include <sys/sysctl.h>
73 #include <sys/kauth.h>
74
75 #include <net/if.h>
76 #include <net/slip.h>
77
78 #include <net/bpf.h>
79 #include <net/bpfdesc.h>
80
81 #include <net/if_arc.h>
82 #include <net/if_ether.h>
83
84 #include <netinet/in.h>
85 #include <netinet/if_inarp.h>
86
87
88 #include <compat/sys/sockio.h>
89
90 #ifndef BPF_BUFSIZE
91 /*
92 * 4096 is too small for FDDI frames. 8192 is too small for gigabit Ethernet
93 * jumbos (circa 9k), ATM, or Intel gig/10gig ethernet jumbos (16k).
94 */
95 # define BPF_BUFSIZE 32768
96 #endif
97
98 #define PRINET 26 /* interruptible */
99
100 /*
101 * The default read buffer size, and limit for BIOCSBLEN, is sysctl'able.
102 * XXX the default values should be computed dynamically based
103 * on available memory size and available mbuf clusters.
104 */
105 int bpf_bufsize = BPF_BUFSIZE;
106 int bpf_maxbufsize = BPF_DFLTBUFSIZE; /* XXX set dynamically, see above */
107
108
109 /*
110 * Global BPF statistics returned by net.bpf.stats sysctl.
111 */
112 struct bpf_stat bpf_gstats;
113
114 /*
115 * Use a mutex to avoid a race condition between gathering the stats/peers
116 * and opening/closing the device.
117 */
118 static kmutex_t bpf_mtx;
119
120 /*
121 * bpf_iflist is the list of interfaces; each corresponds to an ifnet
122 * bpf_dtab holds the descriptors, indexed by minor device #
123 */
124 struct bpf_if *bpf_iflist;
125 LIST_HEAD(, bpf_d) bpf_list;
126
127 static int bpf_allocbufs(struct bpf_d *);
128 static void bpf_deliver(struct bpf_if *,
129 void *(*cpfn)(void *, const void *, size_t),
130 void *, u_int, u_int, struct ifnet *);
131 static void bpf_freed(struct bpf_d *);
132 static void bpf_ifname(struct ifnet *, struct ifreq *);
133 static void *bpf_mcpy(void *, const void *, size_t);
134 static int bpf_movein(struct uio *, int, int,
135 struct mbuf **, struct sockaddr *);
136 static void bpf_attachd(struct bpf_d *, struct bpf_if *);
137 static void bpf_detachd(struct bpf_d *);
138 static int bpf_setif(struct bpf_d *, struct ifreq *);
139 static void bpf_timed_out(void *);
140 static inline void
141 bpf_wakeup(struct bpf_d *);
142 static void catchpacket(struct bpf_d *, u_char *, u_int, u_int,
143 void *(*)(void *, const void *, size_t), struct timespec *);
144 static void reset_d(struct bpf_d *);
145 static int bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
146 static int bpf_setdlt(struct bpf_d *, u_int);
147
148 static int bpf_read(struct file *, off_t *, struct uio *, kauth_cred_t,
149 int);
150 static int bpf_write(struct file *, off_t *, struct uio *, kauth_cred_t,
151 int);
152 static int bpf_ioctl(struct file *, u_long, void *);
153 static int bpf_poll(struct file *, int);
154 static int bpf_stat(struct file *, struct stat *);
155 static int bpf_close(struct file *);
156 static int bpf_kqfilter(struct file *, struct knote *);
157 static void bpf_softintr(void *);
158
159 static const struct fileops bpf_fileops = {
160 .fo_read = bpf_read,
161 .fo_write = bpf_write,
162 .fo_ioctl = bpf_ioctl,
163 .fo_fcntl = fnullop_fcntl,
164 .fo_poll = bpf_poll,
165 .fo_stat = bpf_stat,
166 .fo_close = bpf_close,
167 .fo_kqfilter = bpf_kqfilter,
168 .fo_restart = fnullop_restart,
169 };
170
171 dev_type_open(bpfopen);
172
173 const struct cdevsw bpf_cdevsw = {
174 bpfopen, noclose, noread, nowrite, noioctl,
175 nostop, notty, nopoll, nommap, nokqfilter, D_OTHER
176 };
177
178 static int
179 bpf_movein(struct uio *uio, int linktype, int mtu, struct mbuf **mp,
180 struct sockaddr *sockp)
181 {
182 struct mbuf *m;
183 int error;
184 int len;
185 int hlen;
186 int align;
187
188 /*
189 * Build a sockaddr based on the data link layer type.
190 * We do this at this level because the ethernet header
191 * is copied directly into the data field of the sockaddr.
192 * In the case of SLIP, there is no header and the packet
193 * is forwarded as is.
194 * Also, we are careful to leave room at the front of the mbuf
195 * for the link level header.
196 */
197 switch (linktype) {
198
199 case DLT_SLIP:
200 sockp->sa_family = AF_INET;
201 hlen = 0;
202 align = 0;
203 break;
204
205 case DLT_PPP:
206 sockp->sa_family = AF_UNSPEC;
207 hlen = 0;
208 align = 0;
209 break;
210
211 case DLT_EN10MB:
212 sockp->sa_family = AF_UNSPEC;
213 /* XXX Would MAXLINKHDR be better? */
214 /* 6(dst)+6(src)+2(type) */
215 hlen = sizeof(struct ether_header);
216 align = 2;
217 break;
218
219 case DLT_ARCNET:
220 sockp->sa_family = AF_UNSPEC;
221 hlen = ARC_HDRLEN;
222 align = 5;
223 break;
224
225 case DLT_FDDI:
226 sockp->sa_family = AF_LINK;
227 /* XXX 4(FORMAC)+6(dst)+6(src) */
228 hlen = 16;
229 align = 0;
230 break;
231
232 case DLT_ECONET:
233 sockp->sa_family = AF_UNSPEC;
234 hlen = 6;
235 align = 2;
236 break;
237
238 case DLT_NULL:
239 sockp->sa_family = AF_UNSPEC;
240 hlen = 0;
241 align = 0;
242 break;
243
244 default:
245 return (EIO);
246 }
247
248 len = uio->uio_resid;
249 /*
250 * If there aren't enough bytes for a link level header or the
251 * packet length exceeds the interface mtu, return an error.
252 */
253 if (len < hlen || len - hlen > mtu)
254 return (EMSGSIZE);
255
256 /*
257 * XXX Avoid complicated buffer chaining ---
258 * bail if it won't fit in a single mbuf.
259 * (Take into account possible alignment bytes)
260 */
261 if ((unsigned)len > MCLBYTES - align)
262 return (EIO);
263
264 m = m_gethdr(M_WAIT, MT_DATA);
265 m->m_pkthdr.rcvif = 0;
266 m->m_pkthdr.len = len - hlen;
267 if (len > MHLEN - align) {
268 m_clget(m, M_WAIT);
269 if ((m->m_flags & M_EXT) == 0) {
270 error = ENOBUFS;
271 goto bad;
272 }
273 }
274
275 /* Insure the data is properly aligned */
276 if (align > 0) {
277 m->m_data += align;
278 m->m_len -= align;
279 }
280
281 error = uiomove(mtod(m, void *), len, uio);
282 if (error)
283 goto bad;
284 if (hlen != 0) {
285 memcpy(sockp->sa_data, mtod(m, void *), hlen);
286 m->m_data += hlen; /* XXX */
287 len -= hlen;
288 }
289 m->m_len = len;
290 *mp = m;
291 return (0);
292
293 bad:
294 m_freem(m);
295 return (error);
296 }
297
298 /*
299 * Attach file to the bpf interface, i.e. make d listen on bp.
300 * Must be called at splnet.
301 */
302 static void
303 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
304 {
305 /*
306 * Point d at bp, and add d to the interface's list of listeners.
307 * Finally, point the driver's bpf cookie at the interface so
308 * it will divert packets to bpf.
309 */
310 d->bd_bif = bp;
311 d->bd_next = bp->bif_dlist;
312 bp->bif_dlist = d;
313
314 *bp->bif_driverp = bp;
315 }
316
317 /*
318 * Detach a file from its interface.
319 */
320 static void
321 bpf_detachd(struct bpf_d *d)
322 {
323 struct bpf_d **p;
324 struct bpf_if *bp;
325
326 bp = d->bd_bif;
327 /*
328 * Check if this descriptor had requested promiscuous mode.
329 * If so, turn it off.
330 */
331 if (d->bd_promisc) {
332 int error;
333
334 d->bd_promisc = 0;
335 /*
336 * Take device out of promiscuous mode. Since we were
337 * able to enter promiscuous mode, we should be able
338 * to turn it off. But we can get an error if
339 * the interface was configured down, so only panic
340 * if we don't get an unexpected error.
341 */
342 error = ifpromisc(bp->bif_ifp, 0);
343 if (error && error != EINVAL)
344 panic("%s: ifpromisc failed: %d", __func__, error);
345 }
346 /* Remove d from the interface's descriptor list. */
347 p = &bp->bif_dlist;
348 while (*p != d) {
349 p = &(*p)->bd_next;
350 if (*p == 0)
351 panic("%s: descriptor not in list", __func__);
352 }
353 *p = (*p)->bd_next;
354 if (bp->bif_dlist == 0)
355 /*
356 * Let the driver know that there are no more listeners.
357 */
358 *d->bd_bif->bif_driverp = 0;
359 d->bd_bif = 0;
360 }
361
362
363 /*
364 * bpfilterattach() is called at boot time.
365 */
366 /* ARGSUSED */
367 void
368 bpfilterattach(int n)
369 {
370
371 mutex_init(&bpf_mtx, MUTEX_DEFAULT, IPL_NONE);
372
373 LIST_INIT(&bpf_list);
374
375 bpf_gstats.bs_recv = 0;
376 bpf_gstats.bs_drop = 0;
377 bpf_gstats.bs_capt = 0;
378 }
379
380 /*
381 * Open ethernet device. Clones.
382 */
383 /* ARGSUSED */
384 int
385 bpfopen(dev_t dev, int flag, int mode, struct lwp *l)
386 {
387 struct bpf_d *d;
388 struct file *fp;
389 int error, fd;
390
391 /* falloc() will use the descriptor for us. */
392 if ((error = fd_allocfile(&fp, &fd)) != 0)
393 return error;
394
395 d = malloc(sizeof(*d), M_DEVBUF, M_WAITOK|M_ZERO);
396 d->bd_bufsize = bpf_bufsize;
397 d->bd_seesent = 1;
398 d->bd_pid = l->l_proc->p_pid;
399 getnanotime(&d->bd_btime);
400 d->bd_atime = d->bd_mtime = d->bd_btime;
401 callout_init(&d->bd_callout, 0);
402 selinit(&d->bd_sel);
403 d->bd_sih = softint_establish(SOFTINT_CLOCK, bpf_softintr, d);
404
405 mutex_enter(&bpf_mtx);
406 LIST_INSERT_HEAD(&bpf_list, d, bd_list);
407 mutex_exit(&bpf_mtx);
408
409 return fd_clone(fp, fd, flag, &bpf_fileops, d);
410 }
411
412 /*
413 * Close the descriptor by detaching it from its interface,
414 * deallocating its buffers, and marking it free.
415 */
416 /* ARGSUSED */
417 static int
418 bpf_close(struct file *fp)
419 {
420 struct bpf_d *d = fp->f_data;
421 int s;
422
423 KERNEL_LOCK(1, NULL);
424
425 /*
426 * Refresh the PID associated with this bpf file.
427 */
428 d->bd_pid = curproc->p_pid;
429
430 s = splnet();
431 if (d->bd_state == BPF_WAITING)
432 callout_stop(&d->bd_callout);
433 d->bd_state = BPF_IDLE;
434 if (d->bd_bif)
435 bpf_detachd(d);
436 splx(s);
437 bpf_freed(d);
438 mutex_enter(&bpf_mtx);
439 LIST_REMOVE(d, bd_list);
440 mutex_exit(&bpf_mtx);
441 callout_destroy(&d->bd_callout);
442 seldestroy(&d->bd_sel);
443 softint_disestablish(d->bd_sih);
444 free(d, M_DEVBUF);
445 fp->f_data = NULL;
446
447 KERNEL_UNLOCK_ONE(NULL);
448
449 return (0);
450 }
451
452 /*
453 * Rotate the packet buffers in descriptor d. Move the store buffer
454 * into the hold slot, and the free buffer into the store slot.
455 * Zero the length of the new store buffer.
456 */
457 #define ROTATE_BUFFERS(d) \
458 (d)->bd_hbuf = (d)->bd_sbuf; \
459 (d)->bd_hlen = (d)->bd_slen; \
460 (d)->bd_sbuf = (d)->bd_fbuf; \
461 (d)->bd_slen = 0; \
462 (d)->bd_fbuf = 0;
463 /*
464 * bpfread - read next chunk of packets from buffers
465 */
466 static int
467 bpf_read(struct file *fp, off_t *offp, struct uio *uio,
468 kauth_cred_t cred, int flags)
469 {
470 struct bpf_d *d = fp->f_data;
471 int timed_out;
472 int error;
473 int s;
474
475 getnanotime(&d->bd_atime);
476 /*
477 * Restrict application to use a buffer the same size as
478 * the kernel buffers.
479 */
480 if (uio->uio_resid != d->bd_bufsize)
481 return (EINVAL);
482
483 KERNEL_LOCK(1, NULL);
484 s = splnet();
485 if (d->bd_state == BPF_WAITING)
486 callout_stop(&d->bd_callout);
487 timed_out = (d->bd_state == BPF_TIMED_OUT);
488 d->bd_state = BPF_IDLE;
489 /*
490 * If the hold buffer is empty, then do a timed sleep, which
491 * ends when the timeout expires or when enough packets
492 * have arrived to fill the store buffer.
493 */
494 while (d->bd_hbuf == 0) {
495 if (fp->f_flag & FNONBLOCK) {
496 if (d->bd_slen == 0) {
497 splx(s);
498 KERNEL_UNLOCK_ONE(NULL);
499 return (EWOULDBLOCK);
500 }
501 ROTATE_BUFFERS(d);
502 break;
503 }
504
505 if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
506 /*
507 * A packet(s) either arrived since the previous
508 * read or arrived while we were asleep.
509 * Rotate the buffers and return what's here.
510 */
511 ROTATE_BUFFERS(d);
512 break;
513 }
514 error = tsleep(d, PRINET|PCATCH, "bpf",
515 d->bd_rtout);
516 if (error == EINTR || error == ERESTART) {
517 splx(s);
518 KERNEL_UNLOCK_ONE(NULL);
519 return (error);
520 }
521 if (error == EWOULDBLOCK) {
522 /*
523 * On a timeout, return what's in the buffer,
524 * which may be nothing. If there is something
525 * in the store buffer, we can rotate the buffers.
526 */
527 if (d->bd_hbuf)
528 /*
529 * We filled up the buffer in between
530 * getting the timeout and arriving
531 * here, so we don't need to rotate.
532 */
533 break;
534
535 if (d->bd_slen == 0) {
536 splx(s);
537 KERNEL_UNLOCK_ONE(NULL);
538 return (0);
539 }
540 ROTATE_BUFFERS(d);
541 break;
542 }
543 if (error != 0)
544 goto done;
545 }
546 /*
547 * At this point, we know we have something in the hold slot.
548 */
549 splx(s);
550
551 /*
552 * Move data from hold buffer into user space.
553 * We know the entire buffer is transferred since
554 * we checked above that the read buffer is bpf_bufsize bytes.
555 */
556 error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
557
558 s = splnet();
559 d->bd_fbuf = d->bd_hbuf;
560 d->bd_hbuf = 0;
561 d->bd_hlen = 0;
562 done:
563 splx(s);
564 KERNEL_UNLOCK_ONE(NULL);
565 return (error);
566 }
567
568
569 /*
570 * If there are processes sleeping on this descriptor, wake them up.
571 */
572 static inline void
573 bpf_wakeup(struct bpf_d *d)
574 {
575 wakeup(d);
576 if (d->bd_async)
577 softint_schedule(d->bd_sih);
578 selnotify(&d->bd_sel, 0, 0);
579 }
580
581 static void
582 bpf_softintr(void *cookie)
583 {
584 struct bpf_d *d;
585
586 d = cookie;
587 if (d->bd_async)
588 fownsignal(d->bd_pgid, SIGIO, 0, 0, NULL);
589 }
590
591 static void
592 bpf_timed_out(void *arg)
593 {
594 struct bpf_d *d = arg;
595 int s;
596
597 s = splnet();
598 if (d->bd_state == BPF_WAITING) {
599 d->bd_state = BPF_TIMED_OUT;
600 if (d->bd_slen != 0)
601 bpf_wakeup(d);
602 }
603 splx(s);
604 }
605
606
607 static int
608 bpf_write(struct file *fp, off_t *offp, struct uio *uio,
609 kauth_cred_t cred, int flags)
610 {
611 struct bpf_d *d = fp->f_data;
612 struct ifnet *ifp;
613 struct mbuf *m;
614 int error, s;
615 static struct sockaddr_storage dst;
616
617 m = NULL; /* XXX gcc */
618
619 KERNEL_LOCK(1, NULL);
620
621 if (d->bd_bif == 0) {
622 KERNEL_UNLOCK_ONE(NULL);
623 return (ENXIO);
624 }
625 getnanotime(&d->bd_mtime);
626
627 ifp = d->bd_bif->bif_ifp;
628
629 if (uio->uio_resid == 0) {
630 KERNEL_UNLOCK_ONE(NULL);
631 return (0);
632 }
633
634 error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, ifp->if_mtu, &m,
635 (struct sockaddr *) &dst);
636 if (error) {
637 KERNEL_UNLOCK_ONE(NULL);
638 return (error);
639 }
640
641 if (m->m_pkthdr.len > ifp->if_mtu) {
642 KERNEL_UNLOCK_ONE(NULL);
643 m_freem(m);
644 return (EMSGSIZE);
645 }
646
647 if (d->bd_hdrcmplt)
648 dst.ss_family = pseudo_AF_HDRCMPLT;
649
650 s = splsoftnet();
651 error = (*ifp->if_output)(ifp, m, (struct sockaddr *) &dst, NULL);
652 splx(s);
653 KERNEL_UNLOCK_ONE(NULL);
654 /*
655 * The driver frees the mbuf.
656 */
657 return (error);
658 }
659
660 /*
661 * Reset a descriptor by flushing its packet buffer and clearing the
662 * receive and drop counts. Should be called at splnet.
663 */
664 static void
665 reset_d(struct bpf_d *d)
666 {
667 if (d->bd_hbuf) {
668 /* Free the hold buffer. */
669 d->bd_fbuf = d->bd_hbuf;
670 d->bd_hbuf = 0;
671 }
672 d->bd_slen = 0;
673 d->bd_hlen = 0;
674 d->bd_rcount = 0;
675 d->bd_dcount = 0;
676 d->bd_ccount = 0;
677 }
678
679 /*
680 * FIONREAD Check for read packet available.
681 * BIOCGBLEN Get buffer len [for read()].
682 * BIOCSETF Set ethernet read filter.
683 * BIOCFLUSH Flush read packet buffer.
684 * BIOCPROMISC Put interface into promiscuous mode.
685 * BIOCGDLT Get link layer type.
686 * BIOCGETIF Get interface name.
687 * BIOCSETIF Set interface.
688 * BIOCSRTIMEOUT Set read timeout.
689 * BIOCGRTIMEOUT Get read timeout.
690 * BIOCGSTATS Get packet stats.
691 * BIOCIMMEDIATE Set immediate mode.
692 * BIOCVERSION Get filter language version.
693 * BIOCGHDRCMPLT Get "header already complete" flag.
694 * BIOCSHDRCMPLT Set "header already complete" flag.
695 */
696 /* ARGSUSED */
697 static int
698 bpf_ioctl(struct file *fp, u_long cmd, void *addr)
699 {
700 struct bpf_d *d = fp->f_data;
701 int s, error = 0;
702
703 /*
704 * Refresh the PID associated with this bpf file.
705 */
706 KERNEL_LOCK(1, NULL);
707 d->bd_pid = curproc->p_pid;
708
709 s = splnet();
710 if (d->bd_state == BPF_WAITING)
711 callout_stop(&d->bd_callout);
712 d->bd_state = BPF_IDLE;
713 splx(s);
714
715 switch (cmd) {
716
717 default:
718 error = EINVAL;
719 break;
720
721 /*
722 * Check for read packet available.
723 */
724 case FIONREAD:
725 {
726 int n;
727
728 s = splnet();
729 n = d->bd_slen;
730 if (d->bd_hbuf)
731 n += d->bd_hlen;
732 splx(s);
733
734 *(int *)addr = n;
735 break;
736 }
737
738 /*
739 * Get buffer len [for read()].
740 */
741 case BIOCGBLEN:
742 *(u_int *)addr = d->bd_bufsize;
743 break;
744
745 /*
746 * Set buffer length.
747 */
748 case BIOCSBLEN:
749 if (d->bd_bif != 0)
750 error = EINVAL;
751 else {
752 u_int size = *(u_int *)addr;
753
754 if (size > bpf_maxbufsize)
755 *(u_int *)addr = size = bpf_maxbufsize;
756 else if (size < BPF_MINBUFSIZE)
757 *(u_int *)addr = size = BPF_MINBUFSIZE;
758 d->bd_bufsize = size;
759 }
760 break;
761
762 /*
763 * Set link layer read filter.
764 */
765 case BIOCSETF:
766 error = bpf_setf(d, addr);
767 break;
768
769 /*
770 * Flush read packet buffer.
771 */
772 case BIOCFLUSH:
773 s = splnet();
774 reset_d(d);
775 splx(s);
776 break;
777
778 /*
779 * Put interface into promiscuous mode.
780 */
781 case BIOCPROMISC:
782 if (d->bd_bif == 0) {
783 /*
784 * No interface attached yet.
785 */
786 error = EINVAL;
787 break;
788 }
789 s = splnet();
790 if (d->bd_promisc == 0) {
791 error = ifpromisc(d->bd_bif->bif_ifp, 1);
792 if (error == 0)
793 d->bd_promisc = 1;
794 }
795 splx(s);
796 break;
797
798 /*
799 * Get device parameters.
800 */
801 case BIOCGDLT:
802 if (d->bd_bif == 0)
803 error = EINVAL;
804 else
805 *(u_int *)addr = d->bd_bif->bif_dlt;
806 break;
807
808 /*
809 * Get a list of supported device parameters.
810 */
811 case BIOCGDLTLIST:
812 if (d->bd_bif == 0)
813 error = EINVAL;
814 else
815 error = bpf_getdltlist(d, addr);
816 break;
817
818 /*
819 * Set device parameters.
820 */
821 case BIOCSDLT:
822 if (d->bd_bif == 0)
823 error = EINVAL;
824 else
825 error = bpf_setdlt(d, *(u_int *)addr);
826 break;
827
828 /*
829 * Set interface name.
830 */
831 #ifdef OBIOCGETIF
832 case OBIOCGETIF:
833 #endif
834 case BIOCGETIF:
835 if (d->bd_bif == 0)
836 error = EINVAL;
837 else
838 bpf_ifname(d->bd_bif->bif_ifp, addr);
839 break;
840
841 /*
842 * Set interface.
843 */
844 #ifdef OBIOCSETIF
845 case OBIOCSETIF:
846 #endif
847 case BIOCSETIF:
848 error = bpf_setif(d, addr);
849 break;
850
851 /*
852 * Set read timeout.
853 */
854 case BIOCSRTIMEOUT:
855 {
856 struct timeval *tv = addr;
857
858 /* Compute number of ticks. */
859 d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
860 if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
861 d->bd_rtout = 1;
862 break;
863 }
864
865 #ifdef BIOCGORTIMEOUT
866 /*
867 * Get read timeout.
868 */
869 case BIOCGORTIMEOUT:
870 {
871 struct timeval50 *tv = addr;
872
873 tv->tv_sec = d->bd_rtout / hz;
874 tv->tv_usec = (d->bd_rtout % hz) * tick;
875 break;
876 }
877 #endif
878
879 #ifdef BIOCSORTIMEOUT
880 /*
881 * Set read timeout.
882 */
883 case BIOCSORTIMEOUT:
884 {
885 struct timeval50 *tv = addr;
886
887 /* Compute number of ticks. */
888 d->bd_rtout = tv->tv_sec * hz + tv->tv_usec / tick;
889 if ((d->bd_rtout == 0) && (tv->tv_usec != 0))
890 d->bd_rtout = 1;
891 break;
892 }
893 #endif
894
895 /*
896 * Get read timeout.
897 */
898 case BIOCGRTIMEOUT:
899 {
900 struct timeval *tv = addr;
901
902 tv->tv_sec = d->bd_rtout / hz;
903 tv->tv_usec = (d->bd_rtout % hz) * tick;
904 break;
905 }
906 /*
907 * Get packet stats.
908 */
909 case BIOCGSTATS:
910 {
911 struct bpf_stat *bs = addr;
912
913 bs->bs_recv = d->bd_rcount;
914 bs->bs_drop = d->bd_dcount;
915 bs->bs_capt = d->bd_ccount;
916 break;
917 }
918
919 case BIOCGSTATSOLD:
920 {
921 struct bpf_stat_old *bs = addr;
922
923 bs->bs_recv = d->bd_rcount;
924 bs->bs_drop = d->bd_dcount;
925 break;
926 }
927
928 /*
929 * Set immediate mode.
930 */
931 case BIOCIMMEDIATE:
932 d->bd_immediate = *(u_int *)addr;
933 break;
934
935 case BIOCVERSION:
936 {
937 struct bpf_version *bv = addr;
938
939 bv->bv_major = BPF_MAJOR_VERSION;
940 bv->bv_minor = BPF_MINOR_VERSION;
941 break;
942 }
943
944 case BIOCGHDRCMPLT: /* get "header already complete" flag */
945 *(u_int *)addr = d->bd_hdrcmplt;
946 break;
947
948 case BIOCSHDRCMPLT: /* set "header already complete" flag */
949 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
950 break;
951
952 /*
953 * Get "see sent packets" flag
954 */
955 case BIOCGSEESENT:
956 *(u_int *)addr = d->bd_seesent;
957 break;
958
959 /*
960 * Set "see sent" packets flag
961 */
962 case BIOCSSEESENT:
963 d->bd_seesent = *(u_int *)addr;
964 break;
965
966 case FIONBIO: /* Non-blocking I/O */
967 /*
968 * No need to do anything special as we use IO_NDELAY in
969 * bpfread() as an indication of whether or not to block
970 * the read.
971 */
972 break;
973
974 case FIOASYNC: /* Send signal on receive packets */
975 d->bd_async = *(int *)addr;
976 break;
977
978 case TIOCSPGRP: /* Process or group to send signals to */
979 case FIOSETOWN:
980 error = fsetown(&d->bd_pgid, cmd, addr);
981 break;
982
983 case TIOCGPGRP:
984 case FIOGETOWN:
985 error = fgetown(d->bd_pgid, cmd, addr);
986 break;
987 }
988 KERNEL_UNLOCK_ONE(NULL);
989 return (error);
990 }
991
992 /*
993 * Set d's packet filter program to fp. If this file already has a filter,
994 * free it and replace it. Returns EINVAL for bogus requests.
995 */
996 int
997 bpf_setf(struct bpf_d *d, struct bpf_program *fp)
998 {
999 struct bpf_insn *fcode, *old;
1000 u_int flen, size;
1001 int s;
1002
1003 old = d->bd_filter;
1004 if (fp->bf_insns == 0) {
1005 if (fp->bf_len != 0)
1006 return (EINVAL);
1007 s = splnet();
1008 d->bd_filter = 0;
1009 reset_d(d);
1010 splx(s);
1011 if (old != 0)
1012 free(old, M_DEVBUF);
1013 return (0);
1014 }
1015 flen = fp->bf_len;
1016 if (flen > BPF_MAXINSNS)
1017 return (EINVAL);
1018
1019 size = flen * sizeof(*fp->bf_insns);
1020 fcode = malloc(size, M_DEVBUF, M_WAITOK);
1021 if (copyin(fp->bf_insns, fcode, size) == 0 &&
1022 bpf_validate(fcode, (int)flen)) {
1023 s = splnet();
1024 d->bd_filter = fcode;
1025 reset_d(d);
1026 splx(s);
1027 if (old != 0)
1028 free(old, M_DEVBUF);
1029
1030 return (0);
1031 }
1032 free(fcode, M_DEVBUF);
1033 return (EINVAL);
1034 }
1035
1036 /*
1037 * Detach a file from its current interface (if attached at all) and attach
1038 * to the interface indicated by the name stored in ifr.
1039 * Return an errno or 0.
1040 */
1041 static int
1042 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
1043 {
1044 struct bpf_if *bp;
1045 char *cp;
1046 int unit_seen, i, s, error;
1047
1048 /*
1049 * Make sure the provided name has a unit number, and default
1050 * it to '0' if not specified.
1051 * XXX This is ugly ... do this differently?
1052 */
1053 unit_seen = 0;
1054 cp = ifr->ifr_name;
1055 cp[sizeof(ifr->ifr_name) - 1] = '\0'; /* sanity */
1056 while (*cp++)
1057 if (*cp >= '0' && *cp <= '9')
1058 unit_seen = 1;
1059 if (!unit_seen) {
1060 /* Make sure to leave room for the '\0'. */
1061 for (i = 0; i < (IFNAMSIZ - 1); ++i) {
1062 if ((ifr->ifr_name[i] >= 'a' &&
1063 ifr->ifr_name[i] <= 'z') ||
1064 (ifr->ifr_name[i] >= 'A' &&
1065 ifr->ifr_name[i] <= 'Z'))
1066 continue;
1067 ifr->ifr_name[i] = '0';
1068 }
1069 }
1070
1071 /*
1072 * Look through attached interfaces for the named one.
1073 */
1074 for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1075 struct ifnet *ifp = bp->bif_ifp;
1076
1077 if (ifp == 0 ||
1078 strcmp(ifp->if_xname, ifr->ifr_name) != 0)
1079 continue;
1080 /* skip additional entry */
1081 if ((void **)bp->bif_driverp != &ifp->if_bpf)
1082 continue;
1083 /*
1084 * We found the requested interface.
1085 * Allocate the packet buffers if we need to.
1086 * If we're already attached to requested interface,
1087 * just flush the buffer.
1088 */
1089 if (d->bd_sbuf == 0) {
1090 error = bpf_allocbufs(d);
1091 if (error != 0)
1092 return (error);
1093 }
1094 s = splnet();
1095 if (bp != d->bd_bif) {
1096 if (d->bd_bif)
1097 /*
1098 * Detach if attached to something else.
1099 */
1100 bpf_detachd(d);
1101
1102 bpf_attachd(d, bp);
1103 }
1104 reset_d(d);
1105 splx(s);
1106 return (0);
1107 }
1108 /* Not found. */
1109 return (ENXIO);
1110 }
1111
1112 /*
1113 * Copy the interface name to the ifreq.
1114 */
1115 static void
1116 bpf_ifname(struct ifnet *ifp, struct ifreq *ifr)
1117 {
1118 memcpy(ifr->ifr_name, ifp->if_xname, IFNAMSIZ);
1119 }
1120
1121 static int
1122 bpf_stat(struct file *fp, struct stat *st)
1123 {
1124 struct bpf_d *d = fp->f_data;
1125
1126 (void)memset(st, 0, sizeof(*st));
1127 KERNEL_LOCK(1, NULL);
1128 st->st_dev = makedev(cdevsw_lookup_major(&bpf_cdevsw), d->bd_pid);
1129 st->st_atimespec = d->bd_atime;
1130 st->st_mtimespec = d->bd_mtime;
1131 st->st_ctimespec = st->st_birthtimespec = d->bd_btime;
1132 st->st_uid = kauth_cred_geteuid(fp->f_cred);
1133 st->st_gid = kauth_cred_getegid(fp->f_cred);
1134 KERNEL_UNLOCK_ONE(NULL);
1135 return 0;
1136 }
1137
1138 /*
1139 * Support for poll() system call
1140 *
1141 * Return true iff the specific operation will not block indefinitely - with
1142 * the assumption that it is safe to positively acknowledge a request for the
1143 * ability to write to the BPF device.
1144 * Otherwise, return false but make a note that a selnotify() must be done.
1145 */
1146 static int
1147 bpf_poll(struct file *fp, int events)
1148 {
1149 struct bpf_d *d = fp->f_data;
1150 int s = splnet();
1151 int revents;
1152
1153 /*
1154 * Refresh the PID associated with this bpf file.
1155 */
1156 KERNEL_LOCK(1, NULL);
1157 d->bd_pid = curproc->p_pid;
1158
1159 revents = events & (POLLOUT | POLLWRNORM);
1160 if (events & (POLLIN | POLLRDNORM)) {
1161 /*
1162 * An imitation of the FIONREAD ioctl code.
1163 */
1164 if (d->bd_hlen != 0 ||
1165 ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
1166 d->bd_slen != 0)) {
1167 revents |= events & (POLLIN | POLLRDNORM);
1168 } else {
1169 selrecord(curlwp, &d->bd_sel);
1170 /* Start the read timeout if necessary */
1171 if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1172 callout_reset(&d->bd_callout, d->bd_rtout,
1173 bpf_timed_out, d);
1174 d->bd_state = BPF_WAITING;
1175 }
1176 }
1177 }
1178
1179 KERNEL_UNLOCK_ONE(NULL);
1180 splx(s);
1181 return (revents);
1182 }
1183
1184 static void
1185 filt_bpfrdetach(struct knote *kn)
1186 {
1187 struct bpf_d *d = kn->kn_hook;
1188 int s;
1189
1190 KERNEL_LOCK(1, NULL);
1191 s = splnet();
1192 SLIST_REMOVE(&d->bd_sel.sel_klist, kn, knote, kn_selnext);
1193 splx(s);
1194 KERNEL_UNLOCK_ONE(NULL);
1195 }
1196
1197 static int
1198 filt_bpfread(struct knote *kn, long hint)
1199 {
1200 struct bpf_d *d = kn->kn_hook;
1201 int rv;
1202
1203 KERNEL_LOCK(1, NULL);
1204 kn->kn_data = d->bd_hlen;
1205 if (d->bd_immediate)
1206 kn->kn_data += d->bd_slen;
1207 rv = (kn->kn_data > 0);
1208 KERNEL_UNLOCK_ONE(NULL);
1209 return rv;
1210 }
1211
1212 static const struct filterops bpfread_filtops =
1213 { 1, NULL, filt_bpfrdetach, filt_bpfread };
1214
1215 static int
1216 bpf_kqfilter(struct file *fp, struct knote *kn)
1217 {
1218 struct bpf_d *d = fp->f_data;
1219 struct klist *klist;
1220 int s;
1221
1222 KERNEL_LOCK(1, NULL);
1223
1224 switch (kn->kn_filter) {
1225 case EVFILT_READ:
1226 klist = &d->bd_sel.sel_klist;
1227 kn->kn_fop = &bpfread_filtops;
1228 break;
1229
1230 default:
1231 KERNEL_UNLOCK_ONE(NULL);
1232 return (EINVAL);
1233 }
1234
1235 kn->kn_hook = d;
1236
1237 s = splnet();
1238 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1239 splx(s);
1240 KERNEL_UNLOCK_ONE(NULL);
1241
1242 return (0);
1243 }
1244
1245 /*
1246 * Incoming linkage from device drivers. Process the packet pkt, of length
1247 * pktlen, which is stored in a contiguous buffer. The packet is parsed
1248 * by each process' filter, and if accepted, stashed into the corresponding
1249 * buffer.
1250 */
1251 void
1252 bpf_tap(void *arg, u_char *pkt, u_int pktlen)
1253 {
1254 struct bpf_if *bp;
1255 struct bpf_d *d;
1256 u_int slen;
1257 struct timespec ts;
1258 int gottime=0;
1259
1260 /*
1261 * Note that the ipl does not have to be raised at this point.
1262 * The only problem that could arise here is that if two different
1263 * interfaces shared any data. This is not the case.
1264 */
1265 bp = arg;
1266 for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1267 ++d->bd_rcount;
1268 ++bpf_gstats.bs_recv;
1269 slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1270 if (slen != 0) {
1271 if (!gottime) {
1272 nanotime(&ts);
1273 gottime = 1;
1274 }
1275 catchpacket(d, pkt, pktlen, slen, memcpy, &ts);
1276 }
1277 }
1278 }
1279
1280 /*
1281 * Copy data from an mbuf chain into a buffer. This code is derived
1282 * from m_copydata in sys/uipc_mbuf.c.
1283 */
1284 static void *
1285 bpf_mcpy(void *dst_arg, const void *src_arg, size_t len)
1286 {
1287 const struct mbuf *m;
1288 u_int count;
1289 u_char *dst;
1290
1291 m = src_arg;
1292 dst = dst_arg;
1293 while (len > 0) {
1294 if (m == NULL)
1295 panic("bpf_mcpy");
1296 count = min(m->m_len, len);
1297 memcpy(dst, mtod(m, const void *), count);
1298 m = m->m_next;
1299 dst += count;
1300 len -= count;
1301 }
1302 return dst_arg;
1303 }
1304
1305 /*
1306 * Dispatch a packet to all the listeners on interface bp.
1307 *
1308 * marg pointer to the packet, either a data buffer or an mbuf chain
1309 * buflen buffer length, if marg is a data buffer
1310 * cpfn a function that can copy marg into the listener's buffer
1311 * pktlen length of the packet
1312 * rcvif either NULL or the interface the packet came in on.
1313 */
1314 static inline void
1315 bpf_deliver(struct bpf_if *bp, void *(*cpfn)(void *, const void *, size_t),
1316 void *marg, u_int pktlen, u_int buflen, struct ifnet *rcvif)
1317 {
1318 u_int slen;
1319 struct bpf_d *d;
1320 struct timespec ts;
1321 int gottime = 0;
1322
1323 for (d = bp->bif_dlist; d != 0; d = d->bd_next) {
1324 if (!d->bd_seesent && (rcvif == NULL))
1325 continue;
1326 ++d->bd_rcount;
1327 ++bpf_gstats.bs_recv;
1328 slen = bpf_filter(d->bd_filter, marg, pktlen, buflen);
1329 if (slen != 0) {
1330 if(!gottime) {
1331 nanotime(&ts);
1332 gottime = 1;
1333 }
1334 catchpacket(d, marg, pktlen, slen, cpfn, &ts);
1335 }
1336 }
1337 }
1338
1339 /*
1340 * Incoming linkage from device drivers, when the head of the packet is in
1341 * a buffer, and the tail is in an mbuf chain.
1342 */
1343 void
1344 bpf_mtap2(void *arg, void *data, u_int dlen, struct mbuf *m)
1345 {
1346 struct bpf_if *bp = arg;
1347 u_int pktlen;
1348 struct mbuf mb;
1349
1350 pktlen = m_length(m) + dlen;
1351
1352 /*
1353 * Craft on-stack mbuf suitable for passing to bpf_filter.
1354 * Note that we cut corners here; we only setup what's
1355 * absolutely needed--this mbuf should never go anywhere else.
1356 */
1357 (void)memset(&mb, 0, sizeof(mb));
1358 mb.m_next = m;
1359 mb.m_data = data;
1360 mb.m_len = dlen;
1361
1362 bpf_deliver(bp, bpf_mcpy, &mb, pktlen, 0, m->m_pkthdr.rcvif);
1363 }
1364
1365 /*
1366 * Incoming linkage from device drivers, when packet is in an mbuf chain.
1367 */
1368 void
1369 bpf_mtap(void *arg, struct mbuf *m)
1370 {
1371 void *(*cpfn)(void *, const void *, size_t);
1372 struct bpf_if *bp = arg;
1373 u_int pktlen, buflen;
1374 void *marg;
1375
1376 pktlen = m_length(m);
1377
1378 if (pktlen == m->m_len) {
1379 cpfn = (void *)memcpy;
1380 marg = mtod(m, void *);
1381 buflen = pktlen;
1382 } else {
1383 /*###1299 [cc] warning: assignment from incompatible pointer type%%%*/
1384 cpfn = bpf_mcpy;
1385 marg = m;
1386 buflen = 0;
1387 }
1388
1389 bpf_deliver(bp, cpfn, marg, pktlen, buflen, m->m_pkthdr.rcvif);
1390 }
1391
1392 /*
1393 * We need to prepend the address family as
1394 * a four byte field. Cons up a dummy header
1395 * to pacify bpf. This is safe because bpf
1396 * will only read from the mbuf (i.e., it won't
1397 * try to free it or keep a pointer a to it).
1398 */
1399 void
1400 bpf_mtap_af(void *arg, uint32_t af, struct mbuf *m)
1401 {
1402 struct mbuf m0;
1403
1404 m0.m_flags = 0;
1405 m0.m_next = m;
1406 m0.m_len = 4;
1407 m0.m_data = (char *)⁡
1408
1409 bpf_mtap(arg, &m0);
1410 }
1411
1412 void
1413 bpf_mtap_et(void *arg, uint16_t et, struct mbuf *m)
1414 {
1415 struct mbuf m0;
1416
1417 m0.m_flags = 0;
1418 m0.m_next = m;
1419 m0.m_len = 14;
1420 m0.m_data = m0.m_dat;
1421
1422 ((uint32_t *)m0.m_data)[0] = 0;
1423 ((uint32_t *)m0.m_data)[1] = 0;
1424 ((uint32_t *)m0.m_data)[2] = 0;
1425 ((uint16_t *)m0.m_data)[6] = et;
1426
1427 bpf_mtap(arg, &m0);
1428 }
1429
1430 #if NSL > 0 || NSTRIP > 0
1431 /*
1432 * Put the SLIP pseudo-"link header" in place.
1433 * Note this M_PREPEND() should never fail,
1434 * swince we know we always have enough space
1435 * in the input buffer.
1436 */
1437 void
1438 bpf_mtap_sl_in(void *arg, u_char *chdr, struct mbuf **m)
1439 {
1440 int s;
1441 u_char *hp;
1442
1443 M_PREPEND(*m, SLIP_HDRLEN, M_DONTWAIT);
1444 if (*m == NULL)
1445 return;
1446
1447 hp = mtod(*m, u_char *);
1448 hp[SLX_DIR] = SLIPDIR_IN;
1449 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1450
1451 s = splnet();
1452 bpf_mtap(arg, *m);
1453 splx(s);
1454
1455 m_adj(*m, SLIP_HDRLEN);
1456 }
1457
1458 /*
1459 * Put the SLIP pseudo-"link header" in
1460 * place. The compressed header is now
1461 * at the beginning of the mbuf.
1462 */
1463 void
1464 bpf_mtap_sl_out(void *arg, u_char *chdr, struct mbuf *m)
1465 {
1466 struct mbuf m0;
1467 u_char *hp;
1468 int s;
1469
1470 m0.m_flags = 0;
1471 m0.m_next = m;
1472 m0.m_data = m0.m_dat;
1473 m0.m_len = SLIP_HDRLEN;
1474
1475 hp = mtod(&m0, u_char *);
1476
1477 hp[SLX_DIR] = SLIPDIR_OUT;
1478 (void)memcpy(&hp[SLX_CHDR], chdr, CHDR_LEN);
1479
1480 s = splnet();
1481 bpf_mtap(arg, &m0);
1482 splx(s);
1483 m_freem(m);
1484 }
1485 #endif
1486
1487 /*
1488 * Move the packet data from interface memory (pkt) into the
1489 * store buffer. Return 1 if it's time to wakeup a listener (buffer full),
1490 * otherwise 0. "copy" is the routine called to do the actual data
1491 * transfer. memcpy is passed in to copy contiguous chunks, while
1492 * bpf_mcpy is passed in to copy mbuf chains. In the latter case,
1493 * pkt is really an mbuf.
1494 */
1495 static void
1496 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1497 void *(*cpfn)(void *, const void *, size_t), struct timespec *ts)
1498 {
1499 struct bpf_hdr *hp;
1500 int totlen, curlen;
1501 int hdrlen = d->bd_bif->bif_hdrlen;
1502 int do_wakeup = 0;
1503
1504 ++d->bd_ccount;
1505 ++bpf_gstats.bs_capt;
1506 /*
1507 * Figure out how many bytes to move. If the packet is
1508 * greater or equal to the snapshot length, transfer that
1509 * much. Otherwise, transfer the whole packet (unless
1510 * we hit the buffer size limit).
1511 */
1512 totlen = hdrlen + min(snaplen, pktlen);
1513 if (totlen > d->bd_bufsize)
1514 totlen = d->bd_bufsize;
1515
1516 /*
1517 * Round up the end of the previous packet to the next longword.
1518 */
1519 curlen = BPF_WORDALIGN(d->bd_slen);
1520 if (curlen + totlen > d->bd_bufsize) {
1521 /*
1522 * This packet will overflow the storage buffer.
1523 * Rotate the buffers if we can, then wakeup any
1524 * pending reads.
1525 */
1526 if (d->bd_fbuf == 0) {
1527 /*
1528 * We haven't completed the previous read yet,
1529 * so drop the packet.
1530 */
1531 ++d->bd_dcount;
1532 ++bpf_gstats.bs_drop;
1533 return;
1534 }
1535 ROTATE_BUFFERS(d);
1536 do_wakeup = 1;
1537 curlen = 0;
1538 } else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
1539 /*
1540 * Immediate mode is set, or the read timeout has
1541 * already expired during a select call. A packet
1542 * arrived, so the reader should be woken up.
1543 */
1544 do_wakeup = 1;
1545 }
1546
1547 /*
1548 * Append the bpf header.
1549 */
1550 hp = (struct bpf_hdr *)((char *)d->bd_sbuf + curlen);
1551 hp->bh_tstamp.tv_sec = ts->tv_sec;
1552 hp->bh_tstamp.tv_usec = ts->tv_nsec / 1000;
1553 hp->bh_datalen = pktlen;
1554 hp->bh_hdrlen = hdrlen;
1555 /*
1556 * Copy the packet data into the store buffer and update its length.
1557 */
1558 (*cpfn)((u_char *)hp + hdrlen, pkt, (hp->bh_caplen = totlen - hdrlen));
1559 d->bd_slen = curlen + totlen;
1560
1561 /*
1562 * Call bpf_wakeup after bd_slen has been updated so that kevent(2)
1563 * will cause filt_bpfread() to be called with it adjusted.
1564 */
1565 if (do_wakeup)
1566 bpf_wakeup(d);
1567 }
1568
1569 /*
1570 * Initialize all nonzero fields of a descriptor.
1571 */
1572 static int
1573 bpf_allocbufs(struct bpf_d *d)
1574 {
1575
1576 d->bd_fbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
1577 if (!d->bd_fbuf)
1578 return (ENOBUFS);
1579 d->bd_sbuf = malloc(d->bd_bufsize, M_DEVBUF, M_NOWAIT);
1580 if (!d->bd_sbuf) {
1581 free(d->bd_fbuf, M_DEVBUF);
1582 return (ENOBUFS);
1583 }
1584 d->bd_slen = 0;
1585 d->bd_hlen = 0;
1586 return (0);
1587 }
1588
1589 /*
1590 * Free buffers currently in use by a descriptor.
1591 * Called on close.
1592 */
1593 static void
1594 bpf_freed(struct bpf_d *d)
1595 {
1596 /*
1597 * We don't need to lock out interrupts since this descriptor has
1598 * been detached from its interface and it yet hasn't been marked
1599 * free.
1600 */
1601 if (d->bd_sbuf != 0) {
1602 free(d->bd_sbuf, M_DEVBUF);
1603 if (d->bd_hbuf != 0)
1604 free(d->bd_hbuf, M_DEVBUF);
1605 if (d->bd_fbuf != 0)
1606 free(d->bd_fbuf, M_DEVBUF);
1607 }
1608 if (d->bd_filter)
1609 free(d->bd_filter, M_DEVBUF);
1610 }
1611
1612 /*
1613 * Attach an interface to bpf. dlt is the link layer type; hdrlen is the
1614 * fixed size of the link header (variable length headers not yet supported).
1615 */
1616 void
1617 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1618 {
1619
1620 bpfattach2(ifp, dlt, hdrlen, &ifp->if_bpf);
1621 }
1622
1623 /*
1624 * Attach additional dlt for a interface to bpf. dlt is the link layer type;
1625 * hdrlen is the fixed size of the link header for the specified dlt
1626 * (variable length headers not yet supported).
1627 */
1628 void
1629 bpfattach2(struct ifnet *ifp, u_int dlt, u_int hdrlen, void *driverp)
1630 {
1631 struct bpf_if *bp;
1632 bp = malloc(sizeof(*bp), M_DEVBUF, M_DONTWAIT);
1633 if (bp == 0)
1634 panic("bpfattach");
1635
1636 bp->bif_dlist = 0;
1637 bp->bif_driverp = driverp;
1638 bp->bif_ifp = ifp;
1639 bp->bif_dlt = dlt;
1640
1641 bp->bif_next = bpf_iflist;
1642 bpf_iflist = bp;
1643
1644 *bp->bif_driverp = 0;
1645
1646 /*
1647 * Compute the length of the bpf header. This is not necessarily
1648 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1649 * that the network layer header begins on a longword boundary (for
1650 * performance reasons and to alleviate alignment restrictions).
1651 */
1652 bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1653
1654 #if 0
1655 printf("bpf: %s attached\n", ifp->if_xname);
1656 #endif
1657 }
1658
1659 /*
1660 * Remove an interface from bpf.
1661 */
1662 void
1663 bpfdetach(struct ifnet *ifp)
1664 {
1665 struct bpf_if *bp, **pbp;
1666 struct bpf_d *d;
1667 int s;
1668
1669 /* Nuke the vnodes for any open instances */
1670 LIST_FOREACH(d, &bpf_list, bd_list) {
1671 if (d->bd_bif != NULL && d->bd_bif->bif_ifp == ifp) {
1672 /*
1673 * Detach the descriptor from an interface now.
1674 * It will be free'ed later by close routine.
1675 */
1676 s = splnet();
1677 d->bd_promisc = 0; /* we can't touch device. */
1678 bpf_detachd(d);
1679 splx(s);
1680 }
1681 }
1682
1683 again:
1684 for (bp = bpf_iflist, pbp = &bpf_iflist;
1685 bp != NULL; pbp = &bp->bif_next, bp = bp->bif_next) {
1686 if (bp->bif_ifp == ifp) {
1687 *pbp = bp->bif_next;
1688 free(bp, M_DEVBUF);
1689 goto again;
1690 }
1691 }
1692 }
1693
1694 /*
1695 * Change the data link type of a interface.
1696 */
1697 void
1698 bpf_change_type(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1699 {
1700 struct bpf_if *bp;
1701
1702 for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1703 if ((void **)bp->bif_driverp == &ifp->if_bpf)
1704 break;
1705 }
1706 if (bp == NULL)
1707 panic("bpf_change_type");
1708
1709 bp->bif_dlt = dlt;
1710
1711 /*
1712 * Compute the length of the bpf header. This is not necessarily
1713 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1714 * that the network layer header begins on a longword boundary (for
1715 * performance reasons and to alleviate alignment restrictions).
1716 */
1717 bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1718 }
1719
1720 /*
1721 * Get a list of available data link type of the interface.
1722 */
1723 static int
1724 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
1725 {
1726 int n, error;
1727 struct ifnet *ifp;
1728 struct bpf_if *bp;
1729
1730 ifp = d->bd_bif->bif_ifp;
1731 n = 0;
1732 error = 0;
1733 for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1734 if (bp->bif_ifp != ifp)
1735 continue;
1736 if (bfl->bfl_list != NULL) {
1737 if (n >= bfl->bfl_len)
1738 return ENOMEM;
1739 error = copyout(&bp->bif_dlt,
1740 bfl->bfl_list + n, sizeof(u_int));
1741 }
1742 n++;
1743 }
1744 bfl->bfl_len = n;
1745 return error;
1746 }
1747
1748 /*
1749 * Set the data link type of a BPF instance.
1750 */
1751 static int
1752 bpf_setdlt(struct bpf_d *d, u_int dlt)
1753 {
1754 int s, error, opromisc;
1755 struct ifnet *ifp;
1756 struct bpf_if *bp;
1757
1758 if (d->bd_bif->bif_dlt == dlt)
1759 return 0;
1760 ifp = d->bd_bif->bif_ifp;
1761 for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1762 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1763 break;
1764 }
1765 if (bp == NULL)
1766 return EINVAL;
1767 s = splnet();
1768 opromisc = d->bd_promisc;
1769 bpf_detachd(d);
1770 bpf_attachd(d, bp);
1771 reset_d(d);
1772 if (opromisc) {
1773 error = ifpromisc(bp->bif_ifp, 1);
1774 if (error)
1775 printf("%s: bpf_setdlt: ifpromisc failed (%d)\n",
1776 bp->bif_ifp->if_xname, error);
1777 else
1778 d->bd_promisc = 1;
1779 }
1780 splx(s);
1781 return 0;
1782 }
1783
1784 static int
1785 sysctl_net_bpf_maxbufsize(SYSCTLFN_ARGS)
1786 {
1787 int newsize, error;
1788 struct sysctlnode node;
1789
1790 node = *rnode;
1791 node.sysctl_data = &newsize;
1792 newsize = bpf_maxbufsize;
1793 error = sysctl_lookup(SYSCTLFN_CALL(&node));
1794 if (error || newp == NULL)
1795 return (error);
1796
1797 if (newsize < BPF_MINBUFSIZE || newsize > BPF_MAXBUFSIZE)
1798 return (EINVAL);
1799
1800 bpf_maxbufsize = newsize;
1801
1802 return (0);
1803 }
1804
1805 static int
1806 sysctl_net_bpf_peers(SYSCTLFN_ARGS)
1807 {
1808 int error, elem_count;
1809 struct bpf_d *dp;
1810 struct bpf_d_ext dpe;
1811 size_t len, needed, elem_size, out_size;
1812 char *sp;
1813
1814 if (namelen == 1 && name[0] == CTL_QUERY)
1815 return (sysctl_query(SYSCTLFN_CALL(rnode)));
1816
1817 if (namelen != 2)
1818 return (EINVAL);
1819
1820 /* BPF peers is privileged information. */
1821 error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_INTERFACE,
1822 KAUTH_REQ_NETWORK_INTERFACE_GETPRIV, NULL, NULL, NULL);
1823 if (error)
1824 return (EPERM);
1825
1826 len = (oldp != NULL) ? *oldlenp : 0;
1827 sp = oldp;
1828 elem_size = name[0];
1829 elem_count = name[1];
1830 out_size = MIN(sizeof(dpe), elem_size);
1831 needed = 0;
1832
1833 if (elem_size < 1 || elem_count < 0)
1834 return (EINVAL);
1835
1836 mutex_enter(&bpf_mtx);
1837 LIST_FOREACH(dp, &bpf_list, bd_list) {
1838 if (len >= elem_size && elem_count > 0) {
1839 #define BPF_EXT(field) dpe.bde_ ## field = dp->bd_ ## field
1840 BPF_EXT(bufsize);
1841 BPF_EXT(promisc);
1842 BPF_EXT(promisc);
1843 BPF_EXT(state);
1844 BPF_EXT(immediate);
1845 BPF_EXT(hdrcmplt);
1846 BPF_EXT(seesent);
1847 BPF_EXT(pid);
1848 BPF_EXT(rcount);
1849 BPF_EXT(dcount);
1850 BPF_EXT(ccount);
1851 #undef BPF_EXT
1852 if (dp->bd_bif)
1853 (void)strlcpy(dpe.bde_ifname,
1854 dp->bd_bif->bif_ifp->if_xname,
1855 IFNAMSIZ - 1);
1856 else
1857 dpe.bde_ifname[0] = '\0';
1858
1859 error = copyout(&dpe, sp, out_size);
1860 if (error)
1861 break;
1862 sp += elem_size;
1863 len -= elem_size;
1864 }
1865 needed += elem_size;
1866 if (elem_count > 0 && elem_count != INT_MAX)
1867 elem_count--;
1868 }
1869 mutex_exit(&bpf_mtx);
1870
1871 *oldlenp = needed;
1872
1873 return (error);
1874 }
1875
1876 SYSCTL_SETUP(sysctl_net_bpf_setup, "sysctl net.bpf subtree setup")
1877 {
1878 const struct sysctlnode *node;
1879
1880 sysctl_createv(clog, 0, NULL, NULL,
1881 CTLFLAG_PERMANENT,
1882 CTLTYPE_NODE, "net", NULL,
1883 NULL, 0, NULL, 0,
1884 CTL_NET, CTL_EOL);
1885
1886 node = NULL;
1887 sysctl_createv(clog, 0, NULL, &node,
1888 CTLFLAG_PERMANENT,
1889 CTLTYPE_NODE, "bpf",
1890 SYSCTL_DESCR("BPF options"),
1891 NULL, 0, NULL, 0,
1892 CTL_NET, CTL_CREATE, CTL_EOL);
1893 if (node != NULL) {
1894 sysctl_createv(clog, 0, NULL, NULL,
1895 CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1896 CTLTYPE_INT, "maxbufsize",
1897 SYSCTL_DESCR("Maximum size for data capture buffer"),
1898 sysctl_net_bpf_maxbufsize, 0, &bpf_maxbufsize, 0,
1899 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
1900 sysctl_createv(clog, 0, NULL, NULL,
1901 CTLFLAG_PERMANENT,
1902 CTLTYPE_STRUCT, "stats",
1903 SYSCTL_DESCR("BPF stats"),
1904 NULL, 0, &bpf_gstats, sizeof(bpf_gstats),
1905 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
1906 sysctl_createv(clog, 0, NULL, NULL,
1907 CTLFLAG_PERMANENT,
1908 CTLTYPE_STRUCT, "peers",
1909 SYSCTL_DESCR("BPF peers"),
1910 sysctl_net_bpf_peers, 0, NULL, 0,
1911 CTL_NET, node->sysctl_num, CTL_CREATE, CTL_EOL);
1912 }
1913
1914 }
1915