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