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