xref: /xnu-11215.41.3/bsd/kern/uipc_socket2.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 1998-2020 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 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30  * Copyright (c) 1982, 1986, 1988, 1990, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. All advertising materials mentioning features or use of this software
42  *    must display the following acknowledgement:
43  *	This product includes software developed by the University of
44  *	California, Berkeley and its contributors.
45  * 4. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)uipc_socket2.c	8.1 (Berkeley) 6/10/93
62  */
63 /*
64  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65  * support for mandatory and extensible security protections.  This notice
66  * is included in support of clause 2.2 (b) of the Apple Public License,
67  * Version 2.0.
68  */
69 
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/domain.h>
73 #include <sys/kernel.h>
74 #include <sys/proc_internal.h>
75 #include <sys/kauth.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/mcache.h>
79 #include <sys/protosw.h>
80 #include <sys/stat.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
84 #include <sys/sysctl.h>
85 #include <sys/syslog.h>
86 #include <sys/unpcb.h>
87 #include <sys/ev.h>
88 #include <kern/locks.h>
89 #include <net/route.h>
90 #include <net/content_filter.h>
91 #include <netinet/in.h>
92 #include <netinet/in_pcb.h>
93 #include <netinet/tcp_var.h>
94 #include <sys/kdebug.h>
95 #include <libkern/OSAtomic.h>
96 #include <net/droptap.h>
97 
98 #if CONFIG_MACF
99 #include <security/mac_framework.h>
100 #endif
101 
102 #include <mach/vm_param.h>
103 
104 #if MPTCP
105 #include <netinet/mptcp_var.h>
106 #endif
107 
108 #include <net/sockaddr_utils.h>
109 
110 extern uint32_t net_wake_pkt_debug;
111 
112 #define DBG_FNC_SBDROP          NETDBG_CODE(DBG_NETSOCK, 4)
113 #define DBG_FNC_SBAPPEND        NETDBG_CODE(DBG_NETSOCK, 5)
114 
115 SYSCTL_DECL(_kern_ipc);
116 
117 __private_extern__ u_int32_t net_io_policy_throttle_best_effort = 0;
118 SYSCTL_INT(_kern_ipc, OID_AUTO, throttle_best_effort,
119     CTLFLAG_RW | CTLFLAG_LOCKED, &net_io_policy_throttle_best_effort, 0, "");
120 
121 static inline void sbcompress(struct sockbuf *, struct mbuf *, struct mbuf *);
122 static struct socket *sonewconn_internal(struct socket *, int);
123 static int sbappendcontrol_internal(struct sockbuf *, struct mbuf *,
124     struct mbuf *);
125 static void soevent_ifdenied(struct socket *);
126 
127 static int sbappendrecord_common(struct sockbuf *sb, struct mbuf *m0, boolean_t nodrop);
128 static int sbappend_common(struct sockbuf *sb, struct mbuf *m, boolean_t nodrop);
129 
130 /*
131  * Primitive routines for operating on sockets and socket buffers
132  */
133 static int soqlimitcompat = 1;
134 static int soqlencomp = 0;
135 
136 /*
137  * Based on the number of mbuf clusters configured, high_sb_max and sb_max can
138  * get scaled up or down to suit that memory configuration. high_sb_max is a
139  * higher limit on sb_max that is checked when sb_max gets set through sysctl.
140  */
141 uint32_t       sb_max = SB_MAX;
142 uint32_t       high_sb_max = SB_MAX;
143 
144 static uint32_t sb_efficiency = 8;    /* parameter for sbreserve() */
145 
146 uint32_t net_io_policy_log = 0;        /* log socket policy changes */
147 #if CONFIG_PROC_UUID_POLICY
148 uint32_t net_io_policy_uuid = 1;       /* enable UUID socket policy */
149 #endif /* CONFIG_PROC_UUID_POLICY */
150 
151 /*
152  * Procedures to manipulate state flags of socket
153  * and do appropriate wakeups.  Normal sequence from the
154  * active (originating) side is that soisconnecting() is
155  * called during processing of connect() call,
156  * resulting in an eventual call to soisconnected() if/when the
157  * connection is established.  When the connection is torn down
158  * soisdisconnecting() is called during processing of disconnect() call,
159  * and soisdisconnected() is called when the connection to the peer
160  * is totally severed.  The semantics of these routines are such that
161  * connectionless protocols can call soisconnected() and soisdisconnected()
162  * only, bypassing the in-progress calls when setting up a ``connection''
163  * takes no time.
164  *
165  * From the passive side, a socket is created with
166  * two queues of sockets: so_incomp for connections in progress
167  * and so_comp for connections already made and awaiting user acceptance.
168  * As a protocol is preparing incoming connections, it creates a socket
169  * structure queued on so_incomp by calling sonewconn().  When the connection
170  * is established, soisconnected() is called, and transfers the
171  * socket structure to so_comp, making it available to accept().
172  *
173  * If a socket is closed with sockets on either
174  * so_incomp or so_comp, these sockets are dropped.
175  *
176  * If higher level protocols are implemented in
177  * the kernel, the wakeups done here will sometimes
178  * cause software-interrupt process scheduling.
179  */
180 void
soisconnecting(struct socket * so)181 soisconnecting(struct socket *so)
182 {
183 	so->so_state &= ~(SS_ISCONNECTED | SS_ISDISCONNECTING);
184 	so->so_state |= SS_ISCONNECTING;
185 
186 	sflt_notify(so, sock_evt_connecting, NULL);
187 }
188 
189 void
soisconnected(struct socket * so)190 soisconnected(struct socket *so)
191 {
192 	/*
193 	 * If socket is subject to filter and is pending initial verdict,
194 	 * delay marking socket as connected and do not present the connected
195 	 * socket to user just yet.
196 	 */
197 	if (cfil_sock_connected_pending_verdict(so)) {
198 		return;
199 	}
200 
201 	so->so_state &= ~(SS_ISCONNECTING | SS_ISDISCONNECTING | SS_ISCONFIRMING);
202 	so->so_state |= SS_ISCONNECTED;
203 
204 	soreserve_preconnect(so, 0);
205 
206 	sflt_notify(so, sock_evt_connected, NULL);
207 
208 	if (so->so_head != NULL && (so->so_state & SS_INCOMP)) {
209 		struct socket *head = so->so_head;
210 		int locked = 0;
211 
212 		/*
213 		 * Enforce lock order when the protocol has per socket locks
214 		 */
215 		if (head->so_proto->pr_getlock != NULL) {
216 			socket_lock(head, 1);
217 			so_acquire_accept_list(head, so);
218 			locked = 1;
219 		}
220 		if (so->so_head == head && (so->so_state & SS_INCOMP)) {
221 			so->so_state &= ~SS_INCOMP;
222 			so->so_state |= SS_COMP;
223 			TAILQ_REMOVE(&head->so_incomp, so, so_list);
224 			TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
225 			head->so_incqlen--;
226 
227 			/*
228 			 * We have to release the accept list in
229 			 * case a socket callback calls sock_accept()
230 			 */
231 			if (locked != 0) {
232 				so_release_accept_list(head);
233 				socket_unlock(so, 0);
234 			}
235 			sorwakeup(head);
236 			wakeup_one((caddr_t)&head->so_timeo);
237 
238 			if (locked != 0) {
239 				socket_unlock(head, 1);
240 				socket_lock(so, 0);
241 			}
242 		} else if (locked != 0) {
243 			so_release_accept_list(head);
244 			socket_unlock(head, 1);
245 		}
246 	} else {
247 		wakeup((caddr_t)&so->so_timeo);
248 		sorwakeup(so);
249 		sowwakeup(so);
250 		soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_CONNECTED |
251 		    SO_FILT_HINT_CONNINFO_UPDATED);
252 	}
253 }
254 
255 boolean_t
socanwrite(struct socket * so)256 socanwrite(struct socket *so)
257 {
258 	return (so->so_state & SS_ISCONNECTED) ||
259 	       !(so->so_proto->pr_flags & PR_CONNREQUIRED) ||
260 	       (so->so_flags1 & SOF1_PRECONNECT_DATA);
261 }
262 
263 void
soisdisconnecting(struct socket * so)264 soisdisconnecting(struct socket *so)
265 {
266 	so->so_state &= ~SS_ISCONNECTING;
267 	so->so_state |= (SS_ISDISCONNECTING | SS_CANTRCVMORE | SS_CANTSENDMORE);
268 	soevent(so, SO_FILT_HINT_LOCKED);
269 	sflt_notify(so, sock_evt_disconnecting, NULL);
270 	wakeup((caddr_t)&so->so_timeo);
271 	sowwakeup(so);
272 	sorwakeup(so);
273 }
274 
275 void
soisdisconnected(struct socket * so)276 soisdisconnected(struct socket *so)
277 {
278 	so->so_state &= ~(SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING);
279 	so->so_state |= (SS_CANTRCVMORE | SS_CANTSENDMORE | SS_ISDISCONNECTED);
280 	soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_DISCONNECTED |
281 	    SO_FILT_HINT_CONNINFO_UPDATED);
282 	sflt_notify(so, sock_evt_disconnected, NULL);
283 	wakeup((caddr_t)&so->so_timeo);
284 	sowwakeup(so);
285 	sorwakeup(so);
286 
287 #if CONTENT_FILTER
288 	/* Notify content filters as soon as we cannot send/receive data */
289 	cfil_sock_notify_shutdown(so, SHUT_RDWR);
290 #endif /* CONTENT_FILTER */
291 }
292 
293 /*
294  * This function will issue a wakeup like soisdisconnected but it will not
295  * notify the socket filters. This will avoid unlocking the socket
296  * in the midst of closing it.
297  */
298 void
sodisconnectwakeup(struct socket * so)299 sodisconnectwakeup(struct socket *so)
300 {
301 	so->so_state &= ~(SS_ISCONNECTING | SS_ISCONNECTED | SS_ISDISCONNECTING);
302 	so->so_state |= (SS_CANTRCVMORE | SS_CANTSENDMORE | SS_ISDISCONNECTED);
303 	soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_DISCONNECTED |
304 	    SO_FILT_HINT_CONNINFO_UPDATED);
305 	wakeup((caddr_t)&so->so_timeo);
306 	sowwakeup(so);
307 	sorwakeup(so);
308 
309 #if CONTENT_FILTER
310 	/* Notify content filters as soon as we cannot send/receive data */
311 	cfil_sock_notify_shutdown(so, SHUT_RDWR);
312 #endif /* CONTENT_FILTER */
313 }
314 
315 /*
316  * When an attempt at a new connection is noted on a socket
317  * which accepts connections, sonewconn is called.  If the
318  * connection is possible (subject to space constraints, etc.)
319  * then we allocate a new structure, propoerly linked into the
320  * data structure of the original socket, and return this.
321  * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
322  */
323 static struct socket *
sonewconn_internal(struct socket * head,int connstatus)324 sonewconn_internal(struct socket *head, int connstatus)
325 {
326 	int so_qlen, error = 0;
327 	struct socket *so;
328 	lck_mtx_t *mutex_held;
329 
330 	if (head->so_proto->pr_getlock != NULL) {
331 		mutex_held = (*head->so_proto->pr_getlock)(head, 0);
332 	} else {
333 		mutex_held = head->so_proto->pr_domain->dom_mtx;
334 	}
335 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
336 
337 	if (!soqlencomp) {
338 		/*
339 		 * This is the default case; so_qlen represents the
340 		 * sum of both incomplete and completed queues.
341 		 */
342 		so_qlen = head->so_qlen;
343 	} else {
344 		/*
345 		 * When kern.ipc.soqlencomp is set to 1, so_qlen
346 		 * represents only the completed queue.  Since we
347 		 * cannot let the incomplete queue goes unbounded
348 		 * (in case of SYN flood), we cap the incomplete
349 		 * queue length to at most somaxconn, and use that
350 		 * as so_qlen so that we fail immediately below.
351 		 */
352 		so_qlen = head->so_qlen - head->so_incqlen;
353 		if (head->so_incqlen > somaxconn) {
354 			so_qlen = somaxconn;
355 		}
356 	}
357 
358 	if (so_qlen >=
359 	    (soqlimitcompat ? head->so_qlimit : (3 * head->so_qlimit / 2))) {
360 		return (struct socket *)0;
361 	}
362 	so = soalloc(1, SOCK_DOM(head), head->so_type);
363 	if (so == NULL) {
364 		return (struct socket *)0;
365 	}
366 	/* check if head was closed during the soalloc */
367 	if (head->so_proto == NULL) {
368 		sodealloc(so);
369 		return (struct socket *)0;
370 	}
371 
372 	so->so_type = head->so_type;
373 	so->so_family = head->so_family;
374 	so->so_protocol = head->so_protocol;
375 	so->so_options = head->so_options & ~SO_ACCEPTCONN;
376 	so->so_linger = head->so_linger;
377 	so->so_state = head->so_state | SS_NOFDREF;
378 	so->so_proto = head->so_proto;
379 	so->so_timeo = head->so_timeo;
380 	so->so_pgid  = head->so_pgid;
381 	kauth_cred_ref(head->so_cred);
382 	so->so_cred = head->so_cred;
383 	so->so_persona_id = head->so_persona_id;
384 	so->last_pid = head->last_pid;
385 	so->last_upid = head->last_upid;
386 	memcpy(so->last_uuid, head->last_uuid, sizeof(so->last_uuid));
387 	if (head->so_flags & SOF_DELEGATED) {
388 		so->e_pid = head->e_pid;
389 		so->e_upid = head->e_upid;
390 		memcpy(so->e_uuid, head->e_uuid, sizeof(so->e_uuid));
391 	}
392 	/* inherit socket options stored in so_flags */
393 	so->so_flags = head->so_flags &
394 	    (SOF_NOSIGPIPE | SOF_NOADDRAVAIL | SOF_REUSESHAREUID |
395 	    SOF_NOTIFYCONFLICT | SOF_BINDRANDOMPORT | SOF_NPX_SETOPTSHUT |
396 	    SOF_NODEFUNCT | SOF_PRIVILEGED_TRAFFIC_CLASS | SOF_NOTSENT_LOWAT |
397 	    SOF_DELEGATED);
398 	so->so_flags1 |= SOF1_INBOUND;
399 	so->so_usecount = 1;
400 	so->next_lock_lr = 0;
401 	so->next_unlock_lr = 0;
402 
403 	so->so_rcv.sb_flags |= SB_RECV; /* XXX */
404 	so->so_rcv.sb_so = so->so_snd.sb_so = so;
405 
406 	/* inherit traffic management properties of listener */
407 	so->so_flags1 |=
408 	    head->so_flags1 & (SOF1_TRAFFIC_MGT_SO_BACKGROUND | SOF1_TC_NET_SERV_TYPE |
409 	    SOF1_QOSMARKING_ALLOWED | SOF1_QOSMARKING_POLICY_OVERRIDE);
410 	so->so_background_thread = head->so_background_thread;
411 	so->so_traffic_class = head->so_traffic_class;
412 	so->so_netsvctype = head->so_netsvctype;
413 
414 	if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
415 		sodealloc(so);
416 		return (struct socket *)0;
417 	}
418 	so->so_rcv.sb_flags |= (head->so_rcv.sb_flags & SB_USRSIZE);
419 	so->so_snd.sb_flags |= (head->so_snd.sb_flags & SB_USRSIZE);
420 
421 	/*
422 	 * Must be done with head unlocked to avoid deadlock
423 	 * for protocol with per socket mutexes.
424 	 */
425 	if (head->so_proto->pr_unlock) {
426 		socket_unlock(head, 0);
427 	}
428 	if (((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL) != 0) ||
429 	    error) {
430 		sodealloc(so);
431 		if (head->so_proto->pr_unlock) {
432 			socket_lock(head, 0);
433 		}
434 		return (struct socket *)0;
435 	}
436 	if (head->so_proto->pr_unlock) {
437 		socket_lock(head, 0);
438 		/*
439 		 * Radar 7385998 Recheck that the head is still accepting
440 		 * to avoid race condition when head is getting closed.
441 		 */
442 		if ((head->so_options & SO_ACCEPTCONN) == 0) {
443 			so->so_state &= ~SS_NOFDREF;
444 			soclose(so);
445 			return (struct socket *)0;
446 		}
447 	}
448 
449 	if (so->so_proto->pr_copy_last_owner != NULL) {
450 		(*so->so_proto->pr_copy_last_owner)(so, head);
451 	}
452 	os_atomic_inc(&so->so_proto->pr_domain->dom_refs, relaxed);
453 
454 	/* Insert in head appropriate lists */
455 	so_acquire_accept_list(head, NULL);
456 
457 	so->so_head = head;
458 
459 	/*
460 	 * Since this socket is going to be inserted into the incomp
461 	 * queue, it can be picked up by another thread in
462 	 * tcp_dropdropablreq to get dropped before it is setup..
463 	 * To prevent this race, set in-progress flag which can be
464 	 * cleared later
465 	 */
466 	so->so_flags |= SOF_INCOMP_INPROGRESS;
467 
468 	if (connstatus) {
469 		TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
470 		so->so_state |= SS_COMP;
471 	} else {
472 		TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
473 		so->so_state |= SS_INCOMP;
474 		head->so_incqlen++;
475 	}
476 	head->so_qlen++;
477 
478 	so_release_accept_list(head);
479 
480 	/* Attach socket filters for this protocol */
481 	sflt_initsock(so);
482 
483 	if (connstatus) {
484 		so->so_state |= (short)connstatus;
485 		sorwakeup(head);
486 		wakeup((caddr_t)&head->so_timeo);
487 	}
488 	return so;
489 }
490 
491 
492 struct socket *
sonewconn(struct socket * head,int connstatus,const struct sockaddr * from)493 sonewconn(struct socket *head, int connstatus, const struct sockaddr *from)
494 {
495 	int error = sflt_connectin(head, from);
496 	if (error) {
497 		return NULL;
498 	}
499 
500 	return sonewconn_internal(head, connstatus);
501 }
502 
503 /*
504  * Socantsendmore indicates that no more data will be sent on the
505  * socket; it would normally be applied to a socket when the user
506  * informs the system that no more data is to be sent, by the protocol
507  * code (in case PRU_SHUTDOWN).  Socantrcvmore indicates that no more data
508  * will be received, and will normally be applied to the socket by a
509  * protocol when it detects that the peer will send no more data.
510  * Data queued for reading in the socket may yet be read.
511  */
512 
513 void
socantsendmore(struct socket * so)514 socantsendmore(struct socket *so)
515 {
516 	so->so_state |= SS_CANTSENDMORE;
517 	soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_CANTSENDMORE);
518 	sflt_notify(so, sock_evt_cantsendmore, NULL);
519 	sowwakeup(so);
520 }
521 
522 void
socantrcvmore(struct socket * so)523 socantrcvmore(struct socket *so)
524 {
525 	so->so_state |= SS_CANTRCVMORE;
526 	soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_CANTRCVMORE);
527 	sflt_notify(so, sock_evt_cantrecvmore, NULL);
528 	sorwakeup(so);
529 }
530 
531 /*
532  * Wait for data to arrive at/drain from a socket buffer.
533  */
534 int
sbwait(struct sockbuf * sb)535 sbwait(struct sockbuf *sb)
536 {
537 	boolean_t nointr = (sb->sb_flags & SB_NOINTR);
538 	void *__single lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
539 	struct socket *so = sb->sb_so;
540 	lck_mtx_t *mutex_held;
541 	struct timespec ts;
542 	int error = 0;
543 
544 	if (so == NULL) {
545 		panic("%s: null so, sb=%p sb_flags=0x%x lr=%p",
546 		    __func__, sb, sb->sb_flags, lr_saved);
547 		/* NOTREACHED */
548 	} else if (so->so_usecount < 1) {
549 		panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
550 		    "lrh= %s\n", __func__, sb, sb->sb_flags, so,
551 		    so->so_usecount, lr_saved, solockhistory_nr(so));
552 		/* NOTREACHED */
553 	}
554 
555 	if ((so->so_state & SS_DRAINING) || (so->so_flags & SOF_DEFUNCT)) {
556 		error = EBADF;
557 		if (so->so_flags & SOF_DEFUNCT) {
558 			SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llu [%d,%d] "
559 			    "(%d)\n", __func__, proc_selfpid(),
560 			    proc_best_name(current_proc()),
561 			    so->so_gencnt,
562 			    SOCK_DOM(so), SOCK_TYPE(so), error);
563 		}
564 		return error;
565 	}
566 
567 	if (so->so_proto->pr_getlock != NULL) {
568 		mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
569 	} else {
570 		mutex_held = so->so_proto->pr_domain->dom_mtx;
571 	}
572 
573 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
574 
575 	ts.tv_sec = sb->sb_timeo.tv_sec;
576 	ts.tv_nsec = sb->sb_timeo.tv_usec * 1000;
577 
578 	sb->sb_waiters++;
579 	VERIFY(sb->sb_waiters != 0);
580 
581 	error = msleep((caddr_t)&sb->sb_cc, mutex_held,
582 	    nointr ? PSOCK : PSOCK | PCATCH,
583 	    nointr ? "sbwait_nointr" : "sbwait", &ts);
584 
585 	VERIFY(sb->sb_waiters != 0);
586 	sb->sb_waiters--;
587 
588 	if (so->so_usecount < 1) {
589 		panic("%s: 2 sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
590 		    "lrh= %s\n", __func__, sb, sb->sb_flags, so,
591 		    so->so_usecount, lr_saved, solockhistory_nr(so));
592 		/* NOTREACHED */
593 	}
594 
595 	if ((so->so_state & SS_DRAINING) || (so->so_flags & SOF_DEFUNCT)) {
596 		error = EBADF;
597 		if (so->so_flags & SOF_DEFUNCT) {
598 			SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llu [%d,%d] "
599 			    "(%d)\n", __func__, proc_selfpid(),
600 			    proc_best_name(current_proc()),
601 			    so->so_gencnt,
602 			    SOCK_DOM(so), SOCK_TYPE(so), error);
603 		}
604 	}
605 
606 	return error;
607 }
608 
609 void
sbwakeup(struct sockbuf * sb)610 sbwakeup(struct sockbuf *sb)
611 {
612 	if (sb->sb_waiters > 0) {
613 		wakeup((caddr_t)&sb->sb_cc);
614 	}
615 }
616 
617 /*
618  * Wakeup processes waiting on a socket buffer.
619  * Do asynchronous notification via SIGIO
620  * if the socket has the SS_ASYNC flag set.
621  */
622 void
sowakeup(struct socket * so,struct sockbuf * sb,struct socket * so2)623 sowakeup(struct socket *so, struct sockbuf *sb, struct socket *so2)
624 {
625 	if (so->so_flags & SOF_DEFUNCT) {
626 		SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llu [%d,%d] si 0x%x, "
627 		    "fl 0x%x [%s]\n", __func__, proc_selfpid(),
628 		    proc_best_name(current_proc()),
629 		    so->so_gencnt, SOCK_DOM(so),
630 		    SOCK_TYPE(so), (uint32_t)sb->sb_sel.si_flags, sb->sb_flags,
631 		    (sb->sb_flags & SB_RECV) ? "rcv" : "snd");
632 	}
633 
634 	sb->sb_flags &= ~SB_SEL;
635 	selwakeup(&sb->sb_sel);
636 	sbwakeup(sb);
637 	if (so->so_state & SS_ASYNC) {
638 		if (so->so_pgid < 0) {
639 			gsignal(-so->so_pgid, SIGIO);
640 		} else if (so->so_pgid > 0) {
641 			proc_signal(so->so_pgid, SIGIO);
642 		}
643 	}
644 	if (sb->sb_flags & SB_KNOTE) {
645 		KNOTE(&sb->sb_sel.si_note, SO_FILT_HINT_LOCKED);
646 	}
647 	if (sb->sb_flags & SB_UPCALL) {
648 		void (*sb_upcall)(struct socket *, void *, int);
649 		caddr_t __single sb_upcallarg;
650 		int lock = !(sb->sb_flags & SB_UPCALL_LOCK);
651 
652 		sb_upcall = sb->sb_upcall;
653 		sb_upcallarg = sb->sb_upcallarg;
654 		/* Let close know that we're about to do an upcall */
655 		so->so_upcallusecount++;
656 
657 		if (lock) {
658 			if (so2) {
659 				struct unpcb *unp = sotounpcb(so2);
660 				unp->unp_flags |= UNP_DONTDISCONNECT;
661 				unp->rw_thrcount++;
662 
663 				socket_unlock(so2, 0);
664 			}
665 			socket_unlock(so, 0);
666 		}
667 		(*sb_upcall)(so, sb_upcallarg, M_DONTWAIT);
668 		if (lock) {
669 			if (so2 && so > so2) {
670 				struct unpcb *unp;
671 				socket_lock(so2, 0);
672 
673 				unp = sotounpcb(so2);
674 				unp->rw_thrcount--;
675 				if (unp->rw_thrcount == 0) {
676 					unp->unp_flags &= ~UNP_DONTDISCONNECT;
677 					wakeup(unp);
678 				}
679 			}
680 
681 			socket_lock(so, 0);
682 
683 			if (so2 && so < so2) {
684 				struct unpcb *unp;
685 				socket_lock(so2, 0);
686 
687 				unp = sotounpcb(so2);
688 				unp->rw_thrcount--;
689 				if (unp->rw_thrcount == 0) {
690 					unp->unp_flags &= ~UNP_DONTDISCONNECT;
691 					wakeup(unp);
692 				}
693 			}
694 		}
695 
696 		so->so_upcallusecount--;
697 		/* Tell close that it's safe to proceed */
698 		if ((so->so_flags & SOF_CLOSEWAIT) &&
699 		    so->so_upcallusecount == 0) {
700 			wakeup((caddr_t)&so->so_upcallusecount);
701 		}
702 	}
703 #if CONTENT_FILTER
704 	/*
705 	 * Trap disconnection events for content filters
706 	 */
707 	if ((so->so_flags & SOF_CONTENT_FILTER) != 0) {
708 		if ((sb->sb_flags & SB_RECV)) {
709 			if (so->so_state & (SS_CANTRCVMORE)) {
710 				cfil_sock_notify_shutdown(so, SHUT_RD);
711 			}
712 		} else {
713 			if (so->so_state & (SS_CANTSENDMORE)) {
714 				cfil_sock_notify_shutdown(so, SHUT_WR);
715 			}
716 		}
717 	}
718 #endif /* CONTENT_FILTER */
719 }
720 
721 /*
722  * Socket buffer (struct sockbuf) utility routines.
723  *
724  * Each socket contains two socket buffers: one for sending data and
725  * one for receiving data.  Each buffer contains a queue of mbufs,
726  * information about the number of mbufs and amount of data in the
727  * queue, and other fields allowing select() statements and notification
728  * on data availability to be implemented.
729  *
730  * Data stored in a socket buffer is maintained as a list of records.
731  * Each record is a list of mbufs chained together with the m_next
732  * field.  Records are chained together with the m_nextpkt field. The upper
733  * level routine soreceive() expects the following conventions to be
734  * observed when placing information in the receive buffer:
735  *
736  * 1. If the protocol requires each message be preceded by the sender's
737  *    name, then a record containing that name must be present before
738  *    any associated data (mbuf's must be of type MT_SONAME).
739  * 2. If the protocol supports the exchange of ``access rights'' (really
740  *    just additional data associated with the message), and there are
741  *    ``rights'' to be received, then a record containing this data
742  *    should be present (mbuf's must be of type MT_RIGHTS).
743  * 3. If a name or rights record exists, then it must be followed by
744  *    a data record, perhaps of zero length.
745  *
746  * Before using a new socket structure it is first necessary to reserve
747  * buffer space to the socket, by calling sbreserve().  This should commit
748  * some of the available buffer space in the system buffer pool for the
749  * socket (currently, it does nothing but enforce limits).  The space
750  * should be released by calling sbrelease() when the socket is destroyed.
751  */
752 
753 /*
754  * Returns:	0			Success
755  *		ENOBUFS
756  */
757 int
soreserve(struct socket * so,uint32_t sndcc,uint32_t rcvcc)758 soreserve(struct socket *so, uint32_t sndcc, uint32_t rcvcc)
759 {
760 	if (sbreserve(&so->so_snd, sndcc) == 0) {
761 		goto bad;
762 	} else {
763 		so->so_snd.sb_idealsize = sndcc;
764 	}
765 
766 	if (sbreserve(&so->so_rcv, rcvcc) == 0) {
767 		goto bad2;
768 	} else {
769 		so->so_rcv.sb_idealsize = rcvcc;
770 	}
771 
772 	if (so->so_rcv.sb_lowat == 0) {
773 		so->so_rcv.sb_lowat = 1;
774 	}
775 	if (so->so_snd.sb_lowat == 0) {
776 		so->so_snd.sb_lowat = MCLBYTES;
777 	}
778 	if (so->so_snd.sb_lowat > so->so_snd.sb_hiwat) {
779 		so->so_snd.sb_lowat = so->so_snd.sb_hiwat;
780 	}
781 	return 0;
782 bad2:
783 	so->so_snd.sb_flags &= ~SB_SEL;
784 	selthreadclear(&so->so_snd.sb_sel);
785 	sbrelease(&so->so_snd);
786 bad:
787 	return ENOBUFS;
788 }
789 
790 void
soreserve_preconnect(struct socket * so,unsigned int pre_cc)791 soreserve_preconnect(struct socket *so, unsigned int pre_cc)
792 {
793 	/* As of now, same bytes for both preconnect read and write */
794 	so->so_snd.sb_preconn_hiwat = pre_cc;
795 	so->so_rcv.sb_preconn_hiwat = pre_cc;
796 }
797 
798 /*
799  * Allot mbufs to a sockbuf.
800  * Attempt to scale mbmax so that mbcnt doesn't become limiting
801  * if buffering efficiency is near the normal case.
802  */
803 int
sbreserve(struct sockbuf * sb,uint32_t cc)804 sbreserve(struct sockbuf *sb, uint32_t cc)
805 {
806 	if (cc > sb_max) {
807 		/* We would not end up changing sb_cc, so return 0 */
808 		if (sb->sb_hiwat == sb_max) {
809 			return 0;
810 		}
811 		cc = sb_max;
812 	}
813 	if (cc > sb->sb_hiwat && (sb->sb_flags & SB_LIMITED)) {
814 		return 0;
815 	}
816 	sb->sb_hiwat = cc;
817 	sb->sb_mbmax = cc * sb_efficiency;
818 	if (sb->sb_lowat > sb->sb_hiwat) {
819 		sb->sb_lowat = sb->sb_hiwat;
820 	}
821 	return 1;
822 }
823 
824 /*
825  * Free mbufs held by a socket, and reserved mbuf space.
826  */
827 /*  WARNING needs to do selthreadclear() before calling this */
828 void
sbrelease(struct sockbuf * sb)829 sbrelease(struct sockbuf *sb)
830 {
831 	sbflush(sb);
832 	sb->sb_hiwat = 0;
833 	sb->sb_mbmax = 0;
834 }
835 
836 void
so_update_tx_data_stats(struct socket * so,uint32_t num_pkts,uint32_t space)837 so_update_tx_data_stats(struct socket *so, uint32_t num_pkts, uint32_t space)
838 {
839 	so->so_tc_stats[SO_STATS_DATA].txpackets += num_pkts;
840 	so->so_tc_stats[SO_STATS_DATA].txbytes += space;
841 }
842 
843 static void
sb_update_data_stats(struct sockbuf * sb,uint32_t space)844 sb_update_data_stats(struct sockbuf *sb, uint32_t space)
845 {
846 	if (sb->sb_flags & SB_RECV) {
847 		sb->sb_so->so_tc_stats[SO_STATS_DATA].rxpackets += 1;
848 		sb->sb_so->so_tc_stats[SO_STATS_DATA].rxbytes += space;
849 	} else {
850 		sb->sb_so->so_tc_stats[SO_STATS_DATA].txpackets += 1;
851 		sb->sb_so->so_tc_stats[SO_STATS_DATA].txbytes += space;
852 	}
853 }
854 
855 static void
sb_update_no_space_stats(struct sockbuf * sb,uint32_t space)856 sb_update_no_space_stats(struct sockbuf *sb, uint32_t space)
857 {
858 	if (sb->sb_flags & SB_RECV) {
859 		sb->sb_so->so_tc_stats[SO_STATS_SBNOSPACE].rxpackets += 1;
860 		sb->sb_so->so_tc_stats[SO_STATS_SBNOSPACE].rxbytes += space;
861 	} else {
862 		sb->sb_so->so_tc_stats[SO_STATS_SBNOSPACE].txpackets += 1;
863 		sb->sb_so->so_tc_stats[SO_STATS_SBNOSPACE].txbytes += space;
864 	}
865 }
866 
867 /*
868  * Routines to add and remove
869  * data from an mbuf queue.
870  *
871  * The routines sbappend() or sbappendrecord() are normally called to
872  * append new mbufs to a socket buffer, after checking that adequate
873  * space is available, comparing the function sbspace() with the amount
874  * of data to be added.  sbappendrecord() differs from sbappend() in
875  * that data supplied is treated as the beginning of a new record.
876  * To place a sender's address, optional access rights, and data in a
877  * socket receive buffer, sbappendaddr() should be used.  To place
878  * access rights and data in a socket receive buffer, sbappendrights()
879  * should be used.  In either case, the new data begins a new record.
880  * Note that unlike sbappend() and sbappendrecord(), these routines check
881  * for the caller that there will be enough space to store the data.
882  * Each fails if there is not enough space, or if it cannot find mbufs
883  * to store additional information in.
884  *
885  * Reliable protocols may use the socket send buffer to hold data
886  * awaiting acknowledgement.  Data is normally copied from a socket
887  * send buffer in a protocol with m_copy for output to a peer,
888  * and then removing the data from the socket buffer with sbdrop()
889  * or sbdroprecord() when the data is acknowledged by the peer.
890  */
891 
892 /*
893  * Append mbuf chain m to the last record in the
894  * socket buffer sb.  The additional space associated
895  * the mbuf chain is recorded in sb.  Empty mbufs are
896  * discarded and mbufs are compacted where possible.
897  */
898 static int
sbappend_common(struct sockbuf * sb,struct mbuf * m,boolean_t nodrop)899 sbappend_common(struct sockbuf *sb, struct mbuf *m, boolean_t nodrop)
900 {
901 	struct socket *__single so = sb->sb_so;
902 	struct soflow_hash_entry *__single dgram_flow_entry = NULL;
903 
904 	if (m == NULL || (sb->sb_flags & SB_DROP)) {
905 		if (m != NULL && !nodrop) {
906 			m_freem(m);
907 		}
908 		return 0;
909 	}
910 
911 	SBLASTRECORDCHK(sb, "sbappend 1");
912 
913 	if (sb->sb_lastrecord != NULL && (sb->sb_mbtail->m_flags & M_EOR)) {
914 		return sbappendrecord_common(sb, m, nodrop);
915 	}
916 
917 	if (SOCK_DOM(sb->sb_so) == PF_INET || SOCK_DOM(sb->sb_so) == PF_INET6) {
918 		ASSERT(nodrop == FALSE);
919 
920 		if (NEED_DGRAM_FLOW_TRACKING(so)) {
921 			dgram_flow_entry = soflow_get_flow(so, NULL, NULL, NULL,
922 			    m != NULL ? m_length(m) : 0, false,
923 			    (m != NULL && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0);
924 		}
925 
926 		if (sb->sb_flags & SB_RECV && !(m && m->m_flags & M_SKIPCFIL)) {
927 			int error = sflt_data_in(so, NULL, &m, NULL, 0);
928 			SBLASTRECORDCHK(sb, "sbappend 2");
929 
930 #if CONTENT_FILTER
931 			if (error == 0) {
932 				error = cfil_sock_data_in(so, NULL, m, NULL, 0, dgram_flow_entry);
933 			}
934 #endif /* CONTENT_FILTER */
935 
936 			if (error != 0) {
937 				if (error != EJUSTRETURN) {
938 					m_freem(m);
939 				}
940 				if (dgram_flow_entry != NULL) {
941 					soflow_free_flow(dgram_flow_entry);
942 				}
943 				return 0;
944 			}
945 		} else if (m) {
946 			m->m_flags &= ~M_SKIPCFIL;
947 		}
948 
949 		if (dgram_flow_entry != NULL) {
950 			soflow_free_flow(dgram_flow_entry);
951 		}
952 	}
953 
954 	/* If this is the first record, it's also the last record */
955 	if (sb->sb_lastrecord == NULL) {
956 		sb->sb_lastrecord = m;
957 	}
958 
959 	sbcompress(sb, m, sb->sb_mbtail);
960 	SBLASTRECORDCHK(sb, "sbappend 3");
961 	return 1;
962 }
963 
964 int
sbappend(struct sockbuf * sb,struct mbuf * m)965 sbappend(struct sockbuf *sb, struct mbuf *m)
966 {
967 	return sbappend_common(sb, m, FALSE);
968 }
969 
970 int
sbappend_nodrop(struct sockbuf * sb,struct mbuf * m)971 sbappend_nodrop(struct sockbuf *sb, struct mbuf *m)
972 {
973 	return sbappend_common(sb, m, TRUE);
974 }
975 
976 /*
977  * Similar to sbappend, except that this is optimized for stream sockets.
978  */
979 int
sbappendstream(struct sockbuf * sb,struct mbuf * m)980 sbappendstream(struct sockbuf *sb, struct mbuf *m)
981 {
982 	struct soflow_hash_entry *__single dgram_flow_entry = NULL;
983 	struct socket *__single so = sb->sb_so;
984 
985 	if (m == NULL || (sb->sb_flags & SB_DROP)) {
986 		if (m != NULL) {
987 			m_freem(m);
988 		}
989 		return 0;
990 	}
991 
992 	if (m->m_nextpkt != NULL || (sb->sb_mb != sb->sb_lastrecord)) {
993 		panic("sbappendstream: nexpkt %p || mb %p != lastrecord %p",
994 		    m->m_nextpkt, sb->sb_mb, sb->sb_lastrecord);
995 		/* NOTREACHED */
996 	}
997 
998 	SBLASTMBUFCHK(sb, __func__);
999 
1000 	if (SOCK_DOM(sb->sb_so) == PF_INET || SOCK_DOM(sb->sb_so) == PF_INET6) {
1001 		if (NEED_DGRAM_FLOW_TRACKING(so)) {
1002 			dgram_flow_entry = soflow_get_flow(so, NULL, NULL, NULL,
1003 			    m != NULL ? m_length(m) : 0, false,
1004 			    (m != NULL && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0);
1005 		}
1006 
1007 		if (sb->sb_flags & SB_RECV && !(m && m->m_flags & M_SKIPCFIL)) {
1008 			int error = sflt_data_in(so, NULL, &m, NULL, 0);
1009 			SBLASTRECORDCHK(sb, "sbappendstream 1");
1010 
1011 #if CONTENT_FILTER
1012 			if (error == 0) {
1013 				error = cfil_sock_data_in(so, NULL, m, NULL, 0, dgram_flow_entry);
1014 			}
1015 #endif /* CONTENT_FILTER */
1016 
1017 			if (error != 0) {
1018 				if (error != EJUSTRETURN) {
1019 					m_freem(m);
1020 				}
1021 				if (dgram_flow_entry != NULL) {
1022 					soflow_free_flow(dgram_flow_entry);
1023 				}
1024 				return 0;
1025 			}
1026 		} else if (m) {
1027 			m->m_flags &= ~M_SKIPCFIL;
1028 		}
1029 
1030 		if (dgram_flow_entry != NULL) {
1031 			soflow_free_flow(dgram_flow_entry);
1032 		}
1033 	}
1034 
1035 	sbcompress(sb, m, sb->sb_mbtail);
1036 	sb->sb_lastrecord = sb->sb_mb;
1037 	SBLASTRECORDCHK(sb, "sbappendstream 2");
1038 	return 1;
1039 }
1040 
1041 #ifdef SOCKBUF_DEBUG
1042 void
sbcheck(struct sockbuf * sb)1043 sbcheck(struct sockbuf *sb)
1044 {
1045 	struct mbuf *m;
1046 	struct mbuf *n = 0;
1047 	u_int32_t len = 0, mbcnt = 0;
1048 	lck_mtx_t *mutex_held;
1049 
1050 	if (sb->sb_so->so_proto->pr_getlock != NULL) {
1051 		mutex_held = (*sb->sb_so->so_proto->pr_getlock)(sb->sb_so, 0);
1052 	} else {
1053 		mutex_held = sb->sb_so->so_proto->pr_domain->dom_mtx;
1054 	}
1055 
1056 	LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
1057 
1058 	if (sbchecking == 0) {
1059 		return;
1060 	}
1061 
1062 	for (m = sb->sb_mb; m; m = n) {
1063 		n = m->m_nextpkt;
1064 		for (; m; m = m->m_next) {
1065 			len += m->m_len;
1066 			mbcnt += _MSIZE;
1067 			/* XXX pretty sure this is bogus */
1068 			if (m->m_flags & M_EXT) {
1069 				mbcnt += m->m_ext.ext_size;
1070 			}
1071 		}
1072 	}
1073 	if (len != sb->sb_cc || mbcnt != sb->sb_mbcnt) {
1074 		panic("cc %ld != %ld || mbcnt %ld != %ld", len, sb->sb_cc,
1075 		    mbcnt, sb->sb_mbcnt);
1076 	}
1077 }
1078 #endif
1079 
1080 void
sblastrecordchk(struct sockbuf * sb,const char * where)1081 sblastrecordchk(struct sockbuf *sb, const char *where)
1082 {
1083 	struct mbuf *m = sb->sb_mb;
1084 
1085 	while (m && m->m_nextpkt) {
1086 		m = m->m_nextpkt;
1087 	}
1088 
1089 	if (m != sb->sb_lastrecord) {
1090 		printf("sblastrecordchk: mb 0x%llx lastrecord 0x%llx "
1091 		    "last 0x%llx\n",
1092 		    (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_mb),
1093 		    (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_lastrecord),
1094 		    (uint64_t)VM_KERNEL_ADDRPERM(m));
1095 		printf("packet chain:\n");
1096 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
1097 			printf("\t0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(m));
1098 		}
1099 		panic("sblastrecordchk from %s", where);
1100 	}
1101 }
1102 
1103 void
sblastmbufchk(struct sockbuf * sb,const char * where)1104 sblastmbufchk(struct sockbuf *sb, const char *where)
1105 {
1106 	struct mbuf *m = sb->sb_mb;
1107 	struct mbuf *n;
1108 
1109 	while (m && m->m_nextpkt) {
1110 		m = m->m_nextpkt;
1111 	}
1112 
1113 	while (m && m->m_next) {
1114 		m = m->m_next;
1115 	}
1116 
1117 	if (m != sb->sb_mbtail) {
1118 		printf("sblastmbufchk: mb 0x%llx mbtail 0x%llx last 0x%llx\n",
1119 		    (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_mb),
1120 		    (uint64_t)VM_KERNEL_ADDRPERM(sb->sb_mbtail),
1121 		    (uint64_t)VM_KERNEL_ADDRPERM(m));
1122 		printf("packet tree:\n");
1123 		for (m = sb->sb_mb; m != NULL; m = m->m_nextpkt) {
1124 			printf("\t");
1125 			for (n = m; n != NULL; n = n->m_next) {
1126 				printf("0x%llx ",
1127 				    (uint64_t)VM_KERNEL_ADDRPERM(n));
1128 			}
1129 			printf("\n");
1130 		}
1131 		panic("sblastmbufchk from %s", where);
1132 	}
1133 }
1134 
1135 /*
1136  * Similar to sbappend, except the mbuf chain begins a new record.
1137  */
1138 static int
sbappendrecord_common(struct sockbuf * sb,struct mbuf * m0,boolean_t nodrop)1139 sbappendrecord_common(struct sockbuf *sb, struct mbuf *m0, boolean_t nodrop)
1140 {
1141 	struct soflow_hash_entry *__single dgram_flow_entry = NULL;
1142 	struct socket *__single so = sb->sb_so;
1143 	struct mbuf *m;
1144 	int space = 0;
1145 
1146 	if (m0 == NULL || (sb->sb_flags & SB_DROP)) {
1147 		if (m0 != NULL && nodrop == FALSE) {
1148 			m_freem(m0);
1149 		}
1150 		return 0;
1151 	}
1152 
1153 	for (m = m0; m != NULL; m = m->m_next) {
1154 		space += m->m_len;
1155 	}
1156 
1157 	if (space > sbspace(sb) && !(sb->sb_flags & SB_UNIX)) {
1158 		sb_update_no_space_stats(sb, space);
1159 
1160 		if (nodrop == FALSE) {
1161 			m_freem(m0);
1162 		}
1163 		return 0;
1164 	}
1165 
1166 	if (SOCK_DOM(sb->sb_so) == PF_INET || SOCK_DOM(sb->sb_so) == PF_INET6) {
1167 		ASSERT(nodrop == FALSE);
1168 
1169 		if (NEED_DGRAM_FLOW_TRACKING(so)) {
1170 			dgram_flow_entry = soflow_get_flow(so, NULL, NULL, NULL,
1171 			    m0 != NULL ? m_length(m0) : 0, false,
1172 			    (m0 != NULL && m0->m_pkthdr.rcvif) ? m0->m_pkthdr.rcvif->if_index : 0);
1173 		}
1174 
1175 		if (sb->sb_flags & SB_RECV && !(m0 && m0->m_flags & M_SKIPCFIL)) {
1176 			int error = sflt_data_in(sb->sb_so, NULL, &m0, NULL,
1177 			    sock_data_filt_flag_record);
1178 
1179 #if CONTENT_FILTER
1180 			if (error == 0) {
1181 				error = cfil_sock_data_in(sb->sb_so, NULL, m0, NULL, 0, dgram_flow_entry);
1182 			}
1183 #endif /* CONTENT_FILTER */
1184 
1185 			if (error != 0) {
1186 				SBLASTRECORDCHK(sb, "sbappendrecord 1");
1187 				if (error != EJUSTRETURN) {
1188 					m_freem(m0);
1189 				}
1190 				if (dgram_flow_entry != NULL) {
1191 					soflow_free_flow(dgram_flow_entry);
1192 				}
1193 				return 0;
1194 			}
1195 		} else if (m0) {
1196 			m0->m_flags &= ~M_SKIPCFIL;
1197 		}
1198 
1199 		if (dgram_flow_entry != NULL) {
1200 			soflow_free_flow(dgram_flow_entry);
1201 		}
1202 	}
1203 
1204 	/*
1205 	 * Note this permits zero length records.
1206 	 */
1207 	sballoc(sb, m0);
1208 	SBLASTRECORDCHK(sb, "sbappendrecord 2");
1209 	if (sb->sb_lastrecord != NULL) {
1210 		sb->sb_lastrecord->m_nextpkt = m0;
1211 	} else {
1212 		sb->sb_mb = m0;
1213 	}
1214 	sb->sb_lastrecord = m0;
1215 	sb->sb_mbtail = m0;
1216 
1217 	m = m0->m_next;
1218 	m0->m_next = 0;
1219 	if (m && (m0->m_flags & M_EOR)) {
1220 		m0->m_flags &= ~M_EOR;
1221 		m->m_flags |= M_EOR;
1222 	}
1223 	sbcompress(sb, m, m0);
1224 	SBLASTRECORDCHK(sb, "sbappendrecord 3");
1225 	return 1;
1226 }
1227 
1228 int
sbappendrecord(struct sockbuf * sb,struct mbuf * m0)1229 sbappendrecord(struct sockbuf *sb, struct mbuf *m0)
1230 {
1231 	return sbappendrecord_common(sb, m0, FALSE);
1232 }
1233 
1234 int
sbappendrecord_nodrop(struct sockbuf * sb,struct mbuf * m0)1235 sbappendrecord_nodrop(struct sockbuf *sb, struct mbuf *m0)
1236 {
1237 	return sbappendrecord_common(sb, m0, TRUE);
1238 }
1239 
1240 /*
1241  * Concatenate address (optional), control (optional) and data into one
1242  * single mbuf chain.  If sockbuf *sb is passed in, space check will be
1243  * performed.
1244  *
1245  * Returns:	mbuf chain pointer if succeeded, NULL if failed
1246  */
1247 struct mbuf *
sbconcat_mbufs(struct sockbuf * sb,struct sockaddr * asa,struct mbuf * m0,struct mbuf * control)1248 sbconcat_mbufs(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0, struct mbuf *control)
1249 {
1250 	struct mbuf *m = NULL, *n = NULL;
1251 	int space = 0;
1252 
1253 	if (m0 && (m0->m_flags & M_PKTHDR) == 0) {
1254 		panic("sbconcat_mbufs");
1255 	}
1256 
1257 	if (m0) {
1258 		space += m0->m_pkthdr.len;
1259 	}
1260 	for (n = control; n; n = n->m_next) {
1261 		space += n->m_len;
1262 		if (n->m_next == 0) {   /* keep pointer to last control buf */
1263 			break;
1264 		}
1265 	}
1266 
1267 	if (asa != NULL) {
1268 		_CASSERT(sizeof(asa->sa_len) == sizeof(__uint8_t));
1269 		if (MLEN <= UINT8_MAX && asa->sa_len > MLEN) {
1270 			return NULL;
1271 		}
1272 		space += asa->sa_len;
1273 	}
1274 
1275 	if (sb != NULL && space > sbspace(sb)) {
1276 		sb_update_no_space_stats(sb, space);
1277 
1278 		return NULL;
1279 	}
1280 
1281 	if (n) {
1282 		n->m_next = m0;         /* concatenate data to control */
1283 	} else {
1284 		control = m0;
1285 	}
1286 
1287 	if (asa != NULL) {
1288 		MGET(m, M_DONTWAIT, MT_SONAME);
1289 		if (m == 0) {
1290 			if (n) {
1291 				/* unchain control and data if necessary */
1292 				n->m_next = NULL;
1293 			}
1294 			return NULL;
1295 		}
1296 		m->m_len = asa->sa_len;
1297 		SOCKADDR_COPY(asa, mtod(m, caddr_t), asa->sa_len);
1298 
1299 		m->m_next = control;
1300 	} else {
1301 		m = control;
1302 	}
1303 
1304 	return m;
1305 }
1306 
1307 /*
1308  * Queue mbuf chain to the receive queue of a socket.
1309  * Parameter space is the total len of the mbuf chain.
1310  * If passed in, sockbuf space will be checked.
1311  *
1312  * Returns:	0		Invalid mbuf chain
1313  *			1		Success
1314  */
1315 int
sbappendchain(struct sockbuf * sb,struct mbuf * m)1316 sbappendchain(struct sockbuf *sb, struct mbuf *m)
1317 {
1318 	struct mbuf *n, *nlast;
1319 	int space = 0;
1320 
1321 	if (m == NULL) {
1322 		return 0;
1323 	}
1324 
1325 	for (n = m; n->m_next != NULL; n = n->m_next) {
1326 		space += n->m_len;
1327 		sballoc(sb, n);
1328 	}
1329 	space += n->m_len;
1330 	sballoc(sb, n);
1331 	nlast = n;
1332 
1333 	if (sb->sb_lastrecord != NULL) {
1334 		sb->sb_lastrecord->m_nextpkt = m;
1335 	} else {
1336 		sb->sb_mb = m;
1337 	}
1338 	sb->sb_lastrecord = m;
1339 	sb->sb_mbtail = nlast;
1340 
1341 	sb_update_data_stats(sb, space);
1342 
1343 	SBLASTMBUFCHK(sb, __func__);
1344 	SBLASTRECORDCHK(sb, "sbappendadddr 2");
1345 	return 1;
1346 }
1347 
1348 /*
1349  * Returns:	0			Error: No space/out of mbufs/etc.
1350  *		1			Success
1351  *
1352  * Imputed:	(*error_out)		errno for error
1353  *		ENOBUFS
1354  *	sflt_data_in:???		[whatever a filter author chooses]
1355  */
1356 int
sbappendaddr(struct sockbuf * sb,struct sockaddr * asa,struct mbuf * m0,struct mbuf * control,int * error_out)1357 sbappendaddr(struct sockbuf *sb, struct sockaddr *asa, struct mbuf *m0,
1358     struct mbuf *control, int *error_out)
1359 {
1360 	int result = 0;
1361 	boolean_t sb_unix = (sb->sb_flags & SB_UNIX);
1362 	struct mbuf *mbuf_chain = NULL;
1363 	struct soflow_hash_entry *__single dgram_flow_entry = NULL;
1364 	struct socket *__single so = sb->sb_so;
1365 
1366 	if (error_out) {
1367 		*error_out = 0;
1368 	}
1369 
1370 	if (m0 && (m0->m_flags & M_PKTHDR) == 0) {
1371 		panic("sbappendaddrorfree");
1372 	}
1373 
1374 	if (sb->sb_flags & SB_DROP) {
1375 		if (m0 != NULL) {
1376 			m_freem(m0);
1377 		}
1378 		if (control != NULL && !sb_unix) {
1379 			m_freem(control);
1380 		}
1381 		if (error_out != NULL) {
1382 			*error_out = EINVAL;
1383 		}
1384 		return 0;
1385 	}
1386 
1387 	if (SOCK_DOM(sb->sb_so) == PF_INET || SOCK_DOM(sb->sb_so) == PF_INET6) {
1388 		/* Call socket data in filters */
1389 
1390 		if (NEED_DGRAM_FLOW_TRACKING(so)) {
1391 			dgram_flow_entry = soflow_get_flow(so, NULL, asa, control,
1392 			    m0 != NULL ? m_length(m0) : 0,
1393 			    false,
1394 			    (m0 != NULL && m0->m_pkthdr.rcvif) ? m0->m_pkthdr.rcvif->if_index : 0);
1395 		}
1396 
1397 		if (sb->sb_flags & SB_RECV && !(m0 && m0->m_flags & M_SKIPCFIL)) {
1398 			int error;
1399 			error = sflt_data_in(sb->sb_so, asa, &m0, &control, 0);
1400 			SBLASTRECORDCHK(sb, __func__);
1401 
1402 #if CONTENT_FILTER
1403 			if (error == 0) {
1404 				error = cfil_sock_data_in(sb->sb_so, asa, m0, control,
1405 				    0, dgram_flow_entry);
1406 			}
1407 #endif /* CONTENT_FILTER */
1408 
1409 			if (error) {
1410 				if (error != EJUSTRETURN) {
1411 					if (m0) {
1412 						m_freem(m0);
1413 					}
1414 					if (control != NULL && !sb_unix) {
1415 						m_freem(control);
1416 					}
1417 					if (error_out) {
1418 						*error_out = error;
1419 					}
1420 				}
1421 				if (dgram_flow_entry != NULL) {
1422 					soflow_free_flow(dgram_flow_entry);
1423 				}
1424 				return 0;
1425 			}
1426 		} else if (m0) {
1427 			m0->m_flags &= ~M_SKIPCFIL;
1428 		}
1429 
1430 		if (dgram_flow_entry != NULL) {
1431 			soflow_free_flow(dgram_flow_entry);
1432 		}
1433 	}
1434 
1435 	mbuf_chain = sbconcat_mbufs(sb, asa, m0, control);
1436 	SBLASTRECORDCHK(sb, "sbappendadddr 1");
1437 	result = sbappendchain(sb, mbuf_chain);
1438 	if (result == 0) {
1439 		if (m0) {
1440 			m_freem(m0);
1441 		}
1442 		if (control != NULL && !sb_unix) {
1443 			m_freem(control);
1444 		}
1445 		if (error_out) {
1446 			*error_out = ENOBUFS;
1447 		}
1448 	}
1449 
1450 	return result;
1451 }
1452 
1453 inline boolean_t
is_cmsg_valid(struct mbuf * control,struct cmsghdr * cmsg)1454 is_cmsg_valid(struct mbuf *control, struct cmsghdr *cmsg)
1455 {
1456 	if (cmsg == NULL) {
1457 		return FALSE;
1458 	}
1459 
1460 	if (cmsg->cmsg_len < sizeof(struct cmsghdr)) {
1461 		return FALSE;
1462 	}
1463 
1464 	if ((uintptr_t)control->m_data >= (uintptr_t)cmsg + cmsg->cmsg_len) {
1465 		return FALSE;
1466 	}
1467 
1468 	if ((uintptr_t)control->m_data + control->m_len <
1469 	    (uintptr_t)cmsg + cmsg->cmsg_len) {
1470 		return FALSE;
1471 	}
1472 
1473 	return TRUE;
1474 }
1475 
1476 static int
sbappendcontrol_internal(struct sockbuf * sb,struct mbuf * m0,struct mbuf * control)1477 sbappendcontrol_internal(struct sockbuf *sb, struct mbuf *m0,
1478     struct mbuf *control)
1479 {
1480 	struct mbuf *m, *mlast, *n;
1481 	int space = 0;
1482 
1483 	if (control == 0) {
1484 		panic("sbappendcontrol");
1485 	}
1486 
1487 	for (m = control;; m = m->m_next) {
1488 		space += m->m_len;
1489 		if (m->m_next == 0) {
1490 			break;
1491 		}
1492 	}
1493 	n = m;                  /* save pointer to last control buffer */
1494 	for (m = m0; m; m = m->m_next) {
1495 		space += m->m_len;
1496 	}
1497 	if (space > sbspace(sb) && !(sb->sb_flags & SB_UNIX)) {
1498 		sb_update_no_space_stats(sb, space);
1499 
1500 		return 0;
1501 	}
1502 	n->m_next = m0;                 /* concatenate data to control */
1503 	SBLASTRECORDCHK(sb, "sbappendcontrol 1");
1504 
1505 	for (m = control; m->m_next != NULL; m = m->m_next) {
1506 		sballoc(sb, m);
1507 	}
1508 	sballoc(sb, m);
1509 	mlast = m;
1510 
1511 	if (sb->sb_lastrecord != NULL) {
1512 		sb->sb_lastrecord->m_nextpkt = control;
1513 	} else {
1514 		sb->sb_mb = control;
1515 	}
1516 	sb->sb_lastrecord = control;
1517 	sb->sb_mbtail = mlast;
1518 
1519 	sb_update_data_stats(sb, space);
1520 
1521 	SBLASTMBUFCHK(sb, __func__);
1522 	SBLASTRECORDCHK(sb, "sbappendcontrol 2");
1523 	return 1;
1524 }
1525 
1526 int
sbappendcontrol(struct sockbuf * sb,struct mbuf * m0,struct mbuf * control,int * error_out)1527 sbappendcontrol(struct sockbuf *sb, struct mbuf *m0, struct mbuf *control,
1528     int *error_out)
1529 {
1530 	struct soflow_hash_entry *__single dgram_flow_entry = NULL;
1531 	struct socket *__single so = sb->sb_so;
1532 	int result = 0;
1533 	boolean_t sb_unix = (sb->sb_flags & SB_UNIX);
1534 
1535 	if (error_out) {
1536 		*error_out = 0;
1537 	}
1538 
1539 	if (sb->sb_flags & SB_DROP) {
1540 		if (m0 != NULL) {
1541 			m_freem(m0);
1542 		}
1543 		if (control != NULL && !sb_unix) {
1544 			m_freem(control);
1545 		}
1546 		if (error_out != NULL) {
1547 			*error_out = EINVAL;
1548 		}
1549 		return 0;
1550 	}
1551 
1552 	if (SOCK_DOM(sb->sb_so) == PF_INET || SOCK_DOM(sb->sb_so) == PF_INET6) {
1553 		if (NEED_DGRAM_FLOW_TRACKING(so)) {
1554 			dgram_flow_entry = soflow_get_flow(so, NULL, NULL, control,
1555 			    m0 != NULL ? m_length(m0) : 0, false,
1556 			    (m0 != NULL && m0->m_pkthdr.rcvif) ? m0->m_pkthdr.rcvif->if_index : 0);
1557 		}
1558 
1559 		if (sb->sb_flags & SB_RECV && !(m0 && m0->m_flags & M_SKIPCFIL)) {
1560 			int error;
1561 
1562 			error = sflt_data_in(sb->sb_so, NULL, &m0, &control, 0);
1563 			SBLASTRECORDCHK(sb, __func__);
1564 
1565 #if CONTENT_FILTER
1566 			if (error == 0) {
1567 				error = cfil_sock_data_in(sb->sb_so, NULL, m0, control,
1568 				    0, dgram_flow_entry);
1569 			}
1570 #endif /* CONTENT_FILTER */
1571 
1572 			if (error) {
1573 				if (error != EJUSTRETURN) {
1574 					if (m0) {
1575 						m_freem(m0);
1576 					}
1577 					if (control != NULL && !sb_unix) {
1578 						m_freem(control);
1579 					}
1580 					if (error_out) {
1581 						*error_out = error;
1582 					}
1583 				}
1584 				if (dgram_flow_entry != NULL) {
1585 					soflow_free_flow(dgram_flow_entry);
1586 				}
1587 				return 0;
1588 			}
1589 		} else if (m0) {
1590 			m0->m_flags &= ~M_SKIPCFIL;
1591 		}
1592 
1593 		if (dgram_flow_entry != NULL) {
1594 			soflow_free_flow(dgram_flow_entry);
1595 		}
1596 	}
1597 
1598 	result = sbappendcontrol_internal(sb, m0, control);
1599 	if (result == 0) {
1600 		if (m0) {
1601 			m_freem(m0);
1602 		}
1603 		if (control != NULL && !sb_unix) {
1604 			m_freem(control);
1605 		}
1606 		if (error_out) {
1607 			*error_out = ENOBUFS;
1608 		}
1609 	}
1610 
1611 	return result;
1612 }
1613 
1614 /*
1615  * TCP streams have Multipath TCP support or are regular TCP sockets.
1616  */
1617 int
sbappendstream_rcvdemux(struct socket * so,struct mbuf * m)1618 sbappendstream_rcvdemux(struct socket *so, struct mbuf *m)
1619 {
1620 	int ret = 0;
1621 
1622 	if ((m != NULL) &&
1623 	    m_pktlen(m) <= 0 &&
1624 	    !((so->so_flags & SOF_MP_SUBFLOW) &&
1625 	    (m->m_flags & M_PKTHDR) &&
1626 	    (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN))) {
1627 		m_freem(m);
1628 		return ret;
1629 	}
1630 
1631 #if MPTCP
1632 	if (so->so_flags & SOF_MP_SUBFLOW) {
1633 		return sbappendmptcpstream_rcv(&so->so_rcv, m);
1634 	} else
1635 #endif /* MPTCP */
1636 	{
1637 		return sbappendstream(&so->so_rcv, m);
1638 	}
1639 }
1640 
1641 #if MPTCP
1642 int
sbappendmptcpstream_rcv(struct sockbuf * sb,struct mbuf * m)1643 sbappendmptcpstream_rcv(struct sockbuf *sb, struct mbuf *m)
1644 {
1645 	struct socket *so = sb->sb_so;
1646 
1647 	VERIFY(m == NULL || (m->m_flags & M_PKTHDR));
1648 	/* SB_NOCOMPRESS must be set prevent loss of M_PKTHDR data */
1649 	VERIFY((sb->sb_flags & (SB_RECV | SB_NOCOMPRESS)) ==
1650 	    (SB_RECV | SB_NOCOMPRESS));
1651 
1652 	if (m == NULL || m_pktlen(m) == 0 || (sb->sb_flags & SB_DROP) ||
1653 	    (so->so_state & SS_CANTRCVMORE)) {
1654 		if (m && (m->m_flags & M_PKTHDR) &&
1655 		    m_pktlen(m) == 0 &&
1656 		    (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN)) {
1657 			mptcp_input(tptomptp(sototcpcb(so))->mpt_mpte, m);
1658 			return 1;
1659 		} else if (m != NULL) {
1660 			m_freem(m);
1661 		}
1662 		return 0;
1663 	}
1664 	/* the socket is not closed, so SOF_MP_SUBFLOW must be set */
1665 	VERIFY(so->so_flags & SOF_MP_SUBFLOW);
1666 
1667 	if (m->m_nextpkt != NULL || (sb->sb_mb != sb->sb_lastrecord)) {
1668 		panic("%s: nexpkt %p || mb %p != lastrecord %p", __func__,
1669 		    m->m_nextpkt, sb->sb_mb, sb->sb_lastrecord);
1670 		/* NOTREACHED */
1671 	}
1672 
1673 	SBLASTMBUFCHK(sb, __func__);
1674 
1675 	/* No filter support (SB_RECV) on mptcp subflow sockets */
1676 
1677 	sbcompress(sb, m, sb->sb_mbtail);
1678 	sb->sb_lastrecord = sb->sb_mb;
1679 	SBLASTRECORDCHK(sb, __func__);
1680 	return 1;
1681 }
1682 #endif /* MPTCP */
1683 
1684 /*
1685  * Compress mbuf chain m into the socket
1686  * buffer sb following mbuf n.  If n
1687  * is null, the buffer is presumed empty.
1688  */
1689 static inline void
sbcompress(struct sockbuf * sb,struct mbuf * m,struct mbuf * n)1690 sbcompress(struct sockbuf *sb, struct mbuf *m, struct mbuf *n)
1691 {
1692 	int eor = 0, compress = (!(sb->sb_flags & SB_NOCOMPRESS));
1693 	struct mbuf *o;
1694 	int space = 0;
1695 
1696 	if (m == NULL) {
1697 		/* There is nothing to compress; just update the tail */
1698 		for (; n->m_next != NULL; n = n->m_next) {
1699 			;
1700 		}
1701 		sb->sb_mbtail = n;
1702 		goto done;
1703 	}
1704 
1705 	while (m != NULL) {
1706 		space += m->m_len;
1707 		eor |= m->m_flags & M_EOR;
1708 		if (compress && m->m_len == 0 && (eor == 0 ||
1709 		    (((o = m->m_next) || (o = n)) && o->m_type == m->m_type))) {
1710 			if (sb->sb_lastrecord == m) {
1711 				sb->sb_lastrecord = m->m_next;
1712 			}
1713 			m = m_free(m);
1714 			continue;
1715 		}
1716 		if (compress && n != NULL && (n->m_flags & M_EOR) == 0 &&
1717 #ifndef __APPLE__
1718 		    M_WRITABLE(n) &&
1719 #endif
1720 		    m->m_len <= MCLBYTES / 4 && /* XXX: Don't copy too much */
1721 		    m->m_len <= M_TRAILINGSPACE(n) &&
1722 		    n->m_type == m->m_type) {
1723 			bcopy(mtod(m, caddr_t), mtod(n, caddr_t) + n->m_len,
1724 			    (unsigned)m->m_len);
1725 			n->m_len += m->m_len;
1726 			sb->sb_cc += m->m_len;
1727 			if (!m_has_mtype(m, MTF_DATA | MTF_HEADER | MTF_OOBDATA)) {
1728 				/* XXX: Probably don't need */
1729 				sb->sb_ctl += m->m_len;
1730 			}
1731 
1732 			/* update send byte count */
1733 			if (sb->sb_flags & SB_SNDBYTE_CNT) {
1734 				inp_incr_sndbytes_total(sb->sb_so,
1735 				    m->m_len);
1736 				inp_incr_sndbytes_unsent(sb->sb_so,
1737 				    m->m_len);
1738 			}
1739 			m = m_free(m);
1740 			continue;
1741 		}
1742 		if (n != NULL) {
1743 			n->m_next = m;
1744 		} else {
1745 			sb->sb_mb = m;
1746 		}
1747 		sb->sb_mbtail = m;
1748 		sballoc(sb, m);
1749 		n = m;
1750 		m->m_flags &= ~M_EOR;
1751 		m = m->m_next;
1752 		n->m_next = NULL;
1753 	}
1754 	if (eor != 0) {
1755 		if (n != NULL) {
1756 			n->m_flags |= M_EOR;
1757 		} else {
1758 			printf("semi-panic: sbcompress\n");
1759 		}
1760 	}
1761 	sb_update_data_stats(sb, space);
1762 done:
1763 	SBLASTMBUFCHK(sb, __func__);
1764 }
1765 
1766 void
sb_empty_assert(struct sockbuf * sb,const char * where)1767 sb_empty_assert(struct sockbuf *sb, const char *where)
1768 {
1769 	if (!(sb->sb_cc == 0 && sb->sb_mb == NULL && sb->sb_mbcnt == 0 &&
1770 	    sb->sb_mbtail == NULL && sb->sb_lastrecord == NULL)) {
1771 		panic("%s: sb %p so %p cc %d mbcnt %d mb %p mbtail %p "
1772 		    "lastrecord %p\n", where, sb, sb->sb_so, sb->sb_cc,
1773 		    sb->sb_mbcnt, sb->sb_mb, sb->sb_mbtail,
1774 		    sb->sb_lastrecord);
1775 		/* NOTREACHED */
1776 	}
1777 }
1778 
1779 /*
1780  * Free all mbufs in a sockbuf.
1781  * Check that all resources are reclaimed.
1782  */
1783 void
sbflush(struct sockbuf * sb)1784 sbflush(struct sockbuf *sb)
1785 {
1786 	void *__single lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
1787 	struct socket *so = sb->sb_so;
1788 
1789 	/* so_usecount may be 0 if we get here from sofreelastref() */
1790 	if (so == NULL) {
1791 		panic("%s: null so, sb=%p sb_flags=0x%x lr=%p",
1792 		    __func__, sb, sb->sb_flags, lr_saved);
1793 		/* NOTREACHED */
1794 	} else if (so->so_usecount < 0) {
1795 		panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
1796 		    "lrh= %s\n", __func__, sb, sb->sb_flags, so,
1797 		    so->so_usecount, lr_saved, solockhistory_nr(so));
1798 		/* NOTREACHED */
1799 	}
1800 
1801 	/*
1802 	 * Obtain lock on the socket buffer (SB_LOCK).  This is required
1803 	 * to prevent the socket buffer from being unexpectedly altered
1804 	 * while it is used by another thread in socket send/receive.
1805 	 *
1806 	 * sblock() must not fail here, hence the assertion.
1807 	 */
1808 	(void) sblock(sb, SBL_WAIT | SBL_NOINTR | SBL_IGNDEFUNCT);
1809 	VERIFY(sb->sb_flags & SB_LOCK);
1810 
1811 	while (sb->sb_mbcnt > 0) {
1812 		/*
1813 		 * Don't call sbdrop(sb, 0) if the leading mbuf is non-empty:
1814 		 * we would loop forever. Panic instead.
1815 		 */
1816 		if (!sb->sb_cc && (sb->sb_mb == NULL || sb->sb_mb->m_len)) {
1817 			break;
1818 		}
1819 		sbdrop(sb, (int)sb->sb_cc);
1820 	}
1821 
1822 	if (sb->sb_flags & SB_SENDHEAD) {
1823 		sb->sb_sendhead = NULL;
1824 	}
1825 
1826 	sb_empty_assert(sb, __func__);
1827 	sbunlock(sb, TRUE);     /* keep socket locked */
1828 }
1829 
1830 /*
1831  * Drop data from (the front of) a sockbuf.
1832  * use m_freem_list to free the mbuf structures
1833  * under a single lock... this is done by pruning
1834  * the top of the tree from the body by keeping track
1835  * of where we get to in the tree and then zeroing the
1836  * two pertinent pointers m_nextpkt and m_next
1837  * the socket buffer is then updated to point at the new
1838  * top of the tree and the pruned area is released via
1839  * m_freem_list.
1840  */
1841 void
sbdrop(struct sockbuf * sb,int len)1842 sbdrop(struct sockbuf *sb, int len)
1843 {
1844 	struct mbuf *m, *free_list, *ml;
1845 	struct mbuf *next, *last;
1846 
1847 	next = (m = sb->sb_mb) ? m->m_nextpkt : 0;
1848 #if MPTCP
1849 	if (m != NULL && len > 0 && !(sb->sb_flags & SB_RECV) &&
1850 	    ((sb->sb_so->so_flags & SOF_MP_SUBFLOW) ||
1851 	    (SOCK_CHECK_DOM(sb->sb_so, PF_MULTIPATH) &&
1852 	    SOCK_CHECK_PROTO(sb->sb_so, IPPROTO_TCP))) &&
1853 	    !(sb->sb_so->so_flags1 & SOF1_POST_FALLBACK_SYNC)) {
1854 		mptcp_preproc_sbdrop(sb->sb_so, m, (unsigned int)len);
1855 	}
1856 	if (m != NULL && len > 0 && !(sb->sb_flags & SB_RECV) &&
1857 	    (sb->sb_so->so_flags & SOF_MP_SUBFLOW) &&
1858 	    (sb->sb_so->so_flags1 & SOF1_POST_FALLBACK_SYNC)) {
1859 		mptcp_fallback_sbdrop(sb->sb_so, m, len);
1860 	}
1861 #endif /* MPTCP */
1862 	KERNEL_DEBUG((DBG_FNC_SBDROP | DBG_FUNC_START), sb, len, 0, 0, 0);
1863 
1864 	free_list = last = m;
1865 	ml = (struct mbuf *)0;
1866 
1867 	if (sb->sb_flags & SB_SENDHEAD) {
1868 		sb->sb_sendoff -= MIN(len, sb->sb_sendoff);
1869 	}
1870 
1871 	while (len > 0) {
1872 		if (m == NULL) {
1873 			if (next == NULL) {
1874 				/*
1875 				 * temporarily replacing this panic with printf
1876 				 * because it occurs occasionally when closing
1877 				 * a socket when there is no harm in ignoring
1878 				 * it. This problem will be investigated
1879 				 * further.
1880 				 */
1881 				/* panic("sbdrop"); */
1882 				printf("sbdrop - count not zero\n");
1883 				len = 0;
1884 				/*
1885 				 * zero the counts. if we have no mbufs,
1886 				 * we have no data (PR-2986815)
1887 				 */
1888 				sb->sb_cc = 0;
1889 				sb->sb_mbcnt = 0;
1890 				break;
1891 			}
1892 			m = last = next;
1893 			next = m->m_nextpkt;
1894 			continue;
1895 		}
1896 		if (m->m_len > len) {
1897 			m->m_len -= len;
1898 			m->m_data += len;
1899 			sb->sb_cc -= len;
1900 			/* update the send byte count */
1901 			if (sb->sb_flags & SB_SNDBYTE_CNT) {
1902 				inp_decr_sndbytes_total(sb->sb_so, len);
1903 			}
1904 			if (sb->sb_flags & SB_SENDHEAD) {
1905 				if (sb->sb_sendhead == m) {
1906 					sb->sb_sendhead = NULL;
1907 				}
1908 			}
1909 			if (!m_has_mtype(m, MTF_DATA | MTF_HEADER | MTF_OOBDATA)) {
1910 				sb->sb_ctl -= len;
1911 			}
1912 			break;
1913 		}
1914 		len -= m->m_len;
1915 		sbfree(sb, m);
1916 
1917 		ml = m;
1918 		m = m->m_next;
1919 	}
1920 	while (m && m->m_len == 0) {
1921 		sbfree(sb, m);
1922 
1923 		ml = m;
1924 		m = m->m_next;
1925 	}
1926 	if (ml) {
1927 		ml->m_next = (struct mbuf *)0;
1928 		last->m_nextpkt = (struct mbuf *)0;
1929 		m_freem_list(free_list);
1930 	}
1931 	if (m) {
1932 		sb->sb_mb = m;
1933 		m->m_nextpkt = next;
1934 	} else {
1935 		sb->sb_mb = next;
1936 	}
1937 
1938 	/*
1939 	 * First part is an inline SB_EMPTY_FIXUP().  Second part
1940 	 * makes sure sb_lastrecord is up-to-date if we dropped
1941 	 * part of the last record.
1942 	 */
1943 	m = sb->sb_mb;
1944 	if (m == NULL) {
1945 		sb->sb_mbtail = NULL;
1946 		sb->sb_lastrecord = NULL;
1947 	} else if (m->m_nextpkt == NULL) {
1948 		sb->sb_lastrecord = m;
1949 	}
1950 
1951 #if CONTENT_FILTER
1952 	cfil_sock_buf_update(sb);
1953 #endif /* CONTENT_FILTER */
1954 
1955 	KERNEL_DEBUG((DBG_FNC_SBDROP | DBG_FUNC_END), sb, 0, 0, 0, 0);
1956 }
1957 
1958 /*
1959  * Drop a record off the front of a sockbuf
1960  * and move the next record to the front.
1961  */
1962 void
sbdroprecord(struct sockbuf * sb)1963 sbdroprecord(struct sockbuf *sb)
1964 {
1965 	struct mbuf *m, *mn;
1966 
1967 	m = sb->sb_mb;
1968 	if (m) {
1969 		sb->sb_mb = m->m_nextpkt;
1970 		do {
1971 			sbfree(sb, m);
1972 			MFREE(m, mn);
1973 			m = mn;
1974 		} while (m);
1975 	}
1976 	SB_EMPTY_FIXUP(sb);
1977 }
1978 
1979 /*
1980  * Create a "control" mbuf containing the specified data
1981  * with the specified type for presentation on a socket buffer.
1982  */
1983 struct mbuf *
sbcreatecontrol(caddr_t __sized_by (size)p,int size,int type,int level)1984 sbcreatecontrol(caddr_t __sized_by(size) p, int size, int type, int level)
1985 {
1986 	struct cmsghdr *cp;
1987 	struct mbuf *m;
1988 
1989 	if (CMSG_SPACE((u_int)size) > MLEN) {
1990 		return (struct mbuf *)NULL;
1991 	}
1992 	if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL) {
1993 		return (struct mbuf *)NULL;
1994 	}
1995 	cp = mtod(m, struct cmsghdr *);
1996 	VERIFY(IS_P2ALIGNED(cp, sizeof(u_int32_t)));
1997 	/* XXX check size? */
1998 	(void) memcpy(CMSG_DATA(cp), p, size);
1999 	m->m_len = (int32_t)CMSG_SPACE(size);
2000 	cp->cmsg_len = CMSG_LEN(size);
2001 	cp->cmsg_level = level;
2002 	cp->cmsg_type = type;
2003 	return m;
2004 }
2005 
2006 struct mbuf **
sbcreatecontrol_mbuf(caddr_t __sized_by (size)p,int size,int type,int level,struct mbuf ** mp)2007 sbcreatecontrol_mbuf(caddr_t __sized_by(size) p, int size, int type, int level, struct mbuf **mp)
2008 {
2009 	struct mbuf *m;
2010 	struct cmsghdr *cp;
2011 
2012 	if (*mp == NULL) {
2013 		*mp = sbcreatecontrol(p, size, type, level);
2014 		return mp;
2015 	}
2016 
2017 	if (CMSG_SPACE((u_int)size) + (*mp)->m_len > MLEN) {
2018 		mp = &(*mp)->m_next;
2019 		*mp = sbcreatecontrol(p, size, type, level);
2020 		return mp;
2021 	}
2022 
2023 	m = *mp;
2024 
2025 	cp = (struct cmsghdr *)(void *)(mtod(m, char *) + m->m_len);
2026 	/* CMSG_SPACE ensures 32-bit alignment */
2027 	VERIFY(IS_P2ALIGNED(cp, sizeof(u_int32_t)));
2028 	m->m_len += (int32_t)CMSG_SPACE(size);
2029 
2030 	/* XXX check size? */
2031 	(void) memcpy(CMSG_DATA(cp), p, size);
2032 	cp->cmsg_len = CMSG_LEN(size);
2033 	cp->cmsg_level = level;
2034 	cp->cmsg_type = type;
2035 
2036 	return mp;
2037 }
2038 
2039 
2040 /*
2041  * Some routines that return EOPNOTSUPP for entry points that are not
2042  * supported by a protocol.  Fill in as needed.
2043  */
2044 int
pru_abort_notsupp(struct socket * so)2045 pru_abort_notsupp(struct socket *so)
2046 {
2047 #pragma unused(so)
2048 	return EOPNOTSUPP;
2049 }
2050 
2051 int
pru_accept_notsupp(struct socket * so,struct sockaddr ** nam)2052 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
2053 {
2054 #pragma unused(so, nam)
2055 	return EOPNOTSUPP;
2056 }
2057 
2058 int
pru_attach_notsupp(struct socket * so,int proto,struct proc * p)2059 pru_attach_notsupp(struct socket *so, int proto, struct proc *p)
2060 {
2061 #pragma unused(so, proto, p)
2062 	return EOPNOTSUPP;
2063 }
2064 
2065 int
pru_bind_notsupp(struct socket * so,struct sockaddr * nam,struct proc * p)2066 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
2067 {
2068 #pragma unused(so, nam, p)
2069 	return EOPNOTSUPP;
2070 }
2071 
2072 int
pru_connect_notsupp(struct socket * so,struct sockaddr * nam,struct proc * p)2073 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct proc *p)
2074 {
2075 #pragma unused(so, nam, p)
2076 	return EOPNOTSUPP;
2077 }
2078 
2079 int
pru_connect2_notsupp(struct socket * so1,struct socket * so2)2080 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
2081 {
2082 #pragma unused(so1, so2)
2083 	return EOPNOTSUPP;
2084 }
2085 
2086 int
pru_connectx_notsupp(struct socket * so,struct sockaddr * src,struct sockaddr * dst,struct proc * p,uint32_t ifscope,sae_associd_t aid,sae_connid_t * pcid,uint32_t flags,void * arg,uint32_t arglen,struct uio * uio,user_ssize_t * bytes_written)2087 pru_connectx_notsupp(struct socket *so, struct sockaddr *src,
2088     struct sockaddr *dst, struct proc *p, uint32_t ifscope,
2089     sae_associd_t aid, sae_connid_t *pcid, uint32_t flags, void *arg,
2090     uint32_t arglen, struct uio *uio, user_ssize_t *bytes_written)
2091 {
2092 #pragma unused(so, src, dst, p, ifscope, aid, pcid, flags, arg, arglen, uio, bytes_written)
2093 	return EOPNOTSUPP;
2094 }
2095 
2096 int
pru_control_notsupp(struct socket * so,u_long cmd,caddr_t __sized_by (IOCPARM_LEN (cmd))data,struct ifnet * ifp,struct proc * p)2097 pru_control_notsupp(struct socket *so,
2098     u_long cmd, caddr_t __sized_by(IOCPARM_LEN(cmd)) data,
2099     struct ifnet *ifp, struct proc *p)
2100 {
2101 #pragma unused(so, cmd, data, ifp, p)
2102 	return EOPNOTSUPP;
2103 }
2104 
2105 int
pru_detach_notsupp(struct socket * so)2106 pru_detach_notsupp(struct socket *so)
2107 {
2108 #pragma unused(so)
2109 	return EOPNOTSUPP;
2110 }
2111 
2112 int
pru_disconnect_notsupp(struct socket * so)2113 pru_disconnect_notsupp(struct socket *so)
2114 {
2115 #pragma unused(so)
2116 	return EOPNOTSUPP;
2117 }
2118 
2119 int
pru_disconnectx_notsupp(struct socket * so,sae_associd_t aid,sae_connid_t cid)2120 pru_disconnectx_notsupp(struct socket *so, sae_associd_t aid, sae_connid_t cid)
2121 {
2122 #pragma unused(so, aid, cid)
2123 	return EOPNOTSUPP;
2124 }
2125 
2126 int
pru_listen_notsupp(struct socket * so,struct proc * p)2127 pru_listen_notsupp(struct socket *so, struct proc *p)
2128 {
2129 #pragma unused(so, p)
2130 	return EOPNOTSUPP;
2131 }
2132 
2133 int
pru_peeraddr_notsupp(struct socket * so,struct sockaddr ** nam)2134 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
2135 {
2136 #pragma unused(so, nam)
2137 	return EOPNOTSUPP;
2138 }
2139 
2140 int
pru_rcvd_notsupp(struct socket * so,int flags)2141 pru_rcvd_notsupp(struct socket *so, int flags)
2142 {
2143 #pragma unused(so, flags)
2144 	return EOPNOTSUPP;
2145 }
2146 
2147 int
pru_rcvoob_notsupp(struct socket * so,struct mbuf * m,int flags)2148 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
2149 {
2150 #pragma unused(so, m, flags)
2151 	return EOPNOTSUPP;
2152 }
2153 
2154 int
pru_send_notsupp(struct socket * so,int flags,struct mbuf * m,struct sockaddr * addr,struct mbuf * control,struct proc * p)2155 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
2156     struct sockaddr *addr, struct mbuf *control, struct proc *p)
2157 {
2158 #pragma unused(so, flags, m, addr, control, p)
2159 	return EOPNOTSUPP;
2160 }
2161 
2162 int
pru_send_list_notsupp(struct socket * so,struct mbuf * m,u_int * pktcnt,int flags)2163 pru_send_list_notsupp(struct socket *so, struct mbuf *m, u_int *pktcnt,
2164     int flags)
2165 {
2166 #pragma unused(so, m, pktcnt, flags)
2167 	return EOPNOTSUPP;
2168 }
2169 
2170 /*
2171  * This isn't really a ``null'' operation, but it's the default one
2172  * and doesn't do anything destructive.
2173  */
2174 int
pru_sense_null(struct socket * so,void * ub,int isstat64)2175 pru_sense_null(struct socket *so, void *ub, int isstat64)
2176 {
2177 	if (isstat64 != 0) {
2178 		struct stat64 *sb64;
2179 
2180 		sb64 = (struct stat64 *)ub;
2181 		sb64->st_blksize = so->so_snd.sb_hiwat;
2182 	} else {
2183 		struct stat *sb;
2184 
2185 		sb = (struct stat *)ub;
2186 		sb->st_blksize = so->so_snd.sb_hiwat;
2187 	}
2188 
2189 	return 0;
2190 }
2191 
2192 int
pru_sosend_notsupp(struct socket * so,struct sockaddr * addr,struct uio * uio,struct mbuf * top,struct mbuf * control,int flags)2193 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
2194     struct mbuf *top, struct mbuf *control, int flags)
2195 {
2196 #pragma unused(so, addr, uio, top, control, flags)
2197 	return EOPNOTSUPP;
2198 }
2199 
2200 int
pru_sosend_list_notsupp(struct socket * so,struct mbuf * m,size_t total_len,u_int * pktcnt,int flags)2201 pru_sosend_list_notsupp(struct socket *so, struct mbuf *m, size_t total_len, u_int *pktcnt, int flags)
2202 {
2203 #pragma unused(so, m, total_len, pktcnt, flags)
2204 	return EOPNOTSUPP;
2205 }
2206 
2207 int
pru_soreceive_notsupp(struct socket * so,struct sockaddr ** paddr,struct uio * uio,struct mbuf ** mp0,struct mbuf ** controlp,int * flagsp)2208 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
2209     struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2210 {
2211 #pragma unused(so, paddr, uio, mp0, controlp, flagsp)
2212 	return EOPNOTSUPP;
2213 }
2214 
2215 int
pru_shutdown_notsupp(struct socket * so)2216 pru_shutdown_notsupp(struct socket *so)
2217 {
2218 #pragma unused(so)
2219 	return EOPNOTSUPP;
2220 }
2221 
2222 int
pru_sockaddr_notsupp(struct socket * so,struct sockaddr ** nam)2223 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
2224 {
2225 #pragma unused(so, nam)
2226 	return EOPNOTSUPP;
2227 }
2228 
2229 int
pru_sopoll_notsupp(struct socket * so,int events,kauth_cred_t cred,void * wql)2230 pru_sopoll_notsupp(struct socket *so, int events, kauth_cred_t cred, void *wql)
2231 {
2232 #pragma unused(so, events, cred, wql)
2233 	return EOPNOTSUPP;
2234 }
2235 
2236 int
pru_socheckopt_null(struct socket * so,struct sockopt * sopt)2237 pru_socheckopt_null(struct socket *so, struct sockopt *sopt)
2238 {
2239 #pragma unused(so, sopt)
2240 	/*
2241 	 * Allow all options for set/get by default.
2242 	 */
2243 	return 0;
2244 }
2245 
2246 static int
pru_preconnect_null(struct socket * so)2247 pru_preconnect_null(struct socket *so)
2248 {
2249 #pragma unused(so)
2250 	return 0;
2251 }
2252 
2253 static int
pru_defunct_null(struct socket * so)2254 pru_defunct_null(struct socket *so)
2255 {
2256 #pragma unused(so)
2257 	return 0;
2258 }
2259 
2260 
2261 void
pru_sanitize(struct pr_usrreqs * pru)2262 pru_sanitize(struct pr_usrreqs *pru)
2263 {
2264 #define DEFAULT(foo, bar)       if ((foo) == NULL) (foo) = (bar)
2265 	DEFAULT(pru->pru_abort, pru_abort_notsupp);
2266 	DEFAULT(pru->pru_accept, pru_accept_notsupp);
2267 	DEFAULT(pru->pru_attach, pru_attach_notsupp);
2268 	DEFAULT(pru->pru_bind, pru_bind_notsupp);
2269 	DEFAULT(pru->pru_connect, pru_connect_notsupp);
2270 	DEFAULT(pru->pru_connect2, pru_connect2_notsupp);
2271 	DEFAULT(pru->pru_connectx, pru_connectx_notsupp);
2272 	DEFAULT(pru->pru_control, pru_control_notsupp);
2273 	DEFAULT(pru->pru_detach, pru_detach_notsupp);
2274 	DEFAULT(pru->pru_disconnect, pru_disconnect_notsupp);
2275 	DEFAULT(pru->pru_disconnectx, pru_disconnectx_notsupp);
2276 	DEFAULT(pru->pru_listen, pru_listen_notsupp);
2277 	DEFAULT(pru->pru_peeraddr, pru_peeraddr_notsupp);
2278 	DEFAULT(pru->pru_rcvd, pru_rcvd_notsupp);
2279 	DEFAULT(pru->pru_rcvoob, pru_rcvoob_notsupp);
2280 	DEFAULT(pru->pru_send, pru_send_notsupp);
2281 	DEFAULT(pru->pru_send_list, pru_send_list_notsupp);
2282 	DEFAULT(pru->pru_sense, pru_sense_null);
2283 	DEFAULT(pru->pru_shutdown, pru_shutdown_notsupp);
2284 	DEFAULT(pru->pru_sockaddr, pru_sockaddr_notsupp);
2285 	DEFAULT(pru->pru_sopoll, pru_sopoll_notsupp);
2286 	DEFAULT(pru->pru_soreceive, pru_soreceive_notsupp);
2287 	DEFAULT(pru->pru_sosend, pru_sosend_notsupp);
2288 	DEFAULT(pru->pru_sosend_list, pru_sosend_list_notsupp);
2289 	DEFAULT(pru->pru_socheckopt, pru_socheckopt_null);
2290 	DEFAULT(pru->pru_preconnect, pru_preconnect_null);
2291 	DEFAULT(pru->pru_defunct, pru_defunct_null);
2292 #undef DEFAULT
2293 }
2294 
2295 /*
2296  * The following are macros on BSD and functions on Darwin
2297  */
2298 
2299 /*
2300  * Do we need to notify the other side when I/O is possible?
2301  */
2302 
2303 int
sb_notify(struct sockbuf * sb)2304 sb_notify(struct sockbuf *sb)
2305 {
2306 	return sb->sb_waiters > 0 ||
2307 	       (sb->sb_flags & (SB_SEL | SB_ASYNC | SB_UPCALL | SB_KNOTE));
2308 }
2309 
2310 /*
2311  * How much space is there in a socket buffer (so->so_snd or so->so_rcv)?
2312  * This is problematical if the fields are unsigned, as the space might
2313  * still be negative (cc > hiwat or mbcnt > mbmax).  Should detect
2314  * overflow and return 0.
2315  */
2316 int
sbspace(struct sockbuf * sb)2317 sbspace(struct sockbuf *sb)
2318 {
2319 	int pending = 0;
2320 	int space;
2321 
2322 	if (sb->sb_flags & SB_KCTL) {
2323 		space = (int)(sb->sb_hiwat - sb->sb_cc);
2324 	} else {
2325 		space = imin((int)(sb->sb_hiwat - sb->sb_cc),
2326 		    (int)(sb->sb_mbmax - sb->sb_mbcnt));
2327 	}
2328 	if (sb->sb_preconn_hiwat != 0) {
2329 		space = imin((int)(sb->sb_preconn_hiwat - sb->sb_cc), space);
2330 	}
2331 
2332 	if (space < 0) {
2333 		space = 0;
2334 	}
2335 
2336 	/* Compensate for data being processed by content filters */
2337 #if CONTENT_FILTER
2338 	pending = cfil_sock_data_space(sb);
2339 #endif /* CONTENT_FILTER */
2340 	if (pending > space) {
2341 		space = 0;
2342 	} else {
2343 		space -= pending;
2344 	}
2345 
2346 	return space;
2347 }
2348 
2349 /* do we have to send all at once on a socket? */
2350 int
sosendallatonce(struct socket * so)2351 sosendallatonce(struct socket *so)
2352 {
2353 	return so->so_proto->pr_flags & PR_ATOMIC;
2354 }
2355 
2356 /* can we read something from so? */
2357 int
soreadable(struct socket * so)2358 soreadable(struct socket *so)
2359 {
2360 	return so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2361 	       ((so->so_state & SS_CANTRCVMORE)
2362 #if CONTENT_FILTER
2363 	       && cfil_sock_data_pending(&so->so_rcv) == 0
2364 #endif /* CONTENT_FILTER */
2365 	       ) ||
2366 	       so->so_comp.tqh_first || so->so_error;
2367 }
2368 
2369 /* can we write something to so? */
2370 
2371 int
sowriteable(struct socket * so)2372 sowriteable(struct socket *so)
2373 {
2374 	if ((so->so_state & SS_CANTSENDMORE) ||
2375 	    so->so_error > 0) {
2376 		return 1;
2377 	}
2378 	if (so_wait_for_if_feedback(so) || !socanwrite(so)) {
2379 		return 0;
2380 	}
2381 	if (so->so_flags1 & SOF1_PRECONNECT_DATA) {
2382 		return 1;
2383 	}
2384 
2385 	int64_t data = sbspace(&so->so_snd);
2386 	int64_t lowat = so->so_snd.sb_lowat;
2387 	/*
2388 	 * Deal with connected UNIX domain sockets which
2389 	 * rely on the fact that the sender's socket buffer is
2390 	 * actually the receiver's socket buffer.
2391 	 */
2392 	if (SOCK_DOM(so) == PF_LOCAL) {
2393 		struct unpcb *unp = sotounpcb(so);
2394 		if (unp != NULL && unp->unp_conn != NULL &&
2395 		    unp->unp_conn->unp_socket != NULL) {
2396 			struct socket *so2 = unp->unp_conn->unp_socket;
2397 			/*
2398 			 * At this point we know that `so' is locked
2399 			 * and that `unp_conn` isn't going to change.
2400 			 * However, we don't lock `so2` because doing so
2401 			 * may require unlocking `so'
2402 			 * (see unp_get_locks_in_order()).
2403 			 *
2404 			 * Two cases can happen:
2405 			 *
2406 			 * 1) we return 1 and tell the application that
2407 			 *    it can write.  Meanwhile, another thread
2408 			 *    fills up the socket buffer.  This will either
2409 			 *    lead to a blocking send or EWOULDBLOCK
2410 			 *    which the application should deal with.
2411 			 * 2) we return 0 and tell the application that
2412 			 *    the socket is not writable.  Meanwhile,
2413 			 *    another thread depletes the receive socket
2414 			 *    buffer. In this case the application will
2415 			 *    be woken up by sb_notify().
2416 			 *
2417 			 * MIN() is required because otherwise sosendcheck()
2418 			 * may return EWOULDBLOCK since it only considers
2419 			 * so->so_snd.
2420 			 */
2421 			data = MIN(data, sbspace(&so2->so_rcv));
2422 		}
2423 	}
2424 
2425 	if (data >= lowat) {
2426 		if (so->so_flags & SOF_NOTSENT_LOWAT) {
2427 			if ((SOCK_DOM(so) == PF_INET6 ||
2428 			    SOCK_DOM(so) == PF_INET) &&
2429 			    so->so_type == SOCK_STREAM) {
2430 				return tcp_notsent_lowat_check(so);
2431 			}
2432 #if MPTCP
2433 			else if ((SOCK_DOM(so) == PF_MULTIPATH) &&
2434 			    (SOCK_PROTO(so) == IPPROTO_TCP)) {
2435 				return mptcp_notsent_lowat_check(so);
2436 			}
2437 #endif
2438 			else {
2439 				return 1;
2440 			}
2441 		} else {
2442 			return 1;
2443 		}
2444 	}
2445 	return 0;
2446 }
2447 
2448 /* adjust counters in sb reflecting allocation of m */
2449 
2450 void
sballoc(struct sockbuf * sb,struct mbuf * m)2451 sballoc(struct sockbuf *sb, struct mbuf *m)
2452 {
2453 	sb->sb_cc += m->m_len;
2454 	if (!m_has_mtype(m, MTF_DATA | MTF_HEADER | MTF_OOBDATA)) {
2455 		sb->sb_ctl += m->m_len;
2456 	}
2457 	sb->sb_mbcnt += _MSIZE;
2458 
2459 	if (m->m_flags & M_EXT) {
2460 		sb->sb_mbcnt += m->m_ext.ext_size;
2461 	}
2462 
2463 	/*
2464 	 * If data is being added to the send socket buffer,
2465 	 * update the send byte count
2466 	 */
2467 	if (sb->sb_flags & SB_SNDBYTE_CNT) {
2468 		inp_incr_sndbytes_total(sb->sb_so, m->m_len);
2469 		inp_incr_sndbytes_unsent(sb->sb_so, m->m_len);
2470 	}
2471 }
2472 
2473 /* adjust counters in sb reflecting freeing of m */
2474 void
sbfree(struct sockbuf * sb,struct mbuf * m)2475 sbfree(struct sockbuf *sb, struct mbuf *m)
2476 {
2477 	sb->sb_cc -= m->m_len;
2478 	if (!m_has_mtype(m, MTF_DATA | MTF_HEADER | MTF_OOBDATA)) {
2479 		sb->sb_ctl -= m->m_len;
2480 	}
2481 	sb->sb_mbcnt -= _MSIZE;
2482 	if (m->m_flags & M_EXT) {
2483 		sb->sb_mbcnt -= m->m_ext.ext_size;
2484 	}
2485 
2486 	/*
2487 	 * If data is being removed from the send socket buffer,
2488 	 * update the send byte count
2489 	 */
2490 	if (sb->sb_flags & SB_SNDBYTE_CNT) {
2491 		inp_decr_sndbytes_total(sb->sb_so, m->m_len);
2492 	}
2493 
2494 	if (sb->sb_flags & SB_SENDHEAD) {
2495 		if (m == sb->sb_sendhead) {
2496 			sb->sb_sendhead = NULL;
2497 		}
2498 	}
2499 }
2500 
2501 /*
2502  * Set lock on sockbuf sb; sleep if lock is already held.
2503  * Unless SB_NOINTR is set on sockbuf, sleep is interruptible.
2504  * Returns error without lock if sleep is interrupted.
2505  */
2506 int
sblock(struct sockbuf * sb,uint32_t flags)2507 sblock(struct sockbuf *sb, uint32_t flags)
2508 {
2509 	boolean_t nointr = ((sb->sb_flags & SB_NOINTR) || (flags & SBL_NOINTR));
2510 	void *__single lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
2511 	struct socket *so = sb->sb_so;
2512 	void * wchan;
2513 	int error = 0;
2514 	thread_t __single tp = current_thread();
2515 
2516 	VERIFY((flags & SBL_VALID) == flags);
2517 
2518 	/* so_usecount may be 0 if we get here from sofreelastref() */
2519 	if (so == NULL) {
2520 		panic("%s: null so, sb=%p sb_flags=0x%x lr=%p",
2521 		    __func__, sb, sb->sb_flags, lr_saved);
2522 		/* NOTREACHED */
2523 	} else if (so->so_usecount < 0) {
2524 		panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
2525 		    "lrh= %s\n", __func__, sb, sb->sb_flags, so,
2526 		    so->so_usecount, lr_saved, solockhistory_nr(so));
2527 		/* NOTREACHED */
2528 	}
2529 
2530 	/*
2531 	 * The content filter thread must hold the sockbuf lock
2532 	 */
2533 	if ((so->so_flags & SOF_CONTENT_FILTER) && sb->sb_cfil_thread == tp) {
2534 		/*
2535 		 * Don't panic if we are defunct because SB_LOCK has
2536 		 * been cleared by sodefunct()
2537 		 */
2538 		if (!(so->so_flags & SOF_DEFUNCT) && !(sb->sb_flags & SB_LOCK)) {
2539 			panic("%s: SB_LOCK not held for %p",
2540 			    __func__, sb);
2541 		}
2542 
2543 		/* Keep the sockbuf locked */
2544 		return 0;
2545 	}
2546 
2547 	if ((sb->sb_flags & SB_LOCK) && !(flags & SBL_WAIT)) {
2548 		return EWOULDBLOCK;
2549 	}
2550 	/*
2551 	 * We may get here from sorflush(), in which case "sb" may not
2552 	 * point to the real socket buffer.  Use the actual socket buffer
2553 	 * address from the socket instead.
2554 	 */
2555 	wchan = (sb->sb_flags & SB_RECV) ?
2556 	    &so->so_rcv.sb_flags : &so->so_snd.sb_flags;
2557 
2558 	/*
2559 	 * A content filter thread has exclusive access to the sockbuf
2560 	 * until it clears the
2561 	 */
2562 	while ((sb->sb_flags & SB_LOCK) ||
2563 	    ((so->so_flags & SOF_CONTENT_FILTER) &&
2564 	    sb->sb_cfil_thread != NULL)) {
2565 		lck_mtx_t *mutex_held;
2566 
2567 		/*
2568 		 * XXX: This code should be moved up above outside of this loop;
2569 		 * however, we may get here as part of sofreelastref(), and
2570 		 * at that time pr_getlock() may no longer be able to return
2571 		 * us the lock.  This will be fixed in future.
2572 		 */
2573 		if (so->so_proto->pr_getlock != NULL) {
2574 			mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
2575 		} else {
2576 			mutex_held = so->so_proto->pr_domain->dom_mtx;
2577 		}
2578 
2579 		LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
2580 
2581 		sb->sb_wantlock++;
2582 		VERIFY(sb->sb_wantlock != 0);
2583 
2584 		error = msleep(wchan, mutex_held,
2585 		    nointr ? PSOCK : PSOCK | PCATCH,
2586 		    nointr ? "sb_lock_nointr" : "sb_lock", NULL);
2587 
2588 		VERIFY(sb->sb_wantlock != 0);
2589 		sb->sb_wantlock--;
2590 
2591 		if (error == 0 && (so->so_flags & SOF_DEFUNCT) &&
2592 		    !(flags & SBL_IGNDEFUNCT)) {
2593 			error = EBADF;
2594 			SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llu [%d,%d] "
2595 			    "(%d)\n", __func__, proc_selfpid(),
2596 			    proc_best_name(current_proc()),
2597 			    so->so_gencnt,
2598 			    SOCK_DOM(so), SOCK_TYPE(so), error);
2599 		}
2600 
2601 		if (error != 0) {
2602 			return error;
2603 		}
2604 	}
2605 	sb->sb_flags |= SB_LOCK;
2606 	return 0;
2607 }
2608 
2609 /*
2610  * Release lock on sockbuf sb
2611  */
2612 void
sbunlock(struct sockbuf * sb,boolean_t keeplocked)2613 sbunlock(struct sockbuf *sb, boolean_t keeplocked)
2614 {
2615 	void *__single lr_saved = __unsafe_forge_single(void *, __builtin_return_address(0));
2616 	struct socket *so = sb->sb_so;
2617 	thread_t __single tp = current_thread();
2618 
2619 	/* so_usecount may be 0 if we get here from sofreelastref() */
2620 	if (so == NULL) {
2621 		panic("%s: null so, sb=%p sb_flags=0x%x lr=%p",
2622 		    __func__, sb, sb->sb_flags, lr_saved);
2623 		/* NOTREACHED */
2624 	} else if (so->so_usecount < 0) {
2625 		panic("%s: sb=%p sb_flags=0x%x sb_so=%p usecount=%d lr=%p "
2626 		    "lrh= %s\n", __func__, sb, sb->sb_flags, so,
2627 		    so->so_usecount, lr_saved, solockhistory_nr(so));
2628 		/* NOTREACHED */
2629 	}
2630 
2631 	/*
2632 	 * The content filter thread must hold the sockbuf lock
2633 	 */
2634 	if ((so->so_flags & SOF_CONTENT_FILTER) && sb->sb_cfil_thread == tp) {
2635 		/*
2636 		 * Don't panic if we are defunct because SB_LOCK has
2637 		 * been cleared by sodefunct()
2638 		 */
2639 		if (!(so->so_flags & SOF_DEFUNCT) &&
2640 		    !(sb->sb_flags & SB_LOCK) &&
2641 		    !(so->so_state & SS_DEFUNCT) &&
2642 		    !(so->so_flags1 & SOF1_DEFUNCTINPROG)) {
2643 			panic("%s: SB_LOCK not held for %p",
2644 			    __func__, sb);
2645 		}
2646 		/* Keep the sockbuf locked and proceed */
2647 	} else {
2648 		VERIFY((sb->sb_flags & SB_LOCK) ||
2649 		    (so->so_state & SS_DEFUNCT) ||
2650 		    (so->so_flags1 & SOF1_DEFUNCTINPROG));
2651 
2652 		sb->sb_flags &= ~SB_LOCK;
2653 
2654 		if (sb->sb_wantlock > 0) {
2655 			/*
2656 			 * We may get here from sorflush(), in which case "sb"
2657 			 * may not point to the real socket buffer.  Use the
2658 			 * actual socket buffer address from the socket instead.
2659 			 */
2660 			wakeup((sb->sb_flags & SB_RECV) ? &so->so_rcv.sb_flags :
2661 			    &so->so_snd.sb_flags);
2662 		}
2663 	}
2664 
2665 	if (!keeplocked) {      /* unlock on exit */
2666 		if (so->so_flags & SOF_MP_SUBFLOW || SOCK_DOM(so) == PF_MULTIPATH) {
2667 			(*so->so_proto->pr_unlock)(so, 1, lr_saved);
2668 		} else {
2669 			lck_mtx_t *mutex_held;
2670 
2671 			if (so->so_proto->pr_getlock != NULL) {
2672 				mutex_held = (*so->so_proto->pr_getlock)(so, PR_F_WILLUNLOCK);
2673 			} else {
2674 				mutex_held = so->so_proto->pr_domain->dom_mtx;
2675 			}
2676 
2677 			LCK_MTX_ASSERT(mutex_held, LCK_MTX_ASSERT_OWNED);
2678 
2679 			VERIFY(so->so_usecount > 0);
2680 			so->so_usecount--;
2681 			so->unlock_lr[so->next_unlock_lr] = lr_saved;
2682 			so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
2683 			lck_mtx_unlock(mutex_held);
2684 		}
2685 	}
2686 }
2687 
2688 void
sorwakeup(struct socket * so)2689 sorwakeup(struct socket *so)
2690 {
2691 	if (sb_notify(&so->so_rcv)) {
2692 		sowakeup(so, &so->so_rcv, NULL);
2693 	}
2694 }
2695 
2696 void
sowwakeup(struct socket * so)2697 sowwakeup(struct socket *so)
2698 {
2699 	if (sb_notify(&so->so_snd)) {
2700 		sowakeup(so, &so->so_snd, NULL);
2701 	}
2702 }
2703 
2704 static void
soevupcall(struct socket * so,uint32_t hint)2705 soevupcall(struct socket *so, uint32_t hint)
2706 {
2707 	if (so->so_event != NULL) {
2708 		caddr_t __single so_eventarg = so->so_eventarg;
2709 
2710 		hint &= so->so_eventmask;
2711 		if (hint != 0) {
2712 			so->so_event(so, so_eventarg, hint);
2713 		}
2714 	}
2715 }
2716 
2717 void
soevent(struct socket * so,uint32_t hint)2718 soevent(struct socket *so, uint32_t hint)
2719 {
2720 	if (net_wake_pkt_debug > 0 && (hint & SO_FILT_HINT_WAKE_PKT)) {
2721 		os_log(OS_LOG_DEFAULT, "%s: SO_FILT_HINT_WAKE_PKT so %p",
2722 		    __func__, so);
2723 	}
2724 
2725 	if (so->so_flags & SOF_KNOTE) {
2726 		KNOTE(&so->so_klist, hint);
2727 	}
2728 
2729 	soevupcall(so, hint);
2730 
2731 	/*
2732 	 * Don't post an event if this a subflow socket or
2733 	 * the app has opted out of using cellular interface
2734 	 */
2735 	if ((hint & SO_FILT_HINT_IFDENIED) &&
2736 	    !(so->so_flags & SOF_MP_SUBFLOW) &&
2737 	    !(so->so_restrictions & SO_RESTRICT_DENY_CELLULAR) &&
2738 	    !(so->so_restrictions & SO_RESTRICT_DENY_EXPENSIVE) &&
2739 	    !(so->so_restrictions & SO_RESTRICT_DENY_CONSTRAINED)) {
2740 		soevent_ifdenied(so);
2741 	}
2742 }
2743 
2744 static void
soevent_ifdenied(struct socket * so)2745 soevent_ifdenied(struct socket *so)
2746 {
2747 	struct kev_netpolicy_ifdenied ev_ifdenied;
2748 
2749 	bzero(&ev_ifdenied, sizeof(ev_ifdenied));
2750 	/*
2751 	 * The event consumer is interested about the effective {upid,pid,uuid}
2752 	 * info which can be different than the those related to the process
2753 	 * that recently performed a system call on the socket, i.e. when the
2754 	 * socket is delegated.
2755 	 */
2756 	if (so->so_flags & SOF_DELEGATED) {
2757 		ev_ifdenied.ev_data.eupid = so->e_upid;
2758 		ev_ifdenied.ev_data.epid = so->e_pid;
2759 		uuid_copy(ev_ifdenied.ev_data.euuid, so->e_uuid);
2760 	} else {
2761 		ev_ifdenied.ev_data.eupid = so->last_upid;
2762 		ev_ifdenied.ev_data.epid = so->last_pid;
2763 		uuid_copy(ev_ifdenied.ev_data.euuid, so->last_uuid);
2764 	}
2765 
2766 	if (++so->so_ifdenied_notifies > 1) {
2767 		/*
2768 		 * Allow for at most one kernel event to be generated per
2769 		 * socket; so_ifdenied_notifies is reset upon changes in
2770 		 * the UUID policy.  See comments in inp_update_policy.
2771 		 */
2772 		if (net_io_policy_log) {
2773 			uuid_string_t buf;
2774 
2775 			uuid_unparse(ev_ifdenied.ev_data.euuid, buf);
2776 			log(LOG_DEBUG, "%s[%d]: so %llu [%d,%d] epid %llu "
2777 			    "euuid %s%s has %d redundant events supressed\n",
2778 			    __func__, so->last_pid,
2779 			    so->so_gencnt, SOCK_DOM(so),
2780 			    SOCK_TYPE(so), ev_ifdenied.ev_data.epid, buf,
2781 			    ((so->so_flags & SOF_DELEGATED) ?
2782 			    " [delegated]" : ""), so->so_ifdenied_notifies);
2783 		}
2784 	} else {
2785 		if (net_io_policy_log) {
2786 			uuid_string_t buf;
2787 
2788 			uuid_unparse(ev_ifdenied.ev_data.euuid, buf);
2789 			log(LOG_DEBUG, "%s[%d]: so %llu [%d,%d] epid %llu "
2790 			    "euuid %s%s event posted\n", __func__,
2791 			    so->last_pid, so->so_gencnt,
2792 			    SOCK_DOM(so), SOCK_TYPE(so),
2793 			    ev_ifdenied.ev_data.epid, buf,
2794 			    ((so->so_flags & SOF_DELEGATED) ?
2795 			    " [delegated]" : ""));
2796 		}
2797 		netpolicy_post_msg(KEV_NETPOLICY_IFDENIED, &ev_ifdenied.ev_data,
2798 		    sizeof(ev_ifdenied));
2799 	}
2800 }
2801 
2802 /*
2803  * Make a copy of a sockaddr in a malloced buffer of type SONAME.
2804  */
2805 struct sockaddr *
dup_sockaddr(struct sockaddr * sa,int canwait)2806 dup_sockaddr(struct sockaddr *sa, int canwait)
2807 {
2808 	struct sockaddr *sa2;
2809 
2810 	sa2 = SA(alloc_sockaddr(sa->sa_len, canwait ? Z_WAITOK : Z_NOWAIT));
2811 	if (sa2 != NULL) {
2812 		SOCKADDR_COPY(sa, sa2, sa->sa_len);
2813 	}
2814 	return sa2;
2815 }
2816 
2817 /*
2818  * Create an external-format (``xsocket'') structure using the information
2819  * in the kernel-format socket structure pointed to by so.  This is done
2820  * to reduce the spew of irrelevant information over this interface,
2821  * to isolate user code from changes in the kernel structure, and
2822  * potentially to provide information-hiding if we decide that
2823  * some of this information should be hidden from users.
2824  */
2825 void
sotoxsocket(struct socket * so,struct xsocket * xso)2826 sotoxsocket(struct socket *so, struct xsocket *xso)
2827 {
2828 	xso->xso_len = sizeof(*xso);
2829 	xso->xso_so = (_XSOCKET_PTR(struct socket *))VM_KERNEL_ADDRHASH(so);
2830 	xso->so_type = so->so_type;
2831 	xso->so_options = (short)(so->so_options & 0xffff);
2832 	xso->so_linger = so->so_linger;
2833 	xso->so_state = so->so_state;
2834 	xso->so_pcb = (_XSOCKET_PTR(caddr_t))VM_KERNEL_ADDRHASH(so->so_pcb);
2835 	if (so->so_proto) {
2836 		xso->xso_protocol = SOCK_PROTO(so);
2837 		xso->xso_family = SOCK_DOM(so);
2838 	} else {
2839 		xso->xso_protocol = xso->xso_family = 0;
2840 	}
2841 	xso->so_qlen = so->so_qlen;
2842 	xso->so_incqlen = so->so_incqlen;
2843 	xso->so_qlimit = so->so_qlimit;
2844 	xso->so_timeo = so->so_timeo;
2845 	xso->so_error = so->so_error;
2846 	xso->so_pgid = so->so_pgid;
2847 	xso->so_oobmark = so->so_oobmark;
2848 	sbtoxsockbuf(&so->so_snd, &xso->so_snd);
2849 	sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
2850 	xso->so_uid = kauth_cred_getuid(so->so_cred);
2851 }
2852 
2853 
2854 #if XNU_TARGET_OS_OSX
2855 
2856 void
sotoxsocket64(struct socket * so,struct xsocket64 * xso)2857 sotoxsocket64(struct socket *so, struct xsocket64 *xso)
2858 {
2859 	xso->xso_len = sizeof(*xso);
2860 	xso->xso_so = (u_int64_t)VM_KERNEL_ADDRHASH(so);
2861 	xso->so_type = so->so_type;
2862 	xso->so_options = (short)(so->so_options & 0xffff);
2863 	xso->so_linger = so->so_linger;
2864 	xso->so_state = so->so_state;
2865 	xso->so_pcb = (u_int64_t)VM_KERNEL_ADDRHASH(so->so_pcb);
2866 	if (so->so_proto) {
2867 		xso->xso_protocol = SOCK_PROTO(so);
2868 		xso->xso_family = SOCK_DOM(so);
2869 	} else {
2870 		xso->xso_protocol = xso->xso_family = 0;
2871 	}
2872 	xso->so_qlen = so->so_qlen;
2873 	xso->so_incqlen = so->so_incqlen;
2874 	xso->so_qlimit = so->so_qlimit;
2875 	xso->so_timeo = so->so_timeo;
2876 	xso->so_error = so->so_error;
2877 	xso->so_pgid = so->so_pgid;
2878 	xso->so_oobmark = so->so_oobmark;
2879 	sbtoxsockbuf(&so->so_snd, &xso->so_snd);
2880 	sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
2881 	xso->so_uid = kauth_cred_getuid(so->so_cred);
2882 }
2883 
2884 #endif /* XNU_TARGET_OS_OSX */
2885 
2886 /*
2887  * This does the same for sockbufs.  Note that the xsockbuf structure,
2888  * since it is always embedded in a socket, does not include a self
2889  * pointer nor a length.  We make this entry point public in case
2890  * some other mechanism needs it.
2891  */
2892 void
sbtoxsockbuf(struct sockbuf * sb,struct xsockbuf * xsb)2893 sbtoxsockbuf(struct sockbuf *sb, struct xsockbuf *xsb)
2894 {
2895 	xsb->sb_cc = sb->sb_cc;
2896 	xsb->sb_hiwat = sb->sb_hiwat;
2897 	xsb->sb_mbcnt = sb->sb_mbcnt;
2898 	xsb->sb_mbmax = sb->sb_mbmax;
2899 	xsb->sb_lowat = sb->sb_lowat;
2900 	xsb->sb_flags = (short)sb->sb_flags;
2901 	xsb->sb_timeo = (short)
2902 	    ((sb->sb_timeo.tv_sec * hz) + sb->sb_timeo.tv_usec / tick);
2903 	if (xsb->sb_timeo == 0 && sb->sb_timeo.tv_usec != 0) {
2904 		xsb->sb_timeo = 1;
2905 	}
2906 }
2907 
2908 /*
2909  * Based on the policy set by an all knowing decison maker, throttle sockets
2910  * that either have been marked as belonging to "background" process.
2911  */
2912 inline int
soisthrottled(struct socket * so)2913 soisthrottled(struct socket *so)
2914 {
2915 	return so->so_flags1 & SOF1_TRAFFIC_MGT_SO_BACKGROUND;
2916 }
2917 
2918 inline int
soisprivilegedtraffic(struct socket * so)2919 soisprivilegedtraffic(struct socket *so)
2920 {
2921 	return (so->so_flags & SOF_PRIVILEGED_TRAFFIC_CLASS) ? 1 : 0;
2922 }
2923 
2924 inline int
soissrcbackground(struct socket * so)2925 soissrcbackground(struct socket *so)
2926 {
2927 	return (so->so_flags1 & SOF1_TRAFFIC_MGT_SO_BACKGROUND) ||
2928 	       IS_SO_TC_BACKGROUND(so->so_traffic_class);
2929 }
2930 
2931 inline int
soissrcrealtime(struct socket * so)2932 soissrcrealtime(struct socket *so)
2933 {
2934 	return so->so_traffic_class >= SO_TC_AV &&
2935 	       so->so_traffic_class <= SO_TC_VO;
2936 }
2937 
2938 inline int
soissrcbesteffort(struct socket * so)2939 soissrcbesteffort(struct socket *so)
2940 {
2941 	return so->so_traffic_class == SO_TC_BE ||
2942 	       so->so_traffic_class == SO_TC_RD ||
2943 	       so->so_traffic_class == SO_TC_OAM;
2944 }
2945 
2946 void
soclearfastopen(struct socket * so)2947 soclearfastopen(struct socket *so)
2948 {
2949 	if (so->so_flags1 & SOF1_PRECONNECT_DATA) {
2950 		so->so_flags1 &= ~SOF1_PRECONNECT_DATA;
2951 	}
2952 
2953 	if (so->so_flags1 & SOF1_DATA_IDEMPOTENT) {
2954 		so->so_flags1 &= ~SOF1_DATA_IDEMPOTENT;
2955 	}
2956 }
2957 
2958 void
sonullevent(struct socket * so,void * arg,uint32_t hint)2959 sonullevent(struct socket *so, void *arg, uint32_t hint)
2960 {
2961 #pragma unused(so, arg, hint)
2962 }
2963 
2964 /*
2965  * Here is the definition of some of the basic objects in the kern.ipc
2966  * branch of the MIB.
2967  */
2968 SYSCTL_NODE(_kern, KERN_IPC, ipc,
2969     CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_ANYBODY, 0, "IPC");
2970 
2971 /* Check that the maximum socket buffer size is within a range */
2972 
2973 static int
2974 sysctl_sb_max SYSCTL_HANDLER_ARGS
2975 {
2976 #pragma unused(oidp, arg1, arg2)
2977 	u_int32_t new_value;
2978 	int changed = 0;
2979 	int error = sysctl_io_number(req, sb_max, sizeof(u_int32_t),
2980 	    &new_value, &changed);
2981 	if (!error && changed) {
2982 		if (new_value > LOW_SB_MAX && new_value <= high_sb_max) {
2983 			sb_max = new_value;
2984 		} else {
2985 			error = ERANGE;
2986 		}
2987 	}
2988 	return error;
2989 }
2990 
2991 SYSCTL_PROC(_kern_ipc, KIPC_MAXSOCKBUF, maxsockbuf,
2992     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
2993     &sb_max, 0, &sysctl_sb_max, "IU", "Maximum socket buffer size");
2994 
2995 SYSCTL_INT(_kern_ipc, KIPC_SOCKBUF_WASTE, sockbuf_waste_factor,
2996     CTLFLAG_RW | CTLFLAG_LOCKED, &sb_efficiency, 0, "");
2997 
2998 SYSCTL_INT(_kern_ipc, KIPC_NMBCLUSTERS, nmbclusters,
2999     CTLFLAG_RD | CTLFLAG_LOCKED, &nmbclusters, 0, "");
3000 
3001 SYSCTL_INT(_kern_ipc, OID_AUTO, njcl,
3002     CTLFLAG_RD | CTLFLAG_LOCKED, &njcl, 0, "");
3003 
3004 SYSCTL_INT(_kern_ipc, OID_AUTO, njclbytes,
3005     CTLFLAG_RD | CTLFLAG_LOCKED, &njclbytes, 0, "");
3006 
3007 SYSCTL_INT(_kern_ipc, KIPC_SOQLIMITCOMPAT, soqlimitcompat,
3008     CTLFLAG_RW | CTLFLAG_LOCKED, &soqlimitcompat, 1,
3009     "Enable socket queue limit compatibility");
3010 
3011 /*
3012  * Hack alert -- rdar://33572856
3013  * A loopback test we cannot change was failing because it sets
3014  * SO_SENDTIMEO to 5 seconds and that's also the value
3015  * of the minimum persist timer. Because of the persist timer,
3016  * the connection was not idle for 5 seconds and SO_SNDTIMEO
3017  * was not triggering at 5 seconds causing the test failure.
3018  * As a workaround we check the sysctl soqlencomp the test is already
3019  * setting to set disable auto tuning of the receive buffer.
3020  */
3021 
3022 extern u_int32_t tcp_do_autorcvbuf;
3023 
3024 static int
3025 sysctl_soqlencomp SYSCTL_HANDLER_ARGS
3026 {
3027 #pragma unused(oidp, arg1, arg2)
3028 	u_int32_t new_value;
3029 	int changed = 0;
3030 	int error = sysctl_io_number(req, soqlencomp, sizeof(u_int32_t),
3031 	    &new_value, &changed);
3032 	if (!error && changed) {
3033 		soqlencomp = new_value;
3034 		if (new_value != 0) {
3035 			tcp_do_autorcvbuf = 0;
3036 			tcptv_persmin_val = 6 * TCP_RETRANSHZ;
3037 		}
3038 	}
3039 	return error;
3040 }
3041 SYSCTL_PROC(_kern_ipc, OID_AUTO, soqlencomp,
3042     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
3043     &soqlencomp, 0, &sysctl_soqlencomp, "IU", "");
3044 
3045 SYSCTL_NODE(_kern_ipc, OID_AUTO, io_policy, CTLFLAG_RW, 0, "network IO policy");
3046 
3047 SYSCTL_INT(_kern_ipc_io_policy, OID_AUTO, log, CTLFLAG_RW | CTLFLAG_LOCKED,
3048     &net_io_policy_log, 0, "");
3049 
3050 #if CONFIG_PROC_UUID_POLICY
3051 SYSCTL_INT(_kern_ipc_io_policy, OID_AUTO, uuid, CTLFLAG_RW | CTLFLAG_LOCKED,
3052     &net_io_policy_uuid, 0, "");
3053 #endif /* CONFIG_PROC_UUID_POLICY */
3054