xref: /xnu-11215.41.3/bsd/net/bpf.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1990, 1991, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * This code is derived from the Stanford/CMU enet packet filter,
33  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
34  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
35  * Berkeley Laboratory.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)bpf.c	8.2 (Berkeley) 3/28/94
66  *
67  * $FreeBSD: src/sys/net/bpf.c,v 1.59.2.5 2001/01/05 04:49:09 jdp Exp $
68  */
69 /*
70  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
71  * support for mandatory and extensible security protections.  This notice
72  * is included in support of clause 2.2 (b) of the Apple Public License,
73  * Version 2.0.
74  */
75 
76 #include "bpf.h"
77 
78 #ifndef __GNUC__
79 #define inline
80 #else
81 #define inline __inline
82 #endif
83 
84 #include <sys/param.h>
85 #include <sys/systm.h>
86 #include <sys/conf.h>
87 #include <sys/malloc.h>
88 #include <sys/mbuf.h>
89 #include <sys/time.h>
90 #include <sys/proc.h>
91 #include <sys/signalvar.h>
92 #include <sys/filio.h>
93 #include <sys/sockio.h>
94 #include <sys/ttycom.h>
95 #include <sys/filedesc.h>
96 #include <sys/uio_internal.h>
97 #include <sys/file_internal.h>
98 #include <sys/event.h>
99 
100 #include <sys/poll.h>
101 
102 #include <sys/socket.h>
103 #include <sys/socketvar.h>
104 #include <sys/vnode.h>
105 
106 #include <net/if.h>
107 #include <net/bpf.h>
108 #include <net/bpfdesc.h>
109 
110 #include <netinet/in.h>
111 #include <netinet/ip.h>
112 #include <netinet/ip6.h>
113 #include <netinet/in_pcb.h>
114 #include <netinet/in_var.h>
115 #include <netinet/ip_var.h>
116 #include <netinet/tcp.h>
117 #include <netinet/tcp_var.h>
118 #include <netinet/udp.h>
119 #include <netinet/udp_var.h>
120 #include <netinet/if_ether.h>
121 #include <netinet/isakmp.h>
122 #include <netinet6/esp.h>
123 #include <sys/kernel.h>
124 #include <sys/sysctl.h>
125 #include <net/firewire.h>
126 
127 #include <miscfs/devfs/devfs.h>
128 #include <net/dlil.h>
129 #include <net/pktap.h>
130 
131 #include <kern/assert.h>
132 #include <kern/locks.h>
133 #include <kern/thread_call.h>
134 #include <libkern/section_keywords.h>
135 
136 #include <os/log.h>
137 
138 #include <IOKit/IOBSD.h>
139 
140 #include <net/sockaddr_utils.h>
141 
142 extern int tvtohz(struct timeval *);
143 extern const char *proc_name_address(void *p);
144 
145 #define BPF_BUFSIZE 4096
146 
147 #define PRINET  26                      /* interruptible */
148 
149 #define ISAKMP_HDR_SIZE (sizeof(struct isakmp) + sizeof(struct isakmp_gen))
150 #define ESP_HDR_SIZE sizeof(struct newesp)
151 
152 #define BPF_WRITE_LEEWAY 18     /* space for link layer header */
153 
154 #define BPF_WRITE_MAX 0x1000000 /* 16 MB arbitrary value */
155 
156 typedef void (*pktcopyfunc_t)(const void *, void *, size_t);
157 
158 /*
159  * The default read buffer size is patchable.
160  */
161 static unsigned int bpf_bufsize = BPF_BUFSIZE;
162 SYSCTL_INT(_debug, OID_AUTO, bpf_bufsize, CTLFLAG_RW | CTLFLAG_LOCKED,
163     &bpf_bufsize, 0, "");
164 
165 __private_extern__ unsigned int bpf_maxbufsize = BPF_MAXBUFSIZE;
166 static int sysctl_bpf_maxbufsize SYSCTL_HANDLER_ARGS;
167 SYSCTL_PROC(_debug, OID_AUTO, bpf_maxbufsize, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
168     &bpf_maxbufsize, 0,
169     sysctl_bpf_maxbufsize, "I", "Default BPF max buffer size");
170 
171 extern const int copysize_limit_panic;
172 #define BPF_BUFSIZE_CAP (copysize_limit_panic >> 1)
173 static int sysctl_bpf_bufsize_cap SYSCTL_HANDLER_ARGS;
174 SYSCTL_PROC(_debug, OID_AUTO, bpf_bufsize_cap, CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_LOCKED,
175     0, 0,
176     sysctl_bpf_bufsize_cap, "I", "Upper limit on BPF max buffer size");
177 
178 #define BPF_MAX_DEVICES 256
179 static unsigned int bpf_maxdevices = BPF_MAX_DEVICES;
180 SYSCTL_UINT(_debug, OID_AUTO, bpf_maxdevices, CTLFLAG_RD | CTLFLAG_LOCKED,
181     &bpf_maxdevices, 0, "");
182 
183 /*
184  * bpf_wantpktap controls the defaul visibility of DLT_PKTAP
185  * For OS X is off by default so process need to use the ioctl BPF_WANT_PKTAP
186  * explicitly to be able to use DLT_PKTAP.
187  */
188 #if !XNU_TARGET_OS_OSX
189 static unsigned int bpf_wantpktap = 1;
190 #else /* XNU_TARGET_OS_OSX */
191 static unsigned int bpf_wantpktap = 0;
192 #endif /* XNU_TARGET_OS_OSX */
193 SYSCTL_UINT(_debug, OID_AUTO, bpf_wantpktap, CTLFLAG_RW | CTLFLAG_LOCKED,
194     &bpf_wantpktap, 0, "");
195 
196 static int bpf_debug = 0;
197 SYSCTL_INT(_debug, OID_AUTO, bpf_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
198     &bpf_debug, 0, "");
199 
200 static unsigned long bpf_trunc_overflow = 0;
201 SYSCTL_ULONG(_debug, OID_AUTO, bpf_trunc_overflow, CTLFLAG_RD | CTLFLAG_LOCKED,
202     &bpf_trunc_overflow, "");
203 
204 static int bpf_hdr_comp_enable = 1;
205 SYSCTL_INT(_debug, OID_AUTO, bpf_hdr_comp_enable, CTLFLAG_RW | CTLFLAG_LOCKED,
206     &bpf_hdr_comp_enable, 1, "");
207 
208 static int sysctl_bpf_stats SYSCTL_HANDLER_ARGS;
209 SYSCTL_PROC(_debug, OID_AUTO, bpf_stats, CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
210     0, 0,
211     sysctl_bpf_stats, "S", "BPF statistics");
212 
213 /*
214  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
215  *  bpf_dtab holds pointer to the descriptors, indexed by minor device #
216  */
217 static struct bpf_if    *bpf_iflist;
218 /*
219  * BSD now stores the bpf_d in the dev_t which is a struct
220  * on their system. Our dev_t is an int, so we still store
221  * the bpf_d in a separate table indexed by minor device #.
222  *
223  * The value stored in bpf_dtab[n] represent three states:
224  *  NULL: device not opened
225  *  BPF_DEV_RESERVED: device opening or closing
226  *  other: device <n> opened with pointer to storage
227  */
228 static struct bpf_d *BPF_DEV_RESERVED = __unsafe_forge_single(struct bpf_d *, 1);
229 static unsigned int bpf_dtab_size = 0;
230 static struct bpf_d **__counted_by(bpf_dtab_size) bpf_dtab = NULL;
231 static unsigned int nbpfilter = 0;
232 static unsigned bpf_bpfd_cnt = 0;
233 
234 static LCK_GRP_DECLARE(bpf_mlock_grp, "bpf");
235 static LCK_MTX_DECLARE(bpf_mlock_data, &bpf_mlock_grp);
236 static lck_mtx_t *const bpf_mlock = &bpf_mlock_data;
237 
238 static int      bpf_allocbufs(struct bpf_d *);
239 static errno_t  bpf_attachd(struct bpf_d *d, struct bpf_if *bp);
240 static int      bpf_detachd(struct bpf_d *d);
241 static void     bpf_freed(struct bpf_d *);
242 static int      bpf_setif(struct bpf_d *, ifnet_t ifp, bool, bool, bool);
243 static void     bpf_timed_out(void *, void *);
244 static void     bpf_wakeup(struct bpf_d *);
245 static uint32_t get_pkt_trunc_len(struct bpf_packet *);
246 static void     catchpacket(struct bpf_d *, struct bpf_packet *, u_int, int);
247 static void     reset_d(struct bpf_d *);
248 static int      bpf_setf(struct bpf_d *, u_int, user_addr_t, u_long);
249 static int      bpf_getdltlist(struct bpf_d *, caddr_t __bidi_indexable, struct proc *);
250 static int      bpf_setdlt(struct bpf_d *, u_int);
251 static int      bpf_set_traffic_class(struct bpf_d *, int);
252 static void     bpf_set_packet_service_class(struct mbuf *, int);
253 
254 static void     bpf_acquire_d(struct bpf_d *);
255 static void     bpf_release_d(struct bpf_d *);
256 
257 static  int bpf_devsw_installed;
258 
259 void bpf_init(void *unused);
260 static int bpf_tap_callback(struct ifnet *ifp, struct mbuf *m);
261 
262 /*
263  * Darwin differs from BSD here, the following are static
264  * on BSD and not static on Darwin.
265  */
266 d_open_t            bpfopen;
267 d_close_t           bpfclose;
268 d_read_t            bpfread;
269 d_write_t           bpfwrite;
270 ioctl_fcn_t         bpfioctl;
271 select_fcn_t        bpfselect;
272 
273 /* Darwin's cdevsw struct differs slightly from BSDs */
274 #define CDEV_MAJOR 23
275 static const struct cdevsw bpf_cdevsw = {
276 	.d_open       = bpfopen,
277 	.d_close      = bpfclose,
278 	.d_read       = bpfread,
279 	.d_write      = bpfwrite,
280 	.d_ioctl      = bpfioctl,
281 	.d_stop       = eno_stop,
282 	.d_reset      = eno_reset,
283 	.d_ttys       = NULL,
284 	.d_select     = bpfselect,
285 	.d_mmap       = eno_mmap,
286 	.d_strategy   = eno_strat,
287 	.d_reserved_1 = eno_getc,
288 	.d_reserved_2 = eno_putc,
289 	.d_type       = 0
290 };
291 
292 #define SOCKADDR_HDR_LEN           offsetof(struct sockaddr, sa_data)
293 
294 static int
bpf_copy_uio_to_mbuf_packet(struct uio * auio,int bytes_to_copy,struct mbuf * top)295 bpf_copy_uio_to_mbuf_packet(struct uio *auio, int bytes_to_copy, struct mbuf *top)
296 {
297 	int error = 0;
298 
299 	for (struct mbuf *m = top; m != NULL; m = m->m_next) {
300 		int mlen;
301 
302 		if (m->m_flags & M_EXT) {
303 			mlen = m->m_ext.ext_size - (int)M_LEADINGSPACE(m);
304 		} else if (m->m_flags & M_PKTHDR) {
305 			mlen = MHLEN - (int)M_LEADINGSPACE(m);
306 		} else {
307 			mlen = MLEN - (int)M_LEADINGSPACE(m);
308 		}
309 		int copy_len = imin((int)mlen, bytes_to_copy);
310 
311 		error = uiomove(mtod(m, caddr_t), (int)copy_len, auio);
312 		if (error != 0) {
313 			os_log(OS_LOG_DEFAULT, "bpf_copy_uio_to_mbuf_packet: len %d error %d",
314 			    copy_len, error);
315 			goto done;
316 		}
317 		m->m_len = copy_len;
318 		top->m_pkthdr.len += copy_len;
319 
320 		if (bytes_to_copy > copy_len) {
321 			bytes_to_copy -= copy_len;
322 		} else {
323 			break;
324 		}
325 	}
326 done:
327 	return error;
328 }
329 
330 static inline void
bpf_set_bcast_mcast(mbuf_t m,struct ether_header * eh)331 bpf_set_bcast_mcast(mbuf_t m, struct ether_header * eh)
332 {
333 	if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
334 		if (_ether_cmp(etherbroadcastaddr, eh->ether_dhost) == 0) {
335 			m->m_flags |= M_BCAST;
336 		} else {
337 			m->m_flags |= M_MCAST;
338 		}
339 	}
340 }
341 
342 #if DEBUG | DEVELOPMENT
343 static void
bpf_log_bcast(const char * func,const char * ifname,uint16_t flags,bool hdrcmplt)344 bpf_log_bcast(const char * func, const char * ifname, uint16_t flags,
345     bool hdrcmplt)
346 {
347 	const char *    type;
348 
349 	if ((flags & M_BCAST) != 0) {
350 		type = "broadcast";
351 	} else if ((flags & M_MCAST) != 0) {
352 		type = "multicast";
353 	} else {
354 		type = "unicast";
355 	}
356 	os_log(OS_LOG_DEFAULT, "%s %s %s hdrcmplt=%s", func, ifname, type,
357 	    hdrcmplt ? "true" : "false");
358 }
359 #endif /* DEBUG | DEVELOPMENT */
360 
361 static int
bpf_movein(struct uio * uio,int copy_len,struct bpf_d * d,struct mbuf ** mp,struct sockaddr * sockp)362 bpf_movein(struct uio *uio, int copy_len, struct bpf_d *d, struct mbuf **mp,
363     struct sockaddr *sockp)
364 {
365 	mbuf_ref_t m = NULL;
366 	int error;
367 	int len;
368 	uint8_t sa_family;
369 	int hlen = 0;
370 	struct ifnet *ifp = d->bd_bif->bif_ifp;
371 	int linktype = (int)d->bd_bif->bif_dlt;
372 
373 	switch (linktype) {
374 #if SLIP
375 	case DLT_SLIP:
376 		sa_family = AF_INET;
377 		hlen = 0;
378 		break;
379 #endif /* SLIP */
380 
381 	case DLT_EN10MB:
382 		sa_family = AF_UNSPEC;
383 		/* XXX Would MAXLINKHDR be better? */
384 		hlen = sizeof(struct ether_header);
385 		break;
386 
387 #if FDDI
388 	case DLT_FDDI:
389 #if defined(__FreeBSD__) || defined(__bsdi__)
390 		sa_family = AF_IMPLINK;
391 		hlen = 0;
392 #else
393 		sa_family = AF_UNSPEC;
394 		/* XXX 4(FORMAC)+6(dst)+6(src)+3(LLC)+5(SNAP) */
395 		hlen = 24;
396 #endif
397 		break;
398 #endif /* FDDI */
399 
400 	case DLT_RAW:
401 	case DLT_NULL:
402 		sa_family = AF_UNSPEC;
403 		hlen = 0;
404 		break;
405 
406 #ifdef __FreeBSD__
407 	case DLT_ATM_RFC1483:
408 		/*
409 		 * en atm driver requires 4-byte atm pseudo header.
410 		 * though it isn't standard, vpi:vci needs to be
411 		 * specified anyway.
412 		 */
413 		sa_family = AF_UNSPEC;
414 		hlen = 12;      /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
415 		break;
416 #endif
417 
418 	case DLT_PPP:
419 		sa_family = AF_UNSPEC;
420 		hlen = 4;       /* This should match PPP_HDRLEN */
421 		break;
422 
423 	case DLT_APPLE_IP_OVER_IEEE1394:
424 		sa_family = AF_UNSPEC;
425 		hlen = sizeof(struct firewire_header);
426 		break;
427 
428 	case DLT_IEEE802_11:            /* IEEE 802.11 wireless */
429 		sa_family = AF_IEEE80211;
430 		hlen = 0;
431 		break;
432 
433 	case DLT_IEEE802_11_RADIO:
434 		sa_family = AF_IEEE80211;
435 		hlen = 0;
436 		break;
437 
438 	default:
439 		return EIO;
440 	}
441 
442 	if (sockp) {
443 		/*
444 		 * Build a sockaddr based on the data link layer type.
445 		 * We do this at this level because the ethernet header
446 		 * is copied directly into the data field of the sockaddr.
447 		 * In the case of SLIP, there is no header and the packet
448 		 * is forwarded as is.
449 		 * Also, we are careful to leave room at the front of the mbuf
450 		 * for the link level header.
451 		 */
452 		if ((hlen + SOCKADDR_HDR_LEN) > sockp->sa_len) {
453 			return EIO;
454 		}
455 		sockp->sa_family = sa_family;
456 	} else {
457 		/*
458 		 * We're directly sending the packet data supplied by
459 		 * the user; we don't need to make room for the link
460 		 * header, and don't need the header length value any
461 		 * more, so set it to 0.
462 		 */
463 		hlen = 0;
464 	}
465 
466 	len = (int)uio_resid(uio);
467 	if (len < copy_len) {
468 		os_log(OS_LOG_DEFAULT, "bpfwrite: len %d if %s less than copy_len %d",
469 		    (unsigned)len, ifp->if_xname, copy_len);
470 		return EMSGSIZE;
471 	}
472 	len = copy_len;
473 	if (len < hlen || (unsigned)len > BPF_WRITE_MAX) {
474 		os_log(OS_LOG_DEFAULT, "bpfwrite: bad len %d if %s",
475 		    (unsigned)len, ifp->if_xname);
476 		return EMSGSIZE;
477 	}
478 	if (d->bd_write_size_max != 0) {
479 		if ((len - hlen) > (d->bd_write_size_max + BPF_WRITE_LEEWAY)) {
480 			os_log(OS_LOG_DEFAULT, "bpfwrite: len %u - hlen %u too big if %s write_size_max %u",
481 			    (unsigned)len, (unsigned)hlen, ifp->if_xname, d->bd_write_size_max);
482 		}
483 	} else if ((len - hlen) > (ifp->if_mtu + BPF_WRITE_LEEWAY)) {
484 		os_log(OS_LOG_DEFAULT, "bpfwrite: len %u - hlen %u too big if %s mtu %u",
485 		    (unsigned)len, (unsigned)hlen, ifp->if_xname, ifp->if_mtu);
486 		return EMSGSIZE;
487 	}
488 
489 	/* drop lock while allocating mbuf and copying data */
490 	lck_mtx_unlock(bpf_mlock);
491 
492 	error = mbuf_allocpacket(MBUF_WAITOK, len, NULL, &m);
493 	if (error != 0) {
494 		os_log(OS_LOG_DEFAULT,
495 		    "bpfwrite mbuf_allocpacket len %d error %d", len, error);
496 		goto bad;
497 	}
498 	/*
499 	 * Make room for link header -- the packet length is 0 at this stage
500 	 */
501 	if (hlen != 0) {
502 		m->m_data += hlen; /* leading space */
503 		error = uiomove((caddr_t)sockp->sa_data, hlen, uio);
504 		if (error) {
505 			os_log(OS_LOG_DEFAULT,
506 			    "bpfwrite uiomove hlen %d error %d", hlen, error);
507 			goto bad;
508 		}
509 		len -= hlen;
510 		if (linktype == DLT_EN10MB) {
511 			struct ether_header * eh;
512 
513 			eh = (struct ether_header *)(void *)sockp->sa_data;
514 			bpf_set_bcast_mcast(m, eh);
515 #if DEBUG || DEVELOPMENT
516 			if (__improbable(bpf_debug != 0)) {
517 				bpf_log_bcast(__func__, ifp->if_xname,
518 				    m->m_flags, false);
519 			}
520 #endif /* DEBUG || DEVELOPMENT */
521 		}
522 	}
523 	/*
524 	 * bpf_copy_uio_to_mbuf_packet() does set the length of each mbuf and adds it to
525 	 * the total packet length
526 	 */
527 	error = bpf_copy_uio_to_mbuf_packet(uio, len, m);
528 	if (error != 0) {
529 		os_log(OS_LOG_DEFAULT,
530 		    "bpfwrite bpf_copy_uio_to_mbuf_packet error %d", error);
531 		goto bad;
532 	}
533 
534 	/* Check for multicast destination */
535 	if (hlen == 0 && linktype == DLT_EN10MB) {
536 		struct ether_header *eh;
537 
538 		eh = mtod(m, struct ether_header *);
539 		bpf_set_bcast_mcast(m, eh);
540 #if DEBUG || DEVELOPMENT
541 		if (__improbable(bpf_debug != 0)) {
542 			bpf_log_bcast(__func__, ifp->if_xname,
543 			    m->m_flags, true);
544 		}
545 #endif /* DEBUG || DEVELOPMENT */
546 	}
547 	*mp = m;
548 
549 	lck_mtx_lock(bpf_mlock);
550 	return 0;
551 bad:
552 	if (m != NULL) {
553 		m_freem(m);
554 	}
555 	lck_mtx_lock(bpf_mlock);
556 	return error;
557 }
558 
559 static int
bpf_movein_batch(struct uio * uio,struct bpf_d * d,struct mbuf ** mp,struct sockaddr * sockp)560 bpf_movein_batch(struct uio *uio, struct bpf_d *d, struct mbuf **mp,
561     struct sockaddr *sockp)
562 {
563 	int error = 0;
564 	user_ssize_t resid;
565 	int count = 0;
566 	struct mbuf *last = NULL;
567 
568 	*mp = NULL;
569 	while ((resid = uio_resid(uio)) >= sizeof(struct bpf_hdr)) {
570 		struct bpf_hdr bpfhdr = {};
571 		int bpf_hdr_min_len = offsetof(struct bpf_hdr, bh_hdrlen) + sizeof(bpfhdr.bh_hdrlen);
572 		int padding_len;
573 
574 		error = uiomove((caddr_t)&bpfhdr, bpf_hdr_min_len, uio);
575 		if (error != 0) {
576 			os_log(OS_LOG_DEFAULT, "bpf_movein_batch uiomove error %d", error);
577 			break;
578 		}
579 		/*
580 		 * Buffer validation:
581 		 * - ignore bh_tstamp
582 		 * - bh_hdrlen must fit
583 		 * - bh_caplen and bh_datalen must be equal
584 		 */
585 		if (bpfhdr.bh_hdrlen < bpf_hdr_min_len) {
586 			error = EINVAL;
587 			os_log(OS_LOG_DEFAULT, "bpf_movein_batch bh_hdrlen %u too small",
588 			    bpfhdr.bh_hdrlen);
589 			break;
590 		}
591 		if (bpfhdr.bh_caplen != bpfhdr.bh_datalen) {
592 			error = EINVAL;
593 			os_log(OS_LOG_DEFAULT, "bpf_movein_batch bh_caplen %u != bh_datalen %u",
594 			    bpfhdr.bh_caplen, bpfhdr.bh_datalen);
595 			break;
596 		}
597 		if (bpfhdr.bh_hdrlen > resid) {
598 			error = EINVAL;
599 			os_log(OS_LOG_DEFAULT, "bpf_movein_batch bh_hdrlen %u too large",
600 			    bpfhdr.bh_hdrlen);
601 			break;
602 		}
603 
604 		/*
605 		 * Ignore additional bytes in the header
606 		 */
607 		padding_len = bpfhdr.bh_hdrlen - bpf_hdr_min_len;
608 		if (padding_len > 0) {
609 			uio_update(uio, padding_len);
610 		}
611 
612 		/* skip empty packets */
613 		if (bpfhdr.bh_caplen > 0) {
614 			mbuf_ref_t m;
615 
616 			/*
617 			 * For time being assume all packets have same destination
618 			 */
619 			error = bpf_movein(uio, bpfhdr.bh_caplen, d, &m, sockp);
620 			if (error != 0) {
621 				os_log(OS_LOG_DEFAULT, "bpf_movein_batch bpf_movein error %d",
622 				    error);
623 				break;
624 			}
625 			count += 1;
626 
627 			if (last == NULL) {
628 				*mp = m;
629 			} else {
630 				last->m_nextpkt = m;
631 			}
632 			last = m;
633 		}
634 
635 		/*
636 		 * Each BPF packet is padded for alignment
637 		 */
638 		padding_len = BPF_WORDALIGN(bpfhdr.bh_hdrlen + bpfhdr.bh_caplen) - (bpfhdr.bh_hdrlen + bpfhdr.bh_caplen);
639 		if (padding_len > 0) {
640 			uio_update(uio, padding_len);
641 		}
642 	}
643 
644 	if (error != 0) {
645 		if (*mp != NULL) {
646 			m_freem_list(*mp);
647 			*mp = NULL;
648 		}
649 	}
650 	return error;
651 }
652 
653 /*
654  * The dynamic addition of a new device node must block all processes that
655  * are opening the last device so that no process will get an unexpected
656  * ENOENT
657  */
658 static void
bpf_make_dev_t(int maj)659 bpf_make_dev_t(int maj)
660 {
661 	static int              bpf_growing = 0;
662 	unsigned int    cur_size = nbpfilter, i;
663 
664 	if (nbpfilter >= BPF_MAX_DEVICES) {
665 		return;
666 	}
667 
668 	while (bpf_growing) {
669 		/* Wait until new device has been created */
670 		(void) tsleep((caddr_t)&bpf_growing, PZERO, "bpf_growing", 0);
671 	}
672 	if (nbpfilter > cur_size) {
673 		/* other thread grew it already */
674 		return;
675 	}
676 	bpf_growing = 1;
677 
678 	/* need to grow bpf_dtab first */
679 	if (nbpfilter == bpf_dtab_size) {
680 		unsigned int new_dtab_size;
681 		struct bpf_d **new_dtab = NULL;
682 
683 		new_dtab_size = bpf_dtab_size + NBPFILTER;
684 		new_dtab = krealloc_type(struct bpf_d *,
685 		    bpf_dtab_size, new_dtab_size, bpf_dtab, Z_WAITOK | Z_ZERO);
686 
687 		if (new_dtab == 0) {
688 			os_log_error(OS_LOG_DEFAULT, "bpf_make_dev_t: malloc bpf_dtab failed");
689 			goto done;
690 		}
691 		bpf_dtab = new_dtab;
692 		bpf_dtab_size = new_dtab_size;
693 	}
694 	i = nbpfilter++;
695 	(void) devfs_make_node(makedev(maj, i),
696 	    DEVFS_CHAR, UID_ROOT, GID_WHEEL, 0600,
697 	    "bpf%d", i);
698 done:
699 	bpf_growing = 0;
700 	wakeup((caddr_t)&bpf_growing);
701 }
702 
703 /*
704  * Attach file to the bpf interface, i.e. make d listen on bp.
705  */
706 static errno_t
bpf_attachd(struct bpf_d * d,struct bpf_if * bp)707 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
708 {
709 	int first = bp->bif_dlist == NULL;
710 	int     error = 0;
711 
712 	/*
713 	 * Point d at bp, and add d to the interface's list of listeners.
714 	 * Finally, point the driver's bpf cookie at the interface so
715 	 * it will divert packets to bpf.
716 	 */
717 	d->bd_bif = bp;
718 	d->bd_next = bp->bif_dlist;
719 	bp->bif_dlist = d;
720 	bpf_bpfd_cnt++;
721 
722 	/*
723 	 * Take a reference on the device even if an error is returned
724 	 * because we keep the device in the interface's list of listeners
725 	 */
726 	bpf_acquire_d(d);
727 
728 	if (first) {
729 		/* Find the default bpf entry for this ifp */
730 		if (bp->bif_ifp->if_bpf == NULL) {
731 			struct bpf_if   *tmp, *primary = NULL;
732 
733 			for (tmp = bpf_iflist; tmp; tmp = tmp->bif_next) {
734 				if (tmp->bif_ifp == bp->bif_ifp) {
735 					primary = tmp;
736 					break;
737 				}
738 			}
739 			bp->bif_ifp->if_bpf = primary;
740 		}
741 		/* Only call dlil_set_bpf_tap for primary dlt */
742 		if (bp->bif_ifp->if_bpf == bp) {
743 			dlil_set_bpf_tap(bp->bif_ifp, BPF_TAP_INPUT_OUTPUT,
744 			    bpf_tap_callback);
745 		}
746 
747 		if (bp->bif_tap != NULL) {
748 			error = bp->bif_tap(bp->bif_ifp, bp->bif_dlt,
749 			    BPF_TAP_INPUT_OUTPUT);
750 		}
751 	}
752 
753 	/*
754 	 * Reset the detach flags in case we previously detached an interface
755 	 */
756 	d->bd_flags &= ~(BPF_DETACHING | BPF_DETACHED);
757 
758 	if (bp->bif_dlt == DLT_PKTAP) {
759 		d->bd_flags |= BPF_FINALIZE_PKTAP;
760 	} else {
761 		d->bd_flags &= ~BPF_FINALIZE_PKTAP;
762 	}
763 	return error;
764 }
765 
766 /*
767  * Detach a file from its interface.
768  *
769  * Return 1 if was closed by some thread, 0 otherwise
770  */
771 static int
bpf_detachd(struct bpf_d * d)772 bpf_detachd(struct bpf_d *d)
773 {
774 	struct bpf_d **p;
775 	struct bpf_if *bp;
776 	struct ifnet  *ifp;
777 	uint32_t dlt;
778 	bpf_tap_func disable_tap;
779 	uint8_t bd_promisc;
780 
781 	int bpf_closed = d->bd_flags & BPF_CLOSING;
782 	/*
783 	 * Some other thread already detached
784 	 */
785 	if ((d->bd_flags & (BPF_DETACHED | BPF_DETACHING)) != 0) {
786 		goto done;
787 	}
788 	/*
789 	 * This thread is doing the detach
790 	 */
791 	d->bd_flags |= BPF_DETACHING;
792 
793 	ifp = d->bd_bif->bif_ifp;
794 	bp = d->bd_bif;
795 
796 	/* Remove d from the interface's descriptor list. */
797 	p = &bp->bif_dlist;
798 	while (*p != d) {
799 		p = &(*p)->bd_next;
800 		if (*p == 0) {
801 			panic("bpf_detachd: descriptor not in list");
802 		}
803 	}
804 	*p = (*p)->bd_next;
805 	bpf_bpfd_cnt--;
806 	disable_tap = NULL;
807 	if (bp->bif_dlist == 0) {
808 		/*
809 		 * Let the driver know that there are no more listeners.
810 		 */
811 		/* Only call dlil_set_bpf_tap for primary dlt */
812 		if (bp->bif_ifp->if_bpf == bp) {
813 			dlil_set_bpf_tap(ifp, BPF_TAP_DISABLE, NULL);
814 		}
815 
816 		disable_tap = bp->bif_tap;
817 		if (disable_tap) {
818 			dlt = bp->bif_dlt;
819 		}
820 
821 		for (bp = bpf_iflist; bp; bp = bp->bif_next) {
822 			if (bp->bif_ifp == ifp && bp->bif_dlist != 0) {
823 				break;
824 			}
825 		}
826 		if (bp == NULL) {
827 			ifp->if_bpf = NULL;
828 		}
829 	}
830 	d->bd_bif = NULL;
831 
832 	/*
833 	 * Stop disabling input
834 	 */
835 	if ((d->bd_flags & BPF_DIVERT_IN) != 0) {
836 		if_clear_xflags(ifp, IFXF_DISABLE_INPUT);
837 		d->bd_flags &= ~BPF_DIVERT_IN;
838 
839 		os_log(OS_LOG_DEFAULT,
840 		    "bpf_detachd: bpf%d %s disable input 0",
841 		    d->bd_dev_minor, if_name(ifp));
842 	}
843 
844 	/*
845 	 * Check if this descriptor had requested promiscuous mode.
846 	 * If so, turn it off.
847 	 */
848 	bd_promisc = d->bd_promisc;
849 	d->bd_promisc = 0;
850 
851 	lck_mtx_unlock(bpf_mlock);
852 	if (bd_promisc) {
853 		if (ifnet_set_promiscuous(ifp, 0)) {
854 			/*
855 			 * Something is really wrong if we were able to put
856 			 * the driver into promiscuous mode, but can't
857 			 * take it out.
858 			 * Most likely the network interface is gone.
859 			 */
860 			os_log_error(OS_LOG_DEFAULT,
861 			    "%s: bpf%d ifnet_set_promiscuous %s failed",
862 			    __func__, d->bd_dev_minor, if_name(ifp));
863 		}
864 	}
865 
866 	if (disable_tap) {
867 		disable_tap(ifp, dlt, BPF_TAP_DISABLE);
868 	}
869 	lck_mtx_lock(bpf_mlock);
870 
871 	/*
872 	 * Wake up other thread that are waiting for this thread to finish
873 	 * detaching
874 	 */
875 	d->bd_flags &= ~BPF_DETACHING;
876 	d->bd_flags |= BPF_DETACHED;
877 
878 	/* Refresh the local variable as d could have been modified */
879 	bpf_closed = d->bd_flags & BPF_CLOSING;
880 
881 	os_log(OS_LOG_DEFAULT, "bpf%d%s detached from %s fcount %llu dcount %llu",
882 	    d->bd_dev_minor, bpf_closed ? " closed and" : "", if_name(ifp),
883 	    d->bd_fcount, d->bd_dcount);
884 
885 	/*
886 	 * Note that We've kept the reference because we may have dropped
887 	 * the lock when turning off promiscuous mode
888 	 */
889 	bpf_release_d(d);
890 done:
891 	/*
892 	 * Let the caller know the bpf_d is closed
893 	 */
894 	if (bpf_closed) {
895 		return 1;
896 	} else {
897 		return 0;
898 	}
899 }
900 
901 /*
902  * Start asynchronous timer, if necessary.
903  * Must be called with bpf_mlock held.
904  */
905 static void
bpf_start_timer(struct bpf_d * d)906 bpf_start_timer(struct bpf_d *d)
907 {
908 	uint64_t deadline;
909 	struct timeval tv;
910 
911 	if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
912 		tv.tv_sec = d->bd_rtout / hz;
913 		tv.tv_usec = (d->bd_rtout % hz) * tick;
914 
915 		clock_interval_to_deadline(
916 			(uint32_t)tv.tv_sec * USEC_PER_SEC + tv.tv_usec,
917 			NSEC_PER_USEC, &deadline);
918 		/*
919 		 * The state is BPF_IDLE, so the timer hasn't
920 		 * been started yet, and hasn't gone off yet;
921 		 * there is no thread call scheduled, so this
922 		 * won't change the schedule.
923 		 *
924 		 * XXX - what if, by the time it gets entered,
925 		 * the deadline has already passed?
926 		 */
927 		thread_call_enter_delayed(d->bd_thread_call, deadline);
928 		d->bd_state = BPF_WAITING;
929 	}
930 }
931 
932 /*
933  * Cancel asynchronous timer.
934  * Must be called with bpf_mlock held.
935  */
936 static boolean_t
bpf_stop_timer(struct bpf_d * d)937 bpf_stop_timer(struct bpf_d *d)
938 {
939 	/*
940 	 * If the timer has already gone off, this does nothing.
941 	 * Our caller is expected to set d->bd_state to BPF_IDLE,
942 	 * with the bpf_mlock, after we are called. bpf_timed_out()
943 	 * also grabs bpf_mlock, so, if the timer has gone off and
944 	 * bpf_timed_out() hasn't finished, it's waiting for the
945 	 * lock; when this thread releases the lock, it will
946 	 * find the state is BPF_IDLE, and just release the
947 	 * lock and return.
948 	 */
949 	return thread_call_cancel(d->bd_thread_call);
950 }
951 
952 void
bpf_acquire_d(struct bpf_d * d)953 bpf_acquire_d(struct bpf_d *d)
954 {
955 	void *__single lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
956 
957 	LCK_MTX_ASSERT(bpf_mlock, LCK_MTX_ASSERT_OWNED);
958 
959 	d->bd_refcnt += 1;
960 
961 	d->bd_ref_lr[d->bd_next_ref_lr] = lr_saved;
962 	d->bd_next_ref_lr = (d->bd_next_ref_lr + 1) % BPF_REF_HIST;
963 }
964 
965 void
bpf_release_d(struct bpf_d * d)966 bpf_release_d(struct bpf_d *d)
967 {
968 	void *__single lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
969 
970 	LCK_MTX_ASSERT(bpf_mlock, LCK_MTX_ASSERT_OWNED);
971 
972 	if (d->bd_refcnt <= 0) {
973 		panic("%s: %p refcnt <= 0", __func__, d);
974 	}
975 
976 	d->bd_refcnt -= 1;
977 
978 	d->bd_unref_lr[d->bd_next_unref_lr] = lr_saved;
979 	d->bd_next_unref_lr = (d->bd_next_unref_lr + 1) % BPF_REF_HIST;
980 
981 	if (d->bd_refcnt == 0) {
982 		/* Assert the device is detached */
983 		if ((d->bd_flags & BPF_DETACHED) == 0) {
984 			panic("%s: %p BPF_DETACHED not set", __func__, d);
985 		}
986 
987 		kfree_type(struct bpf_d, d);
988 	}
989 }
990 
991 /*
992  * Open ethernet device.  Returns ENXIO for illegal minor device number,
993  * EBUSY if file is open by another process.
994  */
995 /* ARGSUSED */
996 int
bpfopen(dev_t dev,int flags,__unused int fmt,struct proc * p)997 bpfopen(dev_t dev, int flags, __unused int fmt,
998     struct proc *p)
999 {
1000 	struct bpf_d *d;
1001 
1002 	lck_mtx_lock(bpf_mlock);
1003 	if ((unsigned int) minor(dev) >= nbpfilter) {
1004 		lck_mtx_unlock(bpf_mlock);
1005 		return ENXIO;
1006 	}
1007 	/*
1008 	 * New device nodes are created on demand when opening the last one.
1009 	 * The programming model is for processes to loop on the minor starting
1010 	 * at 0 as long as EBUSY is returned. The loop stops when either the
1011 	 * open succeeds or an error other that EBUSY is returned. That means
1012 	 * that bpf_make_dev_t() must block all processes that are opening the
1013 	 * last  node. If not all processes are blocked, they could unexpectedly
1014 	 * get ENOENT and abort their opening loop.
1015 	 */
1016 	if ((unsigned int) minor(dev) == (nbpfilter - 1)) {
1017 		bpf_make_dev_t(major(dev));
1018 	}
1019 
1020 	/*
1021 	 * Each minor can be opened by only one process.  If the requested
1022 	 * minor is in use, return EBUSY.
1023 	 *
1024 	 * Important: bpfopen() and bpfclose() have to check and set the status
1025 	 * of a device in the same lockin context otherwise the device may be
1026 	 * leaked because the vnode use count will be unpextectly greater than 1
1027 	 * when close() is called.
1028 	 */
1029 	if (bpf_dtab[minor(dev)] == NULL) {
1030 		/* Reserve while opening */
1031 		bpf_dtab[minor(dev)] = BPF_DEV_RESERVED;
1032 	} else {
1033 		lck_mtx_unlock(bpf_mlock);
1034 		return EBUSY;
1035 	}
1036 	d = kalloc_type(struct bpf_d, Z_WAITOK | Z_ZERO);
1037 	if (d == NULL) {
1038 		/* this really is a catastrophic failure */
1039 		os_log_error(OS_LOG_DEFAULT,
1040 		    "bpfopen: bpf%d kalloc_type bpf_d failed", minor(dev));
1041 		bpf_dtab[minor(dev)] = NULL;
1042 		lck_mtx_unlock(bpf_mlock);
1043 		return ENOMEM;
1044 	}
1045 
1046 	/* Mark "in use" and do most initialization. */
1047 	bpf_acquire_d(d);
1048 	d->bd_bufsize = bpf_bufsize;
1049 	d->bd_sig = SIGIO;
1050 	d->bd_direction = BPF_D_INOUT;
1051 	d->bd_oflags = flags;
1052 	d->bd_state = BPF_IDLE;
1053 	d->bd_traffic_class = SO_TC_BE;
1054 	d->bd_flags |= BPF_DETACHED;
1055 	if (bpf_wantpktap) {
1056 		d->bd_flags |= BPF_WANT_PKTAP;
1057 	} else {
1058 		d->bd_flags &= ~BPF_WANT_PKTAP;
1059 	}
1060 
1061 	d->bd_thread_call = thread_call_allocate(bpf_timed_out, d);
1062 	if (d->bd_thread_call == NULL) {
1063 		os_log_error(OS_LOG_DEFAULT, "bpfopen: bpf%d malloc thread call failed",
1064 		    minor(dev));
1065 		bpf_dtab[minor(dev)] = NULL;
1066 		bpf_release_d(d);
1067 		lck_mtx_unlock(bpf_mlock);
1068 
1069 		return ENOMEM;
1070 	}
1071 	d->bd_opened_by = p;
1072 	uuid_generate(d->bd_uuid);
1073 	d->bd_pid = proc_pid(p);
1074 
1075 	d->bd_dev_minor = minor(dev);
1076 	bpf_dtab[minor(dev)] = d;         /* Mark opened */
1077 	lck_mtx_unlock(bpf_mlock);
1078 
1079 	if (bpf_debug) {
1080 		os_log(OS_LOG_DEFAULT, "bpf%u opened by %s.%u",
1081 		    d->bd_dev_minor, proc_name_address(p), d->bd_pid);
1082 	}
1083 	return 0;
1084 }
1085 
1086 /*
1087  * Close the descriptor by detaching it from its interface,
1088  * deallocating its buffers, and marking it free.
1089  */
1090 /* ARGSUSED */
1091 int
bpfclose(dev_t dev,__unused int flags,__unused int fmt,__unused struct proc * p)1092 bpfclose(dev_t dev, __unused int flags, __unused int fmt,
1093     __unused struct proc *p)
1094 {
1095 	struct bpf_d *d;
1096 
1097 	/* Take BPF lock to ensure no other thread is using the device */
1098 	lck_mtx_lock(bpf_mlock);
1099 
1100 	d = bpf_dtab[minor(dev)];
1101 	if (d == NULL || d == BPF_DEV_RESERVED) {
1102 		lck_mtx_unlock(bpf_mlock);
1103 		return ENXIO;
1104 	}
1105 
1106 	/*
1107 	 * Other threads may call bpd_detachd() if we drop the bpf_mlock
1108 	 */
1109 	d->bd_flags |= BPF_CLOSING;
1110 
1111 	if (bpf_debug != 0) {
1112 		os_log(OS_LOG_DEFAULT, "%s: bpf%d",
1113 		    __func__, d->bd_dev_minor);
1114 	}
1115 
1116 	bpf_dtab[minor(dev)] = BPF_DEV_RESERVED; /* Reserve while closing */
1117 
1118 	/*
1119 	 * Deal with any in-progress timeouts.
1120 	 */
1121 	switch (d->bd_state) {
1122 	case BPF_IDLE:
1123 		/*
1124 		 * Not waiting for a timeout, and no timeout happened.
1125 		 */
1126 		break;
1127 
1128 	case BPF_WAITING:
1129 		/*
1130 		 * Waiting for a timeout.
1131 		 * Cancel any timer that has yet to go off,
1132 		 * and mark the state as "closing".
1133 		 * Then drop the lock to allow any timers that
1134 		 * *have* gone off to run to completion, and wait
1135 		 * for them to finish.
1136 		 */
1137 		if (!bpf_stop_timer(d)) {
1138 			/*
1139 			 * There was no pending call, so the call must
1140 			 * have been in progress. Wait for the call to
1141 			 * complete; we have to drop the lock while
1142 			 * waiting. to let the in-progrss call complete
1143 			 */
1144 			d->bd_state = BPF_DRAINING;
1145 			while (d->bd_state == BPF_DRAINING) {
1146 				msleep((caddr_t)d, bpf_mlock, PRINET,
1147 				    "bpfdraining", NULL);
1148 			}
1149 		}
1150 		d->bd_state = BPF_IDLE;
1151 		break;
1152 
1153 	case BPF_TIMED_OUT:
1154 		/*
1155 		 * Timer went off, and the timeout routine finished.
1156 		 */
1157 		d->bd_state = BPF_IDLE;
1158 		break;
1159 
1160 	case BPF_DRAINING:
1161 		/*
1162 		 * Another thread is blocked on a close waiting for
1163 		 * a timeout to finish.
1164 		 * This "shouldn't happen", as the first thread to enter
1165 		 * bpfclose() will set bpf_dtab[minor(dev)] to 1, and
1166 		 * all subsequent threads should see that and fail with
1167 		 * ENXIO.
1168 		 */
1169 		panic("Two threads blocked in a BPF close");
1170 		break;
1171 	}
1172 
1173 	if (d->bd_bif) {
1174 		bpf_detachd(d);
1175 	}
1176 	selthreadclear(&d->bd_sel);
1177 	thread_call_free(d->bd_thread_call);
1178 
1179 	while (d->bd_hbuf_read || d->bd_hbuf_write) {
1180 		msleep((caddr_t)d, bpf_mlock, PRINET, "bpfclose", NULL);
1181 	}
1182 
1183 	if (bpf_debug) {
1184 		os_log(OS_LOG_DEFAULT,
1185 		    "bpf%u closed by %s.%u dcount %llu fcount %llu ccount %llu",
1186 		    d->bd_dev_minor, proc_name_address(p), d->bd_pid,
1187 		    d->bd_dcount, d->bd_fcount, d->bd_bcs.bcs_count_compressed_prefix);
1188 	}
1189 
1190 	bpf_freed(d);
1191 
1192 	/* Mark free in same context as bpfopen comes to check */
1193 	bpf_dtab[minor(dev)] = NULL;                    /* Mark closed */
1194 
1195 	bpf_release_d(d);
1196 
1197 	lck_mtx_unlock(bpf_mlock);
1198 
1199 	return 0;
1200 }
1201 
1202 #define BPF_SLEEP bpf_sleep
1203 
1204 static int
bpf_sleep(struct bpf_d * d,int pri,const char * wmesg,int timo)1205 bpf_sleep(struct bpf_d *d, int pri, const char *wmesg, int timo)
1206 {
1207 	u_int64_t abstime = 0;
1208 
1209 	if (timo != 0) {
1210 		clock_interval_to_deadline(timo, NSEC_PER_SEC / hz, &abstime);
1211 	}
1212 
1213 	return msleep1((caddr_t)d, bpf_mlock, pri, wmesg, abstime);
1214 }
1215 
1216 static void
bpf_finalize_pktap(struct bpf_hdr * hp,struct pktap_header * pktaphdr)1217 bpf_finalize_pktap(struct bpf_hdr *hp, struct pktap_header *pktaphdr)
1218 {
1219 	if (pktaphdr->pth_flags & PTH_FLAG_V2_HDR) {
1220 		struct pktap_v2_hdr *pktap_v2_hdr;
1221 
1222 		pktap_v2_hdr = (struct pktap_v2_hdr *)pktaphdr;
1223 
1224 		if (pktap_v2_hdr->pth_flags & PTH_FLAG_DELAY_PKTAP) {
1225 			pktap_v2_finalize_proc_info(pktap_v2_hdr);
1226 		}
1227 	} else {
1228 		if (pktaphdr->pth_flags & PTH_FLAG_DELAY_PKTAP) {
1229 			pktap_finalize_proc_info(pktaphdr);
1230 		}
1231 
1232 		if (pktaphdr->pth_flags & PTH_FLAG_TSTAMP) {
1233 			hp->bh_tstamp.tv_sec = pktaphdr->pth_tstamp.tv_sec;
1234 			hp->bh_tstamp.tv_usec = pktaphdr->pth_tstamp.tv_usec;
1235 		}
1236 	}
1237 }
1238 
1239 /*
1240  * Rotate the packet buffers in descriptor d.  Move the store buffer
1241  * into the hold slot, and the free buffer into the store slot.
1242  * Zero the length of the new store buffer.
1243  *
1244  * Note: in head drop mode, the hold buffer can be dropped so the fist packet of the
1245  * store buffer cannot be compressed as it otherwise would refer to deleted data
1246  * in a dropped hold buffer that the reader process does know about
1247  */
1248 #define ROTATE_BUFFERS(d) do { \
1249 	if (d->bd_hbuf_read) \
1250 	        panic("rotating bpf buffers during read"); \
1251 	(d)->bd_hbuf = (d)->bd_sbuf; \
1252 	(d)->bd_hlen = (d)->bd_slen; \
1253 	(d)->bd_hcnt = (d)->bd_scnt; \
1254 	(d)->bd_sbuf = (d)->bd_fbuf; \
1255 	(d)->bd_slen = 0; \
1256 	(d)->bd_scnt = 0; \
1257 	(d)->bd_fbuf = NULL; \
1258 	if ((d)->bd_headdrop != 0) \
1259 	        (d)->bd_prev_slen = 0; \
1260 } while(false)
1261 
1262 /*
1263  *  bpfread - read next chunk of packets from buffers
1264  */
1265 int
bpfread(dev_t dev,struct uio * uio,int ioflag)1266 bpfread(dev_t dev, struct uio *uio, int ioflag)
1267 {
1268 	struct bpf_d *d;
1269 	caddr_t hbuf;
1270 	int timed_out, hbuf_len;
1271 	int error;
1272 	int flags;
1273 
1274 	lck_mtx_lock(bpf_mlock);
1275 
1276 	d = bpf_dtab[minor(dev)];
1277 	if (d == NULL || d == BPF_DEV_RESERVED ||
1278 	    (d->bd_flags & BPF_CLOSING) != 0) {
1279 		lck_mtx_unlock(bpf_mlock);
1280 		return ENXIO;
1281 	}
1282 
1283 	bpf_acquire_d(d);
1284 
1285 	/*
1286 	 * Restrict application to use a buffer the same size as
1287 	 * as kernel buffers.
1288 	 */
1289 	if (uio_resid(uio) != d->bd_bufsize) {
1290 		bpf_release_d(d);
1291 		lck_mtx_unlock(bpf_mlock);
1292 		return EINVAL;
1293 	}
1294 
1295 	if (d->bd_state == BPF_WAITING) {
1296 		bpf_stop_timer(d);
1297 	}
1298 
1299 	timed_out = (d->bd_state == BPF_TIMED_OUT);
1300 	d->bd_state = BPF_IDLE;
1301 
1302 	while (d->bd_hbuf_read) {
1303 		msleep((caddr_t)d, bpf_mlock, PRINET, "bpfread", NULL);
1304 	}
1305 
1306 	if ((d->bd_flags & BPF_CLOSING) != 0) {
1307 		bpf_release_d(d);
1308 		lck_mtx_unlock(bpf_mlock);
1309 		return ENXIO;
1310 	}
1311 	/*
1312 	 * If the hold buffer is empty, then do a timed sleep, which
1313 	 * ends when the timeout expires or when enough packets
1314 	 * have arrived to fill the store buffer.
1315 	 */
1316 	while (d->bd_hbuf == 0) {
1317 		if ((d->bd_immediate || timed_out || (ioflag & IO_NDELAY)) &&
1318 		    d->bd_slen != 0) {
1319 			/*
1320 			 * We're in immediate mode, or are reading
1321 			 * in non-blocking mode, or a timer was
1322 			 * started before the read (e.g., by select()
1323 			 * or poll()) and has expired and a packet(s)
1324 			 * either arrived since the previous
1325 			 * read or arrived while we were asleep.
1326 			 * Rotate the buffers and return what's here.
1327 			 */
1328 			ROTATE_BUFFERS(d);
1329 			break;
1330 		}
1331 
1332 		/*
1333 		 * No data is available, check to see if the bpf device
1334 		 * is still pointed at a real interface.  If not, return
1335 		 * ENXIO so that the userland process knows to rebind
1336 		 * it before using it again.
1337 		 */
1338 		if (d->bd_bif == NULL) {
1339 			bpf_release_d(d);
1340 			lck_mtx_unlock(bpf_mlock);
1341 			return ENXIO;
1342 		}
1343 		if (ioflag & IO_NDELAY) {
1344 			bpf_release_d(d);
1345 			lck_mtx_unlock(bpf_mlock);
1346 			return EWOULDBLOCK;
1347 		}
1348 		error = BPF_SLEEP(d, PRINET | PCATCH, "bpf", d->bd_rtout);
1349 		/*
1350 		 * Make sure device is still opened
1351 		 */
1352 		if ((d->bd_flags & BPF_CLOSING) != 0) {
1353 			bpf_release_d(d);
1354 			lck_mtx_unlock(bpf_mlock);
1355 			return ENXIO;
1356 		}
1357 
1358 		while (d->bd_hbuf_read) {
1359 			msleep((caddr_t)d, bpf_mlock, PRINET, "bpf_read",
1360 			    NULL);
1361 		}
1362 
1363 		if ((d->bd_flags & BPF_CLOSING) != 0) {
1364 			bpf_release_d(d);
1365 			lck_mtx_unlock(bpf_mlock);
1366 			return ENXIO;
1367 		}
1368 
1369 		if (error == EINTR || error == ERESTART) {
1370 			if (d->bd_hbuf != NULL) {
1371 				/*
1372 				 * Because we msleep, the hold buffer might
1373 				 * be filled when we wake up.  Avoid rotating
1374 				 * in this case.
1375 				 */
1376 				break;
1377 			}
1378 			if (d->bd_slen != 0) {
1379 				/*
1380 				 * Sometimes we may be interrupted often and
1381 				 * the sleep above will not timeout.
1382 				 * Regardless, we should rotate the buffers
1383 				 * if there's any new data pending and
1384 				 * return it.
1385 				 */
1386 				ROTATE_BUFFERS(d);
1387 				break;
1388 			}
1389 			bpf_release_d(d);
1390 			lck_mtx_unlock(bpf_mlock);
1391 			if (error == ERESTART) {
1392 				os_log(OS_LOG_DEFAULT, "%s: bpf%d ERESTART to EINTR",
1393 				    __func__, d->bd_dev_minor);
1394 				error = EINTR;
1395 			}
1396 			return error;
1397 		}
1398 		if (error == EWOULDBLOCK) {
1399 			/*
1400 			 * On a timeout, return what's in the buffer,
1401 			 * which may be nothing.  If there is something
1402 			 * in the store buffer, we can rotate the buffers.
1403 			 */
1404 			if (d->bd_hbuf) {
1405 				/*
1406 				 * We filled up the buffer in between
1407 				 * getting the timeout and arriving
1408 				 * here, so we don't need to rotate.
1409 				 */
1410 				break;
1411 			}
1412 
1413 			if (d->bd_slen == 0) {
1414 				bpf_release_d(d);
1415 				lck_mtx_unlock(bpf_mlock);
1416 				return 0;
1417 			}
1418 			ROTATE_BUFFERS(d);
1419 			break;
1420 		}
1421 	}
1422 	/*
1423 	 * At this point, we know we have something in the hold slot.
1424 	 */
1425 
1426 	/*
1427 	 * Set the hold buffer read. So we do not
1428 	 * rotate the buffers until the hold buffer
1429 	 * read is complete. Also to avoid issues resulting
1430 	 * from page faults during disk sleep (<rdar://problem/13436396>).
1431 	 */
1432 	d->bd_hbuf_read = true;
1433 	hbuf = d->bd_hbuf;
1434 	hbuf_len = d->bd_hlen;
1435 	flags = d->bd_flags;
1436 	d->bd_bcs.bcs_total_read += d->bd_hcnt;
1437 	lck_mtx_unlock(bpf_mlock);
1438 
1439 	/*
1440 	 * Before we move data to userland, we fill out the extended
1441 	 * header fields.
1442 	 */
1443 	if (flags & BPF_EXTENDED_HDR) {
1444 		char *p;
1445 
1446 		p = hbuf;
1447 		while (p < hbuf + hbuf_len) {
1448 			struct bpf_hdr_ext *ehp;
1449 			uint32_t flowid;
1450 			struct so_procinfo soprocinfo;
1451 			int found = 0;
1452 
1453 			ehp = (struct bpf_hdr_ext *)(void *)p;
1454 			if ((flowid = ehp->bh_flowid) != 0) {
1455 				if (ehp->bh_flags & BPF_HDR_EXT_FLAGS_TCP) {
1456 					ehp->bh_flags &= ~BPF_HDR_EXT_FLAGS_TCP;
1457 					found = inp_findinpcb_procinfo(&tcbinfo,
1458 					    flowid, &soprocinfo);
1459 				} else if (ehp->bh_flags == BPF_HDR_EXT_FLAGS_UDP) {
1460 					ehp->bh_flags &= ~BPF_HDR_EXT_FLAGS_UDP;
1461 					found = inp_findinpcb_procinfo(&udbinfo,
1462 					    flowid, &soprocinfo);
1463 				}
1464 				if (found == 1) {
1465 					ehp->bh_pid = soprocinfo.spi_pid;
1466 					strbufcpy(ehp->bh_comm,
1467 					    soprocinfo.spi_proc_name);
1468 				}
1469 				ehp->bh_flowid = 0;
1470 			}
1471 
1472 			if ((flags & BPF_FINALIZE_PKTAP) != 0 && ehp->bh_complen == 0) {
1473 				struct pktap_header *pktaphdr;
1474 
1475 				pktaphdr = (struct pktap_header *)(void *)
1476 				    (p + BPF_WORDALIGN(ehp->bh_hdrlen));
1477 
1478 				bpf_finalize_pktap((struct bpf_hdr *) ehp,
1479 				    pktaphdr);
1480 			}
1481 			p += BPF_WORDALIGN(ehp->bh_hdrlen + ehp->bh_caplen);
1482 		}
1483 	} else if (flags & BPF_FINALIZE_PKTAP) {
1484 		char *p;
1485 
1486 		p = hbuf;
1487 
1488 		while (p < hbuf + hbuf_len) {
1489 			struct bpf_hdr *hp;
1490 			struct pktap_header *pktaphdr;
1491 
1492 			hp = (struct bpf_hdr *)(void *)p;
1493 
1494 			/*
1495 			 * Cannot finalize a compressed pktap header as we may not have
1496 			 * all the fields present
1497 			 */
1498 			if (d->bd_flags & BPF_COMP_ENABLED) {
1499 				struct bpf_comp_hdr *hcp;
1500 
1501 				hcp = (struct bpf_comp_hdr *)(void *)p;
1502 
1503 				if (hcp->bh_complen != 0) {
1504 					p += BPF_WORDALIGN(hcp->bh_hdrlen + hcp->bh_caplen);
1505 					continue;
1506 				}
1507 			}
1508 
1509 			pktaphdr = (struct pktap_header *)(void *)
1510 			    (p + BPF_WORDALIGN(hp->bh_hdrlen));
1511 
1512 			bpf_finalize_pktap(hp, pktaphdr);
1513 
1514 			p += BPF_WORDALIGN(hp->bh_hdrlen + hp->bh_caplen);
1515 		}
1516 	}
1517 
1518 	/*
1519 	 * Move data from hold buffer into user space.
1520 	 * We know the entire buffer is transferred since
1521 	 * we checked above that the read buffer is bpf_bufsize bytes.
1522 	 */
1523 	error = uiomove(hbuf, hbuf_len, uio);
1524 
1525 	lck_mtx_lock(bpf_mlock);
1526 	/*
1527 	 * Make sure device is still opened
1528 	 */
1529 	if ((d->bd_flags & BPF_CLOSING) != 0) {
1530 		bpf_release_d(d);
1531 		lck_mtx_unlock(bpf_mlock);
1532 		return ENXIO;
1533 	}
1534 
1535 	d->bd_hbuf_read = false;
1536 	d->bd_fbuf = d->bd_hbuf;
1537 	d->bd_hbuf = NULL;
1538 	d->bd_hlen = 0;
1539 	d->bd_hcnt = 0;
1540 	wakeup((caddr_t)d);
1541 
1542 	bpf_release_d(d);
1543 	lck_mtx_unlock(bpf_mlock);
1544 	return error;
1545 }
1546 
1547 /*
1548  * If there are processes sleeping on this descriptor, wake them up.
1549  */
1550 static void
bpf_wakeup(struct bpf_d * d)1551 bpf_wakeup(struct bpf_d *d)
1552 {
1553 	if (d->bd_state == BPF_WAITING) {
1554 		bpf_stop_timer(d);
1555 		d->bd_state = BPF_IDLE;
1556 	}
1557 	wakeup((caddr_t)d);
1558 	if (d->bd_async && d->bd_sig && d->bd_sigio) {
1559 		pgsigio(d->bd_sigio, d->bd_sig);
1560 	}
1561 
1562 	selwakeup(&d->bd_sel);
1563 	if ((d->bd_flags & BPF_KNOTE)) {
1564 		KNOTE(&d->bd_sel.si_note, 1);
1565 	}
1566 }
1567 
1568 static void
bpf_timed_out(void * arg,__unused void * dummy)1569 bpf_timed_out(void *arg, __unused void *dummy)
1570 {
1571 	struct bpf_d *d = (struct bpf_d *)arg;
1572 
1573 	lck_mtx_lock(bpf_mlock);
1574 	if (d->bd_state == BPF_WAITING) {
1575 		/*
1576 		 * There's a select or kqueue waiting for this; if there's
1577 		 * now stuff to read, wake it up.
1578 		 */
1579 		d->bd_state = BPF_TIMED_OUT;
1580 		if (d->bd_slen != 0) {
1581 			bpf_wakeup(d);
1582 		}
1583 	} else if (d->bd_state == BPF_DRAINING) {
1584 		/*
1585 		 * A close is waiting for this to finish.
1586 		 * Mark it as finished, and wake the close up.
1587 		 */
1588 		d->bd_state = BPF_IDLE;
1589 		bpf_wakeup(d);
1590 	}
1591 	lck_mtx_unlock(bpf_mlock);
1592 }
1593 
1594 /* keep in sync with bpf_movein above: */
1595 #define MAX_DATALINK_HDR_LEN    (sizeof(struct firewire_header))
1596 
1597 int
bpfwrite(dev_t dev,struct uio * uio,__unused int ioflag)1598 bpfwrite(dev_t dev, struct uio *uio, __unused int ioflag)
1599 {
1600 	struct bpf_d *d;
1601 	struct ifnet *ifp;
1602 	mbuf_ref_t m = NULL;
1603 	int error = 0;
1604 	char dst_buf[SOCKADDR_HDR_LEN + MAX_DATALINK_HDR_LEN] = {};
1605 	int bif_dlt;
1606 	int bd_hdrcmplt;
1607 	bpf_send_func bif_send;
1608 
1609 	lck_mtx_lock(bpf_mlock);
1610 
1611 	while (true) {
1612 		d = bpf_dtab[minor(dev)];
1613 		if (d == NULL || d == BPF_DEV_RESERVED ||
1614 		    (d->bd_flags & BPF_CLOSING) != 0) {
1615 			lck_mtx_unlock(bpf_mlock);
1616 			return ENXIO;
1617 		}
1618 
1619 		if (d->bd_hbuf_write) {
1620 			msleep((caddr_t)d, bpf_mlock, PRINET, "bpfwrite",
1621 			    NULL);
1622 		} else {
1623 			break;
1624 		}
1625 	}
1626 	d->bd_hbuf_write = true;
1627 
1628 	bpf_acquire_d(d);
1629 
1630 	++d->bd_wcount;
1631 
1632 	if (d->bd_bif == NULL) {
1633 		error = ENXIO;
1634 		goto done;
1635 	}
1636 
1637 	ifp = d->bd_bif->bif_ifp;
1638 
1639 	if (IFNET_IS_MANAGEMENT(ifp) &&
1640 	    IOCurrentTaskHasEntitlement(MANAGEMENT_DATA_ENTITLEMENT) == false) {
1641 		++d->bd_wdcount;
1642 		bpf_release_d(d);
1643 		lck_mtx_unlock(bpf_mlock);
1644 		return ENETDOWN;
1645 	}
1646 
1647 	if ((ifp->if_flags & IFF_UP) == 0) {
1648 		error = ENETDOWN;
1649 		goto done;
1650 	}
1651 	int resid = (int)uio_resid(uio);
1652 	if (resid <= 0) {
1653 		error = resid == 0 ? 0 : EINVAL;
1654 		os_log(OS_LOG_DEFAULT, "bpfwrite: resid %d error %d", resid, error);
1655 		goto done;
1656 	}
1657 	SA(dst_buf)->sa_len = sizeof(dst_buf);
1658 
1659 	/*
1660 	 * geting variables onto stack before dropping the lock
1661 	 */
1662 	bif_dlt = (int)d->bd_bif->bif_dlt;
1663 	bd_hdrcmplt  = d->bd_hdrcmplt;
1664 	bool batch_write = (d->bd_flags & BPF_BATCH_WRITE) ? true : false;
1665 
1666 	if (batch_write) {
1667 		error = bpf_movein_batch(uio, d, &m, bd_hdrcmplt ? NULL : SA(dst_buf));
1668 		if (error != 0) {
1669 			goto done;
1670 		}
1671 	} else {
1672 		error = bpf_movein(uio, resid, d, &m, bd_hdrcmplt ? NULL : SA(dst_buf));
1673 		if (error != 0) {
1674 			goto done;
1675 		}
1676 		bpf_set_packet_service_class(m, d->bd_traffic_class);
1677 	}
1678 
1679 	/* verify the device is still open */
1680 	if ((d->bd_flags & BPF_CLOSING) != 0) {
1681 		error = ENXIO;
1682 		goto done;
1683 	}
1684 
1685 	if (d->bd_bif == NULL || d->bd_bif->bif_ifp != ifp) {
1686 		error = ENXIO;
1687 		goto done;
1688 	}
1689 
1690 	bif_send = d->bd_bif->bif_send;
1691 
1692 	lck_mtx_unlock(bpf_mlock);
1693 
1694 	if (bd_hdrcmplt) {
1695 		if (bif_send) {
1696 			/*
1697 			 * Send one packet at a time, the driver frees the mbuf
1698 			 * but we need to take care of the leftover
1699 			 */
1700 			while (m != NULL && error == 0) {
1701 				struct mbuf *next = m->m_nextpkt;
1702 
1703 				m->m_nextpkt = NULL;
1704 				error = bif_send(ifp, bif_dlt, m);
1705 				m = next;
1706 			}
1707 		} else {
1708 			error = dlil_output(ifp, 0, m, NULL, NULL,
1709 			    DLIL_OUTPUT_FLAGS_RAW, NULL);
1710 			/* Make sure we do not double free */
1711 			m = NULL;
1712 		}
1713 	} else {
1714 		error = dlil_output(ifp, PF_INET, m, NULL, SA(dst_buf),
1715 		    DLIL_OUTPUT_FLAGS_NONE, NULL);
1716 		/* Make sure we do not double free */
1717 		m = NULL;
1718 	}
1719 
1720 	lck_mtx_lock(bpf_mlock);
1721 done:
1722 	if (error != 0 && m != NULL) {
1723 		++d->bd_wdcount;
1724 	}
1725 	if (m != NULL) {
1726 		m_freem_list(m);
1727 	}
1728 	d->bd_hbuf_write = false;
1729 	wakeup((caddr_t)d);
1730 	bpf_release_d(d);
1731 	lck_mtx_unlock(bpf_mlock);
1732 
1733 	return error;
1734 }
1735 
1736 /*
1737  * Reset a descriptor by flushing its packet buffer and clearing the
1738  * receive and drop counts.
1739  */
1740 static void
reset_d(struct bpf_d * d)1741 reset_d(struct bpf_d *d)
1742 {
1743 	if (d->bd_hbuf_read) {
1744 		panic("resetting buffers during read");
1745 	}
1746 
1747 	if (d->bd_hbuf) {
1748 		/* Free the hold buffer. */
1749 		d->bd_fbuf = d->bd_hbuf;
1750 		d->bd_hbuf = NULL;
1751 	}
1752 	d->bd_slen = 0;
1753 	d->bd_hlen = 0;
1754 	d->bd_scnt = 0;
1755 	d->bd_hcnt = 0;
1756 	d->bd_rcount = 0;
1757 	d->bd_dcount = 0;
1758 	d->bd_fcount = 0;
1759 	d->bd_wcount = 0;
1760 	d->bd_wdcount = 0;
1761 
1762 	d->bd_prev_slen = 0;
1763 }
1764 
1765 static struct bpf_d *
bpf_get_device_from_uuid(uuid_t uuid)1766 bpf_get_device_from_uuid(uuid_t uuid)
1767 {
1768 	unsigned int i;
1769 
1770 	for (i = 0; i < nbpfilter; i++) {
1771 		struct bpf_d *d = bpf_dtab[i];
1772 
1773 		if (d == NULL || d == BPF_DEV_RESERVED ||
1774 		    (d->bd_flags & BPF_CLOSING) != 0) {
1775 			continue;
1776 		}
1777 		if (uuid_compare(uuid, d->bd_uuid) == 0) {
1778 			return d;
1779 		}
1780 	}
1781 
1782 	return NULL;
1783 }
1784 
1785 /*
1786  * The BIOCSETUP command "atomically" attach to the interface and
1787  * copy the buffer from another interface. This minimizes the risk
1788  * of missing packet because this is done while holding
1789  * the BPF global lock
1790  */
1791 static int
bpf_setup(struct bpf_d * d_to,uuid_t uuid_from,ifnet_t ifp)1792 bpf_setup(struct bpf_d *d_to, uuid_t uuid_from, ifnet_t ifp)
1793 {
1794 	struct bpf_d *d_from;
1795 	int error = 0;
1796 
1797 	LCK_MTX_ASSERT(bpf_mlock, LCK_MTX_ASSERT_OWNED);
1798 
1799 	/*
1800 	 * Sanity checks
1801 	 */
1802 	d_from = bpf_get_device_from_uuid(uuid_from);
1803 	if (d_from == NULL) {
1804 		error = ENOENT;
1805 		os_log_error(OS_LOG_DEFAULT,
1806 		    "%s: uuids not found error %d",
1807 		    __func__, error);
1808 		return error;
1809 	}
1810 	if (d_from->bd_opened_by != d_to->bd_opened_by) {
1811 		error = EACCES;
1812 		os_log_error(OS_LOG_DEFAULT,
1813 		    "%s: processes not matching error %d",
1814 		    __func__, error);
1815 		return error;
1816 	}
1817 
1818 	/*
1819 	 * Prevent any read or write while copying
1820 	 */
1821 	while (d_to->bd_hbuf_read || d_to->bd_hbuf_write) {
1822 		msleep((caddr_t)d_to, bpf_mlock, PRINET, __func__, NULL);
1823 	}
1824 	d_to->bd_hbuf_read = true;
1825 	d_to->bd_hbuf_write = true;
1826 
1827 	while (d_from->bd_hbuf_read || d_from->bd_hbuf_write) {
1828 		msleep((caddr_t)d_from, bpf_mlock, PRINET, __func__, NULL);
1829 	}
1830 	d_from->bd_hbuf_read = true;
1831 	d_from->bd_hbuf_write = true;
1832 
1833 	/*
1834 	 * Verify the devices have not been closed
1835 	 */
1836 	if (d_to->bd_flags & BPF_CLOSING) {
1837 		error = ENXIO;
1838 		os_log_error(OS_LOG_DEFAULT,
1839 		    "%s: d_to is closing error %d",
1840 		    __func__, error);
1841 		goto done;
1842 	}
1843 	if (d_from->bd_flags & BPF_CLOSING) {
1844 		error = ENXIO;
1845 		os_log_error(OS_LOG_DEFAULT,
1846 		    "%s: d_from is closing error %d",
1847 		    __func__, error);
1848 		goto done;
1849 	}
1850 
1851 	/*
1852 	 * For now require the same buffer size
1853 	 */
1854 	if (d_from->bd_bufsize != d_to->bd_bufsize) {
1855 		error = EINVAL;
1856 		os_log_error(OS_LOG_DEFAULT,
1857 		    "%s: bufsizes not matching error %d",
1858 		    __func__, error);
1859 		goto done;
1860 	}
1861 
1862 	/*
1863 	 * Copy relevant options and flags
1864 	 */
1865 	d_to->bd_flags = d_from->bd_flags & (BPF_EXTENDED_HDR | BPF_WANT_PKTAP |
1866 	    BPF_FINALIZE_PKTAP | BPF_TRUNCATE | BPF_PKTHDRV2 |
1867 	    BPF_COMP_REQ | BPF_COMP_ENABLED);
1868 
1869 	d_to->bd_headdrop = d_from->bd_headdrop;
1870 
1871 	/*
1872 	 * Allocate and copy the buffers
1873 	 */
1874 	error = bpf_allocbufs(d_to);
1875 	if (error != 0) {
1876 		goto done;
1877 	}
1878 
1879 	/*
1880 	 * Make sure the buffers are setup as expected by bpf_setif()
1881 	 */
1882 	ASSERT(d_to->bd_hbuf == NULL);
1883 	ASSERT(d_to->bd_sbuf != NULL);
1884 	ASSERT(d_to->bd_fbuf != NULL);
1885 
1886 	/*
1887 	 * Copy the buffers and update the pointers and counts
1888 	 */
1889 	memcpy(d_to->bd_sbuf, d_from->bd_sbuf, d_from->bd_slen);
1890 	d_to->bd_slen = d_from->bd_slen;
1891 	d_to->bd_scnt = d_from->bd_scnt;
1892 
1893 	if (d_from->bd_hbuf != NULL) {
1894 		d_to->bd_hbuf = d_to->bd_fbuf;
1895 		d_to->bd_fbuf = NULL;
1896 		memcpy(d_to->bd_hbuf, d_from->bd_hbuf, d_from->bd_hlen);
1897 	}
1898 	d_to->bd_hlen = d_from->bd_hlen;
1899 	d_to->bd_hcnt = d_from->bd_hcnt;
1900 
1901 	if (d_to->bd_flags & BPF_COMP_REQ) {
1902 		ASSERT(d_to->bd_prev_sbuf != NULL);
1903 		ASSERT(d_to->bd_prev_fbuf != NULL);
1904 
1905 		d_to->bd_prev_slen = d_from->bd_prev_slen;
1906 		ASSERT(d_to->bd_prev_slen <= BPF_HDR_COMP_LEN_MAX);
1907 		memcpy(d_to->bd_prev_sbuf, d_from->bd_prev_sbuf, BPF_HDR_COMP_LEN_MAX);
1908 	}
1909 
1910 	d_to->bd_bcs = d_from->bd_bcs;
1911 
1912 	/*
1913 	 * Attach to the interface:
1914 	 * - don't reset the buffers
1915 	 * - we already prevent reads and writes
1916 	 * - the buffers are already allocated
1917 	 */
1918 	error = bpf_setif(d_to, ifp, false, true, true);
1919 	if (error != 0) {
1920 		os_log_error(OS_LOG_DEFAULT,
1921 		    "%s: bpf_setif() failed error %d",
1922 		    __func__, error);
1923 		goto done;
1924 	}
1925 done:
1926 	d_from->bd_hbuf_read = false;
1927 	d_from->bd_hbuf_write = false;
1928 	wakeup((caddr_t)d_from);
1929 
1930 	d_to->bd_hbuf_read = false;
1931 	d_to->bd_hbuf_write = false;
1932 	wakeup((caddr_t)d_to);
1933 
1934 	return error;
1935 }
1936 
1937 #if DEVELOPMENT || DEBUG
1938 #define BPF_IOC_LIST \
1939 	X(FIONREAD) \
1940 	X(SIOCGIFADDR) \
1941 	X(BIOCGBLEN) \
1942 	X(BIOCSBLEN) \
1943 	X(BIOCSETF32) \
1944 	X(BIOCSETFNR32) \
1945 	X(BIOCSETF64) \
1946 	X(BIOCSETFNR64) \
1947 	X(BIOCFLUSH) \
1948 	X(BIOCPROMISC) \
1949 	X(BIOCGDLT) \
1950 	X(BIOCGDLTLIST) \
1951 	X(BIOCSDLT) \
1952 	X(BIOCGETIF) \
1953 	X(BIOCSETIF) \
1954 	X(BIOCSRTIMEOUT32) \
1955 	X(BIOCSRTIMEOUT64) \
1956 	X(BIOCGRTIMEOUT32) \
1957 	X(BIOCGRTIMEOUT64) \
1958 	X(BIOCGSTATS) \
1959 	X(BIOCIMMEDIATE) \
1960 	X(BIOCVERSION) \
1961 	X(BIOCGHDRCMPLT) \
1962 	X(BIOCSHDRCMPLT) \
1963 	X(BIOCGSEESENT) \
1964 	X(BIOCSSEESENT) \
1965 	X(BIOCSETTC) \
1966 	X(BIOCGETTC) \
1967 	X(FIONBIO) \
1968 	X(FIOASYNC) \
1969 	X(BIOCSRSIG) \
1970 	X(BIOCGRSIG) \
1971 	X(BIOCSEXTHDR) \
1972 	X(BIOCGIFATTACHCOUNT) \
1973 	X(BIOCGWANTPKTAP) \
1974 	X(BIOCSWANTPKTAP) \
1975 	X(BIOCSHEADDROP) \
1976 	X(BIOCGHEADDROP) \
1977 	X(BIOCSTRUNCATE) \
1978 	X(BIOCGETUUID) \
1979 	X(BIOCSETUP) \
1980 	X(BIOCSPKTHDRV2) \
1981 	X(BIOCGHDRCOMP) \
1982 	X(BIOCSHDRCOMP) \
1983 	X(BIOCGHDRCOMPSTATS) \
1984 	X(BIOCGHDRCOMPON) \
1985 	X(BIOCGDIRECTION) \
1986 	X(BIOCSDIRECTION) \
1987 	X(BIOCSWRITEMAX) \
1988 	X(BIOCGWRITEMAX) \
1989 	X(BIOCGBATCHWRITE) \
1990 	X(BIOCSBATCHWRITE) \
1991 	X(BIOCGNOTSTAMP) \
1992 	X(BIOCSNOTSTAMP)
1993 
1994 static void
log_bpf_ioctl_str(struct bpf_d * d,u_long cmd)1995 log_bpf_ioctl_str(struct bpf_d *d, u_long cmd)
1996 {
1997 	const char *p = NULL;
1998 	char str[32];
1999 
2000 #define X(x) case x: { p = #x ; printf("%s\n", p); break; }
2001 	switch (cmd) {
2002 		BPF_IOC_LIST
2003 	}
2004 #undef X
2005 	if (p == NULL) {
2006 		snprintf(str, sizeof(str), "0x%08x", (unsigned int)cmd);
2007 		p = str;
2008 	}
2009 	os_log(OS_LOG_DEFAULT, "bpfioctl bpf%u %s",
2010 	    d->bd_dev_minor, p);
2011 }
2012 #endif /* DEVELOPMENT || DEBUG */
2013 
2014 /*
2015  *  FIONREAD		Check for read packet available.
2016  *  SIOCGIFADDR		Get interface address - convenient hook to driver.
2017  *  BIOCGBLEN		Get buffer len [for read()].
2018  *  BIOCSETF		Set ethernet read filter.
2019  *  BIOCFLUSH		Flush read packet buffer.
2020  *  BIOCPROMISC		Put interface into promiscuous mode.
2021  *  BIOCGDLT		Get link layer type.
2022  *  BIOCGETIF		Get interface name.
2023  *  BIOCSETIF		Set interface.
2024  *  BIOCSRTIMEOUT	Set read timeout.
2025  *  BIOCGRTIMEOUT	Get read timeout.
2026  *  BIOCGSTATS		Get packet stats.
2027  *  BIOCIMMEDIATE	Set immediate mode.
2028  *  BIOCVERSION		Get filter language version.
2029  *  BIOCGHDRCMPLT	Get "header already complete" flag
2030  *  BIOCSHDRCMPLT	Set "header already complete" flag
2031  *  BIOCGSEESENT	Get "see packets sent" flag
2032  *  BIOCSSEESENT	Set "see packets sent" flag
2033  *  BIOCSETTC		Set traffic class.
2034  *  BIOCGETTC		Get traffic class.
2035  *  BIOCSEXTHDR		Set "extended header" flag
2036  *  BIOCSHEADDROP	Drop head of the buffer if user is not reading
2037  *  BIOCGHEADDROP	Get "head-drop" flag
2038  */
2039 /* ARGSUSED */
2040 int
bpfioctl(dev_t dev,u_long cmd,caddr_t __sized_by (IOCPARM_LEN (cmd))addr,__unused int flags,struct proc * p)2041 bpfioctl(dev_t dev, u_long cmd, caddr_t __sized_by(IOCPARM_LEN(cmd)) addr,
2042     __unused int flags, struct proc *p)
2043 {
2044 	struct bpf_d *d;
2045 	int error = 0;
2046 	u_int int_arg;
2047 	struct ifreq ifr = {};
2048 
2049 	lck_mtx_lock(bpf_mlock);
2050 	d = bpf_dtab[minor(dev)];
2051 	if (d == NULL || d == BPF_DEV_RESERVED ||
2052 	    (d->bd_flags & BPF_CLOSING) != 0) {
2053 		lck_mtx_unlock(bpf_mlock);
2054 		return ENXIO;
2055 	}
2056 
2057 	bpf_acquire_d(d);
2058 
2059 	if (d->bd_state == BPF_WAITING) {
2060 		bpf_stop_timer(d);
2061 	}
2062 	d->bd_state = BPF_IDLE;
2063 
2064 #if DEVELOPMENT || DEBUG
2065 	if (bpf_debug > 0) {
2066 		log_bpf_ioctl_str(d, cmd);
2067 	}
2068 #endif /* DEVELOPMENT || DEBUG */
2069 
2070 	switch (cmd) {
2071 	default:
2072 		error = EINVAL;
2073 		break;
2074 
2075 	/*
2076 	 * Check for read packet available.
2077 	 */
2078 	case FIONREAD: {                 /* int */
2079 		int n;
2080 
2081 		n = d->bd_slen;
2082 		if (d->bd_hbuf && d->bd_hbuf_read) {
2083 			n += d->bd_hlen;
2084 		}
2085 
2086 		bcopy(&n, addr, sizeof(n));
2087 		break;
2088 	}
2089 
2090 	case SIOCGIFADDR: {              /* struct ifreq */
2091 		struct ifnet *ifp;
2092 
2093 		if (d->bd_bif == 0) {
2094 			error = EINVAL;
2095 		} else {
2096 			ifp = d->bd_bif->bif_ifp;
2097 			error = ifnet_ioctl(ifp, 0, cmd, addr);
2098 		}
2099 		break;
2100 	}
2101 
2102 	/*
2103 	 * Get buffer len [for read()].
2104 	 */
2105 	case BIOCGBLEN: {                /* u_int */
2106 		_CASSERT(sizeof(d->bd_bufsize) == sizeof(u_int));
2107 		bcopy(&d->bd_bufsize, addr, sizeof(u_int));
2108 		break;
2109 	}
2110 
2111 	/*
2112 	 * Set buffer length.
2113 	 */
2114 	case BIOCSBLEN: {               /* u_int */
2115 		u_int size;
2116 
2117 		if (d->bd_bif != 0 || (d->bd_flags & BPF_DETACHING)) {
2118 			/*
2119 			 * Interface already attached, unable to change buffers
2120 			 */
2121 			error = EINVAL;
2122 			break;
2123 		}
2124 		bcopy(addr, &size, sizeof(size));
2125 
2126 		if (size > BPF_BUFSIZE_CAP) {
2127 			d->bd_bufsize = BPF_BUFSIZE_CAP;
2128 
2129 			os_log_info(OS_LOG_DEFAULT,
2130 			    "bpf%d BIOCSBLEN capped to %u from %u",
2131 			    minor(dev), d->bd_bufsize, size);
2132 		} else if (size < BPF_MINBUFSIZE) {
2133 			d->bd_bufsize = BPF_MINBUFSIZE;
2134 
2135 			os_log_info(OS_LOG_DEFAULT,
2136 			    "bpf%d BIOCSBLEN bumped to %u from %u",
2137 			    minor(dev), d->bd_bufsize, size);
2138 		} else {
2139 			d->bd_bufsize = size;
2140 
2141 			os_log_info(OS_LOG_DEFAULT,
2142 			    "bpf%d BIOCSBLEN %u",
2143 			    minor(dev), d->bd_bufsize);
2144 		}
2145 
2146 		/* It's a read/write ioctl */
2147 		bcopy(&d->bd_bufsize, addr, sizeof(u_int));
2148 		break;
2149 	}
2150 	/*
2151 	 * Set link layer read filter.
2152 	 */
2153 	case BIOCSETF32:
2154 	case BIOCSETFNR32: {            /* struct bpf_program32 */
2155 		struct bpf_program32 prg32;
2156 
2157 		bcopy(addr, &prg32, sizeof(prg32));
2158 		error = bpf_setf(d, prg32.bf_len,
2159 		    CAST_USER_ADDR_T(prg32.bf_insns), cmd);
2160 		break;
2161 	}
2162 
2163 	case BIOCSETF64:
2164 	case BIOCSETFNR64: {            /* struct bpf_program64 */
2165 		struct bpf_program64 prg64;
2166 
2167 		bcopy(addr, &prg64, sizeof(prg64));
2168 		error = bpf_setf(d, prg64.bf_len, CAST_USER_ADDR_T(prg64.bf_insns), cmd);
2169 		break;
2170 	}
2171 
2172 	/*
2173 	 * Flush read packet buffer.
2174 	 */
2175 	case BIOCFLUSH:
2176 		while (d->bd_hbuf_read) {
2177 			msleep((caddr_t)d, bpf_mlock, PRINET, "BIOCFLUSH",
2178 			    NULL);
2179 		}
2180 		if ((d->bd_flags & BPF_CLOSING) != 0) {
2181 			error = ENXIO;
2182 			break;
2183 		}
2184 		reset_d(d);
2185 		break;
2186 
2187 	/*
2188 	 * Put interface into promiscuous mode.
2189 	 */
2190 	case BIOCPROMISC:
2191 		if (d->bd_bif == 0) {
2192 			/*
2193 			 * No interface attached yet.
2194 			 */
2195 			error = EINVAL;
2196 			break;
2197 		}
2198 		if (d->bd_promisc == 0) {
2199 			lck_mtx_unlock(bpf_mlock);
2200 			error = ifnet_set_promiscuous(d->bd_bif->bif_ifp, 1);
2201 			lck_mtx_lock(bpf_mlock);
2202 			if (error == 0) {
2203 				d->bd_promisc = 1;
2204 			}
2205 		}
2206 		break;
2207 
2208 	/*
2209 	 * Get device parameters.
2210 	 */
2211 	case BIOCGDLT: {                 /* u_int */
2212 		if (d->bd_bif == 0) {
2213 			error = EINVAL;
2214 		} else {
2215 			_CASSERT(sizeof(d->bd_bif->bif_dlt) == sizeof(u_int));
2216 			bcopy(&d->bd_bif->bif_dlt, addr, sizeof(u_int));
2217 		}
2218 		break;
2219 	}
2220 
2221 	/*
2222 	 * Get a list of supported data link types.
2223 	 */
2224 	case BIOCGDLTLIST:              /* struct bpf_dltlist */
2225 		if (d->bd_bif == NULL) {
2226 			error = EINVAL;
2227 		} else {
2228 			error = bpf_getdltlist(d, addr, p);
2229 		}
2230 		break;
2231 
2232 	/*
2233 	 * Set data link type.
2234 	 */
2235 	case BIOCSDLT:                  /* u_int */
2236 		if (d->bd_bif == NULL) {
2237 			error = EINVAL;
2238 		} else {
2239 			u_int dlt;
2240 
2241 			bcopy(addr, &dlt, sizeof(dlt));
2242 
2243 			if (dlt == DLT_PKTAP &&
2244 			    !(d->bd_flags & BPF_WANT_PKTAP)) {
2245 				dlt = DLT_RAW;
2246 			}
2247 			error = bpf_setdlt(d, dlt);
2248 		}
2249 		break;
2250 
2251 	/*
2252 	 * Get interface name.
2253 	 */
2254 	case BIOCGETIF:                 /* struct ifreq */
2255 		if (d->bd_bif == 0) {
2256 			error = EINVAL;
2257 		} else {
2258 			struct ifnet *const ifp = d->bd_bif->bif_ifp;
2259 
2260 			snprintf(((struct ifreq *)(void *)addr)->ifr_name,
2261 			    sizeof(ifr.ifr_name), "%s", if_name(ifp));
2262 		}
2263 		break;
2264 
2265 	/*
2266 	 * Set interface.
2267 	 */
2268 	case BIOCSETIF: {               /* struct ifreq */
2269 		ifnet_t ifp;
2270 
2271 		bcopy(addr, &ifr, sizeof(ifr));
2272 		ifr.ifr_name[IFNAMSIZ - 1] = '\0';
2273 		ifp = ifunit(__unsafe_null_terminated_from_indexable(ifr.ifr_name,
2274 		    &ifr.ifr_name[IFNAMSIZ - 1]));
2275 		if (ifp == NULL) {
2276 			error = ENXIO;
2277 		} else {
2278 			error = bpf_setif(d, ifp, true, false, false);
2279 		}
2280 		break;
2281 	}
2282 
2283 	/*
2284 	 * Set read timeout.
2285 	 */
2286 	case BIOCSRTIMEOUT32: {         /* struct user32_timeval */
2287 		struct user32_timeval _tv;
2288 		struct timeval tv;
2289 
2290 		bcopy(addr, &_tv, sizeof(_tv));
2291 		tv.tv_sec  = _tv.tv_sec;
2292 		tv.tv_usec = _tv.tv_usec;
2293 
2294 		/*
2295 		 * Subtract 1 tick from tvtohz() since this isn't
2296 		 * a one-shot timer.
2297 		 */
2298 		if ((error = itimerfix(&tv)) == 0) {
2299 			d->bd_rtout = tvtohz(&tv) - 1;
2300 		}
2301 		break;
2302 	}
2303 
2304 	case BIOCSRTIMEOUT64: {         /* struct user64_timeval */
2305 		struct user64_timeval _tv;
2306 		struct timeval tv;
2307 
2308 		bcopy(addr, &_tv, sizeof(_tv));
2309 		tv.tv_sec  = (__darwin_time_t)_tv.tv_sec;
2310 		tv.tv_usec = _tv.tv_usec;
2311 
2312 		/*
2313 		 * Subtract 1 tick from tvtohz() since this isn't
2314 		 * a one-shot timer.
2315 		 */
2316 		if ((error = itimerfix(&tv)) == 0) {
2317 			d->bd_rtout = tvtohz(&tv) - 1;
2318 		}
2319 		break;
2320 	}
2321 
2322 	/*
2323 	 * Get read timeout.
2324 	 */
2325 	case BIOCGRTIMEOUT32: {         /* struct user32_timeval */
2326 		struct user32_timeval tv;
2327 
2328 		bzero(&tv, sizeof(tv));
2329 		tv.tv_sec = d->bd_rtout / hz;
2330 		tv.tv_usec = (d->bd_rtout % hz) * tick;
2331 		bcopy(&tv, addr, sizeof(tv));
2332 		break;
2333 	}
2334 
2335 	case BIOCGRTIMEOUT64: {         /* struct user64_timeval */
2336 		struct user64_timeval tv;
2337 
2338 		bzero(&tv, sizeof(tv));
2339 		tv.tv_sec = d->bd_rtout / hz;
2340 		tv.tv_usec = (d->bd_rtout % hz) * tick;
2341 		bcopy(&tv, addr, sizeof(tv));
2342 		break;
2343 	}
2344 
2345 	/*
2346 	 * Get packet stats.
2347 	 */
2348 	case BIOCGSTATS: {              /* struct bpf_stat */
2349 		struct bpf_stat bs;
2350 
2351 		bzero(&bs, sizeof(bs));
2352 		bs.bs_recv = (u_int)d->bd_rcount;
2353 		bs.bs_drop = (u_int)d->bd_dcount;
2354 		bcopy(&bs, addr, sizeof(bs));
2355 		break;
2356 	}
2357 
2358 	/*
2359 	 * Set immediate mode.
2360 	 */
2361 	case BIOCIMMEDIATE:             /* u_int */
2362 		d->bd_immediate = *(u_char *)(void *)addr;
2363 		break;
2364 
2365 	case BIOCVERSION: {             /* struct bpf_version */
2366 		struct bpf_version bv;
2367 
2368 		bzero(&bv, sizeof(bv));
2369 		bv.bv_major = BPF_MAJOR_VERSION;
2370 		bv.bv_minor = BPF_MINOR_VERSION;
2371 		bcopy(&bv, addr, sizeof(bv));
2372 		break;
2373 	}
2374 
2375 	/*
2376 	 * Get "header already complete" flag
2377 	 */
2378 	case BIOCGHDRCMPLT: {            /* u_int */
2379 		u_int *addr_int = (u_int *)(void *)addr;
2380 		*addr_int = d->bd_hdrcmplt;
2381 		break;
2382 	}
2383 
2384 	/*
2385 	 * Set "header already complete" flag
2386 	 */
2387 	case BIOCSHDRCMPLT:             /* u_int */
2388 		bcopy(addr, &int_arg, sizeof(int_arg));
2389 		if (int_arg == 0 && (d->bd_flags & BPF_BATCH_WRITE)) {
2390 			os_log(OS_LOG_DEFAULT,
2391 			    "bpf%u cannot set BIOCSHDRCMPLT when BIOCSBATCHWRITE is set",
2392 			    d->bd_dev_minor);
2393 			error = EINVAL;
2394 			break;
2395 		}
2396 		d->bd_hdrcmplt = int_arg ? 1 : 0;
2397 		break;
2398 
2399 	/*
2400 	 * Get "see sent packets" flag
2401 	 */
2402 	case BIOCGSEESENT: {            /* u_int */
2403 		int_arg = 0;
2404 
2405 		if (d->bd_direction & BPF_D_OUT) {
2406 			int_arg = 1;
2407 		}
2408 		bcopy(&int_arg, addr, sizeof(u_int));
2409 		break;
2410 	}
2411 	/*
2412 	 * Set "see sent packets" flag
2413 	 */
2414 	case BIOCSSEESENT: {            /* u_int */
2415 		bcopy(addr, &int_arg, sizeof(u_int));
2416 
2417 		if (int_arg == 0) {
2418 			d->bd_direction = BPF_D_IN;
2419 		} else {
2420 			d->bd_direction = BPF_D_INOUT;
2421 		}
2422 		break;
2423 	}
2424 	/*
2425 	 * Get direction of tapped packets that can be seen for reading
2426 	 */
2427 	case BIOCGDIRECTION: {          /* u_int */
2428 		int_arg = d->bd_direction;
2429 
2430 		bcopy(&int_arg, addr, sizeof(u_int));
2431 		break;
2432 	}
2433 	/*
2434 	 * Set direction of tapped packets that can be seen for reading
2435 	 */
2436 	case BIOCSDIRECTION: {          /* u_int */
2437 		bcopy(addr, &int_arg, sizeof(u_int));
2438 
2439 		switch (int_arg) {
2440 		case BPF_D_NONE:
2441 		case BPF_D_IN:
2442 		case BPF_D_OUT:
2443 		case BPF_D_INOUT:
2444 			d->bd_direction = int_arg;
2445 			break;
2446 		default:
2447 			error = EINVAL;
2448 			break;
2449 		}
2450 		break;
2451 	}
2452 	/*
2453 	 * Set traffic service class
2454 	 */
2455 	case BIOCSETTC: {               /* int */
2456 		int tc;
2457 
2458 		bcopy(addr, &tc, sizeof(int));
2459 		if (tc != 0 && (d->bd_flags & BPF_BATCH_WRITE)) {
2460 			os_log(OS_LOG_DEFAULT,
2461 			    "bpf%u cannot set BIOCSETTC when BIOCSBATCHWRITE is set",
2462 			    d->bd_dev_minor);
2463 			error = EINVAL;
2464 			break;
2465 		}
2466 		error = bpf_set_traffic_class(d, tc);
2467 		break;
2468 	}
2469 
2470 	/*
2471 	 * Get traffic service class
2472 	 */
2473 	case BIOCGETTC: {                /* int */
2474 		_CASSERT(sizeof(d->bd_traffic_class) == sizeof(int));
2475 		bcopy(&d->bd_traffic_class, addr, sizeof(int));
2476 		break;
2477 	}
2478 
2479 	case FIONBIO:           /* Non-blocking I/O; int */
2480 		break;
2481 
2482 	case FIOASYNC: {        /* Send signal on receive packets; int */
2483 		_CASSERT(sizeof(d->bd_async) == sizeof(int));
2484 		bcopy(addr, &d->bd_async, sizeof(int));
2485 		break;
2486 	}
2487 
2488 	case BIOCSRSIG: {         /* Set receive signal; u_int */
2489 		u_int sig;
2490 
2491 		bcopy(addr, &sig, sizeof(u_int));
2492 
2493 		if (sig >= NSIG) {
2494 			error = EINVAL;
2495 		} else {
2496 			d->bd_sig = sig;
2497 		}
2498 		break;
2499 	}
2500 	case BIOCGRSIG: {                /* u_int */
2501 		_CASSERT(sizeof(d->bd_sig) == sizeof(u_int));
2502 		bcopy(&d->bd_sig, addr, sizeof(u_int));
2503 		break;
2504 	}
2505 
2506 	case BIOCSEXTHDR:               /* u_int */
2507 		bcopy(addr, &int_arg, sizeof(int_arg));
2508 		if (int_arg) {
2509 			d->bd_flags |= BPF_EXTENDED_HDR;
2510 		} else {
2511 			d->bd_flags &= ~BPF_EXTENDED_HDR;
2512 		}
2513 		break;
2514 
2515 	case BIOCGIFATTACHCOUNT: {              /* struct ifreq */
2516 		ifnet_t ifp;
2517 		struct bpf_if *bp;
2518 
2519 		bcopy(addr, &ifr, sizeof(ifr));
2520 		ifr.ifr_name[IFNAMSIZ - 1] = '\0';
2521 		ifp = ifunit(__unsafe_null_terminated_from_indexable(ifr.ifr_name,
2522 		    &ifr.ifr_name[IFNAMSIZ - 1]));
2523 		if (ifp == NULL) {
2524 			error = ENXIO;
2525 			break;
2526 		}
2527 		ifr.ifr_intval = 0;
2528 		for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
2529 			struct bpf_d *bpf_d;
2530 
2531 			if (bp->bif_ifp == NULL || bp->bif_ifp != ifp) {
2532 				continue;
2533 			}
2534 			for (bpf_d = bp->bif_dlist; bpf_d;
2535 			    bpf_d = bpf_d->bd_next) {
2536 				ifr.ifr_intval += 1;
2537 			}
2538 		}
2539 		bcopy(&ifr, addr, sizeof(ifr));
2540 		break;
2541 	}
2542 	case BIOCGWANTPKTAP:                    /* u_int */
2543 		int_arg = d->bd_flags & BPF_WANT_PKTAP ? 1 : 0;
2544 		bcopy(&int_arg, addr, sizeof(int_arg));
2545 		break;
2546 
2547 	case BIOCSWANTPKTAP:                    /* u_int */
2548 		bcopy(addr, &int_arg, sizeof(int_arg));
2549 		if (int_arg) {
2550 			d->bd_flags |= BPF_WANT_PKTAP;
2551 		} else {
2552 			d->bd_flags &= ~BPF_WANT_PKTAP;
2553 		}
2554 		break;
2555 
2556 	case BIOCSHEADDROP:
2557 		bcopy(addr, &int_arg, sizeof(int_arg));
2558 		d->bd_headdrop = int_arg ? 1 : 0;
2559 		break;
2560 
2561 	case BIOCGHEADDROP: {
2562 		u_int *addr_int = (uint *)(void *)addr;
2563 		*addr_int = d->bd_headdrop;
2564 		break;
2565 	}
2566 
2567 	case BIOCSTRUNCATE:
2568 		bcopy(addr, &int_arg, sizeof(int_arg));
2569 		if (int_arg) {
2570 			d->bd_flags |=  BPF_TRUNCATE;
2571 		} else {
2572 			d->bd_flags &= ~BPF_TRUNCATE;
2573 		}
2574 		break;
2575 
2576 	case BIOCGETUUID: /* uuid_t */
2577 		bcopy(&d->bd_uuid, addr, sizeof(uuid_t));
2578 		break;
2579 
2580 	case BIOCSETUP: {
2581 		struct bpf_setup_args bsa;
2582 		ifnet_t ifp;
2583 
2584 		bcopy(addr, &bsa, sizeof(struct bpf_setup_args));
2585 		bsa.bsa_ifname[IFNAMSIZ - 1] = 0;
2586 		ifp = ifunit(__unsafe_null_terminated_from_indexable(bsa.bsa_ifname,
2587 		    &bsa.bsa_ifname[IFNAMSIZ - 1]));
2588 		if (ifp == NULL) {
2589 			error = ENXIO;
2590 			os_log_error(OS_LOG_DEFAULT,
2591 			    "%s: ifnet not found for %s error %d",
2592 			    __func__, bsa.bsa_ifname, error);
2593 			break;
2594 		}
2595 
2596 		error = bpf_setup(d, bsa.bsa_uuid, ifp);
2597 		break;
2598 	}
2599 	case BIOCSPKTHDRV2:
2600 		bcopy(addr, &int_arg, sizeof(int_arg));
2601 		if (int_arg != 0) {
2602 			d->bd_flags |= BPF_PKTHDRV2;
2603 		} else {
2604 			d->bd_flags &= ~BPF_PKTHDRV2;
2605 		}
2606 		break;
2607 
2608 	case BIOCGPKTHDRV2:
2609 		int_arg = d->bd_flags & BPF_PKTHDRV2 ? 1 : 0;
2610 		bcopy(&int_arg, addr, sizeof(int_arg));
2611 		break;
2612 
2613 	case BIOCGHDRCOMP:
2614 		int_arg = d->bd_flags & BPF_COMP_REQ ? 1 : 0;
2615 		bcopy(&int_arg, addr, sizeof(int_arg));
2616 		break;
2617 
2618 	case BIOCSHDRCOMP:
2619 		bcopy(addr, &int_arg, sizeof(int_arg));
2620 		if (int_arg != 0 && int_arg != 1) {
2621 			return EINVAL;
2622 		}
2623 		if (d->bd_bif != 0 || (d->bd_flags & BPF_DETACHING)) {
2624 			/*
2625 			 * Interface already attached, unable to change buffers
2626 			 */
2627 			error = EINVAL;
2628 			break;
2629 		}
2630 		if (int_arg != 0) {
2631 			d->bd_flags |= BPF_COMP_REQ;
2632 			if (bpf_hdr_comp_enable != 0) {
2633 				d->bd_flags |= BPF_COMP_ENABLED;
2634 			}
2635 		} else {
2636 			d->bd_flags &= ~(BPF_COMP_REQ | BPF_COMP_ENABLED);
2637 		}
2638 		break;
2639 
2640 	case BIOCGHDRCOMPON:
2641 		int_arg = d->bd_flags & BPF_COMP_ENABLED ? 1 : 0;
2642 		bcopy(&int_arg, addr, sizeof(int_arg));
2643 		break;
2644 
2645 	case BIOCGHDRCOMPSTATS: {
2646 		struct bpf_comp_stats bcs = {};
2647 
2648 		bcs = d->bd_bcs;
2649 
2650 		bcopy(&bcs, addr, sizeof(bcs));
2651 		break;
2652 	}
2653 	case BIOCSWRITEMAX:
2654 		bcopy(addr, &int_arg, sizeof(int_arg));
2655 		if (int_arg > BPF_WRITE_MAX) {
2656 			os_log(OS_LOG_DEFAULT, "bpf%u bd_write_size_max %u too big",
2657 			    d->bd_dev_minor, d->bd_write_size_max);
2658 			error = EINVAL;
2659 			break;
2660 		}
2661 		d->bd_write_size_max = int_arg;
2662 		break;
2663 
2664 	case BIOCGWRITEMAX:
2665 		int_arg = d->bd_write_size_max;
2666 		bcopy(&int_arg, addr, sizeof(int_arg));
2667 		break;
2668 
2669 	case BIOCGBATCHWRITE:                    /* int */
2670 		int_arg = d->bd_flags & BPF_BATCH_WRITE ? 1 : 0;
2671 		bcopy(&int_arg, addr, sizeof(int_arg));
2672 		break;
2673 
2674 	case BIOCSBATCHWRITE:                    /* int */
2675 		bcopy(addr, &int_arg, sizeof(int_arg));
2676 		if (int_arg != 0) {
2677 			if (d->bd_hdrcmplt == 0) {
2678 				os_log(OS_LOG_DEFAULT,
2679 				    "bpf%u cannot set BIOCSBATCHWRITE when BIOCSHDRCMPLT is not set",
2680 				    d->bd_dev_minor);
2681 				error = EINVAL;
2682 				break;
2683 			}
2684 			if (d->bd_traffic_class != 0) {
2685 				os_log(OS_LOG_DEFAULT,
2686 				    "bpf%u cannot set BIOCSBATCHWRITE when BIOCSETTC is set",
2687 				    d->bd_dev_minor);
2688 				error = EINVAL;
2689 				break;
2690 			}
2691 			d->bd_flags |= BPF_BATCH_WRITE;
2692 		} else {
2693 			d->bd_flags &= ~BPF_BATCH_WRITE;
2694 		}
2695 		break;
2696 	case BIOCGNOTSTAMP:
2697 		if (d->bd_tstamp == BPF_T_NONE) {
2698 			int_arg = 1;
2699 		} else {
2700 			int_arg = 0;
2701 		}
2702 		bcopy(&int_arg, addr, sizeof(int_arg));
2703 		break;
2704 	case BIOCSNOTSTAMP:
2705 		bcopy(addr, &int_arg, sizeof(int_arg));
2706 		switch (int_arg) {
2707 		case 0:
2708 			d->bd_tstamp  = BPF_T_MICROTIME;
2709 			break;
2710 		default:
2711 			d->bd_tstamp = BPF_T_NONE;
2712 			break;
2713 		}
2714 		break;
2715 	case BIOCGDVRTIN:
2716 		int_arg = d->bd_flags & BPF_DIVERT_IN ? 1 : 0;
2717 		bcopy(&int_arg, addr, sizeof(int_arg));
2718 		break;
2719 	case BIOCSDVRTIN:
2720 		if (d->bd_bif == NULL) {
2721 			/*
2722 			 * No interface attached yet.
2723 			 */
2724 			error = ENXIO;
2725 			break;
2726 		}
2727 		bcopy(addr, &int_arg, sizeof(int_arg));
2728 		if (int_arg == 0) {
2729 			if ((d->bd_flags & BPF_DIVERT_IN) == 0) {
2730 				error = EINVAL;
2731 				break;
2732 			}
2733 			d->bd_flags &= ~BPF_DIVERT_IN;
2734 			if_clear_xflags(d->bd_bif->bif_ifp, IFXF_DISABLE_INPUT);
2735 		} else {
2736 			if ((d->bd_flags & BPF_DIVERT_IN) != 0 ||
2737 			    (d->bd_bif->bif_ifp->if_xflags & IFXF_DISABLE_INPUT) != 0) {
2738 				error = EALREADY;
2739 				break;
2740 			}
2741 			d->bd_flags |= BPF_DIVERT_IN;
2742 			if_set_xflags(d->bd_bif->bif_ifp, IFXF_DISABLE_INPUT);
2743 		}
2744 		break;
2745 	}
2746 
2747 	bpf_release_d(d);
2748 	lck_mtx_unlock(bpf_mlock);
2749 
2750 	return error;
2751 }
2752 
2753 /*
2754  * Set d's packet filter program to fp.  If this file already has a filter,
2755  * free it and replace it.  Returns EINVAL for bogus requests.
2756  */
2757 static int
bpf_setf(struct bpf_d * d,u_int bf_len,user_addr_t bf_insns,u_long cmd)2758 bpf_setf(struct bpf_d *d, u_int bf_len, user_addr_t bf_insns,
2759     u_long cmd)
2760 {
2761 	struct bpf_insn *fcode, *old;
2762 	u_int flen, size;
2763 
2764 	while (d->bd_hbuf_read) {
2765 		msleep((caddr_t)d, bpf_mlock, PRINET, "bpf_setf", NULL);
2766 	}
2767 
2768 	if ((d->bd_flags & BPF_CLOSING) != 0) {
2769 		return ENXIO;
2770 	}
2771 
2772 	old = d->bd_filter;
2773 	if (bf_insns == USER_ADDR_NULL) {
2774 		if (bf_len != 0) {
2775 			return EINVAL;
2776 		}
2777 		d->bd_filter = NULL;
2778 		d->bd_filter_len = 0;
2779 		reset_d(d);
2780 		if (old != 0) {
2781 			kfree_data_addr(old);
2782 		}
2783 		return 0;
2784 	}
2785 	flen = bf_len;
2786 	if (flen > BPF_MAXINSNS) {
2787 		return EINVAL;
2788 	}
2789 
2790 	size = flen * sizeof(struct bpf_insn);
2791 	fcode = (struct bpf_insn *) kalloc_data(size, Z_WAITOK | Z_ZERO);
2792 	if (fcode == NULL) {
2793 		return ENOMEM;
2794 	}
2795 	if (copyin(bf_insns, (caddr_t)fcode, size) == 0 &&
2796 	    bpf_validate(fcode, (int)flen)) {
2797 		d->bd_filter = fcode;
2798 		d->bd_filter_len = flen;
2799 
2800 		if (cmd == BIOCSETF32 || cmd == BIOCSETF64) {
2801 			reset_d(d);
2802 		}
2803 
2804 		if (old != 0) {
2805 			kfree_data_addr(old);
2806 		}
2807 
2808 		return 0;
2809 	}
2810 	kfree_data(fcode, size);
2811 	return EINVAL;
2812 }
2813 
2814 /*
2815  * Detach a file from its current interface (if attached at all) and attach
2816  * to the interface indicated by the name stored in ifr.
2817  * Return an errno or 0.
2818  */
2819 static int
bpf_setif(struct bpf_d * d,ifnet_t theywant,bool do_reset,bool has_hbuf_read_write,bool has_bufs_allocated)2820 bpf_setif(struct bpf_d *d, ifnet_t theywant, bool do_reset, bool has_hbuf_read_write,
2821     bool has_bufs_allocated)
2822 {
2823 	struct bpf_if *bp;
2824 	int error;
2825 
2826 	while (!has_hbuf_read_write && (d->bd_hbuf_read || d->bd_hbuf_write)) {
2827 		msleep((caddr_t)d, bpf_mlock, PRINET, "bpf_setif", NULL);
2828 	}
2829 
2830 	if ((d->bd_flags & BPF_CLOSING) != 0) {
2831 		return ENXIO;
2832 	}
2833 
2834 	/*
2835 	 * Look through attached interfaces for the named one.
2836 	 */
2837 	for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
2838 		struct ifnet *ifp = bp->bif_ifp;
2839 
2840 		if (ifp == 0 || ifp != theywant) {
2841 			continue;
2842 		}
2843 		/*
2844 		 * Do not use DLT_PKTAP, unless requested explicitly
2845 		 */
2846 		if (bp->bif_dlt == DLT_PKTAP && !(d->bd_flags & BPF_WANT_PKTAP)) {
2847 			continue;
2848 		}
2849 		/*
2850 		 * Skip the coprocessor interface
2851 		 */
2852 		if (!intcoproc_unrestricted && IFNET_IS_INTCOPROC(ifp)) {
2853 			continue;
2854 		}
2855 		/*
2856 		 * We found the requested interface.
2857 		 * Allocate the packet buffers.
2858 		 */
2859 		if (has_bufs_allocated == false) {
2860 			error = bpf_allocbufs(d);
2861 			if (error != 0) {
2862 				return error;
2863 			}
2864 		}
2865 		/*
2866 		 * Detach if attached to something else.
2867 		 */
2868 		if (bp != d->bd_bif) {
2869 			if (d->bd_bif != NULL) {
2870 				if (bpf_detachd(d) != 0) {
2871 					return ENXIO;
2872 				}
2873 			}
2874 			if (bpf_attachd(d, bp) != 0) {
2875 				return ENXIO;
2876 			}
2877 		}
2878 		if (do_reset) {
2879 			reset_d(d);
2880 		}
2881 		os_log(OS_LOG_DEFAULT, "bpf%u attached to %s",
2882 		    d->bd_dev_minor, if_name(theywant));
2883 		return 0;
2884 	}
2885 	/* Not found. */
2886 	return ENXIO;
2887 }
2888 
2889 /*
2890  * Get a list of available data link type of the interface.
2891  */
2892 static int
bpf_getdltlist(struct bpf_d * d,caddr_t __bidi_indexable addr,struct proc * p)2893 bpf_getdltlist(struct bpf_d *d, caddr_t __bidi_indexable addr, struct proc *p)
2894 {
2895 	u_int           n;
2896 	int             error;
2897 	struct ifnet    *ifp;
2898 	struct bpf_if   *bp;
2899 	user_addr_t     dlist;
2900 	struct bpf_dltlist bfl;
2901 
2902 	bcopy(addr, &bfl, sizeof(bfl));
2903 	if (proc_is64bit(p)) {
2904 		dlist = (user_addr_t)bfl.bfl_u.bflu_pad;
2905 	} else {
2906 		dlist = CAST_USER_ADDR_T(bfl.bfl_u.bflu_list);
2907 	}
2908 
2909 	ifp = d->bd_bif->bif_ifp;
2910 	n = 0;
2911 	error = 0;
2912 
2913 	for (bp = bpf_iflist; bp; bp = bp->bif_next) {
2914 		if (bp->bif_ifp != ifp) {
2915 			continue;
2916 		}
2917 		/*
2918 		 * Do not use DLT_PKTAP, unless requested explicitly
2919 		 */
2920 		if (bp->bif_dlt == DLT_PKTAP && !(d->bd_flags & BPF_WANT_PKTAP)) {
2921 			continue;
2922 		}
2923 		if (dlist != USER_ADDR_NULL) {
2924 			if (n >= bfl.bfl_len) {
2925 				return ENOMEM;
2926 			}
2927 			error = copyout(&bp->bif_dlt, dlist,
2928 			    sizeof(bp->bif_dlt));
2929 			if (error != 0) {
2930 				break;
2931 			}
2932 			dlist += sizeof(bp->bif_dlt);
2933 		}
2934 		n++;
2935 	}
2936 	bfl.bfl_len = n;
2937 	bcopy(&bfl, addr, sizeof(bfl));
2938 
2939 	return error;
2940 }
2941 
2942 /*
2943  * Set the data link type of a BPF instance.
2944  */
2945 static int
bpf_setdlt(struct bpf_d * d,uint32_t dlt)2946 bpf_setdlt(struct bpf_d *d, uint32_t dlt)
2947 {
2948 	int error, opromisc;
2949 	struct ifnet *ifp;
2950 	struct bpf_if *bp;
2951 
2952 	if (d->bd_bif->bif_dlt == dlt) {
2953 		return 0;
2954 	}
2955 
2956 	while (d->bd_hbuf_read) {
2957 		msleep((caddr_t)d, bpf_mlock, PRINET, "bpf_setdlt", NULL);
2958 	}
2959 
2960 	if ((d->bd_flags & BPF_CLOSING) != 0) {
2961 		return ENXIO;
2962 	}
2963 
2964 	ifp = d->bd_bif->bif_ifp;
2965 	for (bp = bpf_iflist; bp; bp = bp->bif_next) {
2966 		if (bp->bif_ifp == ifp && bp->bif_dlt == dlt) {
2967 			/*
2968 			 * Do not use DLT_PKTAP, unless requested explicitly
2969 			 */
2970 			if (bp->bif_dlt == DLT_PKTAP &&
2971 			    !(d->bd_flags & BPF_WANT_PKTAP)) {
2972 				continue;
2973 			}
2974 			break;
2975 		}
2976 	}
2977 	if (bp != NULL) {
2978 		opromisc = d->bd_promisc;
2979 		if (bpf_detachd(d) != 0) {
2980 			return ENXIO;
2981 		}
2982 		error = bpf_attachd(d, bp);
2983 		if (error != 0) {
2984 			os_log_error(OS_LOG_DEFAULT,
2985 			    "bpf_setdlt: bpf%d bpf_attachd %s error %d",
2986 			    d->bd_dev_minor, if_name(bp->bif_ifp),
2987 			    error);
2988 			return error;
2989 		}
2990 		reset_d(d);
2991 		if (opromisc) {
2992 			lck_mtx_unlock(bpf_mlock);
2993 			error = ifnet_set_promiscuous(bp->bif_ifp, 1);
2994 			lck_mtx_lock(bpf_mlock);
2995 			if (error != 0) {
2996 				os_log_error(OS_LOG_DEFAULT,
2997 				    "bpf_setdlt: bpf%d ifpromisc %s error %d",
2998 				    d->bd_dev_minor, if_name(bp->bif_ifp), error);
2999 			} else {
3000 				d->bd_promisc = 1;
3001 			}
3002 		}
3003 	}
3004 	return bp == NULL ? EINVAL : 0;
3005 }
3006 
3007 static int
bpf_set_traffic_class(struct bpf_d * d,int tc)3008 bpf_set_traffic_class(struct bpf_d *d, int tc)
3009 {
3010 	int error = 0;
3011 
3012 	if (!SO_VALID_TC(tc)) {
3013 		error = EINVAL;
3014 	} else {
3015 		d->bd_traffic_class = tc;
3016 	}
3017 
3018 	return error;
3019 }
3020 
3021 static void
bpf_set_packet_service_class(struct mbuf * m,int tc)3022 bpf_set_packet_service_class(struct mbuf *m, int tc)
3023 {
3024 	if (!(m->m_flags & M_PKTHDR)) {
3025 		return;
3026 	}
3027 
3028 	VERIFY(SO_VALID_TC(tc));
3029 	(void) m_set_service_class(m, so_tc2msc(tc));
3030 }
3031 
3032 /*
3033  * Support for select()
3034  *
3035  * Return true iff the specific operation will not block indefinitely.
3036  * Otherwise, return false but make a note that a selwakeup() must be done.
3037  */
3038 int
bpfselect(dev_t dev,int which,void * wql,struct proc * p)3039 bpfselect(dev_t dev, int which, void * wql, struct proc *p)
3040 {
3041 	struct bpf_d *d;
3042 	int ret = 0;
3043 
3044 	lck_mtx_lock(bpf_mlock);
3045 
3046 	d = bpf_dtab[minor(dev)];
3047 	if (d == NULL || d == BPF_DEV_RESERVED ||
3048 	    (d->bd_flags & BPF_CLOSING) != 0) {
3049 		lck_mtx_unlock(bpf_mlock);
3050 		return ENXIO;
3051 	}
3052 
3053 	bpf_acquire_d(d);
3054 
3055 	if (d->bd_bif == NULL) {
3056 		bpf_release_d(d);
3057 		lck_mtx_unlock(bpf_mlock);
3058 		return ENXIO;
3059 	}
3060 
3061 	while (d->bd_hbuf_read) {
3062 		msleep((caddr_t)d, bpf_mlock, PRINET, "bpfselect", NULL);
3063 	}
3064 
3065 	if ((d->bd_flags & BPF_CLOSING) != 0) {
3066 		bpf_release_d(d);
3067 		lck_mtx_unlock(bpf_mlock);
3068 		return ENXIO;
3069 	}
3070 
3071 	switch (which) {
3072 	case FREAD:
3073 		if (d->bd_hlen != 0 ||
3074 		    ((d->bd_immediate ||
3075 		    d->bd_state == BPF_TIMED_OUT) && d->bd_slen != 0)) {
3076 			ret = 1;         /* read has data to return */
3077 		} else {
3078 			/*
3079 			 * Read has no data to return.
3080 			 * Make the select wait, and start a timer if
3081 			 * necessary.
3082 			 */
3083 			selrecord(p, &d->bd_sel, wql);
3084 			bpf_start_timer(d);
3085 		}
3086 		break;
3087 
3088 	case FWRITE:
3089 		/* can't determine whether a write would block */
3090 		ret = 1;
3091 		break;
3092 	}
3093 
3094 	bpf_release_d(d);
3095 	lck_mtx_unlock(bpf_mlock);
3096 
3097 	return ret;
3098 }
3099 
3100 /*
3101  * Support for kevent() system call.  Register EVFILT_READ filters and
3102  * reject all others.
3103  */
3104 int bpfkqfilter(dev_t dev, struct knote *kn);
3105 static void filt_bpfdetach(struct knote *);
3106 static int filt_bpfread(struct knote *, long);
3107 static int filt_bpftouch(struct knote *kn, struct kevent_qos_s *kev);
3108 static int filt_bpfprocess(struct knote *kn, struct kevent_qos_s *kev);
3109 
3110 SECURITY_READ_ONLY_EARLY(struct filterops) bpfread_filtops = {
3111 	.f_isfd = 1,
3112 	.f_detach = filt_bpfdetach,
3113 	.f_event = filt_bpfread,
3114 	.f_touch = filt_bpftouch,
3115 	.f_process = filt_bpfprocess,
3116 };
3117 
3118 static int
filt_bpfread_common(struct knote * kn,struct kevent_qos_s * kev,struct bpf_d * d)3119 filt_bpfread_common(struct knote *kn, struct kevent_qos_s *kev, struct bpf_d *d)
3120 {
3121 	int ready = 0;
3122 	int64_t data = 0;
3123 
3124 	if (d->bd_immediate) {
3125 		/*
3126 		 * If there's data in the hold buffer, it's the
3127 		 * amount of data a read will return.
3128 		 *
3129 		 * If there's no data in the hold buffer, but
3130 		 * there's data in the store buffer, a read will
3131 		 * immediately rotate the store buffer to the
3132 		 * hold buffer, the amount of data in the store
3133 		 * buffer is the amount of data a read will
3134 		 * return.
3135 		 *
3136 		 * If there's no data in either buffer, we're not
3137 		 * ready to read.
3138 		 */
3139 		data = (d->bd_hlen == 0 || d->bd_hbuf_read ?
3140 		    d->bd_slen : d->bd_hlen);
3141 		int64_t lowwat = knote_low_watermark(kn);
3142 		if (lowwat > d->bd_bufsize) {
3143 			lowwat = d->bd_bufsize;
3144 		}
3145 		ready = (data >= lowwat);
3146 	} else {
3147 		/*
3148 		 * If there's data in the hold buffer, it's the
3149 		 * amount of data a read will return.
3150 		 *
3151 		 * If there's no data in the hold buffer, but
3152 		 * there's data in the store buffer, if the
3153 		 * timer has expired a read will immediately
3154 		 * rotate the store buffer to the hold buffer,
3155 		 * so the amount of data in the store buffer is
3156 		 * the amount of data a read will return.
3157 		 *
3158 		 * If there's no data in either buffer, or there's
3159 		 * no data in the hold buffer and the timer hasn't
3160 		 * expired, we're not ready to read.
3161 		 */
3162 		data = ((d->bd_hlen == 0 || d->bd_hbuf_read) &&
3163 		    d->bd_state == BPF_TIMED_OUT ? d->bd_slen : d->bd_hlen);
3164 		ready = (data > 0);
3165 	}
3166 	if (!ready) {
3167 		bpf_start_timer(d);
3168 	} else if (kev) {
3169 		knote_fill_kevent(kn, kev, data);
3170 	}
3171 
3172 	return ready;
3173 }
3174 
3175 int
bpfkqfilter(dev_t dev,struct knote * kn)3176 bpfkqfilter(dev_t dev, struct knote *kn)
3177 {
3178 	struct bpf_d *d;
3179 	int res;
3180 
3181 	/*
3182 	 * Is this device a bpf?
3183 	 */
3184 	if (major(dev) != CDEV_MAJOR || kn->kn_filter != EVFILT_READ) {
3185 		knote_set_error(kn, EINVAL);
3186 		return 0;
3187 	}
3188 
3189 	lck_mtx_lock(bpf_mlock);
3190 
3191 	d = bpf_dtab[minor(dev)];
3192 
3193 	if (d == NULL || d == BPF_DEV_RESERVED ||
3194 	    (d->bd_flags & BPF_CLOSING) != 0 ||
3195 	    d->bd_bif == NULL) {
3196 		lck_mtx_unlock(bpf_mlock);
3197 		knote_set_error(kn, ENXIO);
3198 		return 0;
3199 	}
3200 
3201 	kn->kn_filtid = EVFILTID_BPFREAD;
3202 	knote_kn_hook_set_raw(kn, d);
3203 	KNOTE_ATTACH(&d->bd_sel.si_note, kn);
3204 	d->bd_flags |= BPF_KNOTE;
3205 
3206 	/* capture the current state */
3207 	res = filt_bpfread_common(kn, NULL, d);
3208 
3209 	lck_mtx_unlock(bpf_mlock);
3210 
3211 	return res;
3212 }
3213 
3214 static void
filt_bpfdetach(struct knote * kn)3215 filt_bpfdetach(struct knote *kn)
3216 {
3217 	struct bpf_d *d = (struct bpf_d *)knote_kn_hook_get_raw(kn);
3218 
3219 	lck_mtx_lock(bpf_mlock);
3220 	if (d->bd_flags & BPF_KNOTE) {
3221 		KNOTE_DETACH(&d->bd_sel.si_note, kn);
3222 		d->bd_flags &= ~BPF_KNOTE;
3223 	}
3224 	lck_mtx_unlock(bpf_mlock);
3225 }
3226 
3227 static int
filt_bpfread(struct knote * kn,long hint)3228 filt_bpfread(struct knote *kn, long hint)
3229 {
3230 #pragma unused(hint)
3231 	struct bpf_d *d = (struct bpf_d *)knote_kn_hook_get_raw(kn);
3232 
3233 	return filt_bpfread_common(kn, NULL, d);
3234 }
3235 
3236 static int
filt_bpftouch(struct knote * kn,struct kevent_qos_s * kev)3237 filt_bpftouch(struct knote *kn, struct kevent_qos_s *kev)
3238 {
3239 	struct bpf_d *d = (struct bpf_d *)knote_kn_hook_get_raw(kn);
3240 	int res;
3241 
3242 	lck_mtx_lock(bpf_mlock);
3243 
3244 	/* save off the lowat threshold and flag */
3245 	kn->kn_sdata = kev->data;
3246 	kn->kn_sfflags = kev->fflags;
3247 
3248 	/* output data will be re-generated here */
3249 	res = filt_bpfread_common(kn, NULL, d);
3250 
3251 	lck_mtx_unlock(bpf_mlock);
3252 
3253 	return res;
3254 }
3255 
3256 static int
filt_bpfprocess(struct knote * kn,struct kevent_qos_s * kev)3257 filt_bpfprocess(struct knote *kn, struct kevent_qos_s *kev)
3258 {
3259 	struct bpf_d *d = (struct bpf_d *)knote_kn_hook_get_raw(kn);
3260 	int res;
3261 
3262 	lck_mtx_lock(bpf_mlock);
3263 	res = filt_bpfread_common(kn, kev, d);
3264 	lck_mtx_unlock(bpf_mlock);
3265 
3266 	return res;
3267 }
3268 
3269 /*
3270  * Copy data from an mbuf chain into a buffer.	This code is derived
3271  * from m_copydata in kern/uipc_mbuf.c.
3272  */
3273 static void
bpf_mcopy(struct mbuf * m,uint8_t * __sized_by (len)dst,size_t len,size_t offset)3274 bpf_mcopy(struct mbuf *m, uint8_t *__sized_by(len) dst, size_t len, size_t offset)
3275 {
3276 	u_int count;
3277 
3278 	while (offset >= m->m_len) {
3279 		offset -= m->m_len;
3280 		m = m->m_next;
3281 		if (m == NULL) {
3282 			panic("bpf_mcopy");
3283 		}
3284 		continue;
3285 	}
3286 
3287 	while (len > 0) {
3288 		if (m == NULL) {
3289 			panic("bpf_mcopy");
3290 		}
3291 		count = MIN(m->m_len - (u_int)offset, (u_int)len);
3292 		bcopy(m_mtod_current(m) + offset, dst, count);
3293 		m = m->m_next;
3294 		dst += count;
3295 		len -= count;
3296 		offset = 0;
3297 	}
3298 }
3299 
3300 static inline void
bpf_tap_imp(ifnet_t ifp,u_int32_t dlt,struct bpf_packet * bpf_pkt,int outbound)3301 bpf_tap_imp(
3302 	ifnet_t         ifp,
3303 	u_int32_t       dlt,
3304 	struct bpf_packet *bpf_pkt,
3305 	int             outbound)
3306 {
3307 	struct bpf_d    *d;
3308 	u_int slen;
3309 	struct bpf_if *bp;
3310 
3311 	/*
3312 	 * It's possible that we get here after the bpf descriptor has been
3313 	 * detached from the interface; in such a case we simply return.
3314 	 * Lock ordering is important since we can be called asynchronously
3315 	 * (from IOKit) to process an inbound packet; when that happens
3316 	 * we would have been holding its "gateLock" and will be acquiring
3317 	 * "bpf_mlock" upon entering this routine.  Due to that, we release
3318 	 * "bpf_mlock" prior to calling ifnet_set_promiscuous (which will
3319 	 * acquire "gateLock" in the IOKit), in order to avoid a deadlock
3320 	 * when a ifnet_set_promiscuous request simultaneously collides with
3321 	 * an inbound packet being passed into the tap callback.
3322 	 */
3323 	lck_mtx_lock(bpf_mlock);
3324 	if (ifp->if_bpf == NULL) {
3325 		lck_mtx_unlock(bpf_mlock);
3326 		return;
3327 	}
3328 	for (bp = ifp->if_bpf; bp != NULL; bp = bp->bif_next) {
3329 		if (bp->bif_ifp != ifp) {
3330 			/* wrong interface */
3331 			bp = NULL;
3332 			break;
3333 		}
3334 		if (dlt == 0 || bp->bif_dlt == dlt) {
3335 			/* tapping default DLT or DLT matches */
3336 			break;
3337 		}
3338 	}
3339 	if (bp == NULL) {
3340 		goto done;
3341 	}
3342 	for (d = bp->bif_dlist; d != NULL; d = d->bd_next) {
3343 		struct bpf_packet *bpf_pkt_saved = bpf_pkt;
3344 		u_char *bpf_pkt_ptr = (u_char *)(struct bpf_packet *__bidi_indexable)bpf_pkt;
3345 		struct bpf_packet bpf_pkt_tmp = {};
3346 		struct pktap_header_buffer bpfp_header_tmp = {};
3347 
3348 		if (outbound && (d->bd_direction & BPF_D_OUT) == 0) {
3349 			continue;
3350 		}
3351 		if (!outbound && (d->bd_direction & BPF_D_IN) == 0) {
3352 			continue;
3353 		}
3354 
3355 		++d->bd_rcount;
3356 		slen = bpf_filter(d->bd_filter, d->bd_filter_len,
3357 		    bpf_pkt_ptr,
3358 		    (u_int)bpf_pkt->bpfp_total_length, 0);
3359 
3360 		if (slen != 0) {
3361 			if (bp->bif_ifp->if_type == IFT_PKTAP &&
3362 			    bp->bif_dlt == DLT_PKTAP) {
3363 				if (d->bd_flags & BPF_TRUNCATE) {
3364 					slen = min(slen, get_pkt_trunc_len(bpf_pkt));
3365 				}
3366 				/*
3367 				 * Need to copy the bpf_pkt because the conversion
3368 				 * to v2 pktap header modifies the content of the
3369 				 * bpfp_header
3370 				 */
3371 				if ((d->bd_flags & BPF_PKTHDRV2) &&
3372 				    bpf_pkt->bpfp_header_length <= sizeof(bpfp_header_tmp)) {
3373 					bpf_pkt_tmp = *bpf_pkt;
3374 					bpf_pkt = &bpf_pkt_tmp;
3375 
3376 					memcpy(&bpfp_header_tmp, bpf_pkt->bpfp_header,
3377 					    bpf_pkt->bpfp_header_length);
3378 
3379 					bpf_pkt->bpfp_header = &bpfp_header_tmp;
3380 					bpf_pkt->bpfp_header_length = bpf_pkt->bpfp_header_length;
3381 
3382 					convert_to_pktap_header_to_v2(bpf_pkt,
3383 					    !!(d->bd_flags & BPF_TRUNCATE));
3384 				}
3385 			}
3386 			++d->bd_fcount;
3387 			catchpacket(d, bpf_pkt, slen, outbound);
3388 		}
3389 		bpf_pkt = bpf_pkt_saved;
3390 	}
3391 
3392 done:
3393 	lck_mtx_unlock(bpf_mlock);
3394 }
3395 
3396 static inline void
bpf_tap_mbuf(ifnet_t ifp,u_int32_t dlt,mbuf_t m,void * __sized_by (hlen)hdr,size_t hlen,int outbound)3397 bpf_tap_mbuf(
3398 	ifnet_t         ifp,
3399 	u_int32_t       dlt,
3400 	mbuf_t          m,
3401 	void *__sized_by(hlen) hdr,
3402 	size_t          hlen,
3403 	int             outbound)
3404 {
3405 	struct bpf_packet bpf_pkt;
3406 	mbuf_ref_t m0;
3407 
3408 	if (ifp->if_bpf == NULL) {
3409 		/* quickly check without taking lock */
3410 		return;
3411 	}
3412 	bpf_pkt.bpfp_type = BPF_PACKET_TYPE_MBUF;
3413 	bpf_pkt.bpfp_mbuf = m;
3414 	bpf_pkt.bpfp_total_length = 0;
3415 	for (m0 = m; m0 != NULL; m0 = m0->m_next) {
3416 		bpf_pkt.bpfp_total_length += m0->m_len;
3417 	}
3418 	if (hdr != NULL) {
3419 		bpf_pkt.bpfp_header = hdr;
3420 		bpf_pkt.bpfp_header_length = hlen;
3421 		bpf_pkt.bpfp_total_length += hlen;
3422 	} else {
3423 		bpf_pkt.bpfp_header = NULL;
3424 		bpf_pkt.bpfp_header_length = 0;
3425 	}
3426 	bpf_tap_imp(ifp, dlt, &bpf_pkt, outbound);
3427 }
3428 
3429 void
bpf_tap_out(ifnet_t ifp,u_int32_t dlt,mbuf_t m,void * __sized_by (hlen)hdr,size_t hlen)3430 bpf_tap_out(
3431 	ifnet_t         ifp,
3432 	u_int32_t       dlt,
3433 	mbuf_t          m,
3434 	void *__sized_by(hlen) hdr,
3435 	size_t          hlen)
3436 {
3437 	bpf_tap_mbuf(ifp, dlt, m, hdr, hlen, 1);
3438 }
3439 
3440 void
bpf_tap_in(ifnet_t ifp,u_int32_t dlt,mbuf_t m,void * __sized_by (hlen)hdr,size_t hlen)3441 bpf_tap_in(
3442 	ifnet_t         ifp,
3443 	u_int32_t       dlt,
3444 	mbuf_t          m,
3445 	void *__sized_by(hlen) hdr,
3446 	size_t          hlen)
3447 {
3448 	bpf_tap_mbuf(ifp, dlt, m, hdr, hlen, 0);
3449 }
3450 
3451 /* Callback registered with Ethernet driver. */
3452 static int
bpf_tap_callback(struct ifnet * ifp,struct mbuf * m)3453 bpf_tap_callback(struct ifnet *ifp, struct mbuf *m)
3454 {
3455 	bpf_tap_mbuf(ifp, 0, m, NULL, 0, mbuf_pkthdr_rcvif(m) == NULL);
3456 
3457 	return 0;
3458 }
3459 
3460 #if SKYWALK
3461 #include <skywalk/os_skywalk_private.h>
3462 
3463 static void
bpf_pktcopy(kern_packet_t pkt,uint8_t * __sized_by (len)dst,size_t len,size_t offset)3464 bpf_pktcopy(kern_packet_t pkt, uint8_t *__sized_by(len) dst, size_t len, size_t offset)
3465 {
3466 	kern_buflet_t   buflet = NULL;
3467 	size_t count;
3468 
3469 	while (len > 0) {
3470 		uint8_t   *addr;
3471 		uint32_t buflet_length;
3472 		uint32_t buflet_offset;
3473 		uint32_t limit;
3474 
3475 		buflet = kern_packet_get_next_buflet(pkt, buflet);
3476 		VERIFY(buflet != NULL);
3477 		limit = kern_buflet_get_data_limit(buflet);
3478 		buflet_offset = kern_buflet_get_data_offset(buflet);
3479 		addr = __unsafe_forge_bidi_indexable(uint8_t *,
3480 		    (uintptr_t)kern_buflet_get_data_address(buflet) + buflet_offset,
3481 		    limit - buflet_offset);
3482 		VERIFY(addr != NULL);
3483 		buflet_length = kern_buflet_get_data_length(buflet);
3484 		if (offset >= buflet_length) {
3485 			offset -= buflet_length;
3486 			continue;
3487 		}
3488 		count = MIN(buflet_length - offset, len);
3489 		bcopy((void *)(addr + offset), (void *)dst, count);
3490 		dst += count;
3491 		len -= count;
3492 		offset = 0;
3493 	}
3494 }
3495 
3496 static inline void
bpf_tap_packet(ifnet_t ifp,u_int32_t dlt,kern_packet_t pkt,void * __sized_by (hlen)hdr,size_t hlen,int outbound)3497 bpf_tap_packet(
3498 	ifnet_t         ifp,
3499 	u_int32_t       dlt,
3500 	kern_packet_t   pkt,
3501 	void *__sized_by(hlen) hdr,
3502 	size_t          hlen,
3503 	int             outbound)
3504 {
3505 	struct bpf_packet       bpf_pkt;
3506 	struct mbuf *           m;
3507 
3508 	if (ifp->if_bpf == NULL) {
3509 		/* quickly check without taking lock */
3510 		return;
3511 	}
3512 	m = kern_packet_get_mbuf(pkt);
3513 	if (m != NULL) {
3514 		bpf_pkt.bpfp_type = BPF_PACKET_TYPE_MBUF;
3515 		bpf_pkt.bpfp_mbuf = m;
3516 		bpf_pkt.bpfp_total_length = m_length(m);
3517 	} else {
3518 		bpf_pkt.bpfp_type = BPF_PACKET_TYPE_PKT;
3519 		bpf_pkt.bpfp_pkt = pkt;
3520 		if (PKT_ADDR(pkt)->pkt_pflags & PKT_F_TRUNCATED) {
3521 			struct __kern_buflet *bft = kern_packet_get_next_buflet(pkt, NULL);
3522 			bpf_pkt.bpfp_total_length = kern_buflet_get_data_length(bft);
3523 		} else {
3524 			bpf_pkt.bpfp_total_length = kern_packet_get_data_length(pkt);
3525 		}
3526 	}
3527 	bpf_pkt.bpfp_header = hdr;
3528 	bpf_pkt.bpfp_header_length = hlen;
3529 	if (hlen != 0) {
3530 		bpf_pkt.bpfp_total_length += hlen;
3531 	}
3532 	bpf_tap_imp(ifp, dlt, &bpf_pkt, outbound);
3533 }
3534 
3535 void
bpf_tap_packet_out(ifnet_t ifp,u_int32_t dlt,kern_packet_t pkt,void * __sized_by (hlen)hdr,size_t hlen)3536 bpf_tap_packet_out(
3537 	ifnet_t         ifp,
3538 	u_int32_t       dlt,
3539 	kern_packet_t   pkt,
3540 	void *__sized_by(hlen) hdr,
3541 	size_t          hlen)
3542 {
3543 	bpf_tap_packet(ifp, dlt, pkt, hdr, hlen, 1);
3544 }
3545 
3546 void
bpf_tap_packet_in(ifnet_t ifp,u_int32_t dlt,kern_packet_t pkt,void * __sized_by (hlen)hdr,size_t hlen)3547 bpf_tap_packet_in(
3548 	ifnet_t         ifp,
3549 	u_int32_t       dlt,
3550 	kern_packet_t   pkt,
3551 	void *__sized_by(hlen) hdr,
3552 	size_t          hlen)
3553 {
3554 	bpf_tap_packet(ifp, dlt, pkt, hdr, hlen, 0);
3555 }
3556 
3557 #endif /* SKYWALK */
3558 
3559 static errno_t
bpf_copydata(struct bpf_packet * pkt,size_t off,size_t len,void * __sized_by (len)out_data)3560 bpf_copydata(struct bpf_packet *pkt, size_t off, size_t len, void *__sized_by(len) out_data)
3561 {
3562 	errno_t err = 0;
3563 	if (pkt->bpfp_type == BPF_PACKET_TYPE_MBUF) {
3564 		err = mbuf_copydata(pkt->bpfp_mbuf, off, len, out_data);
3565 #if SKYWALK
3566 	} else if (pkt->bpfp_type == BPF_PACKET_TYPE_PKT) {
3567 		err = kern_packet_copy_bytes(pkt->bpfp_pkt, off, len, out_data);
3568 #endif /* SKYWALK */
3569 	} else {
3570 		err = EINVAL;
3571 	}
3572 
3573 	return err;
3574 }
3575 
3576 static void
copy_bpf_packet_offset(struct bpf_packet * pkt,uint8_t * __sized_by (len)dst,size_t len,size_t offset)3577 copy_bpf_packet_offset(struct bpf_packet * pkt, uint8_t *__sized_by(len) dst, size_t len, size_t offset)
3578 {
3579 	/* copy the optional header */
3580 	if (offset < pkt->bpfp_header_length) {
3581 		size_t  count = MIN(len, pkt->bpfp_header_length - offset);
3582 		caddr_t src =  pkt->bpfp_header;
3583 		bcopy(src + offset, dst, count);
3584 		dst += count;
3585 		len -= count;
3586 		offset = 0;
3587 	} else {
3588 		offset -= pkt->bpfp_header_length;
3589 	}
3590 
3591 	if (len == 0) {
3592 		/* nothing past the header */
3593 		return;
3594 	}
3595 	/* copy the packet */
3596 	switch (pkt->bpfp_type) {
3597 	case BPF_PACKET_TYPE_MBUF:
3598 		bpf_mcopy(pkt->bpfp_mbuf, dst, len, offset);
3599 		break;
3600 #if SKYWALK
3601 	case BPF_PACKET_TYPE_PKT:
3602 		bpf_pktcopy(pkt->bpfp_pkt, dst, len, offset);
3603 		break;
3604 #endif /* SKYWALK */
3605 	default:
3606 		break;
3607 	}
3608 }
3609 
3610 static void
copy_bpf_packet(struct bpf_packet * pkt,uint8_t * __sized_by (len)dst,size_t len)3611 copy_bpf_packet(struct bpf_packet * pkt, uint8_t *__sized_by(len) dst, size_t len)
3612 {
3613 	copy_bpf_packet_offset(pkt, dst, len, 0);
3614 }
3615 
3616 static uint32_t
get_esp_trunc_len(__unused struct bpf_packet * pkt,__unused uint32_t off,const uint32_t remaining_caplen)3617 get_esp_trunc_len(__unused struct bpf_packet *pkt, __unused uint32_t off,
3618     const uint32_t remaining_caplen)
3619 {
3620 	/*
3621 	 * For some reason tcpdump expects to have one byte beyond the ESP header
3622 	 */
3623 	uint32_t trunc_len = ESP_HDR_SIZE + 1;
3624 
3625 	if (trunc_len > remaining_caplen) {
3626 		return remaining_caplen;
3627 	}
3628 
3629 	return trunc_len;
3630 }
3631 
3632 static uint32_t
get_isakmp_trunc_len(__unused struct bpf_packet * pkt,__unused uint32_t off,const uint32_t remaining_caplen)3633 get_isakmp_trunc_len(__unused struct bpf_packet *pkt, __unused uint32_t off,
3634     const uint32_t remaining_caplen)
3635 {
3636 	/*
3637 	 * Include the payload generic header
3638 	 */
3639 	uint32_t trunc_len = ISAKMP_HDR_SIZE;
3640 
3641 	if (trunc_len > remaining_caplen) {
3642 		return remaining_caplen;
3643 	}
3644 
3645 	return trunc_len;
3646 }
3647 
3648 static uint32_t
get_isakmp_natt_trunc_len(struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3649 get_isakmp_natt_trunc_len(struct bpf_packet *pkt, uint32_t off,
3650     const uint32_t remaining_caplen)
3651 {
3652 	int err = 0;
3653 	uint32_t trunc_len = 0;
3654 	char payload[remaining_caplen];
3655 
3656 	err = bpf_copydata(pkt, off, remaining_caplen, payload);
3657 	if (err != 0) {
3658 		return remaining_caplen;
3659 	}
3660 	/*
3661 	 * They are three cases:
3662 	 * - IKE: payload start with 4 bytes header set to zero before ISAKMP header
3663 	 * - keep alive: 1 byte payload
3664 	 * - otherwise it's ESP
3665 	 */
3666 	if (remaining_caplen >= 4 &&
3667 	    payload[0] == 0 && payload[1] == 0 &&
3668 	    payload[2] == 0 && payload[3] == 0) {
3669 		trunc_len = 4 + get_isakmp_trunc_len(pkt, off + 4, remaining_caplen - 4);
3670 	} else if (remaining_caplen == 1) {
3671 		trunc_len = 1;
3672 	} else {
3673 		trunc_len = get_esp_trunc_len(pkt, off, remaining_caplen);
3674 	}
3675 
3676 	if (trunc_len > remaining_caplen) {
3677 		return remaining_caplen;
3678 	}
3679 
3680 	return trunc_len;
3681 }
3682 
3683 static uint32_t
get_udp_trunc_len(struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3684 get_udp_trunc_len(struct bpf_packet *pkt, uint32_t off, const uint32_t remaining_caplen)
3685 {
3686 	int err = 0;
3687 	uint32_t trunc_len = sizeof(struct udphdr);         /* By default no UDP payload */
3688 
3689 	if (trunc_len >= remaining_caplen) {
3690 		return remaining_caplen;
3691 	}
3692 
3693 	struct udphdr udphdr;
3694 	err = bpf_copydata(pkt, off, sizeof(struct udphdr), &udphdr);
3695 	if (err != 0) {
3696 		return remaining_caplen;
3697 	}
3698 
3699 	u_short sport, dport;
3700 
3701 	sport = EXTRACT_SHORT(&udphdr.uh_sport);
3702 	dport = EXTRACT_SHORT(&udphdr.uh_dport);
3703 
3704 	if (dport == PORT_DNS || sport == PORT_DNS) {
3705 		/*
3706 		 * Full UDP payload for DNS
3707 		 */
3708 		trunc_len = remaining_caplen;
3709 	} else if ((sport == PORT_BOOTPS && dport == PORT_BOOTPC) ||
3710 	    (sport == PORT_BOOTPC && dport == PORT_BOOTPS)) {
3711 		/*
3712 		 * Full UDP payload for BOOTP and DHCP
3713 		 */
3714 		trunc_len = remaining_caplen;
3715 	} else if (dport == PORT_ISAKMP && sport == PORT_ISAKMP) {
3716 		/*
3717 		 * Return the ISAKMP header
3718 		 */
3719 		trunc_len += get_isakmp_trunc_len(pkt, off + sizeof(struct udphdr),
3720 		    remaining_caplen - sizeof(struct udphdr));
3721 	} else if (dport == PORT_ISAKMP_NATT && sport == PORT_ISAKMP_NATT) {
3722 		trunc_len += get_isakmp_natt_trunc_len(pkt, off + sizeof(struct udphdr),
3723 		    remaining_caplen - sizeof(struct udphdr));
3724 	}
3725 	if (trunc_len >= remaining_caplen) {
3726 		return remaining_caplen;
3727 	}
3728 
3729 	return trunc_len;
3730 }
3731 
3732 static uint32_t
get_tcp_trunc_len(struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3733 get_tcp_trunc_len(struct bpf_packet *pkt, uint32_t off, const uint32_t remaining_caplen)
3734 {
3735 	int err = 0;
3736 	uint32_t trunc_len = sizeof(struct tcphdr);         /* By default no TCP payload */
3737 	if (trunc_len >= remaining_caplen) {
3738 		return remaining_caplen;
3739 	}
3740 
3741 	struct tcphdr tcphdr;
3742 	err = bpf_copydata(pkt, off, sizeof(struct tcphdr), &tcphdr);
3743 	if (err != 0) {
3744 		return remaining_caplen;
3745 	}
3746 
3747 	u_short sport, dport;
3748 	sport = EXTRACT_SHORT(&tcphdr.th_sport);
3749 	dport = EXTRACT_SHORT(&tcphdr.th_dport);
3750 
3751 	if (dport == PORT_DNS || sport == PORT_DNS) {
3752 		/*
3753 		 * Full TCP payload  for DNS
3754 		 */
3755 		trunc_len = remaining_caplen;
3756 	} else {
3757 		trunc_len = (uint16_t)(tcphdr.th_off << 2);
3758 	}
3759 	if (trunc_len >= remaining_caplen) {
3760 		return remaining_caplen;
3761 	}
3762 
3763 	return trunc_len;
3764 }
3765 
3766 static uint32_t
get_proto_trunc_len(uint8_t proto,struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3767 get_proto_trunc_len(uint8_t proto, struct bpf_packet *pkt, uint32_t off, const uint32_t remaining_caplen)
3768 {
3769 	uint32_t trunc_len;
3770 
3771 	switch (proto) {
3772 	case IPPROTO_ICMP: {
3773 		/*
3774 		 * Full IMCP payload
3775 		 */
3776 		trunc_len = remaining_caplen;
3777 		break;
3778 	}
3779 	case IPPROTO_ICMPV6: {
3780 		/*
3781 		 * Full IMCPV6 payload
3782 		 */
3783 		trunc_len = remaining_caplen;
3784 		break;
3785 	}
3786 	case IPPROTO_IGMP: {
3787 		/*
3788 		 * Full IGMP payload
3789 		 */
3790 		trunc_len = remaining_caplen;
3791 		break;
3792 	}
3793 	case IPPROTO_UDP: {
3794 		trunc_len = get_udp_trunc_len(pkt, off, remaining_caplen);
3795 		break;
3796 	}
3797 	case IPPROTO_TCP: {
3798 		trunc_len = get_tcp_trunc_len(pkt, off, remaining_caplen);
3799 		break;
3800 	}
3801 	case IPPROTO_ESP: {
3802 		trunc_len = get_esp_trunc_len(pkt, off, remaining_caplen);
3803 		break;
3804 	}
3805 	default: {
3806 		/*
3807 		 * By default we only include the IP header
3808 		 */
3809 		trunc_len = 0;
3810 		break;
3811 	}
3812 	}
3813 	if (trunc_len >= remaining_caplen) {
3814 		return remaining_caplen;
3815 	}
3816 
3817 	return trunc_len;
3818 }
3819 
3820 static uint32_t
get_ip_trunc_len(struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3821 get_ip_trunc_len(struct bpf_packet *pkt, uint32_t off, const uint32_t remaining_caplen)
3822 {
3823 	int err = 0;
3824 	uint32_t iplen = sizeof(struct ip);
3825 	if (iplen >= remaining_caplen) {
3826 		return remaining_caplen;
3827 	}
3828 
3829 	struct ip iphdr;
3830 	err =  bpf_copydata(pkt, off, sizeof(struct ip), &iphdr);
3831 	if (err != 0) {
3832 		return remaining_caplen;
3833 	}
3834 
3835 	uint8_t proto = 0;
3836 
3837 	iplen = (uint16_t)(iphdr.ip_hl << 2);
3838 	if (iplen >= remaining_caplen) {
3839 		return remaining_caplen;
3840 	}
3841 
3842 	proto = iphdr.ip_p;
3843 	iplen += get_proto_trunc_len(proto, pkt, off + iplen, remaining_caplen - iplen);
3844 
3845 	if (iplen >= remaining_caplen) {
3846 		return remaining_caplen;
3847 	}
3848 
3849 	return iplen;
3850 }
3851 
3852 static uint32_t
get_ip6_trunc_len(struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3853 get_ip6_trunc_len(struct bpf_packet *pkt, uint32_t off, const uint32_t remaining_caplen)
3854 {
3855 	int err = 0;
3856 	uint32_t iplen = sizeof(struct ip6_hdr);
3857 	if (iplen >= remaining_caplen) {
3858 		return remaining_caplen;
3859 	}
3860 
3861 	struct ip6_hdr ip6hdr;
3862 	err = bpf_copydata(pkt, off, sizeof(struct ip6_hdr), &ip6hdr);
3863 	if (err != 0) {
3864 		return remaining_caplen;
3865 	}
3866 
3867 	uint8_t proto = 0;
3868 
3869 	/*
3870 	 * TBD: process the extension headers
3871 	 */
3872 	proto = ip6hdr.ip6_nxt;
3873 	iplen += get_proto_trunc_len(proto, pkt, off + iplen, remaining_caplen - iplen);
3874 
3875 	if (iplen >= remaining_caplen) {
3876 		return remaining_caplen;
3877 	}
3878 
3879 	return iplen;
3880 }
3881 
3882 static uint32_t
get_ether_trunc_len(struct bpf_packet * pkt,uint32_t off,const uint32_t remaining_caplen)3883 get_ether_trunc_len(struct bpf_packet *pkt, uint32_t off, const uint32_t remaining_caplen)
3884 {
3885 	int err = 0;
3886 	uint32_t ethlen = sizeof(struct ether_header);
3887 	if (ethlen >= remaining_caplen) {
3888 		return remaining_caplen;
3889 	}
3890 
3891 	struct ether_header eh = {};
3892 	err = bpf_copydata(pkt, off, sizeof(struct ether_header), &eh);
3893 	if (err != 0) {
3894 		return remaining_caplen;
3895 	}
3896 
3897 	u_short type = EXTRACT_SHORT(&eh.ether_type);
3898 	/* Include full ARP */
3899 	if (type == ETHERTYPE_ARP) {
3900 		ethlen = remaining_caplen;
3901 	} else if (type == ETHERTYPE_IP) {
3902 		ethlen += get_ip_trunc_len(pkt, off + sizeof(struct ether_header),
3903 		    remaining_caplen - ethlen);
3904 	} else if (type == ETHERTYPE_IPV6) {
3905 		ethlen += get_ip6_trunc_len(pkt, off + sizeof(struct ether_header),
3906 		    remaining_caplen - ethlen);
3907 	} else {
3908 		ethlen = MIN(BPF_MIN_PKT_SIZE, remaining_caplen);
3909 	}
3910 	return ethlen;
3911 }
3912 
3913 static uint32_t
get_pkt_trunc_len(struct bpf_packet * pkt)3914 get_pkt_trunc_len(struct bpf_packet *pkt)
3915 {
3916 	struct pktap_header *pktap = (struct pktap_header *) (pkt->bpfp_header);
3917 	uint32_t in_pkt_len = 0;
3918 	uint32_t out_pkt_len = 0;
3919 	uint32_t tlen = 0;
3920 	uint32_t pre_adjust;         // L2 header not in mbuf or kern_packet
3921 
3922 	// bpfp_total_length must contain the BPF packet header
3923 	assert3u(pkt->bpfp_total_length, >=, pkt->bpfp_header_length);
3924 
3925 	// The BPF packet header must contain the pktap header
3926 	assert3u(pkt->bpfp_header_length, >=, pktap->pth_length);
3927 
3928 	// The pre frame length (L2 header) must be contained in the packet
3929 	assert3u(pkt->bpfp_total_length, >=, pktap->pth_length + pktap->pth_frame_pre_length);
3930 
3931 	/*
3932 	 * pktap->pth_frame_pre_length is the L2 header length and accounts
3933 	 * for both L2 header in the packet payload and pre_adjust.
3934 	 *
3935 	 * pre_adjust represents an adjustment for a pseudo L2 header that is not
3936 	 * part of packet payload -- not in the mbuf or kern_packet -- and comes
3937 	 * just after the pktap header.
3938 	 *
3939 	 * pktap->pth_length is the size of the pktap header (exclude pre_adjust)
3940 	 *
3941 	 * pkt->bpfp_header_length is (pktap->pth_length + pre_adjust)
3942 	 */
3943 	pre_adjust = (uint32_t)(pkt->bpfp_header_length - pktap->pth_length);
3944 
3945 	if (pktap->pth_iftype == IFT_ETHER) {
3946 		/*
3947 		 * We need to parse the Ethernet header to find the network layer
3948 		 * protocol
3949 		 */
3950 		in_pkt_len = (uint32_t)(pkt->bpfp_total_length - pktap->pth_length - pre_adjust);
3951 
3952 		out_pkt_len = get_ether_trunc_len(pkt, 0, in_pkt_len);
3953 
3954 		tlen = pktap->pth_length + pre_adjust + out_pkt_len;
3955 	} else {
3956 		/*
3957 		 * For other interface types, we only know to parse IPv4 and IPv6.
3958 		 *
3959 		 * To get to the beginning of the IPv4 or IPv6 packet, we need to to skip
3960 		 * over the L2 header that is the actual packet payload (mbuf or kern_packet)
3961 		 */
3962 		uint32_t off;         // offset past the L2 header in the actual packet payload
3963 
3964 		off = pktap->pth_frame_pre_length - pre_adjust;
3965 
3966 		in_pkt_len = (uint32_t)(pkt->bpfp_total_length - pktap->pth_length - pktap->pth_frame_pre_length);
3967 
3968 		if (pktap->pth_protocol_family == AF_INET) {
3969 			out_pkt_len = get_ip_trunc_len(pkt, off, in_pkt_len);
3970 		} else if (pktap->pth_protocol_family == AF_INET6) {
3971 			out_pkt_len = get_ip6_trunc_len(pkt, off, in_pkt_len);
3972 		} else {
3973 			out_pkt_len = MIN(BPF_MIN_PKT_SIZE, in_pkt_len);
3974 		}
3975 		tlen = pktap->pth_length + pktap->pth_frame_pre_length + out_pkt_len;
3976 	}
3977 
3978 	// Verify we do not overflow the buffer
3979 	if (__improbable(tlen > pkt->bpfp_total_length)) {
3980 		bool do_panic = bpf_debug != 0 ? true : false;
3981 
3982 #if DEBUG
3983 		do_panic = true;
3984 #endif /* DEBUG */
3985 		if (do_panic) {
3986 			panic("%s:%d tlen %u > bpfp_total_length %lu bpfp_header_length %lu pth_frame_pre_length %u pre_adjust %u in_pkt_len %u out_pkt_len %u",
3987 			    __func__, __LINE__,
3988 			    tlen, pkt->bpfp_total_length, pkt->bpfp_header_length, pktap->pth_frame_pre_length, pre_adjust, in_pkt_len, out_pkt_len);
3989 		} else {
3990 			os_log(OS_LOG_DEFAULT,
3991 			    "%s:%d tlen %u > bpfp_total_length %lu bpfp_header_length %lu pth_frame_pre_length %u pre_adjust %u in_pkt_len %u out_pkt_len %u",
3992 			    __func__, __LINE__,
3993 			    tlen, pkt->bpfp_total_length, pkt->bpfp_header_length, pktap->pth_frame_pre_length, pre_adjust, in_pkt_len, out_pkt_len);
3994 		}
3995 		bpf_trunc_overflow += 1;
3996 		tlen = (uint32_t)pkt->bpfp_total_length;
3997 	}
3998 
3999 	return tlen;
4000 }
4001 
4002 static uint8_t
get_common_prefix_size(const void * __bidi_indexable a,const void * __bidi_indexable b,uint8_t max_bytes)4003 get_common_prefix_size(const void *__bidi_indexable a, const void *__bidi_indexable b, uint8_t max_bytes)
4004 {
4005 	uint8_t max_words = max_bytes >> 2;
4006 	const uint32_t *x = (const uint32_t *)a;
4007 	const uint32_t *y = (const uint32_t *)b;
4008 	uint8_t i;
4009 
4010 	for (i = 0; i < max_words; i++) {
4011 		if (x[i] != y[i]) {
4012 			break;
4013 		}
4014 	}
4015 	return (uint8_t)(i << 2);
4016 }
4017 
4018 /*
4019  * Move the packet data from interface memory (pkt) into the
4020  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
4021  * otherwise 0.
4022  */
4023 static void
catchpacket(struct bpf_d * d,struct bpf_packet * pkt,u_int snaplen,int outbound)4024 catchpacket(struct bpf_d *d, struct bpf_packet * pkt,
4025     u_int snaplen, int outbound)
4026 {
4027 	struct bpf_hdr *hp;
4028 	struct bpf_hdr_ext *ehp;
4029 	uint32_t totlen, curlen;
4030 	uint32_t hdrlen, caplen;
4031 	int do_wakeup = 0;
4032 	u_char *payload;
4033 	struct timeval tv = { .tv_sec = 0, .tv_usec = 0 };
4034 
4035 	hdrlen = (d->bd_flags & BPF_EXTENDED_HDR) ? d->bd_bif->bif_exthdrlen :
4036 	    (d->bd_flags & BPF_COMP_REQ) ? d->bd_bif->bif_comphdrlen:
4037 	    d->bd_bif->bif_hdrlen;
4038 	/*
4039 	 * Figure out how many bytes to move.  If the packet is
4040 	 * greater or equal to the snapshot length, transfer that
4041 	 * much.  Otherwise, transfer the whole packet (unless
4042 	 * we hit the buffer size limit).
4043 	 */
4044 	totlen = hdrlen + MIN(snaplen, (int)pkt->bpfp_total_length);
4045 	if (totlen > d->bd_bufsize) {
4046 		totlen = d->bd_bufsize;
4047 	}
4048 
4049 	if (hdrlen > totlen) {
4050 		return;
4051 	}
4052 
4053 	/*
4054 	 * Round up the end of the previous packet to the next longword.
4055 	 */
4056 	curlen = BPF_WORDALIGN(d->bd_slen);
4057 	if (curlen + totlen > d->bd_bufsize) {
4058 		/*
4059 		 * This packet will overflow the storage buffer.
4060 		 * Rotate the buffers if we can, then wakeup any
4061 		 * pending reads.
4062 		 *
4063 		 * We cannot rotate buffers if a read is in progress
4064 		 * so drop the packet
4065 		 */
4066 		if (d->bd_hbuf_read) {
4067 			++d->bd_dcount;
4068 			return;
4069 		}
4070 
4071 		if (d->bd_fbuf == NULL) {
4072 			if (d->bd_headdrop == 0) {
4073 				/*
4074 				 * We haven't completed the previous read yet,
4075 				 * so drop the packet.
4076 				 */
4077 				++d->bd_dcount;
4078 				return;
4079 			}
4080 			/*
4081 			 * Drop the hold buffer as it contains older packets
4082 			 */
4083 			d->bd_dcount += d->bd_hcnt;
4084 			d->bd_fbuf = d->bd_hbuf;
4085 			ROTATE_BUFFERS(d);
4086 		} else {
4087 			ROTATE_BUFFERS(d);
4088 		}
4089 		do_wakeup = 1;
4090 		curlen = 0;
4091 	} else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT) {
4092 		/*
4093 		 * Immediate mode is set, or the read timeout has
4094 		 * already expired during a select call. A packet
4095 		 * arrived, so the reader should be woken up.
4096 		 */
4097 		do_wakeup = 1;
4098 	}
4099 
4100 	/*
4101 	 * Append the bpf header.
4102 	 */
4103 	if (d->bd_tstamp != BPF_T_NONE) {
4104 		microtime(&tv);
4105 	}
4106 	if (d->bd_flags & BPF_EXTENDED_HDR) {
4107 		ehp = (struct bpf_hdr_ext *)(void *)(d->bd_sbuf + curlen);
4108 		memset(ehp, 0, sizeof(*ehp));
4109 		ehp->bh_tstamp.tv_sec = (int)tv.tv_sec;
4110 		ehp->bh_tstamp.tv_usec = tv.tv_usec;
4111 
4112 		ehp->bh_datalen = (bpf_u_int32)pkt->bpfp_total_length;
4113 		ehp->bh_hdrlen = (u_short)hdrlen;
4114 		caplen = ehp->bh_caplen = totlen - hdrlen;
4115 		payload = (u_char *)ehp + hdrlen;
4116 
4117 		if (outbound) {
4118 			ehp->bh_flags |= BPF_HDR_EXT_FLAGS_DIR_OUT;
4119 		} else {
4120 			ehp->bh_flags |= BPF_HDR_EXT_FLAGS_DIR_IN;
4121 		}
4122 
4123 		if (pkt->bpfp_type == BPF_PACKET_TYPE_MBUF) {
4124 			mbuf_ref_t m = pkt->bpfp_mbuf;
4125 
4126 			if (outbound) {
4127 				/* only do lookups on non-raw INPCB */
4128 				if ((m->m_pkthdr.pkt_flags & (PKTF_FLOW_ID |
4129 				    PKTF_FLOW_LOCALSRC | PKTF_FLOW_RAWSOCK)) ==
4130 				    (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC) &&
4131 				    m->m_pkthdr.pkt_flowsrc == FLOWSRC_INPCB) {
4132 					ehp->bh_flowid = m->m_pkthdr.pkt_flowid;
4133 					if (m->m_pkthdr.pkt_proto == IPPROTO_TCP) {
4134 						ehp->bh_flags |= BPF_HDR_EXT_FLAGS_TCP;
4135 					} else if (m->m_pkthdr.pkt_proto == IPPROTO_UDP) {
4136 						ehp->bh_flags |= BPF_HDR_EXT_FLAGS_UDP;
4137 					}
4138 				}
4139 				ehp->bh_svc = so_svc2tc(m->m_pkthdr.pkt_svc);
4140 				if (m->m_pkthdr.pkt_flags & PKTF_TCP_REXMT) {
4141 					ehp->bh_pktflags |= BPF_PKTFLAGS_TCP_REXMT;
4142 				}
4143 				if (m->m_pkthdr.pkt_flags & PKTF_START_SEQ) {
4144 					ehp->bh_pktflags |= BPF_PKTFLAGS_START_SEQ;
4145 				}
4146 				if (m->m_pkthdr.pkt_flags & PKTF_LAST_PKT) {
4147 					ehp->bh_pktflags |= BPF_PKTFLAGS_LAST_PKT;
4148 				}
4149 				if (m->m_pkthdr.pkt_flags & PKTF_VALID_UNSENT_DATA) {
4150 					ehp->bh_unsent_bytes =
4151 					    m->m_pkthdr.bufstatus_if;
4152 					ehp->bh_unsent_snd =
4153 					    m->m_pkthdr.bufstatus_sndbuf;
4154 				}
4155 			} else {
4156 				if (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT) {
4157 					ehp->bh_pktflags |= BPF_PKTFLAGS_WAKE_PKT;
4158 				}
4159 			}
4160 #if SKYWALK
4161 		} else {
4162 			kern_packet_t kern_pkt = pkt->bpfp_pkt;
4163 			packet_flowid_t flowid = 0;
4164 
4165 			if (outbound) {
4166 				/*
4167 				 * Note: pp_init() asserts that kern_packet_svc_class_t is equivalent
4168 				 * to mbuf_svc_class_t
4169 				 */
4170 				ehp->bh_svc = so_svc2tc((mbuf_svc_class_t)kern_packet_get_service_class(kern_pkt));
4171 				if (kern_packet_get_transport_retransmit(kern_pkt)) {
4172 					ehp->bh_pktflags |= BPF_PKTFLAGS_TCP_REXMT;
4173 				}
4174 				if (kern_packet_get_transport_last_packet(kern_pkt)) {
4175 					ehp->bh_pktflags |= BPF_PKTFLAGS_LAST_PKT;
4176 				}
4177 			} else {
4178 				if (kern_packet_get_wake_flag(kern_pkt)) {
4179 					ehp->bh_pktflags |= BPF_PKTFLAGS_WAKE_PKT;
4180 				}
4181 			}
4182 			ehp->bh_trace_tag = kern_packet_get_trace_tag(kern_pkt);
4183 			if (kern_packet_get_flowid(kern_pkt, &flowid) == 0) {
4184 				ehp->bh_flowid = flowid;
4185 			}
4186 #endif /* SKYWALK */
4187 		}
4188 	} else {
4189 		hp = (struct bpf_hdr *)(void *)(d->bd_sbuf + curlen);
4190 		memset(hp, 0, BPF_WORDALIGN(sizeof(*hp)));
4191 		hp->bh_tstamp.tv_sec = (int)tv.tv_sec;
4192 		hp->bh_tstamp.tv_usec = tv.tv_usec;
4193 		hp->bh_datalen = (bpf_u_int32)pkt->bpfp_total_length;
4194 		hp->bh_hdrlen = (u_short)hdrlen;
4195 		caplen = hp->bh_caplen = totlen - hdrlen;
4196 		payload = (u_char *)hp + hdrlen;
4197 	}
4198 	if (d->bd_flags & BPF_COMP_REQ) {
4199 		uint8_t common_prefix_size = 0;
4200 		uint8_t copy_len = MIN((uint8_t)caplen, BPF_HDR_COMP_LEN_MAX);
4201 
4202 		copy_bpf_packet(pkt, (uint8_t *__bidi_indexable)d->bd_prev_fbuf, copy_len);
4203 
4204 		if (d->bd_prev_slen != 0) {
4205 			common_prefix_size = get_common_prefix_size(d->bd_prev_fbuf,
4206 			    d->bd_prev_sbuf, MIN(copy_len, d->bd_prev_slen));
4207 		}
4208 
4209 		if (d->bd_flags & BPF_COMP_ENABLED) {
4210 			assert3u(caplen, >=, common_prefix_size);
4211 			copy_bpf_packet_offset(pkt, payload, caplen - common_prefix_size,
4212 			    common_prefix_size);
4213 			d->bd_slen = curlen + totlen - common_prefix_size;
4214 		} else {
4215 			copy_bpf_packet(pkt, payload, caplen);
4216 			d->bd_slen = curlen + totlen;
4217 		}
4218 
4219 		/*
4220 		 * Update the caplen only if compression is enabled -- the caller
4221 		 * must pay attention to bpf_hdr_comp_enable
4222 		 */
4223 		if (d->bd_flags & BPF_EXTENDED_HDR) {
4224 			ehp->bh_complen = common_prefix_size;
4225 			if (d->bd_flags & BPF_COMP_ENABLED) {
4226 				ehp->bh_caplen -= common_prefix_size;
4227 			}
4228 		} else {
4229 			struct bpf_comp_hdr *hcp;
4230 
4231 			hcp = (struct bpf_comp_hdr *)(void *)(d->bd_sbuf + curlen);
4232 			hcp->bh_complen = common_prefix_size;
4233 			if (d->bd_flags & BPF_COMP_ENABLED) {
4234 				hcp->bh_caplen -= common_prefix_size;
4235 			}
4236 		}
4237 
4238 		if (common_prefix_size > 0) {
4239 			d->bd_bcs.bcs_total_compressed_prefix_size += common_prefix_size;
4240 			if (common_prefix_size > d->bd_bcs.bcs_max_compressed_prefix_size) {
4241 				d->bd_bcs.bcs_max_compressed_prefix_size = common_prefix_size;
4242 			}
4243 			d->bd_bcs.bcs_count_compressed_prefix += 1;
4244 		} else {
4245 			d->bd_bcs.bcs_count_no_common_prefix += 1;
4246 		}
4247 
4248 		/* The current compression buffer becomes the previous one */
4249 		caddr_t tmp = d->bd_prev_sbuf;
4250 		d->bd_prev_sbuf = d->bd_prev_fbuf;
4251 		d->bd_prev_slen = copy_len;
4252 		d->bd_prev_fbuf = tmp;
4253 	} else {
4254 		/*
4255 		 * Copy the packet data into the store buffer and update its length.
4256 		 */
4257 		copy_bpf_packet(pkt, payload, caplen);
4258 		d->bd_slen = curlen + totlen;
4259 	}
4260 	d->bd_scnt += 1;
4261 	d->bd_bcs.bcs_total_hdr_size += pkt->bpfp_header_length;
4262 	d->bd_bcs.bcs_total_size += caplen;
4263 
4264 	if (do_wakeup) {
4265 		bpf_wakeup(d);
4266 	}
4267 }
4268 
4269 static void
bpf_freebufs(struct bpf_d * d)4270 bpf_freebufs(struct bpf_d *d)
4271 {
4272 	if (d->bd_sbuf != NULL) {
4273 		kfree_data_addr(d->bd_sbuf);
4274 	}
4275 	if (d->bd_hbuf != NULL) {
4276 		kfree_data_addr(d->bd_hbuf);
4277 	}
4278 	if (d->bd_fbuf != NULL) {
4279 		kfree_data_addr(d->bd_fbuf);
4280 	}
4281 
4282 	if (d->bd_prev_sbuf != NULL) {
4283 		kfree_data_addr(d->bd_prev_sbuf);
4284 	}
4285 	if (d->bd_prev_fbuf != NULL) {
4286 		kfree_data_addr(d->bd_prev_fbuf);
4287 	}
4288 }
4289 /*
4290  * Initialize all nonzero fields of a descriptor.
4291  */
4292 static int
bpf_allocbufs(struct bpf_d * d)4293 bpf_allocbufs(struct bpf_d *d)
4294 {
4295 	bpf_freebufs(d);
4296 
4297 	d->bd_fbuf = kalloc_data(d->bd_bufsize, Z_WAITOK | Z_ZERO);
4298 	if (d->bd_fbuf == NULL) {
4299 		goto nobufs;
4300 	}
4301 
4302 	d->bd_sbuf = kalloc_data(d->bd_bufsize, Z_WAITOK | Z_ZERO);
4303 	if (d->bd_sbuf == NULL) {
4304 		goto nobufs;
4305 	}
4306 	d->bd_slen = 0;
4307 	d->bd_hlen = 0;
4308 	d->bd_scnt = 0;
4309 	d->bd_hcnt = 0;
4310 
4311 	d->bd_prev_slen = 0;
4312 	if (d->bd_flags & BPF_COMP_REQ) {
4313 		d->bd_prev_sbuf = kalloc_data(BPF_HDR_COMP_LEN_MAX, Z_WAITOK | Z_ZERO);
4314 		if (d->bd_prev_sbuf == NULL) {
4315 			goto nobufs;
4316 		}
4317 		d->bd_prev_fbuf = kalloc_data(BPF_HDR_COMP_LEN_MAX, Z_WAITOK | Z_ZERO);
4318 		if (d->bd_prev_fbuf == NULL) {
4319 			goto nobufs;
4320 		}
4321 	}
4322 	return 0;
4323 nobufs:
4324 	bpf_freebufs(d);
4325 	return ENOMEM;
4326 }
4327 
4328 /*
4329  * Free buffers currently in use by a descriptor.
4330  * Called on close.
4331  */
4332 static void
bpf_freed(struct bpf_d * d)4333 bpf_freed(struct bpf_d *d)
4334 {
4335 	/*
4336 	 * We don't need to lock out interrupts since this descriptor has
4337 	 * been detached from its interface and it yet hasn't been marked
4338 	 * free.
4339 	 */
4340 	if (d->bd_hbuf_read || d->bd_hbuf_write) {
4341 		panic("bpf buffer freed during read/write");
4342 	}
4343 
4344 	bpf_freebufs(d);
4345 
4346 	if (d->bd_filter) {
4347 		kfree_data_addr_sized_by(d->bd_filter, d->bd_filter_len);
4348 	}
4349 }
4350 
4351 /*
4352  * Attach an interface to bpf.	driverp is a pointer to a (struct bpf_if *)
4353  * in the driver's softc; dlt is the link layer type; hdrlen is the fixed
4354  * size of the link header (variable length headers not yet supported).
4355  */
4356 void
bpfattach(struct ifnet * ifp,u_int dlt,u_int hdrlen)4357 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
4358 {
4359 	bpf_attach(ifp, dlt, hdrlen, NULL, NULL);
4360 }
4361 
4362 errno_t
bpf_attach(ifnet_t ifp,u_int32_t dlt,u_int32_t hdrlen,bpf_send_func send,bpf_tap_func tap)4363 bpf_attach(
4364 	ifnet_t ifp,
4365 	u_int32_t dlt,
4366 	u_int32_t hdrlen,
4367 	bpf_send_func send,
4368 	bpf_tap_func tap)
4369 {
4370 	struct bpf_if *bp;
4371 	struct bpf_if *bp_new;
4372 	struct bpf_if *bp_before_first = NULL;
4373 	struct bpf_if *bp_first = NULL;
4374 	struct bpf_if *bp_last = NULL;
4375 	boolean_t found;
4376 
4377 	/*
4378 	 * Z_NOFAIL will cause a panic if the allocation fails
4379 	 */
4380 	bp_new = kalloc_type(struct bpf_if, Z_WAITOK | Z_NOFAIL | Z_ZERO);
4381 
4382 	lck_mtx_lock(bpf_mlock);
4383 
4384 	/*
4385 	 * Check if this interface/dlt is already attached. Remember the
4386 	 * first and last attachment for this interface, as well as the
4387 	 * element before the first attachment.
4388 	 */
4389 	found = FALSE;
4390 	for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
4391 		if (bp->bif_ifp != ifp) {
4392 			if (bp_first != NULL) {
4393 				/* no more elements for this interface */
4394 				break;
4395 			}
4396 			bp_before_first = bp;
4397 		} else {
4398 			if (bp->bif_dlt == dlt) {
4399 				found = TRUE;
4400 				break;
4401 			}
4402 			if (bp_first == NULL) {
4403 				bp_first = bp;
4404 			}
4405 			bp_last = bp;
4406 		}
4407 	}
4408 	if (found) {
4409 		lck_mtx_unlock(bpf_mlock);
4410 		os_log_error(OS_LOG_DEFAULT,
4411 		    "bpfattach - %s with dlt %d is already attached",
4412 		    if_name(ifp), dlt);
4413 		kfree_type(struct bpf_if, bp_new);
4414 		return EEXIST;
4415 	}
4416 
4417 	bp_new->bif_ifp = ifp;
4418 	bp_new->bif_dlt = dlt;
4419 	bp_new->bif_send = send;
4420 	bp_new->bif_tap = tap;
4421 
4422 	if (bp_first == NULL) {
4423 		/* No other entries for this ifp */
4424 		bp_new->bif_next = bpf_iflist;
4425 		bpf_iflist = bp_new;
4426 	} else {
4427 		if (ifnet_type(ifp) == IFT_ETHER && dlt == DLT_EN10MB) {
4428 			/* Make this the first entry for this interface */
4429 			if (bp_before_first != NULL) {
4430 				/*  point the previous to us */
4431 				bp_before_first->bif_next = bp_new;
4432 			} else {
4433 				/* we're the new head */
4434 				bpf_iflist = bp_new;
4435 			}
4436 			bp_new->bif_next = bp_first;
4437 		} else {
4438 			/* Add this after the last entry for this interface */
4439 			bp_new->bif_next = bp_last->bif_next;
4440 			bp_last->bif_next = bp_new;
4441 		}
4442 	}
4443 
4444 	/*
4445 	 * Compute the length of the bpf header.  This is not necessarily
4446 	 * equal to SIZEOF_BPF_HDR because we want to insert spacing such
4447 	 * that the network layer header begins on a longword boundary (for
4448 	 * performance reasons and to alleviate alignment restrictions).
4449 	 */
4450 	bp_new->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
4451 	bp_new->bif_exthdrlen = BPF_WORDALIGN(hdrlen +
4452 	    sizeof(struct bpf_hdr_ext)) - hdrlen;
4453 	bp_new->bif_comphdrlen = BPF_WORDALIGN(hdrlen +
4454 	    sizeof(struct bpf_comp_hdr)) - hdrlen;
4455 
4456 	/* Take a reference on the interface */
4457 	ifnet_reference(ifp);
4458 
4459 	lck_mtx_unlock(bpf_mlock);
4460 
4461 	return 0;
4462 }
4463 
4464 /*
4465  * Detach bpf from an interface.  This involves detaching each descriptor
4466  * associated with the interface, and leaving bd_bif NULL.  Notify each
4467  * descriptor as it's detached so that any sleepers wake up and get
4468  * ENXIO.
4469  */
4470 void
bpfdetach(struct ifnet * ifp)4471 bpfdetach(struct ifnet *ifp)
4472 {
4473 	struct bpf_if   *bp, *bp_prev, *bp_next;
4474 	struct bpf_d    *d;
4475 
4476 	if (bpf_debug != 0) {
4477 		os_log(OS_LOG_DEFAULT, "%s: %s", __func__, if_name(ifp));
4478 	}
4479 
4480 	lck_mtx_lock(bpf_mlock);
4481 
4482 	/*
4483 	 * Build the list of devices attached to that interface
4484 	 * that we need to free while keeping the lock to maintain
4485 	 * the integrity of the interface list
4486 	 */
4487 	bp_prev = NULL;
4488 	for (bp = bpf_iflist; bp != NULL; bp = bp_next) {
4489 		bp_next = bp->bif_next;
4490 
4491 		if (ifp != bp->bif_ifp) {
4492 			bp_prev = bp;
4493 			continue;
4494 		}
4495 		/* Unlink from the interface list */
4496 		if (bp_prev) {
4497 			bp_prev->bif_next = bp->bif_next;
4498 		} else {
4499 			bpf_iflist = bp->bif_next;
4500 		}
4501 
4502 		/* Detach the devices attached to the interface */
4503 		while ((d = bp->bif_dlist) != NULL) {
4504 			/*
4505 			 * Take an extra reference to prevent the device
4506 			 * from being freed when bpf_detachd() releases
4507 			 * the reference for the interface list
4508 			 */
4509 			bpf_acquire_d(d);
4510 
4511 			/*
4512 			 * Wait for active read and writes to complete
4513 			 */
4514 			while (d->bd_hbuf_read || d->bd_hbuf_write) {
4515 				msleep((caddr_t)d, bpf_mlock, PRINET, "bpfdetach", NULL);
4516 			}
4517 
4518 			bpf_detachd(d);
4519 			bpf_wakeup(d);
4520 			bpf_release_d(d);
4521 		}
4522 		ifnet_release(ifp);
4523 	}
4524 
4525 	lck_mtx_unlock(bpf_mlock);
4526 }
4527 
4528 void
bpf_init(__unused void * unused)4529 bpf_init(__unused void *unused)
4530 {
4531 	int     maj;
4532 
4533 	/* bpf_comp_hdr is an overlay of bpf_hdr */
4534 	_CASSERT(BPF_WORDALIGN(sizeof(struct bpf_hdr)) ==
4535 	    BPF_WORDALIGN(sizeof(struct bpf_comp_hdr)));
4536 
4537 	/* compression length must fits in a byte */
4538 	_CASSERT(BPF_HDR_COMP_LEN_MAX <= UCHAR_MAX );
4539 
4540 	(void) PE_parse_boot_argn("bpf_hdr_comp", &bpf_hdr_comp_enable,
4541 	    sizeof(bpf_hdr_comp_enable));
4542 
4543 	if (bpf_devsw_installed == 0) {
4544 		bpf_devsw_installed = 1;
4545 		maj = cdevsw_add(CDEV_MAJOR, &bpf_cdevsw);
4546 		if (maj == -1) {
4547 			bpf_devsw_installed = 0;
4548 			os_log_error(OS_LOG_DEFAULT,
4549 			    "bpf_init: failed to allocate a major number");
4550 			return;
4551 		}
4552 
4553 		for (int i = 0; i < NBPFILTER; i++) {
4554 			bpf_make_dev_t(maj);
4555 		}
4556 	}
4557 }
4558 
4559 static int
4560 sysctl_bpf_maxbufsize SYSCTL_HANDLER_ARGS
4561 {
4562 #pragma unused(arg1, arg2)
4563 	int i, err;
4564 
4565 	i = bpf_maxbufsize;
4566 
4567 	err = sysctl_handle_int(oidp, &i, 0, req);
4568 	if (err != 0 || req->newptr == USER_ADDR_NULL) {
4569 		return err;
4570 	}
4571 
4572 	if (i < 0 || i > BPF_BUFSIZE_CAP) {
4573 		i = BPF_BUFSIZE_CAP;
4574 	}
4575 
4576 	bpf_maxbufsize = i;
4577 	return err;
4578 }
4579 
4580 static int
4581 sysctl_bpf_bufsize_cap SYSCTL_HANDLER_ARGS
4582 {
4583 #pragma unused(arg1, arg2)
4584 	int i, err;
4585 
4586 	i = BPF_BUFSIZE_CAP;
4587 
4588 	err = sysctl_handle_int(oidp, &i, 0, req);
4589 	if (err != 0 || req->newptr == USER_ADDR_NULL) {
4590 		return err;
4591 	}
4592 
4593 	return err;
4594 }
4595 
4596 /*
4597  * Fill filter statistics
4598  */
4599 static void
bpfstats_fill_xbpf(struct xbpf_d * d,struct bpf_d * bd)4600 bpfstats_fill_xbpf(struct xbpf_d *d, struct bpf_d *bd)
4601 {
4602 	LCK_MTX_ASSERT(bpf_mlock, LCK_MTX_ASSERT_OWNED);
4603 
4604 	d->bd_structsize = sizeof(struct xbpf_d);
4605 	d->bd_promisc = bd->bd_promisc != 0 ? 1 : 0;
4606 	d->bd_immediate = d->bd_immediate != 0 ? 1 : 0;
4607 	d->bd_hdrcmplt = bd->bd_hdrcmplt != 0 ? 1 : 0;
4608 	d->bd_async = bd->bd_async != 0 ? 1 : 0;
4609 	d->bd_headdrop = bd->bd_headdrop != 0 ? 1 : 0;
4610 	d->bd_direction = (uint8_t)bd->bd_direction;
4611 	d->bh_compreq = bd->bd_flags & BPF_COMP_REQ ? 1 : 0;
4612 	d->bh_compenabled = bd->bd_flags & BPF_COMP_ENABLED ? 1 : 0;
4613 	d->bd_exthdr = bd->bd_flags & BPF_EXTENDED_HDR ? 1 : 0;
4614 	d->bd_trunc = bd->bd_flags & BPF_TRUNCATE ? 1 : 0;
4615 	d->bd_pkthdrv2 = bd->bd_flags & BPF_PKTHDRV2 ? 1 : 0;
4616 	d->bd_batch_write = bd->bd_flags & BPF_BATCH_WRITE ? 1 : 0;
4617 	d->bd_divert_in = bd->bd_flags & BPF_DIVERT_IN ? 1 : 0;
4618 
4619 	d->bd_dev_minor = (uint8_t)bd->bd_dev_minor;
4620 
4621 	d->bd_sig = bd->bd_sig;
4622 
4623 	d->bd_rcount = bd->bd_rcount;
4624 	d->bd_dcount = bd->bd_dcount;
4625 	d->bd_fcount = bd->bd_fcount;
4626 	d->bd_wcount = bd->bd_wcount;
4627 	d->bd_wdcount = bd->bd_wdcount;
4628 	d->bd_slen = bd->bd_slen;
4629 	d->bd_hlen = bd->bd_hlen;
4630 	d->bd_bufsize = bd->bd_bufsize;
4631 	d->bd_pid = bd->bd_pid;
4632 	if (bd->bd_bif != NULL && bd->bd_bif->bif_ifp != NULL) {
4633 		strlcpy(d->bd_ifname,
4634 		    bd->bd_bif->bif_ifp->if_xname, IFNAMSIZ);
4635 	}
4636 
4637 	d->bd_comp_count = bd->bd_bcs.bcs_count_compressed_prefix;
4638 	d->bd_comp_size = bd->bd_bcs.bcs_total_compressed_prefix_size;
4639 
4640 	d->bd_scnt = bd->bd_scnt;
4641 	d->bd_hcnt = bd->bd_hcnt;
4642 
4643 	d->bd_read_count = bd->bd_bcs.bcs_total_read;
4644 	d->bd_fsize = bd->bd_bcs.bcs_total_size;
4645 }
4646 
4647 /*
4648  * Handle `netstat -B' stats request
4649  */
4650 static int
4651 sysctl_bpf_stats SYSCTL_HANDLER_ARGS
4652 {
4653 	int error;
4654 	struct xbpf_d *xbdbuf;
4655 	unsigned int x_cnt;
4656 	vm_size_t buf_size;
4657 
4658 	if (req->oldptr == USER_ADDR_NULL) {
4659 		return SYSCTL_OUT(req, 0, nbpfilter * sizeof(struct xbpf_d));
4660 	}
4661 	if (nbpfilter == 0) {
4662 		return SYSCTL_OUT(req, 0, 0);
4663 	}
4664 	buf_size = req->oldlen;
4665 	if (buf_size > BPF_MAX_DEVICES * sizeof(struct xbpf_d)) {
4666 		buf_size = BPF_MAX_DEVICES * sizeof(struct xbpf_d);
4667 	}
4668 	xbdbuf = kalloc_data(buf_size, Z_WAITOK | Z_ZERO);
4669 
4670 	lck_mtx_lock(bpf_mlock);
4671 	if (buf_size < (nbpfilter * sizeof(struct xbpf_d))) {
4672 		lck_mtx_unlock(bpf_mlock);
4673 		kfree_data(xbdbuf, buf_size);
4674 		return ENOMEM;
4675 	}
4676 	x_cnt = 0;
4677 	unsigned int i;
4678 
4679 	for (i = 0; i < nbpfilter; i++) {
4680 		struct bpf_d *bd = bpf_dtab[i];
4681 		struct xbpf_d *xbd;
4682 
4683 		if (bd == NULL || bd == BPF_DEV_RESERVED ||
4684 		    (bd->bd_flags & BPF_CLOSING) != 0) {
4685 			continue;
4686 		}
4687 		VERIFY(x_cnt < nbpfilter);
4688 
4689 		xbd = &xbdbuf[x_cnt++];
4690 		bpfstats_fill_xbpf(xbd, bd);
4691 	}
4692 	lck_mtx_unlock(bpf_mlock);
4693 
4694 	error = SYSCTL_OUT(req, xbdbuf, x_cnt * sizeof(struct xbpf_d));
4695 	kfree_data(xbdbuf, buf_size);
4696 	return error;
4697 }
4698