2 * Copyright (c) 1998-2020 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
30 * Copyright (c) 1982, 1986, 1988, 1990, 1993
31 * The Regents of the University of California. All rights reserved.
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
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.
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
61 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
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,
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/filedesc.h>
74 #include <sys/proc_internal.h>
75 #include <sys/kauth.h>
76 #include <sys/file_internal.h>
77 #include <sys/fcntl.h>
78 #include <sys/malloc.h>
80 #include <sys/domain.h>
81 #include <sys/kernel.h>
82 #include <sys/event.h>
84 #include <sys/protosw.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/resourcevar.h>
88 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/syslog.h>
92 #include <sys/uio_internal.h>
94 #include <sys/kdebug.h>
98 #include <sys/kern_event.h>
99 #include <net/route.h>
100 #include <net/init.h>
101 #include <net/net_api_stats.h>
102 #include <net/ntstat.h>
103 #include <net/content_filter.h>
104 #include <netinet/in.h>
105 #include <netinet/in_pcb.h>
106 #include <netinet/in_tclass.h>
107 #include <netinet/in_var.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet/ip6.h>
110 #include <netinet6/ip6_var.h>
111 #include <netinet/flow_divert.h>
112 #include <kern/zalloc.h>
113 #include <kern/locks.h>
114 #include <machine/limits.h>
115 #include <libkern/OSAtomic.h>
116 #include <pexpert/pexpert.h>
117 #include <kern/assert.h>
118 #include <kern/task.h>
119 #include <kern/policy_internal.h>
121 #include <sys/kpi_mbuf.h>
122 #include <sys/mcache.h>
123 #include <sys/unpcb.h>
124 #include <libkern/section_keywords.h>
127 #include <security/mac_framework.h>
131 #include <netinet/mp_pcb.h>
132 #include <netinet/mptcp_var.h>
133 #endif /* MULTIPATH */
135 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
137 #if DEBUG || DEVELOPMENT
138 #define DEBUG_KERNEL_ADDRPERM(_v) (_v)
140 #define DEBUG_KERNEL_ADDRPERM(_v) VM_KERNEL_ADDRPERM(_v)
143 /* TODO: this should be in a header file somewhere */
144 extern char *proc_name_address(void *p
);
146 static u_int32_t so_cache_hw
; /* High water mark for socache */
147 static u_int32_t so_cache_timeouts
; /* number of timeouts */
148 static u_int32_t so_cache_max_freed
; /* max freed per timeout */
149 static u_int32_t cached_sock_count
= 0;
150 STAILQ_HEAD(, socket
) so_cache_head
;
151 int max_cached_sock_count
= MAX_CACHED_SOCKETS
;
152 static u_int32_t so_cache_time
;
153 static int socketinit_done
;
154 static struct zone
*so_cache_zone
;
156 static lck_grp_t
*so_cache_mtx_grp
;
157 static lck_attr_t
*so_cache_mtx_attr
;
158 static lck_grp_attr_t
*so_cache_mtx_grp_attr
;
159 static lck_mtx_t
*so_cache_mtx
;
161 #include <machine/limits.h>
163 static int filt_sorattach(struct knote
*kn
, struct kevent_qos_s
*kev
);
164 static void filt_sordetach(struct knote
*kn
);
165 static int filt_soread(struct knote
*kn
, long hint
);
166 static int filt_sortouch(struct knote
*kn
, struct kevent_qos_s
*kev
);
167 static int filt_sorprocess(struct knote
*kn
, struct kevent_qos_s
*kev
);
169 static int filt_sowattach(struct knote
*kn
, struct kevent_qos_s
*kev
);
170 static void filt_sowdetach(struct knote
*kn
);
171 static int filt_sowrite(struct knote
*kn
, long hint
);
172 static int filt_sowtouch(struct knote
*kn
, struct kevent_qos_s
*kev
);
173 static int filt_sowprocess(struct knote
*kn
, struct kevent_qos_s
*kev
);
175 static int filt_sockattach(struct knote
*kn
, struct kevent_qos_s
*kev
);
176 static void filt_sockdetach(struct knote
*kn
);
177 static int filt_sockev(struct knote
*kn
, long hint
);
178 static int filt_socktouch(struct knote
*kn
, struct kevent_qos_s
*kev
);
179 static int filt_sockprocess(struct knote
*kn
, struct kevent_qos_s
*kev
);
181 static int sooptcopyin_timeval(struct sockopt
*, struct timeval
*);
182 static int sooptcopyout_timeval(struct sockopt
*, const struct timeval
*);
184 SECURITY_READ_ONLY_EARLY(struct filterops
) soread_filtops
= {
186 .f_attach
= filt_sorattach
,
187 .f_detach
= filt_sordetach
,
188 .f_event
= filt_soread
,
189 .f_touch
= filt_sortouch
,
190 .f_process
= filt_sorprocess
,
193 SECURITY_READ_ONLY_EARLY(struct filterops
) sowrite_filtops
= {
195 .f_attach
= filt_sowattach
,
196 .f_detach
= filt_sowdetach
,
197 .f_event
= filt_sowrite
,
198 .f_touch
= filt_sowtouch
,
199 .f_process
= filt_sowprocess
,
202 SECURITY_READ_ONLY_EARLY(struct filterops
) sock_filtops
= {
204 .f_attach
= filt_sockattach
,
205 .f_detach
= filt_sockdetach
,
206 .f_event
= filt_sockev
,
207 .f_touch
= filt_socktouch
,
208 .f_process
= filt_sockprocess
,
211 SECURITY_READ_ONLY_EARLY(struct filterops
) soexcept_filtops
= {
213 .f_attach
= filt_sorattach
,
214 .f_detach
= filt_sordetach
,
215 .f_event
= filt_soread
,
216 .f_touch
= filt_sortouch
,
217 .f_process
= filt_sorprocess
,
220 SYSCTL_DECL(_kern_ipc
);
222 #define EVEN_MORE_LOCKING_DEBUG 0
224 int socket_debug
= 0;
225 SYSCTL_INT(_kern_ipc
, OID_AUTO
, socket_debug
,
226 CTLFLAG_RW
| CTLFLAG_LOCKED
, &socket_debug
, 0, "");
228 static unsigned long sodefunct_calls
= 0;
229 SYSCTL_LONG(_kern_ipc
, OID_AUTO
, sodefunct_calls
, CTLFLAG_LOCKED
,
230 &sodefunct_calls
, "");
232 ZONE_DECLARE(socket_zone
, "socket", sizeof(struct socket
), ZC_ZFREE_CLEARMEM
);
233 so_gen_t so_gencnt
; /* generation count for sockets */
235 MALLOC_DEFINE(M_SONAME
, "soname", "socket name");
236 MALLOC_DEFINE(M_PCB
, "pcb", "protocol control block");
238 #define DBG_LAYER_IN_BEG NETDBG_CODE(DBG_NETSOCK, 0)
239 #define DBG_LAYER_IN_END NETDBG_CODE(DBG_NETSOCK, 2)
240 #define DBG_LAYER_OUT_BEG NETDBG_CODE(DBG_NETSOCK, 1)
241 #define DBG_LAYER_OUT_END NETDBG_CODE(DBG_NETSOCK, 3)
242 #define DBG_FNC_SOSEND NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 1)
243 #define DBG_FNC_SOSEND_LIST NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 3)
244 #define DBG_FNC_SORECEIVE NETDBG_CODE(DBG_NETSOCK, (8 << 8))
245 #define DBG_FNC_SORECEIVE_LIST NETDBG_CODE(DBG_NETSOCK, (8 << 8) | 3)
246 #define DBG_FNC_SOSHUTDOWN NETDBG_CODE(DBG_NETSOCK, (9 << 8))
248 #define MAX_SOOPTGETM_SIZE (128 * MCLBYTES)
250 int somaxconn
= SOMAXCONN
;
251 SYSCTL_INT(_kern_ipc
, KIPC_SOMAXCONN
, somaxconn
,
252 CTLFLAG_RW
| CTLFLAG_LOCKED
, &somaxconn
, 0, "");
254 /* Should we get a maximum also ??? */
255 static int sosendmaxchain
= 65536;
256 static int sosendminchain
= 16384;
257 static int sorecvmincopy
= 16384;
258 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendminchain
,
259 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendminchain
, 0, "");
260 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorecvmincopy
,
261 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sorecvmincopy
, 0, "");
264 * Set to enable jumbo clusters (if available) for large writes when
265 * the socket is marked with SOF_MULTIPAGES; see below.
268 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendjcl
,
269 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendjcl
, 0, "");
272 * Set this to ignore SOF_MULTIPAGES and use jumbo clusters for large
273 * writes on the socket for all protocols on any network interfaces,
274 * depending upon sosendjcl above. Be extra careful when setting this
275 * to 1, because sending down packets that cross physical pages down to
276 * broken drivers (those that falsely assume that the physical pages
277 * are contiguous) might lead to system panics or silent data corruption.
278 * When set to 0, the system will respect SOF_MULTIPAGES, which is set
279 * only for TCP sockets whose outgoing interface is IFNET_MULTIPAGES
280 * capable. Set this to 1 only for testing/debugging purposes.
282 int sosendjcl_ignore_capab
= 0;
283 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendjcl_ignore_capab
,
284 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendjcl_ignore_capab
, 0, "");
287 * Set this to ignore SOF1_IF_2KCL and use big clusters for large
288 * writes on the socket for all protocols on any network interfaces.
289 * Be extra careful when setting this to 1, because sending down packets with
290 * clusters larger that 2 KB might lead to system panics or data corruption.
291 * When set to 0, the system will respect SOF1_IF_2KCL, which is set
292 * on the outgoing interface
293 * Set this to 1 for testing/debugging purposes only.
295 int sosendbigcl_ignore_capab
= 0;
296 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendbigcl_ignore_capab
,
297 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendbigcl_ignore_capab
, 0, "");
299 int sodefunctlog
= 0;
300 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sodefunctlog
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
301 &sodefunctlog
, 0, "");
303 int sothrottlelog
= 0;
304 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sothrottlelog
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
305 &sothrottlelog
, 0, "");
307 int sorestrictrecv
= 1;
308 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorestrictrecv
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
309 &sorestrictrecv
, 0, "Enable inbound interface restrictions");
311 int sorestrictsend
= 1;
312 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorestrictsend
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
313 &sorestrictsend
, 0, "Enable outbound interface restrictions");
315 int soreserveheadroom
= 1;
316 SYSCTL_INT(_kern_ipc
, OID_AUTO
, soreserveheadroom
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
317 &soreserveheadroom
, 0, "To allocate contiguous datagram buffers");
319 #if (DEBUG || DEVELOPMENT)
320 int so_notsent_lowat_check
= 1;
321 SYSCTL_INT(_kern_ipc
, OID_AUTO
, notsent_lowat
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
322 &so_notsent_lowat_check
, 0, "enable/disable notsnet lowat check");
323 #endif /* DEBUG || DEVELOPMENT */
325 int so_accept_list_waits
= 0;
326 #if (DEBUG || DEVELOPMENT)
327 SYSCTL_INT(_kern_ipc
, OID_AUTO
, accept_list_waits
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
328 &so_accept_list_waits
, 0, "number of waits for listener incomp list");
329 #endif /* DEBUG || DEVELOPMENT */
331 extern struct inpcbinfo tcbinfo
;
333 /* TODO: these should be in header file */
334 extern int get_inpcb_str_size(void);
335 extern int get_tcp_str_size(void);
337 vm_size_t so_cache_zone_element_size
;
339 static int sodelayed_copy(struct socket
*, struct uio
*, struct mbuf
**,
341 static void cached_sock_alloc(struct socket
**, zalloc_flags_t
);
342 static void cached_sock_free(struct socket
*);
345 * Maximum of extended background idle sockets per process
346 * Set to zero to disable further setting of the option
349 #define SO_IDLE_BK_IDLE_MAX_PER_PROC 1
350 #define SO_IDLE_BK_IDLE_TIME 600
351 #define SO_IDLE_BK_IDLE_RCV_HIWAT 131072
353 struct soextbkidlestat soextbkidlestat
;
355 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, maxextbkidleperproc
,
356 CTLFLAG_RW
| CTLFLAG_LOCKED
, &soextbkidlestat
.so_xbkidle_maxperproc
, 0,
357 "Maximum of extended background idle sockets per process");
359 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, extbkidletime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
360 &soextbkidlestat
.so_xbkidle_time
, 0,
361 "Time in seconds to keep extended background idle sockets");
363 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, extbkidlercvhiwat
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
364 &soextbkidlestat
.so_xbkidle_rcvhiwat
, 0,
365 "High water mark for extended background idle sockets");
367 SYSCTL_STRUCT(_kern_ipc
, OID_AUTO
, extbkidlestat
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
368 &soextbkidlestat
, soextbkidlestat
, "");
370 int so_set_extended_bk_idle(struct socket
*, int);
374 * SOTCDB_NO_DSCP is set by default, to prevent the networking stack from
375 * setting the DSCP code on the packet based on the service class; see
376 * <rdar://problem/11277343> for details.
378 __private_extern__ u_int32_t sotcdb
= 0;
379 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sotcdb
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
385 _CASSERT(sizeof(so_gencnt
) == sizeof(uint64_t));
386 VERIFY(IS_P2ALIGNED(&so_gencnt
, sizeof(uint32_t)));
389 _CASSERT(sizeof(struct sa_endpoints
) == sizeof(struct user64_sa_endpoints
));
390 _CASSERT(offsetof(struct sa_endpoints
, sae_srcif
) == offsetof(struct user64_sa_endpoints
, sae_srcif
));
391 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddr
) == offsetof(struct user64_sa_endpoints
, sae_srcaddr
));
392 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddrlen
) == offsetof(struct user64_sa_endpoints
, sae_srcaddrlen
));
393 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddr
) == offsetof(struct user64_sa_endpoints
, sae_dstaddr
));
394 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddrlen
) == offsetof(struct user64_sa_endpoints
, sae_dstaddrlen
));
396 _CASSERT(sizeof(struct sa_endpoints
) == sizeof(struct user32_sa_endpoints
));
397 _CASSERT(offsetof(struct sa_endpoints
, sae_srcif
) == offsetof(struct user32_sa_endpoints
, sae_srcif
));
398 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddr
) == offsetof(struct user32_sa_endpoints
, sae_srcaddr
));
399 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddrlen
) == offsetof(struct user32_sa_endpoints
, sae_srcaddrlen
));
400 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddr
) == offsetof(struct user32_sa_endpoints
, sae_dstaddr
));
401 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddrlen
) == offsetof(struct user32_sa_endpoints
, sae_dstaddrlen
));
404 if (socketinit_done
) {
405 printf("socketinit: already called...\n");
410 PE_parse_boot_argn("socket_debug", &socket_debug
,
411 sizeof(socket_debug
));
414 * allocate lock group attribute and group for socket cache mutex
416 so_cache_mtx_grp_attr
= lck_grp_attr_alloc_init();
417 so_cache_mtx_grp
= lck_grp_alloc_init("so_cache",
418 so_cache_mtx_grp_attr
);
421 * allocate the lock attribute for socket cache mutex
423 so_cache_mtx_attr
= lck_attr_alloc_init();
425 /* cached sockets mutex */
426 so_cache_mtx
= lck_mtx_alloc_init(so_cache_mtx_grp
, so_cache_mtx_attr
);
427 if (so_cache_mtx
== NULL
) {
428 panic("%s: unable to allocate so_cache_mtx\n", __func__
);
431 STAILQ_INIT(&so_cache_head
);
433 so_cache_zone_element_size
= (vm_size_t
)(sizeof(struct socket
) + 4
434 + get_inpcb_str_size() + 4 + get_tcp_str_size());
436 so_cache_zone
= zone_create("socache zone", so_cache_zone_element_size
,
437 ZC_ZFREE_CLEARMEM
| ZC_NOENCRYPT
);
439 bzero(&soextbkidlestat
, sizeof(struct soextbkidlestat
));
440 soextbkidlestat
.so_xbkidle_maxperproc
= SO_IDLE_BK_IDLE_MAX_PER_PROC
;
441 soextbkidlestat
.so_xbkidle_time
= SO_IDLE_BK_IDLE_TIME
;
442 soextbkidlestat
.so_xbkidle_rcvhiwat
= SO_IDLE_BK_IDLE_RCV_HIWAT
;
446 socket_tclass_init();
449 #endif /* MULTIPATH */
453 cached_sock_alloc(struct socket
**so
, zalloc_flags_t how
)
458 lck_mtx_lock(so_cache_mtx
);
460 if (!STAILQ_EMPTY(&so_cache_head
)) {
461 VERIFY(cached_sock_count
> 0);
463 *so
= STAILQ_FIRST(&so_cache_head
);
464 STAILQ_REMOVE_HEAD(&so_cache_head
, so_cache_ent
);
465 STAILQ_NEXT((*so
), so_cache_ent
) = NULL
;
468 lck_mtx_unlock(so_cache_mtx
);
470 temp
= (*so
)->so_saved_pcb
;
471 bzero((caddr_t
)*so
, sizeof(struct socket
));
473 (*so
)->so_saved_pcb
= temp
;
475 lck_mtx_unlock(so_cache_mtx
);
477 *so
= zalloc_flags(so_cache_zone
, how
| Z_ZERO
);
480 * Define offsets for extra structures into our
481 * single block of memory. Align extra structures
482 * on longword boundaries.
485 offset
= (uintptr_t)*so
;
486 offset
+= sizeof(struct socket
);
488 offset
= ALIGN(offset
);
490 (*so
)->so_saved_pcb
= (caddr_t
)offset
;
491 offset
+= get_inpcb_str_size();
493 offset
= ALIGN(offset
);
495 ((struct inpcb
*)(void *)(*so
)->so_saved_pcb
)->inp_saved_ppcb
=
499 OSBitOrAtomic(SOF1_CACHED_IN_SOCK_LAYER
, &(*so
)->so_flags1
);
503 cached_sock_free(struct socket
*so
)
505 lck_mtx_lock(so_cache_mtx
);
507 so_cache_time
= net_uptime();
508 if (++cached_sock_count
> max_cached_sock_count
) {
510 lck_mtx_unlock(so_cache_mtx
);
511 zfree(so_cache_zone
, so
);
513 if (so_cache_hw
< cached_sock_count
) {
514 so_cache_hw
= cached_sock_count
;
517 STAILQ_INSERT_TAIL(&so_cache_head
, so
, so_cache_ent
);
519 so
->cache_timestamp
= so_cache_time
;
520 lck_mtx_unlock(so_cache_mtx
);
525 so_update_last_owner_locked(struct socket
*so
, proc_t self
)
527 if (so
->last_pid
!= 0) {
529 * last_pid and last_upid should remain zero for sockets
530 * created using sock_socket. The check above achieves that
532 if (self
== PROC_NULL
) {
533 self
= current_proc();
536 if (so
->last_upid
!= proc_uniqueid(self
) ||
537 so
->last_pid
!= proc_pid(self
)) {
538 so
->last_upid
= proc_uniqueid(self
);
539 so
->last_pid
= proc_pid(self
);
540 proc_getexecutableuuid(self
, so
->last_uuid
,
541 sizeof(so
->last_uuid
));
542 if (so
->so_proto
!= NULL
&& so
->so_proto
->pr_update_last_owner
!= NULL
) {
543 (*so
->so_proto
->pr_update_last_owner
)(so
, self
, NULL
);
546 proc_pidoriginatoruuid(so
->so_vuuid
, sizeof(so
->so_vuuid
));
551 so_update_policy(struct socket
*so
)
553 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
554 (void) inp_update_policy(sotoinpcb(so
));
560 so_update_necp_policy(struct socket
*so
, struct sockaddr
*override_local_addr
,
561 struct sockaddr
*override_remote_addr
)
563 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
564 inp_update_necp_policy(sotoinpcb(so
), override_local_addr
,
565 override_remote_addr
, 0);
575 boolean_t rc
= FALSE
;
577 lck_mtx_lock(so_cache_mtx
);
579 so_cache_time
= net_uptime();
581 while (!STAILQ_EMPTY(&so_cache_head
)) {
582 VERIFY(cached_sock_count
> 0);
583 p
= STAILQ_FIRST(&so_cache_head
);
584 if ((so_cache_time
- p
->cache_timestamp
) <
585 SO_CACHE_TIME_LIMIT
) {
589 STAILQ_REMOVE_HEAD(&so_cache_head
, so_cache_ent
);
592 zfree(so_cache_zone
, p
);
594 if (++n_freed
>= SO_CACHE_MAX_FREE_BATCH
) {
595 so_cache_max_freed
++;
600 /* Schedule again if there is more to cleanup */
601 if (!STAILQ_EMPTY(&so_cache_head
)) {
605 lck_mtx_unlock(so_cache_mtx
);
610 * Get a socket structure from our zone, and initialize it.
611 * We don't implement `waitok' yet (see comments in uipc_domain.c).
612 * Note that it would probably be better to allocate socket
613 * and PCB at the same time, but I'm not convinced that all
614 * the protocols can be easily modified to do this.
617 soalloc(int waitok
, int dom
, int type
)
619 zalloc_flags_t how
= waitok
? Z_WAITOK
: Z_NOWAIT
;
622 if ((dom
== PF_INET
) && (type
== SOCK_STREAM
)) {
623 cached_sock_alloc(&so
, how
);
625 so
= zalloc_flags(socket_zone
, how
| Z_ZERO
);
628 so
->so_gencnt
= OSIncrementAtomic64((SInt64
*)&so_gencnt
);
631 * Increment the socket allocation statistics
633 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_alloc_total
);
640 socreate_internal(int dom
, struct socket
**aso
, int type
, int proto
,
641 struct proc
*p
, uint32_t flags
, struct proc
*ep
)
646 #if defined(XNU_TARGET_OS_OSX)
651 extern int tcpconsdebug
;
658 prp
= pffindproto(dom
, proto
, type
);
660 prp
= pffindtype(dom
, type
);
663 if (prp
== NULL
|| prp
->pr_usrreqs
->pru_attach
== NULL
) {
664 if (pffinddomain(dom
) == NULL
) {
668 if (pffindprotonotype(dom
, proto
) != NULL
) {
672 return EPROTONOSUPPORT
;
674 if (prp
->pr_type
!= type
) {
677 so
= soalloc(1, dom
, type
);
684 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_local_total
);
687 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_inet_total
);
688 if (type
== SOCK_STREAM
) {
689 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_inet_stream_total
);
691 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_inet_dgram_total
);
695 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_route_total
);
698 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_ndrv_total
);
701 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_key_total
);
704 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_inet6_total
);
705 if (type
== SOCK_STREAM
) {
706 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_inet6_stream_total
);
708 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_inet6_dgram_total
);
712 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_system_total
);
715 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_multipath_total
);
718 INC_ATOMIC_INT64_LIM(net_api_stats
.nas_socket_domain_other_total
);
722 if (flags
& SOCF_MPTCP
) {
723 so
->so_state
|= SS_NBIO
;
726 TAILQ_INIT(&so
->so_incomp
);
727 TAILQ_INIT(&so
->so_comp
);
729 so
->last_upid
= proc_uniqueid(p
);
730 so
->last_pid
= proc_pid(p
);
731 proc_getexecutableuuid(p
, so
->last_uuid
, sizeof(so
->last_uuid
));
732 proc_pidoriginatoruuid(so
->so_vuuid
, sizeof(so
->so_vuuid
));
734 if (ep
!= PROC_NULL
&& ep
!= p
) {
735 so
->e_upid
= proc_uniqueid(ep
);
736 so
->e_pid
= proc_pid(ep
);
737 proc_getexecutableuuid(ep
, so
->e_uuid
, sizeof(so
->e_uuid
));
738 so
->so_flags
|= SOF_DELEGATED
;
739 #if defined(XNU_TARGET_OS_OSX)
740 if (ep
->p_responsible_pid
!= so
->e_pid
) {
741 rpid
= ep
->p_responsible_pid
;
746 #if defined(XNU_TARGET_OS_OSX)
747 if (rpid
< 0 && p
->p_responsible_pid
!= so
->last_pid
) {
748 rpid
= p
->p_responsible_pid
;
752 uuid_clear(so
->so_ruuid
);
754 proc_t rp
= proc_find(rpid
);
755 if (rp
!= PROC_NULL
) {
756 proc_getexecutableuuid(rp
, so
->so_ruuid
, sizeof(so
->so_ruuid
));
763 so
->so_cred
= kauth_cred_proc_ref(p
);
764 if (!suser(kauth_cred_get(), NULL
)) {
765 so
->so_state
|= SS_PRIV
;
769 so
->so_rcv
.sb_flags
|= SB_RECV
;
770 so
->so_rcv
.sb_so
= so
->so_snd
.sb_so
= so
;
771 so
->next_lock_lr
= 0;
772 so
->next_unlock_lr
= 0;
775 * Attachment will create the per pcb lock if necessary and
776 * increase refcount for creation, make sure it's done before
777 * socket is inserted in lists.
781 error
= (*prp
->pr_usrreqs
->pru_attach
)(so
, proto
, p
);
785 * If so_pcb is not zero, the socket will be leaked,
786 * so protocol attachment handler must be coded carefuly
788 so
->so_state
|= SS_NOFDREF
;
789 VERIFY(so
->so_usecount
> 0);
791 sofreelastref(so
, 1); /* will deallocate the socket */
796 * Note: needs so_pcb to be set after pru_attach
798 if (prp
->pr_update_last_owner
!= NULL
) {
799 (*prp
->pr_update_last_owner
)(so
, p
, ep
);
802 atomic_add_32(&prp
->pr_domain
->dom_refs
, 1);
804 /* Attach socket filters for this protocol */
807 if (tcpconsdebug
== 2) {
808 so
->so_options
|= SO_DEBUG
;
811 so_set_default_traffic_class(so
);
814 * If this thread or task is marked to create backgrounded sockets,
815 * mark the socket as background.
817 if (!(flags
& SOCF_MPTCP
) &&
818 proc_get_effective_thread_policy(current_thread(), TASK_POLICY_NEW_SOCKETS_BG
)) {
819 socket_set_traffic_mgt_flags(so
, TRAFFIC_MGT_SO_BACKGROUND
);
820 so
->so_background_thread
= current_thread();
825 * Don't mark Unix domain or system
826 * eligible for defunct by default.
830 so
->so_flags
|= SOF_NODEFUNCT
;
837 * Entitlements can't be checked at socket creation time except if the
838 * application requested a feature guarded by a privilege (c.f., socket
840 * The priv(9) and the Sandboxing APIs are designed with the idea that
841 * a privilege check should only be triggered by a userland request.
842 * A privilege check at socket creation time is time consuming and
843 * could trigger many authorisation error messages from the security
858 * <pru_attach>:ENOBUFS[AF_UNIX]
859 * <pru_attach>:ENOBUFS[TCP]
860 * <pru_attach>:ENOMEM[TCP]
861 * <pru_attach>:??? [other protocol families, IPSEC]
864 socreate(int dom
, struct socket
**aso
, int type
, int proto
)
866 return socreate_internal(dom
, aso
, type
, proto
, current_proc(), 0,
871 socreate_delegate(int dom
, struct socket
**aso
, int type
, int proto
, pid_t epid
)
874 struct proc
*ep
= PROC_NULL
;
876 if ((proc_selfpid() != epid
) && ((ep
= proc_find(epid
)) == PROC_NULL
)) {
881 error
= socreate_internal(dom
, aso
, type
, proto
, current_proc(), 0, ep
);
884 * It might not be wise to hold the proc reference when calling
885 * socreate_internal since it calls soalloc with M_WAITOK
888 if (ep
!= PROC_NULL
) {
897 * <pru_bind>:EINVAL Invalid argument [COMMON_START]
898 * <pru_bind>:EAFNOSUPPORT Address family not supported
899 * <pru_bind>:EADDRNOTAVAIL Address not available.
900 * <pru_bind>:EINVAL Invalid argument
901 * <pru_bind>:EAFNOSUPPORT Address family not supported [notdef]
902 * <pru_bind>:EACCES Permission denied
903 * <pru_bind>:EADDRINUSE Address in use
904 * <pru_bind>:EAGAIN Resource unavailable, try again
905 * <pru_bind>:EPERM Operation not permitted
909 * Notes: It's not possible to fully enumerate the return codes above,
910 * since socket filter authors and protocol family authors may
911 * not choose to limit their error returns to those listed, even
912 * though this may result in some software operating incorrectly.
914 * The error codes which are enumerated above are those known to
915 * be returned by the tcp_usr_bind function supplied.
918 sobindlock(struct socket
*so
, struct sockaddr
*nam
, int dolock
)
920 struct proc
*p
= current_proc();
927 so_update_last_owner_locked(so
, p
);
928 so_update_policy(so
);
931 so_update_necp_policy(so
, nam
, NULL
);
935 * If this is a bind request on a socket that has been marked
936 * as inactive, reject it now before we go any further.
938 if (so
->so_flags
& SOF_DEFUNCT
) {
940 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
941 __func__
, proc_pid(p
), proc_best_name(p
),
942 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
943 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
948 error
= sflt_bind(so
, nam
);
951 error
= (*so
->so_proto
->pr_usrreqs
->pru_bind
)(so
, nam
, p
);
955 socket_unlock(so
, 1);
958 if (error
== EJUSTRETURN
) {
966 sodealloc(struct socket
*so
)
968 kauth_cred_unref(&so
->so_cred
);
970 /* Remove any filters */
974 cfil_sock_detach(so
);
975 #endif /* CONTENT_FILTER */
977 so
->so_gencnt
= OSIncrementAtomic64((SInt64
*)&so_gencnt
);
979 if (so
->so_flags1
& SOF1_CACHED_IN_SOCK_LAYER
) {
980 cached_sock_free(so
);
982 zfree(socket_zone
, so
);
990 * <pru_listen>:EINVAL[AF_UNIX]
991 * <pru_listen>:EINVAL[TCP]
992 * <pru_listen>:EADDRNOTAVAIL[TCP] Address not available.
993 * <pru_listen>:EINVAL[TCP] Invalid argument
994 * <pru_listen>:EAFNOSUPPORT[TCP] Address family not supported [notdef]
995 * <pru_listen>:EACCES[TCP] Permission denied
996 * <pru_listen>:EADDRINUSE[TCP] Address in use
997 * <pru_listen>:EAGAIN[TCP] Resource unavailable, try again
998 * <pru_listen>:EPERM[TCP] Operation not permitted
1001 * Notes: Other <pru_listen> returns depend on the protocol family; all
1002 * <sf_listen> returns depend on what the filter author causes
1003 * their filter to return.
1006 solisten(struct socket
*so
, int backlog
)
1008 struct proc
*p
= current_proc();
1013 so_update_last_owner_locked(so
, p
);
1014 so_update_policy(so
);
1017 so_update_necp_policy(so
, NULL
, NULL
);
1020 if (so
->so_proto
== NULL
) {
1024 if ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) == 0) {
1030 * If the listen request is made on a socket that is not fully
1031 * disconnected, or on a socket that has been marked as inactive,
1032 * reject the request now.
1035 (SS_ISCONNECTED
| SS_ISCONNECTING
| SS_ISDISCONNECTING
)) ||
1036 (so
->so_flags
& SOF_DEFUNCT
)) {
1038 if (so
->so_flags
& SOF_DEFUNCT
) {
1039 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
1040 "(%d)\n", __func__
, proc_pid(p
),
1042 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1043 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1048 if ((so
->so_restrictions
& SO_RESTRICT_DENY_IN
) != 0) {
1053 error
= sflt_listen(so
);
1055 error
= (*so
->so_proto
->pr_usrreqs
->pru_listen
)(so
, p
);
1059 if (error
== EJUSTRETURN
) {
1065 if (TAILQ_EMPTY(&so
->so_comp
)) {
1066 so
->so_options
|= SO_ACCEPTCONN
;
1069 * POSIX: The implementation may have an upper limit on the length of
1070 * the listen queue-either global or per accepting socket. If backlog
1071 * exceeds this limit, the length of the listen queue is set to the
1074 * If listen() is called with a backlog argument value that is less
1075 * than 0, the function behaves as if it had been called with a backlog
1076 * argument value of 0.
1078 * A backlog argument of 0 may allow the socket to accept connections,
1079 * in which case the length of the listen queue may be set to an
1080 * implementation-defined minimum value.
1082 if (backlog
<= 0 || backlog
> somaxconn
) {
1083 backlog
= somaxconn
;
1086 so
->so_qlimit
= backlog
;
1088 socket_unlock(so
, 1);
1093 * The "accept list lock" protects the fields related to the listener queues
1094 * because we can unlock a socket to respect the lock ordering between
1095 * the listener socket and its clients sockets. The lock ordering is first to
1096 * acquire the client socket before the listener socket.
1098 * The accept list lock serializes access to the following fields:
1099 * - of the listener socket:
1104 * - of client sockets that are in so_comp or so_incomp:
1108 * As one can see the accept list lock protects the consistent of the
1109 * linkage of the client sockets.
1111 * Note that those fields may be read without holding the accept list lock
1112 * for a preflight provided the accept list lock is taken when committing
1113 * to take an action based on the result of the preflight. The preflight
1114 * saves the cost of doing the unlock/lock dance.
1117 so_acquire_accept_list(struct socket
*head
, struct socket
*so
)
1119 lck_mtx_t
*mutex_held
;
1121 if (head
->so_proto
->pr_getlock
== NULL
) {
1124 mutex_held
= (*head
->so_proto
->pr_getlock
)(head
, PR_F_WILLUNLOCK
);
1125 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1127 if (!(head
->so_flags1
& SOF1_ACCEPT_LIST_HELD
)) {
1128 head
->so_flags1
|= SOF1_ACCEPT_LIST_HELD
;
1132 socket_unlock(so
, 0);
1134 while (head
->so_flags1
& SOF1_ACCEPT_LIST_HELD
) {
1135 so_accept_list_waits
+= 1;
1136 msleep((caddr_t
)&head
->so_incomp
, mutex_held
,
1137 PSOCK
| PCATCH
, __func__
, NULL
);
1139 head
->so_flags1
|= SOF1_ACCEPT_LIST_HELD
;
1141 socket_unlock(head
, 0);
1143 socket_lock(head
, 0);
1148 so_release_accept_list(struct socket
*head
)
1150 if (head
->so_proto
->pr_getlock
!= NULL
) {
1151 lck_mtx_t
*mutex_held
;
1153 mutex_held
= (*head
->so_proto
->pr_getlock
)(head
, 0);
1154 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1156 head
->so_flags1
&= ~SOF1_ACCEPT_LIST_HELD
;
1157 wakeup((caddr_t
)&head
->so_incomp
);
1162 sofreelastref(struct socket
*so
, int dealloc
)
1164 struct socket
*head
= so
->so_head
;
1166 /* Assume socket is locked */
1168 if (!(so
->so_flags
& SOF_PCBCLEARING
) || !(so
->so_state
& SS_NOFDREF
)) {
1169 selthreadclear(&so
->so_snd
.sb_sel
);
1170 selthreadclear(&so
->so_rcv
.sb_sel
);
1171 so
->so_rcv
.sb_flags
&= ~(SB_SEL
| SB_UPCALL
);
1172 so
->so_snd
.sb_flags
&= ~(SB_SEL
| SB_UPCALL
);
1173 so
->so_event
= sonullevent
;
1178 * Need to lock the listener when the protocol has
1181 if (head
->so_proto
->pr_getlock
!= NULL
) {
1182 socket_lock(head
, 1);
1183 so_acquire_accept_list(head
, so
);
1185 if (so
->so_state
& SS_INCOMP
) {
1186 so
->so_state
&= ~SS_INCOMP
;
1187 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
1192 if (head
->so_proto
->pr_getlock
!= NULL
) {
1193 so_release_accept_list(head
);
1194 socket_unlock(head
, 1);
1196 } else if (so
->so_state
& SS_COMP
) {
1197 if (head
->so_proto
->pr_getlock
!= NULL
) {
1198 so_release_accept_list(head
);
1199 socket_unlock(head
, 1);
1202 * We must not decommission a socket that's
1203 * on the accept(2) queue. If we do, then
1204 * accept(2) may hang after select(2) indicated
1205 * that the listening socket was ready.
1207 selthreadclear(&so
->so_snd
.sb_sel
);
1208 selthreadclear(&so
->so_rcv
.sb_sel
);
1209 so
->so_rcv
.sb_flags
&= ~(SB_SEL
| SB_UPCALL
);
1210 so
->so_snd
.sb_flags
&= ~(SB_SEL
| SB_UPCALL
);
1211 so
->so_event
= sonullevent
;
1214 if (head
->so_proto
->pr_getlock
!= NULL
) {
1215 so_release_accept_list(head
);
1216 socket_unlock(head
, 1);
1218 printf("sofree: not queued\n");
1225 if (so
->so_flags
& SOF_FLOW_DIVERT
) {
1226 flow_divert_detach(so
);
1228 #endif /* FLOW_DIVERT */
1230 /* 3932268: disable upcall */
1231 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
1232 so
->so_snd
.sb_flags
&= ~(SB_UPCALL
| SB_SNDBYTE_CNT
);
1233 so
->so_event
= sonullevent
;
1241 soclose_wait_locked(struct socket
*so
)
1243 lck_mtx_t
*mutex_held
;
1245 if (so
->so_proto
->pr_getlock
!= NULL
) {
1246 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, PR_F_WILLUNLOCK
);
1248 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1250 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1253 * Double check here and return if there's no outstanding upcall;
1254 * otherwise proceed further only if SOF_UPCALLCLOSEWAIT is set.
1256 if (!so
->so_upcallusecount
|| !(so
->so_flags
& SOF_UPCALLCLOSEWAIT
)) {
1259 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
1260 so
->so_snd
.sb_flags
&= ~SB_UPCALL
;
1261 so
->so_flags
|= SOF_CLOSEWAIT
;
1263 (void) msleep((caddr_t
)&so
->so_upcallusecount
, mutex_held
, (PZERO
- 1),
1264 "soclose_wait_locked", NULL
);
1265 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1266 so
->so_flags
&= ~SOF_CLOSEWAIT
;
1270 * Close a socket on last file table reference removal.
1271 * Initiate disconnect if connected.
1272 * Free socket when disconnect complete.
1275 soclose_locked(struct socket
*so
)
1280 if (so
->so_usecount
== 0) {
1281 panic("soclose: so=%p refcount=0\n", so
);
1285 sflt_notify(so
, sock_evt_closing
, NULL
);
1287 if (so
->so_upcallusecount
) {
1288 soclose_wait_locked(so
);
1293 * We have to wait until the content filters are done
1295 if ((so
->so_flags
& SOF_CONTENT_FILTER
) != 0) {
1296 cfil_sock_close_wait(so
);
1297 cfil_sock_is_closed(so
);
1298 cfil_sock_detach(so
);
1300 #endif /* CONTENT_FILTER */
1302 if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
) {
1303 soresume(current_proc(), so
, 1);
1304 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_WANTED
;
1307 if ((so
->so_options
& SO_ACCEPTCONN
)) {
1308 struct socket
*sp
, *sonext
;
1309 int persocklock
= 0;
1310 int incomp_overflow_only
;
1313 * We do not want new connection to be added
1314 * to the connection queues
1316 so
->so_options
&= ~SO_ACCEPTCONN
;
1319 * We can drop the lock on the listener once
1320 * we've acquired the incoming list
1322 if (so
->so_proto
->pr_getlock
!= NULL
) {
1324 so_acquire_accept_list(so
, NULL
);
1325 socket_unlock(so
, 0);
1328 incomp_overflow_only
= 1;
1330 TAILQ_FOREACH_SAFE(sp
, &so
->so_incomp
, so_list
, sonext
) {
1333 * skip sockets thrown away by tcpdropdropblreq
1334 * they will get cleanup by the garbage collection.
1335 * otherwise, remove the incomp socket from the queue
1336 * and let soabort trigger the appropriate cleanup.
1338 if (sp
->so_flags
& SOF_OVERFLOW
) {
1342 if (persocklock
!= 0) {
1348 * The extra reference for the list insure the
1349 * validity of the socket pointer when we perform the
1350 * unlock of the head above
1352 if (sp
->so_state
& SS_INCOMP
) {
1353 sp
->so_state
&= ~SS_INCOMP
;
1355 TAILQ_REMOVE(&so
->so_incomp
, sp
, so_list
);
1361 panic("%s sp %p in so_incomp but !SS_INCOMP",
1365 if (persocklock
!= 0) {
1366 socket_unlock(sp
, 1);
1370 TAILQ_FOREACH_SAFE(sp
, &so
->so_comp
, so_list
, sonext
) {
1371 /* Dequeue from so_comp since sofree() won't do it */
1372 if (persocklock
!= 0) {
1376 if (sp
->so_state
& SS_COMP
) {
1377 sp
->so_state
&= ~SS_COMP
;
1379 TAILQ_REMOVE(&so
->so_comp
, sp
, so_list
);
1384 panic("%s sp %p in so_comp but !SS_COMP",
1389 socket_unlock(sp
, 1);
1393 if (incomp_overflow_only
== 0 && !TAILQ_EMPTY(&so
->so_incomp
)) {
1394 #if (DEBUG | DEVELOPMENT)
1395 panic("%s head %p so_comp not empty\n", __func__
, so
);
1396 #endif /* (DEVELOPMENT || DEBUG) */
1401 if (!TAILQ_EMPTY(&so
->so_comp
)) {
1402 #if (DEBUG | DEVELOPMENT)
1403 panic("%s head %p so_comp not empty\n", __func__
, so
);
1404 #endif /* (DEVELOPMENT || DEBUG) */
1411 so_release_accept_list(so
);
1414 if (so
->so_pcb
== NULL
) {
1415 /* 3915887: mark the socket as ready for dealloc */
1416 so
->so_flags
|= SOF_PCBCLEARING
;
1419 if (so
->so_state
& SS_ISCONNECTED
) {
1420 if ((so
->so_state
& SS_ISDISCONNECTING
) == 0) {
1421 error
= sodisconnectlocked(so
);
1426 if (so
->so_options
& SO_LINGER
) {
1427 lck_mtx_t
*mutex_held
;
1429 if ((so
->so_state
& SS_ISDISCONNECTING
) &&
1430 (so
->so_state
& SS_NBIO
)) {
1433 if (so
->so_proto
->pr_getlock
!= NULL
) {
1434 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, PR_F_WILLUNLOCK
);
1436 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1438 while (so
->so_state
& SS_ISCONNECTED
) {
1439 ts
.tv_sec
= (so
->so_linger
/ 100);
1440 ts
.tv_nsec
= (so
->so_linger
% 100) *
1441 NSEC_PER_USEC
* 1000 * 10;
1442 error
= msleep((caddr_t
)&so
->so_timeo
,
1443 mutex_held
, PSOCK
| PCATCH
, "soclose", &ts
);
1446 * It's OK when the time fires,
1447 * don't report an error
1449 if (error
== EWOULDBLOCK
) {
1458 if (so
->so_usecount
== 0) {
1459 panic("soclose: usecount is zero so=%p\n", so
);
1462 if (so
->so_pcb
!= NULL
&& !(so
->so_flags
& SOF_PCBCLEARING
)) {
1463 int error2
= (*so
->so_proto
->pr_usrreqs
->pru_detach
)(so
);
1468 if (so
->so_usecount
<= 0) {
1469 panic("soclose: usecount is zero so=%p\n", so
);
1473 if (so
->so_pcb
!= NULL
&& !(so
->so_flags
& SOF_MP_SUBFLOW
) &&
1474 (so
->so_state
& SS_NOFDREF
)) {
1475 panic("soclose: NOFDREF");
1478 so
->so_state
|= SS_NOFDREF
;
1480 if ((so
->so_flags
& SOF_KNOTE
) != 0) {
1481 KNOTE(&so
->so_klist
, SO_FILT_HINT_LOCKED
);
1484 atomic_add_32(&so
->so_proto
->pr_domain
->dom_refs
, -1);
1486 VERIFY(so
->so_usecount
> 0);
1493 soclose(struct socket
*so
)
1498 if (so
->so_retaincnt
== 0) {
1499 error
= soclose_locked(so
);
1502 * if the FD is going away, but socket is
1503 * retained in kernel remove its reference
1506 if (so
->so_usecount
< 2) {
1507 panic("soclose: retaincnt non null and so=%p "
1508 "usecount=%d\n", so
, so
->so_usecount
);
1511 socket_unlock(so
, 1);
1516 * Must be called at splnet...
1518 /* Should already be locked */
1520 soabort(struct socket
*so
)
1524 #ifdef MORE_LOCKING_DEBUG
1525 lck_mtx_t
*mutex_held
;
1527 if (so
->so_proto
->pr_getlock
!= NULL
) {
1528 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1530 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1532 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1535 if ((so
->so_flags
& SOF_ABORTED
) == 0) {
1536 so
->so_flags
|= SOF_ABORTED
;
1537 error
= (*so
->so_proto
->pr_usrreqs
->pru_abort
)(so
);
1547 soacceptlock(struct socket
*so
, struct sockaddr
**nam
, int dolock
)
1555 so_update_last_owner_locked(so
, PROC_NULL
);
1556 so_update_policy(so
);
1558 so_update_necp_policy(so
, NULL
, NULL
);
1561 if ((so
->so_state
& SS_NOFDREF
) == 0) {
1562 panic("soaccept: !NOFDREF");
1564 so
->so_state
&= ~SS_NOFDREF
;
1565 error
= (*so
->so_proto
->pr_usrreqs
->pru_accept
)(so
, nam
);
1568 socket_unlock(so
, 1);
1574 soaccept(struct socket
*so
, struct sockaddr
**nam
)
1576 return soacceptlock(so
, nam
, 1);
1580 soacceptfilter(struct socket
*so
, struct socket
*head
)
1582 struct sockaddr
*local
= NULL
, *remote
= NULL
;
1586 * Hold the lock even if this socket has not been made visible
1587 * to the filter(s). For sockets with global locks, this protects
1588 * against the head or peer going away
1591 if (sogetaddr_locked(so
, &remote
, 1) != 0 ||
1592 sogetaddr_locked(so
, &local
, 0) != 0) {
1593 so
->so_state
&= ~SS_NOFDREF
;
1594 socket_unlock(so
, 1);
1596 /* Out of resources; try it again next time */
1597 error
= ECONNABORTED
;
1601 error
= sflt_accept(head
, so
, local
, remote
);
1604 * If we get EJUSTRETURN from one of the filters, mark this socket
1605 * as inactive and return it anyway. This newly accepted socket
1606 * will be disconnected later before we hand it off to the caller.
1608 if (error
== EJUSTRETURN
) {
1610 (void) sosetdefunct(current_proc(), so
,
1611 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
, FALSE
);
1616 * This may seem like a duplication to the above error
1617 * handling part when we return ECONNABORTED, except
1618 * the following is done while holding the lock since
1619 * the socket has been exposed to the filter(s) earlier.
1621 so
->so_state
&= ~SS_NOFDREF
;
1622 socket_unlock(so
, 1);
1624 /* Propagate socket filter's error code to the caller */
1626 socket_unlock(so
, 1);
1629 /* Callee checks for NULL pointer */
1630 sock_freeaddr(remote
);
1631 sock_freeaddr(local
);
1636 * Returns: 0 Success
1637 * EOPNOTSUPP Operation not supported on socket
1638 * EISCONN Socket is connected
1639 * <pru_connect>:EADDRNOTAVAIL Address not available.
1640 * <pru_connect>:EINVAL Invalid argument
1641 * <pru_connect>:EAFNOSUPPORT Address family not supported [notdef]
1642 * <pru_connect>:EACCES Permission denied
1643 * <pru_connect>:EADDRINUSE Address in use
1644 * <pru_connect>:EAGAIN Resource unavailable, try again
1645 * <pru_connect>:EPERM Operation not permitted
1646 * <sf_connect_out>:??? [anything a filter writer might set]
1649 soconnectlock(struct socket
*so
, struct sockaddr
*nam
, int dolock
)
1652 struct proc
*p
= current_proc();
1658 so_update_last_owner_locked(so
, p
);
1659 so_update_policy(so
);
1662 so_update_necp_policy(so
, NULL
, nam
);
1666 * If this is a listening socket or if this is a previously-accepted
1667 * socket that has been marked as inactive, reject the connect request.
1669 if ((so
->so_options
& SO_ACCEPTCONN
) || (so
->so_flags
& SOF_DEFUNCT
)) {
1671 if (so
->so_flags
& SOF_DEFUNCT
) {
1672 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
1673 "(%d)\n", __func__
, proc_pid(p
),
1675 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1676 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1679 socket_unlock(so
, 1);
1684 if ((so
->so_restrictions
& SO_RESTRICT_DENY_OUT
) != 0) {
1686 socket_unlock(so
, 1);
1692 * If protocol is connection-based, can only connect once.
1693 * Otherwise, if connected, try to disconnect first.
1694 * This allows user to disconnect by connecting to, e.g.,
1697 if (so
->so_state
& (SS_ISCONNECTED
| SS_ISCONNECTING
) &&
1698 ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ||
1699 (error
= sodisconnectlocked(so
)))) {
1703 * Run connect filter before calling protocol:
1704 * - non-blocking connect returns before completion;
1706 error
= sflt_connectout(so
, nam
);
1708 if (error
== EJUSTRETURN
) {
1712 error
= (*so
->so_proto
->pr_usrreqs
->pru_connect
)
1715 so
->so_state
&= ~SS_ISCONNECTING
;
1720 socket_unlock(so
, 1);
1726 soconnect(struct socket
*so
, struct sockaddr
*nam
)
1728 return soconnectlock(so
, nam
, 1);
1732 * Returns: 0 Success
1733 * <pru_connect2>:EINVAL[AF_UNIX]
1734 * <pru_connect2>:EPROTOTYPE[AF_UNIX]
1735 * <pru_connect2>:??? [other protocol families]
1737 * Notes: <pru_connect2> is not supported by [TCP].
1740 soconnect2(struct socket
*so1
, struct socket
*so2
)
1744 socket_lock(so1
, 1);
1745 if (so2
->so_proto
->pr_lock
) {
1746 socket_lock(so2
, 1);
1749 error
= (*so1
->so_proto
->pr_usrreqs
->pru_connect2
)(so1
, so2
);
1751 socket_unlock(so1
, 1);
1752 if (so2
->so_proto
->pr_lock
) {
1753 socket_unlock(so2
, 1);
1759 soconnectxlocked(struct socket
*so
, struct sockaddr
*src
,
1760 struct sockaddr
*dst
, struct proc
*p
, uint32_t ifscope
,
1761 sae_associd_t aid
, sae_connid_t
*pcid
, uint32_t flags
, void *arg
,
1762 uint32_t arglen
, uio_t auio
, user_ssize_t
*bytes_written
)
1766 so_update_last_owner_locked(so
, p
);
1767 so_update_policy(so
);
1770 * If this is a listening socket or if this is a previously-accepted
1771 * socket that has been marked as inactive, reject the connect request.
1773 if ((so
->so_options
& SO_ACCEPTCONN
) || (so
->so_flags
& SOF_DEFUNCT
)) {
1775 if (so
->so_flags
& SOF_DEFUNCT
) {
1776 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
1777 "(%d)\n", __func__
, proc_pid(p
),
1779 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1780 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1785 if ((so
->so_restrictions
& SO_RESTRICT_DENY_OUT
) != 0) {
1790 * If protocol is connection-based, can only connect once
1791 * unless PR_MULTICONN is set. Otherwise, if connected,
1792 * try to disconnect first. This allows user to disconnect
1793 * by connecting to, e.g., a null address.
1795 if ((so
->so_state
& (SS_ISCONNECTED
| SS_ISCONNECTING
)) &&
1796 !(so
->so_proto
->pr_flags
& PR_MULTICONN
) &&
1797 ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ||
1798 (error
= sodisconnectlocked(so
)) != 0)) {
1801 if ((so
->so_proto
->pr_flags
& PR_DATA_IDEMPOTENT
) &&
1802 (flags
& CONNECT_DATA_IDEMPOTENT
)) {
1803 so
->so_flags1
|= SOF1_DATA_IDEMPOTENT
;
1805 if (flags
& CONNECT_DATA_AUTHENTICATED
) {
1806 so
->so_flags1
|= SOF1_DATA_AUTHENTICATED
;
1811 * Case 1: CONNECT_RESUME_ON_READ_WRITE set, no data.
1812 * Case 2: CONNECT_RESUME_ON_READ_WRITE set, with data (user error)
1813 * Case 3: CONNECT_RESUME_ON_READ_WRITE not set, with data
1814 * Case 3 allows user to combine write with connect even if they have
1815 * no use for TFO (such as regular TCP, and UDP).
1816 * Case 4: CONNECT_RESUME_ON_READ_WRITE not set, no data (regular case)
1818 if ((so
->so_proto
->pr_flags
& PR_PRECONN_WRITE
) &&
1819 ((flags
& CONNECT_RESUME_ON_READ_WRITE
) || auio
)) {
1820 so
->so_flags1
|= SOF1_PRECONNECT_DATA
;
1824 * If a user sets data idempotent and does not pass an uio, or
1825 * sets CONNECT_RESUME_ON_READ_WRITE, this is an error, reset
1826 * SOF1_DATA_IDEMPOTENT.
1828 if (!(so
->so_flags1
& SOF1_PRECONNECT_DATA
) &&
1829 (so
->so_flags1
& SOF1_DATA_IDEMPOTENT
)) {
1830 /* We should return EINVAL instead perhaps. */
1831 so
->so_flags1
&= ~SOF1_DATA_IDEMPOTENT
;
1835 * Run connect filter before calling protocol:
1836 * - non-blocking connect returns before completion;
1838 error
= sflt_connectout(so
, dst
);
1840 /* Disable PRECONNECT_DATA, as we don't need to send a SYN anymore. */
1841 so
->so_flags1
&= ~SOF1_PRECONNECT_DATA
;
1842 if (error
== EJUSTRETURN
) {
1846 error
= (*so
->so_proto
->pr_usrreqs
->pru_connectx
)
1847 (so
, src
, dst
, p
, ifscope
, aid
, pcid
,
1848 flags
, arg
, arglen
, auio
, bytes_written
);
1850 so
->so_state
&= ~SS_ISCONNECTING
;
1851 if (error
!= EINPROGRESS
) {
1852 so
->so_flags1
&= ~SOF1_PRECONNECT_DATA
;
1862 sodisconnectlocked(struct socket
*so
)
1866 if ((so
->so_state
& SS_ISCONNECTED
) == 0) {
1870 if (so
->so_state
& SS_ISDISCONNECTING
) {
1875 error
= (*so
->so_proto
->pr_usrreqs
->pru_disconnect
)(so
);
1877 sflt_notify(so
, sock_evt_disconnected
, NULL
);
1884 /* Locking version */
1886 sodisconnect(struct socket
*so
)
1891 error
= sodisconnectlocked(so
);
1892 socket_unlock(so
, 1);
1897 sodisconnectxlocked(struct socket
*so
, sae_associd_t aid
, sae_connid_t cid
)
1902 * Call the protocol disconnectx handler; let it handle all
1903 * matters related to the connection state of this session.
1905 error
= (*so
->so_proto
->pr_usrreqs
->pru_disconnectx
)(so
, aid
, cid
);
1908 * The event applies only for the session, not for
1909 * the disconnection of individual subflows.
1911 if (so
->so_state
& (SS_ISDISCONNECTING
| SS_ISDISCONNECTED
)) {
1912 sflt_notify(so
, sock_evt_disconnected
, NULL
);
1919 sodisconnectx(struct socket
*so
, sae_associd_t aid
, sae_connid_t cid
)
1924 error
= sodisconnectxlocked(so
, aid
, cid
);
1925 socket_unlock(so
, 1);
1929 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1932 * sosendcheck will lock the socket buffer if it isn't locked and
1933 * verify that there is space for the data being inserted.
1935 * Returns: 0 Success
1937 * sblock:EWOULDBLOCK
1944 sosendcheck(struct socket
*so
, struct sockaddr
*addr
, user_ssize_t resid
,
1945 int32_t clen
, int32_t atomic
, int flags
, int *sblocked
)
1952 if (*sblocked
== 0) {
1953 if ((so
->so_snd
.sb_flags
& SB_LOCK
) != 0 &&
1954 so
->so_send_filt_thread
!= 0 &&
1955 so
->so_send_filt_thread
== current_thread()) {
1957 * We're being called recursively from a filter,
1958 * allow this to continue. Radar 4150520.
1959 * Don't set sblocked because we don't want
1960 * to perform an unlock later.
1964 error
= sblock(&so
->so_snd
, SBLOCKWAIT(flags
));
1966 if (so
->so_flags
& SOF_DEFUNCT
) {
1976 * If a send attempt is made on a socket that has been marked
1977 * as inactive (disconnected), reject the request.
1979 if (so
->so_flags
& SOF_DEFUNCT
) {
1982 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
1983 __func__
, proc_selfpid(), proc_best_name(current_proc()),
1984 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1985 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1989 if (so
->so_state
& SS_CANTSENDMORE
) {
1992 * Can re-inject data of half closed connections
1994 if ((so
->so_state
& SS_ISDISCONNECTED
) == 0 &&
1995 so
->so_snd
.sb_cfil_thread
== current_thread() &&
1996 cfil_sock_data_pending(&so
->so_snd
) != 0) {
1998 "so %llx ignore SS_CANTSENDMORE",
1999 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
));
2001 #endif /* CONTENT_FILTER */
2005 error
= so
->so_error
;
2010 if ((so
->so_state
& SS_ISCONNECTED
) == 0) {
2011 if ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) != 0) {
2012 if (((so
->so_state
& SS_ISCONFIRMING
) == 0) &&
2013 (resid
!= 0 || clen
== 0) &&
2014 !(so
->so_flags1
& SOF1_PRECONNECT_DATA
)) {
2017 } else if (addr
== 0) {
2018 return (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ?
2019 ENOTCONN
: EDESTADDRREQ
;
2023 space
= sbspace(&so
->so_snd
);
2025 if (flags
& MSG_OOB
) {
2028 if ((atomic
&& resid
> so
->so_snd
.sb_hiwat
) ||
2029 clen
> so
->so_snd
.sb_hiwat
) {
2033 if ((space
< resid
+ clen
&&
2034 (atomic
|| (space
< (int32_t)so
->so_snd
.sb_lowat
) ||
2036 (so
->so_type
== SOCK_STREAM
&& so_wait_for_if_feedback(so
))) {
2038 * don't block the connectx call when there's more data
2039 * than can be copied.
2041 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
2045 if (space
< (int32_t)so
->so_snd
.sb_lowat
) {
2049 if ((so
->so_state
& SS_NBIO
) || (flags
& MSG_NBIO
) ||
2053 sbunlock(&so
->so_snd
, TRUE
); /* keep socket locked */
2055 error
= sbwait(&so
->so_snd
);
2057 if (so
->so_flags
& SOF_DEFUNCT
) {
2069 * If send must go all at once and message is larger than
2070 * send buffering, then hard error.
2071 * Lock against other senders.
2072 * If must go all at once and not enough room now, then
2073 * inform user that this would block and do nothing.
2074 * Otherwise, if nonblocking, send as much as possible.
2075 * The data to be sent is described by "uio" if nonzero,
2076 * otherwise by the mbuf chain "top" (which must be null
2077 * if uio is not). Data provided in mbuf chain must be small
2078 * enough to send all at once.
2080 * Returns nonzero on error, timeout or signal; callers
2081 * must check for short counts if EINTR/ERESTART are returned.
2082 * Data and control buffers are freed on return.
2084 * Returns: 0 Success
2090 * sosendcheck:EWOULDBLOCK
2094 * sosendcheck:??? [value from so_error]
2095 * <pru_send>:ECONNRESET[TCP]
2096 * <pru_send>:EINVAL[TCP]
2097 * <pru_send>:ENOBUFS[TCP]
2098 * <pru_send>:EADDRINUSE[TCP]
2099 * <pru_send>:EADDRNOTAVAIL[TCP]
2100 * <pru_send>:EAFNOSUPPORT[TCP]
2101 * <pru_send>:EACCES[TCP]
2102 * <pru_send>:EAGAIN[TCP]
2103 * <pru_send>:EPERM[TCP]
2104 * <pru_send>:EMSGSIZE[TCP]
2105 * <pru_send>:EHOSTUNREACH[TCP]
2106 * <pru_send>:ENETUNREACH[TCP]
2107 * <pru_send>:ENETDOWN[TCP]
2108 * <pru_send>:ENOMEM[TCP]
2109 * <pru_send>:ENOBUFS[TCP]
2110 * <pru_send>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
2111 * <pru_send>:EINVAL[AF_UNIX]
2112 * <pru_send>:EOPNOTSUPP[AF_UNIX]
2113 * <pru_send>:EPIPE[AF_UNIX]
2114 * <pru_send>:ENOTCONN[AF_UNIX]
2115 * <pru_send>:EISCONN[AF_UNIX]
2116 * <pru_send>:???[AF_UNIX] [whatever a filter author chooses]
2117 * <sf_data_out>:??? [whatever a filter author chooses]
2119 * Notes: Other <pru_send> returns depend on the protocol family; all
2120 * <sf_data_out> returns depend on what the filter author causes
2121 * their filter to return.
2124 sosend(struct socket
*so
, struct sockaddr
*addr
, struct uio
*uio
,
2125 struct mbuf
*top
, struct mbuf
*control
, int flags
)
2128 struct mbuf
*m
, *freelist
= NULL
;
2129 user_ssize_t space
, len
, resid
, orig_resid
;
2130 int clen
= 0, error
, dontroute
, mlen
, sendflags
;
2131 int atomic
= sosendallatonce(so
) || top
;
2133 struct proc
*p
= current_proc();
2134 uint16_t headroom
= 0;
2135 boolean_t en_tracing
= FALSE
;
2138 resid
= uio_resid(uio
);
2140 resid
= top
->m_pkthdr
.len
;
2143 KERNEL_DEBUG((DBG_FNC_SOSEND
| DBG_FUNC_START
), so
, resid
,
2144 so
->so_snd
.sb_cc
, so
->so_snd
.sb_lowat
, so
->so_snd
.sb_hiwat
);
2149 * trace if tracing & network (vs. unix) sockets & and
2152 if (ENTR_SHOULDTRACE
&&
2153 (SOCK_CHECK_DOM(so
, AF_INET
) || SOCK_CHECK_DOM(so
, AF_INET6
))) {
2154 struct inpcb
*inp
= sotoinpcb(so
);
2155 if (inp
->inp_last_outifp
!= NULL
&&
2156 !(inp
->inp_last_outifp
->if_flags
& IFF_LOOPBACK
)) {
2158 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite
, DBG_FUNC_START
,
2159 VM_KERNEL_ADDRPERM(so
),
2160 ((so
->so_state
& SS_NBIO
) ? kEnTrFlagNonBlocking
: 0),
2167 * Re-injection should not affect process accounting
2169 if ((flags
& MSG_SKIPCFIL
) == 0) {
2170 so_update_last_owner_locked(so
, p
);
2171 so_update_policy(so
);
2174 so_update_necp_policy(so
, NULL
, addr
);
2178 if (so
->so_type
!= SOCK_STREAM
&& (flags
& MSG_OOB
) != 0) {
2184 * In theory resid should be unsigned.
2185 * However, space must be signed, as it might be less than 0
2186 * if we over-committed, and we must use a signed comparison
2187 * of space and resid. On the other hand, a negative resid
2188 * causes us to loop sending 0-length segments to the protocol.
2190 * Usually, MSG_EOR isn't used on SOCK_STREAM type sockets.
2192 * Note: We limit resid to be a positive int value as we use
2193 * imin() to set bytes_to_copy -- radr://14558484
2195 if (resid
< 0 || resid
> INT_MAX
||
2196 (so
->so_type
== SOCK_STREAM
&& (flags
& MSG_EOR
))) {
2201 dontroute
= (flags
& MSG_DONTROUTE
) &&
2202 (so
->so_options
& SO_DONTROUTE
) == 0 &&
2203 (so
->so_proto
->pr_flags
& PR_ATOMIC
);
2204 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgsnd
);
2206 if (control
!= NULL
) {
2207 clen
= control
->m_len
;
2210 if (soreserveheadroom
!= 0) {
2211 headroom
= so
->so_pktheadroom
;
2215 error
= sosendcheck(so
, addr
, resid
, clen
, atomic
, flags
,
2222 space
= sbspace(&so
->so_snd
) - clen
;
2223 space
+= ((flags
& MSG_OOB
) ? 1024 : 0);
2228 * Data is prepackaged in "top".
2231 if (flags
& MSG_EOR
) {
2232 top
->m_flags
|= M_EOR
;
2241 bytes_to_copy
= imin(resid
, space
);
2243 bytes_to_alloc
= bytes_to_copy
;
2245 bytes_to_alloc
+= headroom
;
2248 if (sosendminchain
> 0) {
2251 chainlength
= sosendmaxchain
;
2255 * Use big 4 KB cluster when the outgoing interface
2256 * does not prefer 2 KB clusters
2258 bigcl
= !(so
->so_flags1
& SOF1_IF_2KCL
) ||
2259 sosendbigcl_ignore_capab
;
2262 * Attempt to use larger than system page-size
2263 * clusters for large writes only if there is
2264 * a jumbo cluster pool and if the socket is
2265 * marked accordingly.
2267 jumbocl
= sosendjcl
&& njcl
> 0 &&
2268 ((so
->so_flags
& SOF_MULTIPAGES
) ||
2269 sosendjcl_ignore_capab
) &&
2272 socket_unlock(so
, 0);
2276 int hdrs_needed
= (top
== NULL
) ? 1 : 0;
2279 * try to maintain a local cache of mbuf
2280 * clusters needed to complete this
2281 * write the list is further limited to
2282 * the number that are currently needed
2283 * to fill the socket this mechanism
2284 * allows a large number of mbufs/
2285 * clusters to be grabbed under a single
2286 * mbuf lock... if we can't get any
2287 * clusters, than fall back to trying
2288 * for mbufs if we fail early (or
2289 * miscalcluate the number needed) make
2290 * sure to release any clusters we
2291 * haven't yet consumed.
2293 if (freelist
== NULL
&&
2294 bytes_to_alloc
> MBIGCLBYTES
&&
2297 bytes_to_alloc
/ M16KCLBYTES
;
2299 if ((bytes_to_alloc
-
2300 (num_needed
* M16KCLBYTES
))
2306 m_getpackets_internal(
2307 (unsigned int *)&num_needed
,
2308 hdrs_needed
, M_WAIT
, 0,
2311 * Fall back to 4K cluster size
2312 * if allocation failed
2316 if (freelist
== NULL
&&
2317 bytes_to_alloc
> MCLBYTES
&&
2320 bytes_to_alloc
/ MBIGCLBYTES
;
2322 if ((bytes_to_alloc
-
2323 (num_needed
* MBIGCLBYTES
)) >=
2329 m_getpackets_internal(
2330 (unsigned int *)&num_needed
,
2331 hdrs_needed
, M_WAIT
, 0,
2334 * Fall back to cluster size
2335 * if allocation failed
2340 * Allocate a cluster as we want to
2341 * avoid to split the data in more
2342 * that one segment and using MINCLSIZE
2343 * would lead us to allocate two mbufs
2345 if (soreserveheadroom
!= 0 &&
2348 bytes_to_alloc
> _MHLEN
) ||
2349 bytes_to_alloc
> _MLEN
)) {
2350 num_needed
= ROUNDUP(bytes_to_alloc
, MCLBYTES
) /
2353 m_getpackets_internal(
2354 (unsigned int *)&num_needed
,
2355 hdrs_needed
, M_WAIT
, 0,
2358 * Fall back to a single mbuf
2359 * if allocation failed
2361 } else if (freelist
== NULL
&&
2362 bytes_to_alloc
> MINCLSIZE
) {
2364 bytes_to_alloc
/ MCLBYTES
;
2366 if ((bytes_to_alloc
-
2367 (num_needed
* MCLBYTES
)) >=
2373 m_getpackets_internal(
2374 (unsigned int *)&num_needed
,
2375 hdrs_needed
, M_WAIT
, 0,
2378 * Fall back to a single mbuf
2379 * if allocation failed
2383 * For datagram protocols, leave
2384 * headroom for protocol headers
2385 * in the first cluster of the chain
2387 if (freelist
!= NULL
&& atomic
&&
2388 top
== NULL
&& headroom
> 0) {
2389 freelist
->m_data
+= headroom
;
2393 * Fall back to regular mbufs without
2394 * reserving the socket headroom
2396 if (freelist
== NULL
) {
2397 if (SOCK_TYPE(so
) != SOCK_STREAM
|| bytes_to_alloc
<= MINCLSIZE
) {
2407 if (freelist
== NULL
) {
2413 * For datagram protocols,
2414 * leave room for protocol
2415 * headers in first mbuf.
2417 if (atomic
&& top
== NULL
&&
2418 bytes_to_copy
< MHLEN
) {
2424 freelist
= m
->m_next
;
2427 if ((m
->m_flags
& M_EXT
)) {
2428 mlen
= m
->m_ext
.ext_size
-
2430 } else if ((m
->m_flags
& M_PKTHDR
)) {
2432 MHLEN
- M_LEADINGSPACE(m
);
2434 mlen
= MLEN
- M_LEADINGSPACE(m
);
2436 len
= imin(mlen
, bytes_to_copy
);
2442 error
= uiomove(mtod(m
, caddr_t
),
2445 resid
= uio_resid(uio
);
2449 top
->m_pkthdr
.len
+= len
;
2455 if (flags
& MSG_EOR
) {
2456 top
->m_flags
|= M_EOR
;
2460 bytes_to_copy
= min(resid
, space
);
2461 } while (space
> 0 &&
2462 (chainlength
< sosendmaxchain
|| atomic
||
2463 resid
< MINCLSIZE
));
2473 so
->so_options
|= SO_DONTROUTE
;
2477 * Compute flags here, for pru_send and NKEs
2479 * If the user set MSG_EOF, the protocol
2480 * understands this flag and nothing left to
2481 * send then use PRU_SEND_EOF instead of PRU_SEND.
2483 sendflags
= (flags
& MSG_OOB
) ? PRUS_OOB
:
2484 ((flags
& MSG_EOF
) &&
2485 (so
->so_proto
->pr_flags
& PR_IMPLOPCL
) &&
2486 (resid
<= 0)) ? PRUS_EOF
:
2487 /* If there is more to send set PRUS_MORETOCOME */
2488 (resid
> 0 && space
> 0) ? PRUS_MORETOCOME
: 0;
2490 if ((flags
& MSG_SKIPCFIL
) == 0) {
2492 * Socket filter processing
2494 error
= sflt_data_out(so
, addr
, &top
,
2495 &control
, (sendflags
& MSG_OOB
) ?
2496 sock_data_filt_flag_oob
: 0);
2498 if (error
== EJUSTRETURN
) {
2500 goto packet_consumed
;
2506 * Content filter processing
2508 error
= cfil_sock_data_out(so
, addr
, top
,
2509 control
, sendflags
);
2511 if (error
== EJUSTRETURN
) {
2519 #endif /* CONTENT_FILTER */
2521 error
= (*so
->so_proto
->pr_usrreqs
->pru_send
)
2522 (so
, sendflags
, top
, addr
, control
, p
);
2526 so
->so_options
&= ~SO_DONTROUTE
;
2536 } while (resid
&& space
> 0);
2541 sbunlock(&so
->so_snd
, FALSE
); /* will unlock socket */
2543 socket_unlock(so
, 1);
2548 if (control
!= NULL
) {
2551 if (freelist
!= NULL
) {
2552 m_freem_list(freelist
);
2555 soclearfastopen(so
);
2558 /* resid passed here is the bytes left in uio */
2559 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite
, DBG_FUNC_END
,
2560 VM_KERNEL_ADDRPERM(so
),
2561 ((error
== EWOULDBLOCK
) ? kEnTrFlagNoWork
: 0),
2562 (int64_t)(orig_resid
- resid
));
2564 KERNEL_DEBUG(DBG_FNC_SOSEND
| DBG_FUNC_END
, so
, resid
,
2565 so
->so_snd
.sb_cc
, space
, error
);
2571 sosend_reinject(struct socket
*so
, struct sockaddr
*addr
, struct mbuf
*top
, struct mbuf
*control
, uint32_t sendflags
)
2573 struct mbuf
*m0
= NULL
, *control_end
= NULL
;
2575 socket_lock_assert_owned(so
);
2578 * top must points to mbuf chain to be sent.
2579 * If control is not NULL, top must be packet header
2581 VERIFY(top
!= NULL
&&
2582 (control
== NULL
|| top
->m_flags
& M_PKTHDR
));
2585 * If control is not passed in, see if we can get it
2588 if (control
== NULL
&& (top
->m_flags
& M_PKTHDR
) == 0) {
2589 // Locate start of control if present and start of data
2590 for (m0
= top
; m0
!= NULL
; m0
= m0
->m_next
) {
2591 if (m0
->m_flags
& M_PKTHDR
) {
2594 } else if (m0
->m_type
== MT_CONTROL
) {
2595 if (control
== NULL
) {
2596 // Found start of control
2599 if (control
!= NULL
&& m0
->m_next
!= NULL
&& m0
->m_next
->m_type
!= MT_CONTROL
) {
2600 // Found end of control
2605 if (control_end
!= NULL
) {
2606 control_end
->m_next
= NULL
;
2610 int error
= (*so
->so_proto
->pr_usrreqs
->pru_send
)
2611 (so
, sendflags
, top
, addr
, control
, current_proc());
2617 * Supported only connected sockets (no address) without ancillary data
2618 * (control mbuf) for atomic protocols
2621 sosend_list(struct socket
*so
, struct uio
**uioarray
, u_int uiocnt
, int flags
)
2623 struct mbuf
*m
, *freelist
= NULL
;
2624 user_ssize_t len
, resid
;
2625 int error
, dontroute
, mlen
;
2626 int atomic
= sosendallatonce(so
);
2628 struct proc
*p
= current_proc();
2631 struct mbuf
*top
= NULL
;
2632 uint16_t headroom
= 0;
2635 KERNEL_DEBUG((DBG_FNC_SOSEND_LIST
| DBG_FUNC_START
), so
, uiocnt
,
2636 so
->so_snd
.sb_cc
, so
->so_snd
.sb_lowat
, so
->so_snd
.sb_hiwat
);
2638 if (so
->so_type
!= SOCK_DGRAM
) {
2646 if (so
->so_proto
->pr_usrreqs
->pru_send_list
== NULL
) {
2647 error
= EPROTONOSUPPORT
;
2650 if (flags
& ~(MSG_DONTWAIT
| MSG_NBIO
)) {
2654 resid
= uio_array_resid(uioarray
, uiocnt
);
2657 * In theory resid should be unsigned.
2658 * However, space must be signed, as it might be less than 0
2659 * if we over-committed, and we must use a signed comparison
2660 * of space and resid. On the other hand, a negative resid
2661 * causes us to loop sending 0-length segments to the protocol.
2663 * Note: We limit resid to be a positive int value as we use
2664 * imin() to set bytes_to_copy -- radr://14558484
2666 if (resid
< 0 || resid
> INT_MAX
) {
2672 so_update_last_owner_locked(so
, p
);
2673 so_update_policy(so
);
2676 so_update_necp_policy(so
, NULL
, NULL
);
2679 dontroute
= (flags
& MSG_DONTROUTE
) &&
2680 (so
->so_options
& SO_DONTROUTE
) == 0 &&
2681 (so
->so_proto
->pr_flags
& PR_ATOMIC
);
2682 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgsnd
);
2684 error
= sosendcheck(so
, NULL
, resid
, 0, atomic
, flags
, &sblocked
);
2690 * Use big 4 KB clusters when the outgoing interface does not prefer
2693 bigcl
= !(so
->so_flags1
& SOF1_IF_2KCL
) || sosendbigcl_ignore_capab
;
2695 if (soreserveheadroom
!= 0) {
2696 headroom
= so
->so_pktheadroom
;
2703 size_t maxpktlen
= 0;
2706 if (sosendminchain
> 0) {
2709 chainlength
= sosendmaxchain
;
2712 socket_unlock(so
, 0);
2715 * Find a set of uio that fit in a reasonable number
2718 for (i
= uiofirst
; i
< uiocnt
; i
++) {
2719 struct uio
*auio
= uioarray
[i
];
2721 len
= uio_resid(auio
);
2723 /* Do nothing for empty messages */
2731 if (len
> maxpktlen
) {
2736 if (chainlength
> sosendmaxchain
) {
2741 * Nothing left to send
2743 if (num_needed
== 0) {
2748 * Allocate buffer large enough to include headroom space for
2749 * network and link header
2752 bytes_to_alloc
= maxpktlen
+ headroom
;
2755 * Allocate a single contiguous buffer of the smallest available
2756 * size when possible
2758 if (bytes_to_alloc
> MCLBYTES
&&
2759 bytes_to_alloc
<= MBIGCLBYTES
&& bigcl
) {
2760 freelist
= m_getpackets_internal(
2761 (unsigned int *)&num_needed
,
2762 num_needed
, M_WAIT
, 1,
2764 } else if (bytes_to_alloc
> _MHLEN
&&
2765 bytes_to_alloc
<= MCLBYTES
) {
2766 freelist
= m_getpackets_internal(
2767 (unsigned int *)&num_needed
,
2768 num_needed
, M_WAIT
, 1,
2771 freelist
= m_allocpacket_internal(
2772 (unsigned int *)&num_needed
,
2773 bytes_to_alloc
, NULL
, M_WAIT
, 1, 0);
2776 if (freelist
== NULL
) {
2782 * Copy each uio of the set into its own mbuf packet
2784 for (i
= uiofirst
, m
= freelist
;
2785 i
< uiolast
&& m
!= NULL
;
2789 struct uio
*auio
= uioarray
[i
];
2791 bytes_to_copy
= uio_resid(auio
);
2793 /* Do nothing for empty messages */
2794 if (bytes_to_copy
== 0) {
2798 * Leave headroom for protocol headers
2799 * in the first mbuf of the chain
2801 m
->m_data
+= headroom
;
2803 for (n
= m
; n
!= NULL
; n
= n
->m_next
) {
2804 if ((m
->m_flags
& M_EXT
)) {
2805 mlen
= m
->m_ext
.ext_size
-
2807 } else if ((m
->m_flags
& M_PKTHDR
)) {
2809 MHLEN
- M_LEADINGSPACE(m
);
2811 mlen
= MLEN
- M_LEADINGSPACE(m
);
2813 len
= imin(mlen
, bytes_to_copy
);
2816 * Note: uiomove() decrements the iovec
2819 error
= uiomove(mtod(n
, caddr_t
),
2825 m
->m_pkthdr
.len
+= len
;
2827 VERIFY(m
->m_pkthdr
.len
<= maxpktlen
);
2829 bytes_to_copy
-= len
;
2832 if (m
->m_pkthdr
.len
== 0) {
2834 "%s:%d so %llx pkt %llx type %u len null\n",
2836 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
2837 (uint64_t)DEBUG_KERNEL_ADDRPERM(m
),
2855 so
->so_options
|= SO_DONTROUTE
;
2858 if ((flags
& MSG_SKIPCFIL
) == 0) {
2859 struct mbuf
**prevnextp
= NULL
;
2861 for (i
= uiofirst
, m
= top
;
2862 i
< uiolast
&& m
!= NULL
;
2864 struct mbuf
*nextpkt
= m
->m_nextpkt
;
2867 * Socket filter processing
2869 error
= sflt_data_out(so
, NULL
, &m
,
2871 if (error
!= 0 && error
!= EJUSTRETURN
) {
2878 * Content filter processing
2880 error
= cfil_sock_data_out(so
, NULL
, m
,
2882 if (error
!= 0 && error
!= EJUSTRETURN
) {
2886 #endif /* CONTENT_FILTER */
2888 * Remove packet from the list when
2889 * swallowed by a filter
2891 if (error
== EJUSTRETURN
) {
2893 if (prevnextp
!= NULL
) {
2894 *prevnextp
= nextpkt
;
2902 prevnextp
= &m
->m_nextpkt
;
2907 error
= (*so
->so_proto
->pr_usrreqs
->pru_send_list
)
2908 (so
, 0, top
, NULL
, NULL
, p
);
2912 so
->so_options
&= ~SO_DONTROUTE
;
2917 } while (resid
> 0 && error
== 0);
2920 sbunlock(&so
->so_snd
, FALSE
); /* will unlock socket */
2922 socket_unlock(so
, 1);
2928 if (freelist
!= NULL
) {
2929 m_freem_list(freelist
);
2932 KERNEL_DEBUG(DBG_FNC_SOSEND_LIST
| DBG_FUNC_END
, so
, resid
,
2933 so
->so_snd
.sb_cc
, 0, error
);
2939 * May return ERESTART when packet is dropped by MAC policy check
2942 soreceive_addr(struct proc
*p
, struct socket
*so
, struct sockaddr
**psa
,
2943 int flags
, struct mbuf
**mp
, struct mbuf
**nextrecordp
, int canwait
)
2946 struct mbuf
*m
= *mp
;
2947 struct mbuf
*nextrecord
= *nextrecordp
;
2949 KASSERT(m
->m_type
== MT_SONAME
, ("receive 1a"));
2950 #if CONFIG_MACF_SOCKET_SUBSET
2952 * Call the MAC framework for policy checking if we're in
2953 * the user process context and the socket isn't connected.
2955 if (p
!= kernproc
&& !(so
->so_state
& SS_ISCONNECTED
)) {
2956 struct mbuf
*m0
= m
;
2958 * Dequeue this record (temporarily) from the receive
2959 * list since we're about to drop the socket's lock
2960 * where a new record may arrive and be appended to
2961 * the list. Upon MAC policy failure, the record
2962 * will be freed. Otherwise, we'll add it back to
2963 * the head of the list. We cannot rely on SB_LOCK
2964 * because append operation uses the socket's lock.
2967 m
->m_nextpkt
= NULL
;
2968 sbfree(&so
->so_rcv
, m
);
2970 } while (m
!= NULL
);
2972 so
->so_rcv
.sb_mb
= nextrecord
;
2973 SB_EMPTY_FIXUP(&so
->so_rcv
);
2974 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1a");
2975 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1a");
2976 socket_unlock(so
, 0);
2978 if (mac_socket_check_received(proc_ucred(p
), so
,
2979 mtod(m
, struct sockaddr
*)) != 0) {
2981 * MAC policy failure; free this record and
2982 * process the next record (or block until
2983 * one is available). We have adjusted sb_cc
2984 * and sb_mbcnt above so there is no need to
2985 * call sbfree() again.
2989 * Clear SB_LOCK but don't unlock the socket.
2990 * Process the next record or wait for one.
2993 sbunlock(&so
->so_rcv
, TRUE
); /* stay locked */
2999 * If the socket has been defunct'd, drop it.
3001 if (so
->so_flags
& SOF_DEFUNCT
) {
3007 * Re-adjust the socket receive list and re-enqueue
3008 * the record in front of any packets which may have
3009 * been appended while we dropped the lock.
3011 for (m
= m0
; m
->m_next
!= NULL
; m
= m
->m_next
) {
3012 sballoc(&so
->so_rcv
, m
);
3014 sballoc(&so
->so_rcv
, m
);
3015 if (so
->so_rcv
.sb_mb
== NULL
) {
3016 so
->so_rcv
.sb_lastrecord
= m0
;
3017 so
->so_rcv
.sb_mbtail
= m
;
3020 nextrecord
= m
->m_nextpkt
= so
->so_rcv
.sb_mb
;
3021 so
->so_rcv
.sb_mb
= m
;
3022 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1b");
3023 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1b");
3025 #endif /* CONFIG_MACF_SOCKET_SUBSET */
3027 *psa
= dup_sockaddr(mtod(m
, struct sockaddr
*), canwait
);
3028 if ((*psa
== NULL
) && (flags
& MSG_NEEDSA
)) {
3029 error
= EWOULDBLOCK
;
3033 if (flags
& MSG_PEEK
) {
3036 sbfree(&so
->so_rcv
, m
);
3037 if (m
->m_next
== NULL
&& so
->so_rcv
.sb_cc
!= 0) {
3038 panic("%s: about to create invalid socketbuf",
3042 MFREE(m
, so
->so_rcv
.sb_mb
);
3043 m
= so
->so_rcv
.sb_mb
;
3045 m
->m_nextpkt
= nextrecord
;
3047 so
->so_rcv
.sb_mb
= nextrecord
;
3048 SB_EMPTY_FIXUP(&so
->so_rcv
);
3053 *nextrecordp
= nextrecord
;
3059 * Process one or more MT_CONTROL mbufs present before any data mbufs
3060 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
3061 * just copy the data; if !MSG_PEEK, we call into the protocol to
3062 * perform externalization.
3065 soreceive_ctl(struct socket
*so
, struct mbuf
**controlp
, int flags
,
3066 struct mbuf
**mp
, struct mbuf
**nextrecordp
)
3069 struct mbuf
*cm
= NULL
, *cmn
;
3070 struct mbuf
**cme
= &cm
;
3071 struct sockbuf
*sb_rcv
= &so
->so_rcv
;
3072 struct mbuf
**msgpcm
= NULL
;
3073 struct mbuf
*m
= *mp
;
3074 struct mbuf
*nextrecord
= *nextrecordp
;
3075 struct protosw
*pr
= so
->so_proto
;
3078 * Externalizing the control messages would require us to
3079 * drop the socket's lock below. Once we re-acquire the
3080 * lock, the mbuf chain might change. In order to preserve
3081 * consistency, we unlink all control messages from the
3082 * first mbuf chain in one shot and link them separately
3083 * onto a different chain.
3086 if (flags
& MSG_PEEK
) {
3087 if (controlp
!= NULL
) {
3088 if (*controlp
== NULL
) {
3091 *controlp
= m_copy(m
, 0, m
->m_len
);
3094 * If we failed to allocate an mbuf,
3095 * release any previously allocated
3096 * mbufs for control data. Return
3097 * an error. Keep the mbufs in the
3098 * socket as this is using
3101 if (*controlp
== NULL
) {
3106 controlp
= &(*controlp
)->m_next
;
3110 m
->m_nextpkt
= NULL
;
3112 sb_rcv
->sb_mb
= m
->m_next
;
3115 cme
= &(*cme
)->m_next
;
3118 } while (m
!= NULL
&& m
->m_type
== MT_CONTROL
);
3120 if (!(flags
& MSG_PEEK
)) {
3121 if (sb_rcv
->sb_mb
!= NULL
) {
3122 sb_rcv
->sb_mb
->m_nextpkt
= nextrecord
;
3124 sb_rcv
->sb_mb
= nextrecord
;
3125 SB_EMPTY_FIXUP(sb_rcv
);
3127 if (nextrecord
== NULL
) {
3128 sb_rcv
->sb_lastrecord
= m
;
3132 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive ctl");
3133 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive ctl");
3135 while (cm
!= NULL
) {
3140 cmsg_type
= mtod(cm
, struct cmsghdr
*)->cmsg_type
;
3143 * Call the protocol to externalize SCM_RIGHTS message
3144 * and return the modified message to the caller upon
3145 * success. Otherwise, all other control messages are
3146 * returned unmodified to the caller. Note that we
3147 * only get into this loop if MSG_PEEK is not set.
3149 if (pr
->pr_domain
->dom_externalize
!= NULL
&&
3150 cmsg_type
== SCM_RIGHTS
) {
3152 * Release socket lock: see 3903171. This
3153 * would also allow more records to be appended
3154 * to the socket buffer. We still have SB_LOCK
3155 * set on it, so we can be sure that the head
3156 * of the mbuf chain won't change.
3158 socket_unlock(so
, 0);
3159 error
= (*pr
->pr_domain
->dom_externalize
)(cm
);
3165 if (controlp
!= NULL
&& error
== 0) {
3167 controlp
= &(*controlp
)->m_next
;
3174 * Update the value of nextrecord in case we received new
3175 * records when the socket was unlocked above for
3176 * externalizing SCM_RIGHTS.
3179 nextrecord
= sb_rcv
->sb_mb
->m_nextpkt
;
3181 nextrecord
= sb_rcv
->sb_mb
;
3186 *nextrecordp
= nextrecord
;
3192 * If we have less data than requested, block awaiting more
3193 * (subject to any timeout) if:
3194 * 1. the current count is less than the low water mark, or
3195 * 2. MSG_WAITALL is set, and it is possible to do the entire
3196 * receive operation at once if we block (resid <= hiwat).
3197 * 3. MSG_DONTWAIT is not set
3198 * If MSG_WAITALL is set but resid is larger than the receive buffer,
3199 * we have to do the receive in sections, and thus risk returning
3200 * a short count if a timeout or signal occurs after we start.
3203 so_should_wait(struct socket
*so
, struct uio
*uio
, struct mbuf
*m
, int flags
)
3205 struct protosw
*pr
= so
->so_proto
;
3207 /* No mbufs in the receive-queue? Wait! */
3212 /* Not enough data in the receive socket-buffer - we may have to wait */
3213 if ((flags
& MSG_DONTWAIT
) == 0 && so
->so_rcv
.sb_cc
< uio_resid(uio
) &&
3214 m
->m_nextpkt
== NULL
&& (pr
->pr_flags
& PR_ATOMIC
) == 0) {
3216 * Application did set the lowater-mark, so we should wait for
3217 * this data to be present.
3219 if (so
->so_rcv
.sb_cc
< so
->so_rcv
.sb_lowat
) {
3224 * Application wants all the data - so let's try to do the
3225 * receive-operation at once by waiting for everything to
3228 if ((flags
& MSG_WAITALL
) && uio_resid(uio
) <= so
->so_rcv
.sb_hiwat
) {
3237 * Implement receive operations on a socket.
3238 * We depend on the way that records are added to the sockbuf
3239 * by sbappend*. In particular, each record (mbufs linked through m_next)
3240 * must begin with an address if the protocol so specifies,
3241 * followed by an optional mbuf or mbufs containing ancillary data,
3242 * and then zero or more mbufs of data.
3243 * In order to avoid blocking network interrupts for the entire time here,
3244 * we splx() while doing the actual copy to user space.
3245 * Although the sockbuf is locked, new data may still be appended,
3246 * and thus we must maintain consistency of the sockbuf during that time.
3248 * The caller may receive the data as a single mbuf chain by supplying
3249 * an mbuf **mp0 for use in returning the chain. The uio is then used
3250 * only for the count in uio_resid.
3252 * Returns: 0 Success
3257 * sblock:EWOULDBLOCK
3261 * sodelayed_copy:EFAULT
3262 * <pru_rcvoob>:EINVAL[TCP]
3263 * <pru_rcvoob>:EWOULDBLOCK[TCP]
3265 * <pr_domain->dom_externalize>:EMSGSIZE[AF_UNIX]
3266 * <pr_domain->dom_externalize>:ENOBUFS[AF_UNIX]
3267 * <pr_domain->dom_externalize>:???
3269 * Notes: Additional return values from calls through <pru_rcvoob> and
3270 * <pr_domain->dom_externalize> depend on protocols other than
3271 * TCP or AF_UNIX, which are documented above.
3274 soreceive(struct socket
*so
, struct sockaddr
**psa
, struct uio
*uio
,
3275 struct mbuf
**mp0
, struct mbuf
**controlp
, int *flagsp
)
3277 struct mbuf
*m
, **mp
, *ml
= NULL
;
3278 struct mbuf
*nextrecord
, *free_list
;
3279 int flags
, error
, offset
;
3281 struct protosw
*pr
= so
->so_proto
;
3283 user_ssize_t orig_resid
= uio_resid(uio
);
3284 user_ssize_t delayed_copy_len
;
3286 struct proc
*p
= current_proc();
3287 boolean_t en_tracing
= FALSE
;
3290 * Sanity check on the length passed by caller as we are making 'int'
3293 if (orig_resid
< 0 || orig_resid
> INT_MAX
) {
3297 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_START
, so
,
3298 uio_resid(uio
), so
->so_rcv
.sb_cc
, so
->so_rcv
.sb_lowat
,
3299 so
->so_rcv
.sb_hiwat
);
3302 so_update_last_owner_locked(so
, p
);
3303 so_update_policy(so
);
3305 #ifdef MORE_LOCKING_DEBUG
3306 if (so
->so_usecount
== 1) {
3307 panic("%s: so=%x no other reference on socket\n", __func__
, so
);
3315 if (controlp
!= NULL
) {
3318 if (flagsp
!= NULL
) {
3319 flags
= *flagsp
& ~MSG_EOR
;
3325 * If a recv attempt is made on a previously-accepted socket
3326 * that has been marked as inactive (disconnected), reject
3329 if (so
->so_flags
& SOF_DEFUNCT
) {
3330 struct sockbuf
*sb
= &so
->so_rcv
;
3333 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
3334 __func__
, proc_pid(p
), proc_best_name(p
),
3335 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
3336 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
3338 * This socket should have been disconnected and flushed
3339 * prior to being returned from sodefunct(); there should
3340 * be no data on its receive list, so panic otherwise.
3342 if (so
->so_state
& SS_DEFUNCT
) {
3343 sb_empty_assert(sb
, __func__
);
3345 socket_unlock(so
, 1);
3349 if ((so
->so_flags1
& SOF1_PRECONNECT_DATA
) &&
3350 pr
->pr_usrreqs
->pru_preconnect
) {
3352 * A user may set the CONNECT_RESUME_ON_READ_WRITE-flag but not
3353 * calling write() right after this. *If* the app calls a read
3354 * we do not want to block this read indefinetely. Thus,
3355 * we trigger a connect so that the session gets initiated.
3357 error
= (*pr
->pr_usrreqs
->pru_preconnect
)(so
);
3360 socket_unlock(so
, 1);
3365 if (ENTR_SHOULDTRACE
&&
3366 (SOCK_CHECK_DOM(so
, AF_INET
) || SOCK_CHECK_DOM(so
, AF_INET6
))) {
3368 * enable energy tracing for inet sockets that go over
3369 * non-loopback interfaces only.
3371 struct inpcb
*inp
= sotoinpcb(so
);
3372 if (inp
->inp_last_outifp
!= NULL
&&
3373 !(inp
->inp_last_outifp
->if_flags
& IFF_LOOPBACK
)) {
3375 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_START
,
3376 VM_KERNEL_ADDRPERM(so
),
3377 ((so
->so_state
& SS_NBIO
) ?
3378 kEnTrFlagNonBlocking
: 0),
3379 (int64_t)orig_resid
);
3384 * When SO_WANTOOBFLAG is set we try to get out-of-band data
3385 * regardless of the flags argument. Here is the case were
3386 * out-of-band data is not inline.
3388 if ((flags
& MSG_OOB
) ||
3389 ((so
->so_options
& SO_WANTOOBFLAG
) != 0 &&
3390 (so
->so_options
& SO_OOBINLINE
) == 0 &&
3391 (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
)))) {
3392 m
= m_get(M_WAIT
, MT_DATA
);
3394 socket_unlock(so
, 1);
3395 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
,
3396 ENOBUFS
, 0, 0, 0, 0);
3399 error
= (*pr
->pr_usrreqs
->pru_rcvoob
)(so
, m
, flags
& MSG_PEEK
);
3403 socket_unlock(so
, 0);
3405 error
= uiomove(mtod(m
, caddr_t
),
3406 imin(uio_resid(uio
), m
->m_len
), uio
);
3408 } while (uio_resid(uio
) && error
== 0 && m
!= NULL
);
3415 if ((so
->so_options
& SO_WANTOOBFLAG
) != 0) {
3416 if (error
== EWOULDBLOCK
|| error
== EINVAL
) {
3418 * Let's try to get normal data:
3419 * EWOULDBLOCK: out-of-band data not
3420 * receive yet. EINVAL: out-of-band data
3425 } else if (error
== 0 && flagsp
!= NULL
) {
3429 socket_unlock(so
, 1);
3431 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3432 VM_KERNEL_ADDRPERM(so
), 0,
3433 (int64_t)(orig_resid
- uio_resid(uio
)));
3435 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3445 if (so
->so_state
& SS_ISCONFIRMING
&& uio_resid(uio
)) {
3446 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, 0);
3450 delayed_copy_len
= 0;
3452 #ifdef MORE_LOCKING_DEBUG
3453 if (so
->so_usecount
<= 1) {
3454 printf("soreceive: sblock so=0x%llx ref=%d on socket\n",
3455 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), so
->so_usecount
);
3459 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
3460 * and if so just return to the caller. This could happen when
3461 * soreceive() is called by a socket upcall function during the
3462 * time the socket is freed. The socket buffer would have been
3463 * locked across the upcall, therefore we cannot put this thread
3464 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
3465 * we may livelock), because the lock on the socket buffer will
3466 * only be released when the upcall routine returns to its caller.
3467 * Because the socket has been officially closed, there can be
3468 * no further read on it.
3470 * A multipath subflow socket would have its SS_NOFDREF set by
3471 * default, so check for SOF_MP_SUBFLOW socket flag; when the
3472 * socket is closed for real, SOF_MP_SUBFLOW would be cleared.
3474 if ((so
->so_state
& (SS_NOFDREF
| SS_CANTRCVMORE
)) ==
3475 (SS_NOFDREF
| SS_CANTRCVMORE
) && !(so
->so_flags
& SOF_MP_SUBFLOW
)) {
3476 socket_unlock(so
, 1);
3480 error
= sblock(&so
->so_rcv
, SBLOCKWAIT(flags
));
3482 socket_unlock(so
, 1);
3483 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3486 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3487 VM_KERNEL_ADDRPERM(so
), 0,
3488 (int64_t)(orig_resid
- uio_resid(uio
)));
3493 m
= so
->so_rcv
.sb_mb
;
3494 if (so_should_wait(so
, uio
, m
, flags
)) {
3496 * Panic if we notice inconsistencies in the socket's
3497 * receive list; both sb_mb and sb_cc should correctly
3498 * reflect the contents of the list, otherwise we may
3499 * end up with false positives during select() or poll()
3500 * which could put the application in a bad state.
3502 SB_MB_CHECK(&so
->so_rcv
);
3508 error
= so
->so_error
;
3509 if ((flags
& MSG_PEEK
) == 0) {
3514 if (so
->so_state
& SS_CANTRCVMORE
) {
3517 * Deal with half closed connections
3519 if ((so
->so_state
& SS_ISDISCONNECTED
) == 0 &&
3520 cfil_sock_data_pending(&so
->so_rcv
) != 0) {
3522 "so %llx ignore SS_CANTRCVMORE",
3523 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
));
3525 #endif /* CONTENT_FILTER */
3532 for (; m
!= NULL
; m
= m
->m_next
) {
3533 if (m
->m_type
== MT_OOBDATA
|| (m
->m_flags
& M_EOR
)) {
3534 m
= so
->so_rcv
.sb_mb
;
3538 if ((so
->so_state
& (SS_ISCONNECTED
| SS_ISCONNECTING
)) == 0 &&
3539 (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
)) {
3543 if (uio_resid(uio
) == 0) {
3547 if ((so
->so_state
& SS_NBIO
) ||
3548 (flags
& (MSG_DONTWAIT
| MSG_NBIO
))) {
3549 error
= EWOULDBLOCK
;
3552 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 1");
3553 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 1");
3554 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3555 #if EVEN_MORE_LOCKING_DEBUG
3557 printf("Waiting for socket data\n");
3562 * Depending on the protocol (e.g. TCP), the following
3563 * might cause the socket lock to be dropped and later
3564 * be reacquired, and more data could have arrived and
3565 * have been appended to the receive socket buffer by
3566 * the time it returns. Therefore, we only sleep in
3567 * sbwait() below if and only if the wait-condition is still
3570 if ((pr
->pr_flags
& PR_WANTRCVD
) && so
->so_pcb
!= NULL
) {
3571 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3575 if (so_should_wait(so
, uio
, so
->so_rcv
.sb_mb
, flags
)) {
3576 error
= sbwait(&so
->so_rcv
);
3579 #if EVEN_MORE_LOCKING_DEBUG
3581 printf("SORECEIVE - sbwait returned %d\n", error
);
3584 if (so
->so_usecount
< 1) {
3585 panic("%s: after 2nd sblock so=%p ref=%d on socket\n",
3586 __func__
, so
, so
->so_usecount
);
3590 socket_unlock(so
, 1);
3591 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3594 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3595 VM_KERNEL_ADDRPERM(so
), 0,
3596 (int64_t)(orig_resid
- uio_resid(uio
)));
3603 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgrcv
);
3604 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1");
3605 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1");
3606 nextrecord
= m
->m_nextpkt
;
3608 if ((pr
->pr_flags
& PR_ADDR
) && m
->m_type
== MT_SONAME
) {
3609 error
= soreceive_addr(p
, so
, psa
, flags
, &m
, &nextrecord
,
3611 if (error
== ERESTART
) {
3613 } else if (error
!= 0) {
3620 * Process one or more MT_CONTROL mbufs present before any data mbufs
3621 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
3622 * just copy the data; if !MSG_PEEK, we call into the protocol to
3623 * perform externalization.
3625 if (m
!= NULL
&& m
->m_type
== MT_CONTROL
) {
3626 error
= soreceive_ctl(so
, controlp
, flags
, &m
, &nextrecord
);
3634 if (!(flags
& MSG_PEEK
)) {
3636 * We get here because m points to an mbuf following
3637 * any MT_SONAME or MT_CONTROL mbufs which have been
3638 * processed above. In any case, m should be pointing
3639 * to the head of the mbuf chain, and the nextrecord
3640 * should be either NULL or equal to m->m_nextpkt.
3641 * See comments above about SB_LOCK.
3643 if (m
!= so
->so_rcv
.sb_mb
||
3644 m
->m_nextpkt
!= nextrecord
) {
3645 panic("%s: post-control !sync so=%p m=%p "
3646 "nextrecord=%p\n", __func__
, so
, m
,
3650 if (nextrecord
== NULL
) {
3651 so
->so_rcv
.sb_lastrecord
= m
;
3655 if (type
== MT_OOBDATA
) {
3659 if (!(flags
& MSG_PEEK
)) {
3660 SB_EMPTY_FIXUP(&so
->so_rcv
);
3663 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 2");
3664 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 2");
3669 if (!(flags
& MSG_PEEK
) && uio_resid(uio
) > sorecvmincopy
) {
3676 (uio_resid(uio
) - delayed_copy_len
) > 0 && error
== 0) {
3677 if (m
->m_type
== MT_OOBDATA
) {
3678 if (type
!= MT_OOBDATA
) {
3681 } else if (type
== MT_OOBDATA
) {
3685 * Make sure to allways set MSG_OOB event when getting
3686 * out of band data inline.
3688 if ((so
->so_options
& SO_WANTOOBFLAG
) != 0 &&
3689 (so
->so_options
& SO_OOBINLINE
) != 0 &&
3690 (so
->so_state
& SS_RCVATMARK
) != 0) {
3693 so
->so_state
&= ~SS_RCVATMARK
;
3694 len
= uio_resid(uio
) - delayed_copy_len
;
3695 if (so
->so_oobmark
&& len
> so
->so_oobmark
- offset
) {
3696 len
= so
->so_oobmark
- offset
;
3698 if (len
> m
->m_len
- moff
) {
3699 len
= m
->m_len
- moff
;
3702 * If mp is set, just pass back the mbufs.
3703 * Otherwise copy them out via the uio, then free.
3704 * Sockbuf must be consistent here (points to current mbuf,
3705 * it points to next record) when we drop priority;
3706 * we must note any additions to the sockbuf when we
3707 * block interrupts again.
3710 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive uiomove");
3711 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive uiomove");
3712 if (can_delay
&& len
== m
->m_len
) {
3714 * only delay the copy if we're consuming the
3715 * mbuf and we're NOT in MSG_PEEK mode
3716 * and we have enough data to make it worthwile
3717 * to drop and retake the lock... can_delay
3718 * reflects the state of the 2 latter
3719 * constraints moff should always be zero
3722 delayed_copy_len
+= len
;
3724 if (delayed_copy_len
) {
3725 error
= sodelayed_copy(so
, uio
,
3726 &free_list
, &delayed_copy_len
);
3732 * can only get here if MSG_PEEK is not
3733 * set therefore, m should point at the
3734 * head of the rcv queue; if it doesn't,
3735 * it means something drastically
3736 * changed while we were out from behind
3737 * the lock in sodelayed_copy. perhaps
3738 * a RST on the stream. in any event,
3739 * the stream has been interrupted. it's
3740 * probably best just to return whatever
3741 * data we've moved and let the caller
3744 if (m
!= so
->so_rcv
.sb_mb
) {
3748 socket_unlock(so
, 0);
3749 error
= uiomove(mtod(m
, caddr_t
) + moff
,
3758 uio_setresid(uio
, (uio_resid(uio
) - len
));
3760 if (len
== m
->m_len
- moff
) {
3761 if (m
->m_flags
& M_EOR
) {
3764 if (flags
& MSG_PEEK
) {
3768 nextrecord
= m
->m_nextpkt
;
3769 sbfree(&so
->so_rcv
, m
);
3770 m
->m_nextpkt
= NULL
;
3775 so
->so_rcv
.sb_mb
= m
= m
->m_next
;
3778 if (free_list
== NULL
) {
3784 so
->so_rcv
.sb_mb
= m
= m
->m_next
;
3788 m
->m_nextpkt
= nextrecord
;
3789 if (nextrecord
== NULL
) {
3790 so
->so_rcv
.sb_lastrecord
= m
;
3793 so
->so_rcv
.sb_mb
= nextrecord
;
3794 SB_EMPTY_FIXUP(&so
->so_rcv
);
3796 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 3");
3797 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 3");
3800 if (flags
& MSG_PEEK
) {
3806 if (flags
& MSG_DONTWAIT
) {
3807 copy_flag
= M_DONTWAIT
;
3811 *mp
= m_copym(m
, 0, len
, copy_flag
);
3813 * Failed to allocate an mbuf?
3814 * Adjust uio_resid back, it was
3815 * adjusted down by len bytes which
3816 * we didn't copy over.
3820 (uio_resid(uio
) + len
));
3826 so
->so_rcv
.sb_cc
-= len
;
3829 if (so
->so_oobmark
) {
3830 if ((flags
& MSG_PEEK
) == 0) {
3831 so
->so_oobmark
-= len
;
3832 if (so
->so_oobmark
== 0) {
3833 so
->so_state
|= SS_RCVATMARK
;
3838 if (offset
== so
->so_oobmark
) {
3843 if (flags
& MSG_EOR
) {
3847 * If the MSG_WAITALL or MSG_WAITSTREAM flag is set
3848 * (for non-atomic socket), we must not quit until
3849 * "uio->uio_resid == 0" or an error termination.
3850 * If a signal/timeout occurs, return with a short
3851 * count but without error. Keep sockbuf locked
3852 * against other readers.
3854 while (flags
& (MSG_WAITALL
| MSG_WAITSTREAM
) && m
== NULL
&&
3855 (uio_resid(uio
) - delayed_copy_len
) > 0 &&
3856 !sosendallatonce(so
) && !nextrecord
) {
3857 if (so
->so_error
|| ((so
->so_state
& SS_CANTRCVMORE
)
3859 && cfil_sock_data_pending(&so
->so_rcv
) == 0
3860 #endif /* CONTENT_FILTER */
3866 * Depending on the protocol (e.g. TCP), the following
3867 * might cause the socket lock to be dropped and later
3868 * be reacquired, and more data could have arrived and
3869 * have been appended to the receive socket buffer by
3870 * the time it returns. Therefore, we only sleep in
3871 * sbwait() below if and only if the socket buffer is
3872 * empty, in order to avoid a false sleep.
3874 if ((pr
->pr_flags
& PR_WANTRCVD
) && so
->so_pcb
!= NULL
) {
3875 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3878 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 2");
3879 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 2");
3881 if (so
->so_rcv
.sb_mb
== NULL
&& sbwait(&so
->so_rcv
)) {
3886 * have to wait until after we get back from the sbwait
3887 * to do the copy because we will drop the lock if we
3888 * have enough data that has been delayed... by dropping
3889 * the lock we open up a window allowing the netisr
3890 * thread to process the incoming packets and to change
3891 * the state of this socket... we're issuing the sbwait
3892 * because the socket is empty and we're expecting the
3893 * netisr thread to wake us up when more packets arrive;
3894 * if we allow that processing to happen and then sbwait
3895 * we could stall forever with packets sitting in the
3896 * socket if no further packets arrive from the remote
3899 * we want to copy before we've collected all the data
3900 * to satisfy this request to allow the copy to overlap
3901 * the incoming packet processing on an MP system
3903 if (delayed_copy_len
> sorecvmincopy
&&
3904 (delayed_copy_len
> (so
->so_rcv
.sb_hiwat
/ 2))) {
3905 error
= sodelayed_copy(so
, uio
,
3906 &free_list
, &delayed_copy_len
);
3912 m
= so
->so_rcv
.sb_mb
;
3914 nextrecord
= m
->m_nextpkt
;
3916 SB_MB_CHECK(&so
->so_rcv
);
3919 #ifdef MORE_LOCKING_DEBUG
3920 if (so
->so_usecount
<= 1) {
3921 panic("%s: after big while so=%p ref=%d on socket\n",
3922 __func__
, so
, so
->so_usecount
);
3927 if (m
!= NULL
&& pr
->pr_flags
& PR_ATOMIC
) {
3928 if (so
->so_options
& SO_DONTTRUNC
) {
3929 flags
|= MSG_RCVMORE
;
3932 if ((flags
& MSG_PEEK
) == 0) {
3933 (void) sbdroprecord(&so
->so_rcv
);
3939 * pru_rcvd below (for TCP) may cause more data to be received
3940 * if the socket lock is dropped prior to sending the ACK; some
3941 * legacy OpenTransport applications don't handle this well
3942 * (if it receives less data than requested while MSG_HAVEMORE
3943 * is set), and so we set the flag now based on what we know
3944 * prior to calling pru_rcvd.
3946 if ((so
->so_options
& SO_WANTMORE
) && so
->so_rcv
.sb_cc
> 0) {
3947 flags
|= MSG_HAVEMORE
;
3950 if ((flags
& MSG_PEEK
) == 0) {
3952 so
->so_rcv
.sb_mb
= nextrecord
;
3954 * First part is an inline SB_EMPTY_FIXUP(). Second
3955 * part makes sure sb_lastrecord is up-to-date if
3956 * there is still data in the socket buffer.
3958 if (so
->so_rcv
.sb_mb
== NULL
) {
3959 so
->so_rcv
.sb_mbtail
= NULL
;
3960 so
->so_rcv
.sb_lastrecord
= NULL
;
3961 } else if (nextrecord
->m_nextpkt
== NULL
) {
3962 so
->so_rcv
.sb_lastrecord
= nextrecord
;
3964 SB_MB_CHECK(&so
->so_rcv
);
3966 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 4");
3967 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 4");
3968 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
) {
3969 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3973 if (delayed_copy_len
) {
3974 error
= sodelayed_copy(so
, uio
, &free_list
, &delayed_copy_len
);
3979 if (free_list
!= NULL
) {
3980 m_freem_list(free_list
);
3984 if (orig_resid
== uio_resid(uio
) && orig_resid
&&
3985 (flags
& MSG_EOR
) == 0 && (so
->so_state
& SS_CANTRCVMORE
) == 0) {
3986 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3990 if (flagsp
!= NULL
) {
3994 #ifdef MORE_LOCKING_DEBUG
3995 if (so
->so_usecount
<= 1) {
3996 panic("%s: release so=%p ref=%d on socket\n", __func__
,
3997 so
, so
->so_usecount
);
4001 if (delayed_copy_len
) {
4002 error
= sodelayed_copy(so
, uio
, &free_list
, &delayed_copy_len
);
4005 if (free_list
!= NULL
) {
4006 m_freem_list(free_list
);
4009 sbunlock(&so
->so_rcv
, FALSE
); /* will unlock socket */
4012 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
4013 VM_KERNEL_ADDRPERM(so
),
4014 ((error
== EWOULDBLOCK
) ? kEnTrFlagNoWork
: 0),
4015 (int64_t)(orig_resid
- uio_resid(uio
)));
4017 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, so
, uio_resid(uio
),
4018 so
->so_rcv
.sb_cc
, 0, error
);
4024 * Returns: 0 Success
4028 sodelayed_copy(struct socket
*so
, struct uio
*uio
, struct mbuf
**free_list
,
4029 user_ssize_t
*resid
)
4036 socket_unlock(so
, 0);
4038 while (m
!= NULL
&& error
== 0) {
4039 error
= uiomove(mtod(m
, caddr_t
), (int)m
->m_len
, uio
);
4042 m_freem_list(*free_list
);
4053 sodelayed_copy_list(struct socket
*so
, struct recv_msg_elem
*msgarray
,
4054 u_int uiocnt
, struct mbuf
**free_list
, user_ssize_t
*resid
)
4058 struct mbuf
*ml
, *m
;
4062 for (ml
= *free_list
, i
= 0; ml
!= NULL
&& i
< uiocnt
;
4063 ml
= ml
->m_nextpkt
, i
++) {
4064 auio
= msgarray
[i
].uio
;
4065 for (m
= ml
; m
!= NULL
; m
= m
->m_next
) {
4066 error
= uiomove(mtod(m
, caddr_t
), m
->m_len
, auio
);
4073 m_freem_list(*free_list
);
4082 soreceive_list(struct socket
*so
, struct recv_msg_elem
*msgarray
, u_int uiocnt
,
4086 struct mbuf
*nextrecord
;
4087 struct mbuf
*ml
= NULL
, *free_list
= NULL
, *free_tail
= NULL
;
4089 user_ssize_t len
, pktlen
, delayed_copy_len
= 0;
4090 struct protosw
*pr
= so
->so_proto
;
4092 struct proc
*p
= current_proc();
4093 struct uio
*auio
= NULL
;
4096 struct sockaddr
**psa
= NULL
;
4097 struct mbuf
**controlp
= NULL
;
4100 struct mbuf
*free_others
= NULL
;
4102 KERNEL_DEBUG(DBG_FNC_SORECEIVE_LIST
| DBG_FUNC_START
,
4104 so
->so_rcv
.sb_cc
, so
->so_rcv
.sb_lowat
, so
->so_rcv
.sb_hiwat
);
4108 * - Only supports don't wait flags
4109 * - Only support datagram sockets (could be extended to raw)
4111 * - Protocol must support packet chains
4112 * - The uio array is NULL (should we panic?)
4114 if (flagsp
!= NULL
) {
4119 if (flags
& ~(MSG_PEEK
| MSG_WAITALL
| MSG_DONTWAIT
| MSG_NEEDSA
|
4121 printf("%s invalid flags 0x%x\n", __func__
, flags
);
4125 if (so
->so_type
!= SOCK_DGRAM
) {
4129 if (sosendallatonce(so
) == 0) {
4133 if (so
->so_proto
->pr_usrreqs
->pru_send_list
== NULL
) {
4134 error
= EPROTONOSUPPORT
;
4137 if (msgarray
== NULL
) {
4138 printf("%s uioarray is NULL\n", __func__
);
4143 printf("%s uiocnt is 0\n", __func__
);
4148 * Sanity check on the length passed by caller as we are making 'int'
4151 resid
= recv_msg_array_resid(msgarray
, uiocnt
);
4152 if (resid
< 0 || resid
> INT_MAX
) {
4157 if (!(flags
& MSG_PEEK
) && sorecvmincopy
> 0) {
4164 so_update_last_owner_locked(so
, p
);
4165 so_update_policy(so
);
4168 so_update_necp_policy(so
, NULL
, NULL
);
4172 * If a recv attempt is made on a previously-accepted socket
4173 * that has been marked as inactive (disconnected), reject
4176 if (so
->so_flags
& SOF_DEFUNCT
) {
4177 struct sockbuf
*sb
= &so
->so_rcv
;
4180 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
4181 __func__
, proc_pid(p
), proc_best_name(p
),
4182 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
4183 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
4185 * This socket should have been disconnected and flushed
4186 * prior to being returned from sodefunct(); there should
4187 * be no data on its receive list, so panic otherwise.
4189 if (so
->so_state
& SS_DEFUNCT
) {
4190 sb_empty_assert(sb
, __func__
);
4197 * The uio may be empty
4199 if (npkts
>= uiocnt
) {
4205 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
4206 * and if so just return to the caller. This could happen when
4207 * soreceive() is called by a socket upcall function during the
4208 * time the socket is freed. The socket buffer would have been
4209 * locked across the upcall, therefore we cannot put this thread
4210 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
4211 * we may livelock), because the lock on the socket buffer will
4212 * only be released when the upcall routine returns to its caller.
4213 * Because the socket has been officially closed, there can be
4214 * no further read on it.
4216 if ((so
->so_state
& (SS_NOFDREF
| SS_CANTRCVMORE
)) ==
4217 (SS_NOFDREF
| SS_CANTRCVMORE
)) {
4222 error
= sblock(&so
->so_rcv
, SBLOCKWAIT(flags
));
4228 m
= so
->so_rcv
.sb_mb
;
4230 * Block awaiting more datagram if needed
4232 if (m
== NULL
|| (((flags
& MSG_DONTWAIT
) == 0 &&
4233 (so
->so_rcv
.sb_cc
< so
->so_rcv
.sb_lowat
||
4234 ((flags
& MSG_WAITALL
) && npkts
< uiocnt
))))) {
4236 * Panic if we notice inconsistencies in the socket's
4237 * receive list; both sb_mb and sb_cc should correctly
4238 * reflect the contents of the list, otherwise we may
4239 * end up with false positives during select() or poll()
4240 * which could put the application in a bad state.
4242 SB_MB_CHECK(&so
->so_rcv
);
4245 error
= so
->so_error
;
4246 if ((flags
& MSG_PEEK
) == 0) {
4251 if (so
->so_state
& SS_CANTRCVMORE
) {
4254 if ((so
->so_state
& (SS_ISCONNECTED
| SS_ISCONNECTING
)) == 0 &&
4255 (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
)) {
4259 if ((so
->so_state
& SS_NBIO
) ||
4260 (flags
& (MSG_DONTWAIT
| MSG_NBIO
))) {
4261 error
= EWOULDBLOCK
;
4265 * Do not block if we got some data
4267 if (free_list
!= NULL
) {
4272 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 1");
4273 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 1");
4275 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
4278 error
= sbwait(&so
->so_rcv
);
4285 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgrcv
);
4286 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1");
4287 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1");
4290 * Consume the current uio index as we have a datagram
4292 auio
= msgarray
[npkts
].uio
;
4293 resid
= uio_resid(auio
);
4294 msgarray
[npkts
].which
|= SOCK_MSG_DATA
;
4295 psa
= (msgarray
[npkts
].which
& SOCK_MSG_SA
) ?
4296 &msgarray
[npkts
].psa
: NULL
;
4297 controlp
= (msgarray
[npkts
].which
& SOCK_MSG_CONTROL
) ?
4298 &msgarray
[npkts
].controlp
: NULL
;
4300 nextrecord
= m
->m_nextpkt
;
4302 if ((pr
->pr_flags
& PR_ADDR
) && m
->m_type
== MT_SONAME
) {
4303 error
= soreceive_addr(p
, so
, psa
, flags
, &m
, &nextrecord
, 1);
4304 if (error
== ERESTART
) {
4306 } else if (error
!= 0) {
4311 if (m
!= NULL
&& m
->m_type
== MT_CONTROL
) {
4312 error
= soreceive_ctl(so
, controlp
, flags
, &m
, &nextrecord
);
4318 if (m
->m_pkthdr
.len
== 0) {
4319 printf("%s:%d so %llx pkt %llx type %u pktlen null\n",
4321 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
4322 (uint64_t)DEBUG_KERNEL_ADDRPERM(m
),
4327 * Loop to copy the mbufs of the current record
4328 * Support zero length packets
4332 while (m
!= NULL
&& (len
= resid
- pktlen
) >= 0 && error
== 0) {
4333 if (m
->m_len
== 0) {
4334 panic("%p m_len zero", m
);
4336 if (m
->m_type
== 0) {
4337 panic("%p m_type zero", m
);
4340 * Clip to the residual length
4342 if (len
> m
->m_len
) {
4347 * Copy the mbufs via the uio or delay the copy
4348 * Sockbuf must be consistent here (points to current mbuf,
4349 * it points to next record) when we drop priority;
4350 * we must note any additions to the sockbuf when we
4351 * block interrupts again.
4353 if (len
> 0 && can_delay
== 0) {
4354 socket_unlock(so
, 0);
4355 error
= uiomove(mtod(m
, caddr_t
), (int)len
, auio
);
4361 delayed_copy_len
+= len
;
4364 if (len
== m
->m_len
) {
4366 * m was entirely copied
4368 sbfree(&so
->so_rcv
, m
);
4369 nextrecord
= m
->m_nextpkt
;
4370 m
->m_nextpkt
= NULL
;
4373 * Set the first packet to the head of the free list
4375 if (free_list
== NULL
) {
4379 * Link current packet to tail of free list
4382 if (free_tail
!= NULL
) {
4383 free_tail
->m_nextpkt
= m
;
4388 * Link current mbuf to last mbuf of current packet
4396 * Move next buf to head of socket buffer
4398 so
->so_rcv
.sb_mb
= m
= ml
->m_next
;
4402 m
->m_nextpkt
= nextrecord
;
4403 if (nextrecord
== NULL
) {
4404 so
->so_rcv
.sb_lastrecord
= m
;
4407 so
->so_rcv
.sb_mb
= nextrecord
;
4408 SB_EMPTY_FIXUP(&so
->so_rcv
);
4410 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 3");
4411 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 3");
4414 * Stop the loop on partial copy
4419 #ifdef MORE_LOCKING_DEBUG
4420 if (so
->so_usecount
<= 1) {
4421 panic("%s: after big while so=%llx ref=%d on socket\n",
4423 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), so
->so_usecount
);
4428 * Tell the caller we made a partial copy
4431 if (so
->so_options
& SO_DONTTRUNC
) {
4433 * Copyout first the freelist then the partial mbuf
4435 socket_unlock(so
, 0);
4436 if (delayed_copy_len
) {
4437 error
= sodelayed_copy_list(so
, msgarray
,
4438 uiocnt
, &free_list
, &delayed_copy_len
);
4442 error
= uiomove(mtod(m
, caddr_t
), (int)len
,
4452 so
->so_rcv
.sb_cc
-= len
;
4453 flags
|= MSG_RCVMORE
;
4455 (void) sbdroprecord(&so
->so_rcv
);
4456 nextrecord
= so
->so_rcv
.sb_mb
;
4463 so
->so_rcv
.sb_mb
= nextrecord
;
4465 * First part is an inline SB_EMPTY_FIXUP(). Second
4466 * part makes sure sb_lastrecord is up-to-date if
4467 * there is still data in the socket buffer.
4469 if (so
->so_rcv
.sb_mb
== NULL
) {
4470 so
->so_rcv
.sb_mbtail
= NULL
;
4471 so
->so_rcv
.sb_lastrecord
= NULL
;
4472 } else if (nextrecord
->m_nextpkt
== NULL
) {
4473 so
->so_rcv
.sb_lastrecord
= nextrecord
;
4475 SB_MB_CHECK(&so
->so_rcv
);
4477 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 4");
4478 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 4");
4481 * We can continue to the next packet as long as:
4482 * - We haven't exhausted the uio array
4483 * - There was no error
4484 * - A packet was not truncated
4485 * - We can still receive more data
4487 if (npkts
< uiocnt
&& error
== 0 &&
4488 (flags
& (MSG_RCVMORE
| MSG_TRUNC
)) == 0 &&
4489 (so
->so_state
& SS_CANTRCVMORE
) == 0) {
4490 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
4495 if (flagsp
!= NULL
) {
4501 * pru_rcvd may cause more data to be received if the socket lock
4502 * is dropped so we set MSG_HAVEMORE now based on what we know.
4503 * That way the caller won't be surprised if it receives less data
4506 if ((so
->so_options
& SO_WANTMORE
) && so
->so_rcv
.sb_cc
> 0) {
4507 flags
|= MSG_HAVEMORE
;
4510 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
) {
4511 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
4515 sbunlock(&so
->so_rcv
, FALSE
); /* will unlock socket */
4517 socket_unlock(so
, 1);
4520 if (delayed_copy_len
) {
4521 error
= sodelayed_copy_list(so
, msgarray
, uiocnt
,
4522 &free_list
, &delayed_copy_len
);
4526 * Amortize the cost of freeing the mbufs
4528 if (free_list
!= NULL
) {
4529 m_freem_list(free_list
);
4531 if (free_others
!= NULL
) {
4532 m_freem_list(free_others
);
4535 KERNEL_DEBUG(DBG_FNC_SORECEIVE_LIST
| DBG_FUNC_END
, error
,
4541 so_statistics_event_to_nstat_event(int64_t *input_options
,
4542 uint64_t *nstat_event
)
4545 switch (*input_options
) {
4546 case SO_STATISTICS_EVENT_ENTER_CELLFALLBACK
:
4547 *nstat_event
= NSTAT_EVENT_SRC_ENTER_CELLFALLBACK
;
4549 case SO_STATISTICS_EVENT_EXIT_CELLFALLBACK
:
4550 *nstat_event
= NSTAT_EVENT_SRC_EXIT_CELLFALLBACK
;
4552 #if (DEBUG || DEVELOPMENT)
4553 case SO_STATISTICS_EVENT_RESERVED_1
:
4554 *nstat_event
= NSTAT_EVENT_SRC_RESERVED_1
;
4556 case SO_STATISTICS_EVENT_RESERVED_2
:
4557 *nstat_event
= NSTAT_EVENT_SRC_RESERVED_2
;
4559 #endif /* (DEBUG || DEVELOPMENT) */
4568 * Returns: 0 Success
4571 * <pru_shutdown>:EINVAL
4572 * <pru_shutdown>:EADDRNOTAVAIL[TCP]
4573 * <pru_shutdown>:ENOBUFS[TCP]
4574 * <pru_shutdown>:EMSGSIZE[TCP]
4575 * <pru_shutdown>:EHOSTUNREACH[TCP]
4576 * <pru_shutdown>:ENETUNREACH[TCP]
4577 * <pru_shutdown>:ENETDOWN[TCP]
4578 * <pru_shutdown>:ENOMEM[TCP]
4579 * <pru_shutdown>:EACCES[TCP]
4580 * <pru_shutdown>:EMSGSIZE[TCP]
4581 * <pru_shutdown>:ENOBUFS[TCP]
4582 * <pru_shutdown>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
4583 * <pru_shutdown>:??? [other protocol families]
4586 soshutdown(struct socket
*so
, int how
)
4590 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
| DBG_FUNC_START
, how
, 0, 0, 0, 0);
4598 (SS_ISCONNECTED
| SS_ISCONNECTING
| SS_ISDISCONNECTING
)) == 0) {
4601 error
= soshutdownlock(so
, how
);
4603 socket_unlock(so
, 1);
4610 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
| DBG_FUNC_END
, how
, error
, 0, 0, 0);
4616 soshutdownlock_final(struct socket
*so
, int how
)
4618 struct protosw
*pr
= so
->so_proto
;
4621 sflt_notify(so
, sock_evt_shutdown
, &how
);
4623 if (how
!= SHUT_WR
) {
4624 if ((so
->so_state
& SS_CANTRCVMORE
) != 0) {
4625 /* read already shut down */
4631 if (how
!= SHUT_RD
) {
4632 if ((so
->so_state
& SS_CANTSENDMORE
) != 0) {
4633 /* write already shut down */
4637 error
= (*pr
->pr_usrreqs
->pru_shutdown
)(so
);
4640 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
, how
, 1, 0, 0, 0);
4645 soshutdownlock(struct socket
*so
, int how
)
4651 * A content filter may delay the actual shutdown until it
4652 * has processed the pending data
4654 if (so
->so_flags
& SOF_CONTENT_FILTER
) {
4655 error
= cfil_sock_shutdown(so
, &how
);
4656 if (error
== EJUSTRETURN
) {
4659 } else if (error
!= 0) {
4663 #endif /* CONTENT_FILTER */
4665 error
= soshutdownlock_final(so
, how
);
4672 sowflush(struct socket
*so
)
4674 struct sockbuf
*sb
= &so
->so_snd
;
4677 * Obtain lock on the socket buffer (SB_LOCK). This is required
4678 * to prevent the socket buffer from being unexpectedly altered
4679 * while it is used by another thread in socket send/receive.
4681 * sblock() must not fail here, hence the assertion.
4683 (void) sblock(sb
, SBL_WAIT
| SBL_NOINTR
| SBL_IGNDEFUNCT
);
4684 VERIFY(sb
->sb_flags
& SB_LOCK
);
4686 sb
->sb_flags
&= ~(SB_SEL
| SB_UPCALL
);
4687 sb
->sb_flags
|= SB_DROP
;
4688 sb
->sb_upcall
= NULL
;
4689 sb
->sb_upcallarg
= NULL
;
4691 sbunlock(sb
, TRUE
); /* keep socket locked */
4693 selthreadclear(&sb
->sb_sel
);
4698 sorflush(struct socket
*so
)
4700 struct sockbuf
*sb
= &so
->so_rcv
;
4701 struct protosw
*pr
= so
->so_proto
;
4704 lck_mtx_t
*mutex_held
;
4706 * XXX: This code is currently commented out, because we may get here
4707 * as part of sofreelastref(), and at that time, pr_getlock() may no
4708 * longer be able to return us the lock; this will be fixed in future.
4710 if (so
->so_proto
->pr_getlock
!= NULL
) {
4711 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
4713 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
4716 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
4719 sflt_notify(so
, sock_evt_flush_read
, NULL
);
4724 * Obtain lock on the socket buffer (SB_LOCK). This is required
4725 * to prevent the socket buffer from being unexpectedly altered
4726 * while it is used by another thread in socket send/receive.
4728 * sblock() must not fail here, hence the assertion.
4730 (void) sblock(sb
, SBL_WAIT
| SBL_NOINTR
| SBL_IGNDEFUNCT
);
4731 VERIFY(sb
->sb_flags
& SB_LOCK
);
4734 * Copy only the relevant fields from "sb" to "asb" which we
4735 * need for sbrelease() to function. In particular, skip
4736 * sb_sel as it contains the wait queue linkage, which would
4737 * wreak havoc if we were to issue selthreadclear() on "asb".
4738 * Make sure to not carry over SB_LOCK in "asb", as we need
4739 * to acquire it later as part of sbrelease().
4741 bzero(&asb
, sizeof(asb
));
4742 asb
.sb_cc
= sb
->sb_cc
;
4743 asb
.sb_hiwat
= sb
->sb_hiwat
;
4744 asb
.sb_mbcnt
= sb
->sb_mbcnt
;
4745 asb
.sb_mbmax
= sb
->sb_mbmax
;
4746 asb
.sb_ctl
= sb
->sb_ctl
;
4747 asb
.sb_lowat
= sb
->sb_lowat
;
4748 asb
.sb_mb
= sb
->sb_mb
;
4749 asb
.sb_mbtail
= sb
->sb_mbtail
;
4750 asb
.sb_lastrecord
= sb
->sb_lastrecord
;
4751 asb
.sb_so
= sb
->sb_so
;
4752 asb
.sb_flags
= sb
->sb_flags
;
4753 asb
.sb_flags
&= ~(SB_LOCK
| SB_SEL
| SB_KNOTE
| SB_UPCALL
);
4754 asb
.sb_flags
|= SB_DROP
;
4757 * Ideally we'd bzero() these and preserve the ones we need;
4758 * but to do that we'd need to shuffle things around in the
4759 * sockbuf, and we can't do it now because there are KEXTS
4760 * that are directly referring to the socket structure.
4762 * Setting SB_DROP acts as a barrier to prevent further appends.
4763 * Clearing SB_SEL is done for selthreadclear() below.
4772 sb
->sb_mbtail
= NULL
;
4773 sb
->sb_lastrecord
= NULL
;
4774 sb
->sb_timeo
.tv_sec
= 0;
4775 sb
->sb_timeo
.tv_usec
= 0;
4776 sb
->sb_upcall
= NULL
;
4777 sb
->sb_upcallarg
= NULL
;
4778 sb
->sb_flags
&= ~(SB_SEL
| SB_UPCALL
);
4779 sb
->sb_flags
|= SB_DROP
;
4781 sbunlock(sb
, TRUE
); /* keep socket locked */
4784 * Note that selthreadclear() is called on the original "sb" and
4785 * not the local "asb" because of the way wait queue linkage is
4786 * implemented. Given that selwakeup() may be triggered, SB_SEL
4787 * should no longer be set (cleared above.)
4789 selthreadclear(&sb
->sb_sel
);
4791 if ((pr
->pr_flags
& PR_RIGHTS
) && pr
->pr_domain
->dom_dispose
) {
4792 (*pr
->pr_domain
->dom_dispose
)(asb
.sb_mb
);
4799 * Perhaps this routine, and sooptcopyout(), below, ought to come in
4800 * an additional variant to handle the case where the option value needs
4801 * to be some kind of integer, but not a specific size.
4802 * In addition to their use here, these functions are also called by the
4803 * protocol-level pr_ctloutput() routines.
4805 * Returns: 0 Success
4810 sooptcopyin(struct sockopt
*sopt
, void *buf
, size_t len
, size_t minlen
)
4815 * If the user gives us more than we wanted, we ignore it,
4816 * but if we don't get the minimum length the caller
4817 * wants, we return EINVAL. On success, sopt->sopt_valsize
4818 * is set to however much we actually retrieved.
4820 if ((valsize
= sopt
->sopt_valsize
) < minlen
) {
4823 if (valsize
> len
) {
4824 sopt
->sopt_valsize
= valsize
= len
;
4827 if (sopt
->sopt_p
!= kernproc
) {
4828 return copyin(sopt
->sopt_val
, buf
, valsize
);
4831 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), buf
, valsize
);
4836 * sooptcopyin_timeval
4837 * Copy in a timeval value into tv_p, and take into account whether the
4838 * the calling process is 64-bit or 32-bit. Moved the sanity checking
4839 * code here so that we can verify the 64-bit tv_sec value before we lose
4840 * the top 32-bits assigning tv64.tv_sec to tv_p->tv_sec.
4843 sooptcopyin_timeval(struct sockopt
*sopt
, struct timeval
*tv_p
)
4847 if (proc_is64bit(sopt
->sopt_p
)) {
4848 struct user64_timeval tv64
;
4850 if (sopt
->sopt_valsize
< sizeof(tv64
)) {
4854 sopt
->sopt_valsize
= sizeof(tv64
);
4855 if (sopt
->sopt_p
!= kernproc
) {
4856 error
= copyin(sopt
->sopt_val
, &tv64
, sizeof(tv64
));
4861 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), &tv64
,
4864 if (tv64
.tv_sec
< 0 || tv64
.tv_sec
> LONG_MAX
||
4865 tv64
.tv_usec
< 0 || tv64
.tv_usec
>= 1000000) {
4869 tv_p
->tv_sec
= tv64
.tv_sec
;
4870 tv_p
->tv_usec
= tv64
.tv_usec
;
4872 struct user32_timeval tv32
;
4874 if (sopt
->sopt_valsize
< sizeof(tv32
)) {
4878 sopt
->sopt_valsize
= sizeof(tv32
);
4879 if (sopt
->sopt_p
!= kernproc
) {
4880 error
= copyin(sopt
->sopt_val
, &tv32
, sizeof(tv32
));
4885 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), &tv32
,
4890 * K64todo "comparison is always false due to
4891 * limited range of data type"
4893 if (tv32
.tv_sec
< 0 || tv32
.tv_sec
> LONG_MAX
||
4894 tv32
.tv_usec
< 0 || tv32
.tv_usec
>= 1000000) {
4898 tv_p
->tv_sec
= tv32
.tv_sec
;
4899 tv_p
->tv_usec
= tv32
.tv_usec
;
4905 soopt_cred_check(struct socket
*so
, int priv
, boolean_t allow_root
,
4906 boolean_t ignore_delegate
)
4908 kauth_cred_t cred
= NULL
;
4909 proc_t ep
= PROC_NULL
;
4913 if (ignore_delegate
== false && so
->so_flags
& SOF_DELEGATED
) {
4914 ep
= proc_find(so
->e_pid
);
4916 cred
= kauth_cred_proc_ref(ep
);
4920 uid
= kauth_cred_getuid(cred
? cred
: so
->so_cred
);
4922 /* uid is 0 for root */
4923 if (uid
!= 0 || !allow_root
) {
4924 error
= priv_check_cred(cred
? cred
: so
->so_cred
, priv
, 0);
4927 kauth_cred_unref(&cred
);
4929 if (ep
!= PROC_NULL
) {
4937 * Returns: 0 Success
4942 * sooptcopyin:EINVAL
4943 * sooptcopyin:EFAULT
4944 * sooptcopyin_timeval:EINVAL
4945 * sooptcopyin_timeval:EFAULT
4946 * sooptcopyin_timeval:EDOM
4947 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
4948 * <pr_ctloutput>:???w
4949 * sflt_attach_private:??? [whatever a filter author chooses]
4950 * <sf_setoption>:??? [whatever a filter author chooses]
4952 * Notes: Other <pru_listen> returns depend on the protocol family; all
4953 * <sf_listen> returns depend on what the filter author causes
4954 * their filter to return.
4957 sosetoptlock(struct socket
*so
, struct sockopt
*sopt
, int dolock
)
4960 int64_t long_optval
;
4964 if (sopt
->sopt_dir
!= SOPT_SET
) {
4965 sopt
->sopt_dir
= SOPT_SET
;
4972 if ((so
->so_state
& (SS_CANTRCVMORE
| SS_CANTSENDMORE
)) ==
4973 (SS_CANTRCVMORE
| SS_CANTSENDMORE
) &&
4974 (so
->so_flags
& SOF_NPX_SETOPTSHUT
) == 0) {
4975 /* the socket has been shutdown, no more sockopt's */
4980 error
= sflt_setsockopt(so
, sopt
);
4982 if (error
== EJUSTRETURN
) {
4988 if (sopt
->sopt_level
!= SOL_SOCKET
) {
4989 if (so
->so_proto
!= NULL
&&
4990 so
->so_proto
->pr_ctloutput
!= NULL
) {
4991 error
= (*so
->so_proto
->pr_ctloutput
)(so
, sopt
);
4994 error
= ENOPROTOOPT
;
4997 * Allow socket-level (SOL_SOCKET) options to be filtered by
4998 * the protocol layer, if needed. A zero value returned from
4999 * the handler means use default socket-level processing as
5000 * done by the rest of this routine. Otherwise, any other
5001 * return value indicates that the option is unsupported.
5003 if (so
->so_proto
!= NULL
&& (error
= so
->so_proto
->pr_usrreqs
->
5004 pru_socheckopt(so
, sopt
)) != 0) {
5009 switch (sopt
->sopt_name
) {
5012 error
= sooptcopyin(sopt
, &l
, sizeof(l
), sizeof(l
));
5017 so
->so_linger
= (sopt
->sopt_name
== SO_LINGER
) ?
5018 l
.l_linger
: l
.l_linger
* hz
;
5019 if (l
.l_onoff
!= 0) {
5020 so
->so_options
|= SO_LINGER
;
5022 so
->so_options
&= ~SO_LINGER
;
5029 case SO_USELOOPBACK
:
5035 case SO_TIMESTAMP_MONOTONIC
:
5036 case SO_TIMESTAMP_CONTINUOUS
:
5039 case SO_WANTOOBFLAG
:
5040 case SO_NOWAKEFROMSLEEP
:
5041 case SO_NOAPNFALLBK
:
5042 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5048 so
->so_options
|= sopt
->sopt_name
;
5050 so
->so_options
&= ~sopt
->sopt_name
;
5058 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5065 * Values < 1 make no sense for any of these
5066 * options, so disallow them.
5073 switch (sopt
->sopt_name
) {
5076 struct sockbuf
*sb
=
5077 (sopt
->sopt_name
== SO_SNDBUF
) ?
5078 &so
->so_snd
: &so
->so_rcv
;
5079 if (sbreserve(sb
, (u_int32_t
)optval
) == 0) {
5083 sb
->sb_flags
|= SB_USRSIZE
;
5084 sb
->sb_flags
&= ~SB_AUTOSIZE
;
5085 sb
->sb_idealsize
= (u_int32_t
)optval
;
5089 * Make sure the low-water is never greater than
5093 int space
= sbspace(&so
->so_snd
);
5094 u_int32_t hiwat
= so
->so_snd
.sb_hiwat
;
5096 if (so
->so_snd
.sb_flags
& SB_UNIX
) {
5098 (struct unpcb
*)(so
->so_pcb
);
5100 unp
->unp_conn
!= NULL
) {
5101 hiwat
+= unp
->unp_conn
->unp_cc
;
5105 so
->so_snd
.sb_lowat
=
5109 if (space
>= so
->so_snd
.sb_lowat
) {
5116 so
->so_rcv
.sb_lowat
=
5117 (optval
> so
->so_rcv
.sb_hiwat
) ?
5118 so
->so_rcv
.sb_hiwat
: optval
;
5119 data_len
= so
->so_rcv
.sb_cc
5120 - so
->so_rcv
.sb_ctl
;
5121 if (data_len
>= so
->so_rcv
.sb_lowat
) {
5131 error
= sooptcopyin_timeval(sopt
, &tv
);
5136 switch (sopt
->sopt_name
) {
5138 so
->so_snd
.sb_timeo
= tv
;
5141 so
->so_rcv
.sb_timeo
= tv
;
5149 error
= sooptcopyin(sopt
, &nke
, sizeof(nke
),
5155 error
= sflt_attach_internal(so
, nke
.nke_handle
);
5160 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5166 so
->so_flags
|= SOF_NOSIGPIPE
;
5168 so
->so_flags
&= ~SOF_NOSIGPIPE
;
5173 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5179 so
->so_flags
|= SOF_NOADDRAVAIL
;
5181 so
->so_flags
&= ~SOF_NOADDRAVAIL
;
5185 case SO_REUSESHAREUID
:
5186 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5192 so
->so_flags
|= SOF_REUSESHAREUID
;
5194 so
->so_flags
&= ~SOF_REUSESHAREUID
;
5198 case SO_NOTIFYCONFLICT
:
5199 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
5203 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5209 so
->so_flags
|= SOF_NOTIFYCONFLICT
;
5211 so
->so_flags
&= ~SOF_NOTIFYCONFLICT
;
5215 case SO_RESTRICTIONS
:
5216 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5222 error
= so_set_restrictions(so
, optval
);
5225 case SO_AWDL_UNRESTRICTED
:
5226 if (SOCK_DOM(so
) != PF_INET
&&
5227 SOCK_DOM(so
) != PF_INET6
) {
5231 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5237 error
= soopt_cred_check(so
,
5238 PRIV_NET_RESTRICTED_AWDL
, false, false);
5240 inp_set_awdl_unrestricted(
5244 inp_clear_awdl_unrestricted(sotoinpcb(so
));
5247 case SO_INTCOPROC_ALLOW
:
5248 if (SOCK_DOM(so
) != PF_INET6
) {
5252 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5258 inp_get_intcoproc_allowed(sotoinpcb(so
)) == FALSE
) {
5259 error
= soopt_cred_check(so
,
5260 PRIV_NET_RESTRICTED_INTCOPROC
, false, false);
5262 inp_set_intcoproc_allowed(
5265 } else if (optval
== 0) {
5266 inp_clear_intcoproc_allowed(sotoinpcb(so
));
5274 case SO_UPCALLCLOSEWAIT
:
5275 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5281 so
->so_flags
|= SOF_UPCALLCLOSEWAIT
;
5283 so
->so_flags
&= ~SOF_UPCALLCLOSEWAIT
;
5288 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5294 so
->so_flags
|= SOF_BINDRANDOMPORT
;
5296 so
->so_flags
&= ~SOF_BINDRANDOMPORT
;
5300 case SO_NP_EXTENSIONS
: {
5301 struct so_np_extensions sonpx
;
5303 error
= sooptcopyin(sopt
, &sonpx
, sizeof(sonpx
),
5308 if (sonpx
.npx_mask
& ~SONPX_MASK_VALID
) {
5313 * Only one bit defined for now
5315 if ((sonpx
.npx_mask
& SONPX_SETOPTSHUT
)) {
5316 if ((sonpx
.npx_flags
& SONPX_SETOPTSHUT
)) {
5317 so
->so_flags
|= SOF_NPX_SETOPTSHUT
;
5319 so
->so_flags
&= ~SOF_NPX_SETOPTSHUT
;
5325 case SO_TRAFFIC_CLASS
: {
5326 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5331 if (optval
>= SO_TC_NET_SERVICE_OFFSET
) {
5332 int netsvc
= optval
- SO_TC_NET_SERVICE_OFFSET
;
5333 error
= so_set_net_service_type(so
, netsvc
);
5336 error
= so_set_traffic_class(so
, optval
);
5340 so
->so_flags1
&= ~SOF1_TC_NET_SERV_TYPE
;
5341 so
->so_netsvctype
= _NET_SERVICE_TYPE_UNSPEC
;
5345 case SO_RECV_TRAFFIC_CLASS
: {
5346 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5352 so
->so_flags
&= ~SOF_RECV_TRAFFIC_CLASS
;
5354 so
->so_flags
|= SOF_RECV_TRAFFIC_CLASS
;
5359 #if (DEVELOPMENT || DEBUG)
5360 case SO_TRAFFIC_CLASS_DBG
: {
5361 struct so_tcdbg so_tcdbg
;
5363 error
= sooptcopyin(sopt
, &so_tcdbg
,
5364 sizeof(struct so_tcdbg
), sizeof(struct so_tcdbg
));
5368 error
= so_set_tcdbg(so
, &so_tcdbg
);
5374 #endif /* (DEVELOPMENT || DEBUG) */
5376 case SO_PRIVILEGED_TRAFFIC_CLASS
:
5377 error
= priv_check_cred(kauth_cred_get(),
5378 PRIV_NET_PRIVILEGED_TRAFFIC_CLASS
, 0);
5382 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5388 so
->so_flags
&= ~SOF_PRIVILEGED_TRAFFIC_CLASS
;
5390 so
->so_flags
|= SOF_PRIVILEGED_TRAFFIC_CLASS
;
5394 #if (DEVELOPMENT || DEBUG)
5396 error
= sosetdefunct(current_proc(), so
, 0, FALSE
);
5398 error
= sodefunct(current_proc(), so
, 0);
5402 #endif /* (DEVELOPMENT || DEBUG) */
5405 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5407 if (error
!= 0 || (so
->so_flags
& SOF_DEFUNCT
)) {
5414 * Any process can set SO_DEFUNCTOK (clear
5415 * SOF_NODEFUNCT), but only root can clear
5416 * SO_DEFUNCTOK (set SOF_NODEFUNCT).
5419 kauth_cred_issuser(kauth_cred_get()) == 0) {
5424 so
->so_flags
&= ~SOF_NODEFUNCT
;
5426 so
->so_flags
|= SOF_NODEFUNCT
;
5429 if (SOCK_DOM(so
) == PF_INET
||
5430 SOCK_DOM(so
) == PF_INET6
) {
5431 char s
[MAX_IPv6_STR_LEN
];
5432 char d
[MAX_IPv6_STR_LEN
];
5433 struct inpcb
*inp
= sotoinpcb(so
);
5435 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx "
5436 "[%s %s:%d -> %s:%d] is now marked "
5437 "as %seligible for "
5438 "defunct\n", __func__
, proc_selfpid(),
5439 proc_best_name(current_proc()),
5440 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
5441 (SOCK_TYPE(so
) == SOCK_STREAM
) ?
5442 "TCP" : "UDP", inet_ntop(SOCK_DOM(so
),
5443 ((SOCK_DOM(so
) == PF_INET
) ?
5444 (void *)&inp
->inp_laddr
.s_addr
:
5445 (void *)&inp
->in6p_laddr
), s
, sizeof(s
)),
5446 ntohs(inp
->in6p_lport
),
5447 inet_ntop(SOCK_DOM(so
),
5448 (SOCK_DOM(so
) == PF_INET
) ?
5449 (void *)&inp
->inp_faddr
.s_addr
:
5450 (void *)&inp
->in6p_faddr
, d
, sizeof(d
)),
5451 ntohs(inp
->in6p_fport
),
5452 (so
->so_flags
& SOF_NODEFUNCT
) ?
5455 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx [%d,%d] "
5456 "is now marked as %seligible for "
5458 __func__
, proc_selfpid(),
5459 proc_best_name(current_proc()),
5460 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
5461 SOCK_DOM(so
), SOCK_TYPE(so
),
5462 (so
->so_flags
& SOF_NODEFUNCT
) ?
5468 /* This option is not settable */
5472 case SO_OPPORTUNISTIC
:
5473 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5476 error
= so_set_opportunistic(so
, optval
);
5481 /* This option is handled by lower layer(s) */
5486 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5489 error
= so_set_recv_anyif(so
, optval
);
5493 case SO_TRAFFIC_MGT_BACKGROUND
: {
5494 /* This option is handled by lower layer(s) */
5500 case SO_FLOW_DIVERT_TOKEN
:
5501 error
= flow_divert_token_set(so
, sopt
);
5503 #endif /* FLOW_DIVERT */
5507 if ((error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5508 sizeof(optval
))) != 0) {
5512 error
= so_set_effective_pid(so
, optval
, sopt
->sopt_p
, true);
5515 case SO_DELEGATED_UUID
: {
5518 if ((error
= sooptcopyin(sopt
, &euuid
, sizeof(euuid
),
5519 sizeof(euuid
))) != 0) {
5523 error
= so_set_effective_uuid(so
, euuid
, sopt
->sopt_p
, true);
5528 case SO_NECP_ATTRIBUTES
:
5529 error
= necp_set_socket_attributes(so
, sopt
);
5532 case SO_NECP_CLIENTUUID
: {
5533 if (SOCK_DOM(so
) == PF_MULTIPATH
) {
5534 /* Handled by MPTCP itself */
5538 if (SOCK_DOM(so
) != PF_INET
&& SOCK_DOM(so
) != PF_INET6
) {
5543 struct inpcb
*inp
= sotoinpcb(so
);
5544 if (!uuid_is_null(inp
->necp_client_uuid
)) {
5545 // Clear out the old client UUID if present
5546 necp_inpcb_remove_cb(inp
);
5549 error
= sooptcopyin(sopt
, &inp
->necp_client_uuid
,
5550 sizeof(uuid_t
), sizeof(uuid_t
));
5555 if (uuid_is_null(inp
->necp_client_uuid
)) {
5560 pid_t current_pid
= proc_pid(current_proc());
5561 error
= necp_client_register_socket_flow(current_pid
,
5562 inp
->necp_client_uuid
, inp
);
5564 uuid_clear(inp
->necp_client_uuid
);
5568 if (inp
->inp_lport
!= 0) {
5569 // There is a bound local port, so this is not
5570 // a fresh socket. Assign to the client.
5571 necp_client_assign_from_socket(current_pid
, inp
->necp_client_uuid
, inp
);
5576 case SO_NECP_LISTENUUID
: {
5577 if (SOCK_DOM(so
) != PF_INET
&& SOCK_DOM(so
) != PF_INET6
) {
5582 struct inpcb
*inp
= sotoinpcb(so
);
5583 if (!uuid_is_null(inp
->necp_client_uuid
)) {
5588 error
= sooptcopyin(sopt
, &inp
->necp_client_uuid
,
5589 sizeof(uuid_t
), sizeof(uuid_t
));
5594 if (uuid_is_null(inp
->necp_client_uuid
)) {
5599 error
= necp_client_register_socket_listener(proc_pid(current_proc()),
5600 inp
->necp_client_uuid
, inp
);
5602 uuid_clear(inp
->necp_client_uuid
);
5606 // Mark that the port registration is held by NECP
5607 inp
->inp_flags2
|= INP2_EXTERNAL_PORT
;
5613 case SO_EXTENDED_BK_IDLE
:
5614 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5617 error
= so_set_extended_bk_idle(so
, optval
);
5621 case SO_MARK_CELLFALLBACK
:
5622 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5632 so
->so_flags1
&= ~SOF1_CELLFALLBACK
;
5634 so
->so_flags1
|= SOF1_CELLFALLBACK
;
5638 case SO_STATISTICS_EVENT
:
5639 error
= sooptcopyin(sopt
, &long_optval
,
5640 sizeof(long_optval
), sizeof(long_optval
));
5644 u_int64_t nstat_event
= 0;
5645 error
= so_statistics_event_to_nstat_event(
5646 &long_optval
, &nstat_event
);
5650 nstat_pcb_event(sotoinpcb(so
), nstat_event
);
5653 case SO_NET_SERVICE_TYPE
: {
5654 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5659 error
= so_set_net_service_type(so
, optval
);
5663 case SO_QOSMARKING_POLICY_OVERRIDE
:
5664 error
= priv_check_cred(kauth_cred_get(),
5665 PRIV_NET_QOSMARKING_POLICY_OVERRIDE
, 0);
5669 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5675 so
->so_flags1
&= ~SOF1_QOSMARKING_POLICY_OVERRIDE
;
5677 so
->so_flags1
|= SOF1_QOSMARKING_POLICY_OVERRIDE
;
5681 case SO_MPKL_SEND_INFO
: {
5682 struct so_mpkl_send_info so_mpkl_send_info
;
5684 error
= sooptcopyin(sopt
, &so_mpkl_send_info
,
5685 sizeof(struct so_mpkl_send_info
), sizeof(struct so_mpkl_send_info
));
5689 uuid_copy(so
->so_mpkl_send_uuid
, so_mpkl_send_info
.mpkl_uuid
);
5690 so
->so_mpkl_send_proto
= so_mpkl_send_info
.mpkl_proto
;
5692 if (uuid_is_null(so
->so_mpkl_send_uuid
) && so
->so_mpkl_send_proto
== 0) {
5693 so
->so_flags1
&= ~SOF1_MPKL_SEND_INFO
;
5695 so
->so_flags1
|= SOF1_MPKL_SEND_INFO
;
5699 case SO_WANT_KEV_SOCKET_CLOSED
: {
5700 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5706 so
->so_flags1
&= ~SOF1_WANT_KEV_SOCK_CLOSED
;
5708 so
->so_flags1
|= SOF1_WANT_KEV_SOCK_CLOSED
;
5713 error
= ENOPROTOOPT
;
5716 if (error
== 0 && so
->so_proto
!= NULL
&&
5717 so
->so_proto
->pr_ctloutput
!= NULL
) {
5718 (void) so
->so_proto
->pr_ctloutput(so
, sopt
);
5723 socket_unlock(so
, 1);
5728 /* Helper routines for getsockopt */
5730 sooptcopyout(struct sockopt
*sopt
, void *buf
, size_t len
)
5738 * Documented get behavior is that we always return a value,
5739 * possibly truncated to fit in the user's buffer.
5740 * Traditional behavior is that we always tell the user
5741 * precisely how much we copied, rather than something useful
5742 * like the total amount we had available for her.
5743 * Note that this interface is not idempotent; the entire answer must
5744 * generated ahead of time.
5746 valsize
= min(len
, sopt
->sopt_valsize
);
5747 sopt
->sopt_valsize
= valsize
;
5748 if (sopt
->sopt_val
!= USER_ADDR_NULL
) {
5749 if (sopt
->sopt_p
!= kernproc
) {
5750 error
= copyout(buf
, sopt
->sopt_val
, valsize
);
5752 bcopy(buf
, CAST_DOWN(caddr_t
, sopt
->sopt_val
), valsize
);
5759 sooptcopyout_timeval(struct sockopt
*sopt
, const struct timeval
*tv_p
)
5763 struct user64_timeval tv64
= {};
5764 struct user32_timeval tv32
= {};
5769 if (proc_is64bit(sopt
->sopt_p
)) {
5771 tv64
.tv_sec
= tv_p
->tv_sec
;
5772 tv64
.tv_usec
= tv_p
->tv_usec
;
5776 tv32
.tv_sec
= tv_p
->tv_sec
;
5777 tv32
.tv_usec
= tv_p
->tv_usec
;
5780 valsize
= min(len
, sopt
->sopt_valsize
);
5781 sopt
->sopt_valsize
= valsize
;
5782 if (sopt
->sopt_val
!= USER_ADDR_NULL
) {
5783 if (sopt
->sopt_p
!= kernproc
) {
5784 error
= copyout(val
, sopt
->sopt_val
, valsize
);
5786 bcopy(val
, CAST_DOWN(caddr_t
, sopt
->sopt_val
), valsize
);
5795 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
5796 * <pr_ctloutput>:???
5797 * <sf_getoption>:???
5800 sogetoptlock(struct socket
*so
, struct sockopt
*sopt
, int dolock
)
5806 if (sopt
->sopt_dir
!= SOPT_GET
) {
5807 sopt
->sopt_dir
= SOPT_GET
;
5814 error
= sflt_getsockopt(so
, sopt
);
5816 if (error
== EJUSTRETURN
) {
5822 if (sopt
->sopt_level
!= SOL_SOCKET
) {
5823 if (so
->so_proto
!= NULL
&&
5824 so
->so_proto
->pr_ctloutput
!= NULL
) {
5825 error
= (*so
->so_proto
->pr_ctloutput
)(so
, sopt
);
5828 error
= ENOPROTOOPT
;
5831 * Allow socket-level (SOL_SOCKET) options to be filtered by
5832 * the protocol layer, if needed. A zero value returned from
5833 * the handler means use default socket-level processing as
5834 * done by the rest of this routine. Otherwise, any other
5835 * return value indicates that the option is unsupported.
5837 if (so
->so_proto
!= NULL
&& (error
= so
->so_proto
->pr_usrreqs
->
5838 pru_socheckopt(so
, sopt
)) != 0) {
5843 switch (sopt
->sopt_name
) {
5846 l
.l_onoff
= ((so
->so_options
& SO_LINGER
) ? 1 : 0);
5847 l
.l_linger
= (sopt
->sopt_name
== SO_LINGER
) ?
5848 so
->so_linger
: so
->so_linger
/ hz
;
5849 error
= sooptcopyout(sopt
, &l
, sizeof(l
));
5852 case SO_USELOOPBACK
:
5861 case SO_TIMESTAMP_MONOTONIC
:
5862 case SO_TIMESTAMP_CONTINUOUS
:
5865 case SO_WANTOOBFLAG
:
5866 case SO_NOWAKEFROMSLEEP
:
5867 case SO_NOAPNFALLBK
:
5868 optval
= so
->so_options
& sopt
->sopt_name
;
5870 error
= sooptcopyout(sopt
, &optval
, sizeof(optval
));
5874 optval
= so
->so_type
;
5878 if (so
->so_proto
->pr_flags
& PR_ATOMIC
) {
5883 m1
= so
->so_rcv
.sb_mb
;
5884 while (m1
!= NULL
) {
5885 if (m1
->m_type
== MT_DATA
||
5886 m1
->m_type
== MT_HEADER
||
5887 m1
->m_type
== MT_OOBDATA
) {
5888 pkt_total
+= m1
->m_len
;
5894 optval
= so
->so_rcv
.sb_cc
- so
->so_rcv
.sb_ctl
;
5899 if (so
->so_proto
->pr_flags
& PR_ATOMIC
) {
5903 m1
= so
->so_rcv
.sb_mb
;
5904 while (m1
!= NULL
) {
5911 error
= ENOPROTOOPT
;
5916 optval
= so
->so_snd
.sb_cc
;
5920 optval
= so
->so_error
;
5925 u_int32_t hiwat
= so
->so_snd
.sb_hiwat
;
5927 if (so
->so_snd
.sb_flags
& SB_UNIX
) {
5929 (struct unpcb
*)(so
->so_pcb
);
5930 if (unp
!= NULL
&& unp
->unp_conn
!= NULL
) {
5931 hiwat
+= unp
->unp_conn
->unp_cc
;
5939 optval
= so
->so_rcv
.sb_hiwat
;
5943 optval
= so
->so_snd
.sb_lowat
;
5947 optval
= so
->so_rcv
.sb_lowat
;
5952 tv
= (sopt
->sopt_name
== SO_SNDTIMEO
?
5953 so
->so_snd
.sb_timeo
: so
->so_rcv
.sb_timeo
);
5955 error
= sooptcopyout_timeval(sopt
, &tv
);
5959 optval
= (so
->so_flags
& SOF_NOSIGPIPE
);
5963 optval
= (so
->so_flags
& SOF_NOADDRAVAIL
);
5966 case SO_REUSESHAREUID
:
5967 optval
= (so
->so_flags
& SOF_REUSESHAREUID
);
5971 case SO_NOTIFYCONFLICT
:
5972 optval
= (so
->so_flags
& SOF_NOTIFYCONFLICT
);
5975 case SO_RESTRICTIONS
:
5976 optval
= so_get_restrictions(so
);
5979 case SO_AWDL_UNRESTRICTED
:
5980 if (SOCK_DOM(so
) == PF_INET
||
5981 SOCK_DOM(so
) == PF_INET6
) {
5982 optval
= inp_get_awdl_unrestricted(
5990 case SO_INTCOPROC_ALLOW
:
5991 if (SOCK_DOM(so
) == PF_INET6
) {
5992 optval
= inp_get_intcoproc_allowed(
6008 #ifdef __APPLE_API_PRIVATE
6009 case SO_UPCALLCLOSEWAIT
:
6010 optval
= (so
->so_flags
& SOF_UPCALLCLOSEWAIT
);
6014 optval
= (so
->so_flags
& SOF_BINDRANDOMPORT
);
6017 case SO_NP_EXTENSIONS
: {
6018 struct so_np_extensions sonpx
= {};
6020 sonpx
.npx_flags
= (so
->so_flags
& SOF_NPX_SETOPTSHUT
) ?
6021 SONPX_SETOPTSHUT
: 0;
6022 sonpx
.npx_mask
= SONPX_MASK_VALID
;
6024 error
= sooptcopyout(sopt
, &sonpx
,
6025 sizeof(struct so_np_extensions
));
6029 case SO_TRAFFIC_CLASS
:
6030 optval
= so
->so_traffic_class
;
6033 case SO_RECV_TRAFFIC_CLASS
:
6034 optval
= (so
->so_flags
& SOF_RECV_TRAFFIC_CLASS
);
6037 #if (DEVELOPMENT || DEBUG)
6038 case SO_TRAFFIC_CLASS_DBG
:
6039 error
= sogetopt_tcdbg(so
, sopt
);
6041 #endif /* (DEVELOPMENT || DEBUG) */
6043 case SO_PRIVILEGED_TRAFFIC_CLASS
:
6044 optval
= (so
->so_flags
& SOF_PRIVILEGED_TRAFFIC_CLASS
);
6048 optval
= !(so
->so_flags
& SOF_NODEFUNCT
);
6052 optval
= (so
->so_flags
& SOF_DEFUNCT
);
6055 case SO_OPPORTUNISTIC
:
6056 optval
= so_get_opportunistic(so
);
6060 /* This option is not gettable */
6065 optval
= so_get_recv_anyif(so
);
6068 case SO_TRAFFIC_MGT_BACKGROUND
:
6069 /* This option is handled by lower layer(s) */
6070 if (so
->so_proto
!= NULL
&&
6071 so
->so_proto
->pr_ctloutput
!= NULL
) {
6072 (void) so
->so_proto
->pr_ctloutput(so
, sopt
);
6077 case SO_FLOW_DIVERT_TOKEN
:
6078 error
= flow_divert_token_get(so
, sopt
);
6080 #endif /* FLOW_DIVERT */
6083 case SO_NECP_ATTRIBUTES
:
6084 error
= necp_get_socket_attributes(so
, sopt
);
6087 case SO_NECP_CLIENTUUID
: {
6090 if (SOCK_DOM(so
) == PF_MULTIPATH
) {
6091 ncu
= &mpsotomppcb(so
)->necp_client_uuid
;
6092 } else if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6093 ncu
= &sotoinpcb(so
)->necp_client_uuid
;
6099 error
= sooptcopyout(sopt
, ncu
, sizeof(uuid_t
));
6103 case SO_NECP_LISTENUUID
: {
6106 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6107 if (sotoinpcb(so
)->inp_flags2
& INP2_EXTERNAL_PORT
) {
6108 nlu
= &sotoinpcb(so
)->necp_client_uuid
;
6118 error
= sooptcopyout(sopt
, nlu
, sizeof(uuid_t
));
6124 case SO_CFIL_SOCK_ID
: {
6125 cfil_sock_id_t sock_id
;
6127 sock_id
= cfil_sock_id_from_socket(so
);
6129 error
= sooptcopyout(sopt
, &sock_id
,
6130 sizeof(cfil_sock_id_t
));
6133 #endif /* CONTENT_FILTER */
6135 case SO_EXTENDED_BK_IDLE
:
6136 optval
= (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
);
6138 case SO_MARK_CELLFALLBACK
:
6139 optval
= ((so
->so_flags1
& SOF1_CELLFALLBACK
) > 0)
6142 case SO_NET_SERVICE_TYPE
: {
6143 if ((so
->so_flags1
& SOF1_TC_NET_SERV_TYPE
)) {
6144 optval
= so
->so_netsvctype
;
6146 optval
= NET_SERVICE_TYPE_BE
;
6150 case SO_NETSVC_MARKING_LEVEL
:
6151 optval
= so_get_netsvc_marking_level(so
);
6154 case SO_MPKL_SEND_INFO
: {
6155 struct so_mpkl_send_info so_mpkl_send_info
;
6157 uuid_copy(so_mpkl_send_info
.mpkl_uuid
, so
->so_mpkl_send_uuid
);
6158 so_mpkl_send_info
.mpkl_proto
= so
->so_mpkl_send_proto
;
6159 error
= sooptcopyout(sopt
, &so_mpkl_send_info
,
6160 sizeof(struct so_mpkl_send_info
));
6164 error
= ENOPROTOOPT
;
6170 socket_unlock(so
, 1);
6176 * The size limits on our soopt_getm is different from that on FreeBSD.
6177 * We limit the size of options to MCLBYTES. This will have to change
6178 * if we need to define options that need more space than MCLBYTES.
6181 soopt_getm(struct sockopt
*sopt
, struct mbuf
**mp
)
6183 struct mbuf
*m
, *m_prev
;
6184 int sopt_size
= sopt
->sopt_valsize
;
6187 if (sopt_size
<= 0 || sopt_size
> MCLBYTES
) {
6191 how
= sopt
->sopt_p
!= kernproc
? M_WAIT
: M_DONTWAIT
;
6192 MGET(m
, how
, MT_DATA
);
6196 if (sopt_size
> MLEN
) {
6198 if ((m
->m_flags
& M_EXT
) == 0) {
6202 m
->m_len
= min(MCLBYTES
, sopt_size
);
6204 m
->m_len
= min(MLEN
, sopt_size
);
6206 sopt_size
-= m
->m_len
;
6210 while (sopt_size
> 0) {
6211 MGET(m
, how
, MT_DATA
);
6216 if (sopt_size
> MLEN
) {
6218 if ((m
->m_flags
& M_EXT
) == 0) {
6223 m
->m_len
= min(MCLBYTES
, sopt_size
);
6225 m
->m_len
= min(MLEN
, sopt_size
);
6227 sopt_size
-= m
->m_len
;
6234 /* copyin sopt data into mbuf chain */
6236 soopt_mcopyin(struct sockopt
*sopt
, struct mbuf
*m
)
6238 struct mbuf
*m0
= m
;
6240 if (sopt
->sopt_val
== USER_ADDR_NULL
) {
6243 while (m
!= NULL
&& sopt
->sopt_valsize
>= m
->m_len
) {
6244 if (sopt
->sopt_p
!= kernproc
) {
6247 error
= copyin(sopt
->sopt_val
, mtod(m
, char *),
6254 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
),
6255 mtod(m
, char *), m
->m_len
);
6257 sopt
->sopt_valsize
-= m
->m_len
;
6258 sopt
->sopt_val
+= m
->m_len
;
6261 /* should be allocated enoughly at ip6_sooptmcopyin() */
6263 panic("soopt_mcopyin");
6269 /* copyout mbuf chain data into soopt */
6271 soopt_mcopyout(struct sockopt
*sopt
, struct mbuf
*m
)
6273 struct mbuf
*m0
= m
;
6276 if (sopt
->sopt_val
== USER_ADDR_NULL
) {
6279 while (m
!= NULL
&& sopt
->sopt_valsize
>= m
->m_len
) {
6280 if (sopt
->sopt_p
!= kernproc
) {
6283 error
= copyout(mtod(m
, char *), sopt
->sopt_val
,
6290 bcopy(mtod(m
, char *),
6291 CAST_DOWN(caddr_t
, sopt
->sopt_val
), m
->m_len
);
6293 sopt
->sopt_valsize
-= m
->m_len
;
6294 sopt
->sopt_val
+= m
->m_len
;
6295 valsize
+= m
->m_len
;
6299 /* enough soopt buffer should be given from user-land */
6303 sopt
->sopt_valsize
= valsize
;
6308 sohasoutofband(struct socket
*so
)
6310 if (so
->so_pgid
< 0) {
6311 gsignal(-so
->so_pgid
, SIGURG
);
6312 } else if (so
->so_pgid
> 0) {
6313 proc_signal(so
->so_pgid
, SIGURG
);
6315 selwakeup(&so
->so_rcv
.sb_sel
);
6316 if (so
->so_rcv
.sb_flags
& SB_KNOTE
) {
6317 KNOTE(&so
->so_rcv
.sb_sel
.si_note
,
6318 (NOTE_OOB
| SO_FILT_HINT_LOCKED
));
6323 sopoll(struct socket
*so
, int events
, kauth_cred_t cred
, void * wql
)
6325 #pragma unused(cred)
6326 struct proc
*p
= current_proc();
6330 so_update_last_owner_locked(so
, PROC_NULL
);
6331 so_update_policy(so
);
6333 if (events
& (POLLIN
| POLLRDNORM
)) {
6334 if (soreadable(so
)) {
6335 revents
|= events
& (POLLIN
| POLLRDNORM
);
6339 if (events
& (POLLOUT
| POLLWRNORM
)) {
6340 if (sowriteable(so
)) {
6341 revents
|= events
& (POLLOUT
| POLLWRNORM
);
6345 if (events
& (POLLPRI
| POLLRDBAND
)) {
6346 if (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
)) {
6347 revents
|= events
& (POLLPRI
| POLLRDBAND
);
6352 if (events
& (POLLIN
| POLLPRI
| POLLRDNORM
| POLLRDBAND
)) {
6354 * Darwin sets the flag first,
6355 * BSD calls selrecord first
6357 so
->so_rcv
.sb_flags
|= SB_SEL
;
6358 selrecord(p
, &so
->so_rcv
.sb_sel
, wql
);
6361 if (events
& (POLLOUT
| POLLWRNORM
)) {
6363 * Darwin sets the flag first,
6364 * BSD calls selrecord first
6366 so
->so_snd
.sb_flags
|= SB_SEL
;
6367 selrecord(p
, &so
->so_snd
.sb_sel
, wql
);
6371 socket_unlock(so
, 1);
6376 soo_kqfilter(struct fileproc
*fp
, struct knote
*kn
, struct kevent_qos_s
*kev
)
6378 struct socket
*so
= (struct socket
*)fp
->fp_glob
->fg_data
;
6382 so_update_last_owner_locked(so
, PROC_NULL
);
6383 so_update_policy(so
);
6385 switch (kn
->kn_filter
) {
6387 kn
->kn_filtid
= EVFILTID_SOREAD
;
6390 kn
->kn_filtid
= EVFILTID_SOWRITE
;
6393 kn
->kn_filtid
= EVFILTID_SCK
;
6396 kn
->kn_filtid
= EVFILTID_SOEXCEPT
;
6399 socket_unlock(so
, 1);
6400 knote_set_error(kn
, EINVAL
);
6405 * call the appropriate sub-filter attach
6406 * with the socket still locked
6408 result
= knote_fops(kn
)->f_attach(kn
, kev
);
6410 socket_unlock(so
, 1);
6416 filt_soread_common(struct knote
*kn
, struct kevent_qos_s
*kev
, struct socket
*so
)
6421 if (so
->so_options
& SO_ACCEPTCONN
) {
6423 * Radar 6615193 handle the listen case dynamically
6424 * for kqueue read filter. This allows to call listen()
6425 * after registering the kqueue EVFILT_READ.
6428 retval
= !TAILQ_EMPTY(&so
->so_comp
);
6433 /* socket isn't a listener */
6435 * NOTE_LOWAT specifies new low water mark in data, i.e.
6436 * the bytes of protocol data. We therefore exclude any
6439 data
= so
->so_rcv
.sb_cc
- so
->so_rcv
.sb_ctl
;
6441 if (kn
->kn_sfflags
& NOTE_OOB
) {
6442 if (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
)) {
6443 kn
->kn_fflags
|= NOTE_OOB
;
6444 data
-= so
->so_oobmark
;
6450 if ((so
->so_state
& SS_CANTRCVMORE
)
6452 && cfil_sock_data_pending(&so
->so_rcv
) == 0
6453 #endif /* CONTENT_FILTER */
6455 kn
->kn_flags
|= EV_EOF
;
6456 kn
->kn_fflags
= so
->so_error
;
6461 if (so
->so_error
) { /* temporary udp error */
6466 int64_t lowwat
= so
->so_rcv
.sb_lowat
;
6468 * Ensure that when NOTE_LOWAT is used, the derived
6469 * low water mark is bounded by socket's rcv buf's
6470 * high and low water mark values.
6472 if (kn
->kn_sfflags
& NOTE_LOWAT
) {
6473 if (kn
->kn_sdata
> so
->so_rcv
.sb_hiwat
) {
6474 lowwat
= so
->so_rcv
.sb_hiwat
;
6475 } else if (kn
->kn_sdata
> lowwat
) {
6476 lowwat
= kn
->kn_sdata
;
6481 * While the `data` field is the amount of data to read,
6482 * 0-sized packets need to wake up the kqueue, see 58140856,
6483 * so we need to take control bytes into account too.
6485 retval
= (so
->so_rcv
.sb_cc
>= lowwat
);
6488 if (retval
&& kev
) {
6489 knote_fill_kevent(kn
, kev
, data
);
6495 filt_sorattach(struct knote
*kn
, __unused
struct kevent_qos_s
*kev
)
6497 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6502 * If the caller explicitly asked for OOB results (e.g. poll())
6503 * from EVFILT_READ, then save that off in the hookid field
6504 * and reserve the kn_flags EV_OOBAND bit for output only.
6506 if (kn
->kn_filter
== EVFILT_READ
&&
6507 kn
->kn_flags
& EV_OOBAND
) {
6508 kn
->kn_flags
&= ~EV_OOBAND
;
6509 kn
->kn_hook32
= EV_OOBAND
;
6513 if (KNOTE_ATTACH(&so
->so_rcv
.sb_sel
.si_note
, kn
)) {
6514 so
->so_rcv
.sb_flags
|= SB_KNOTE
;
6517 /* indicate if event is already fired */
6518 return filt_soread_common(kn
, NULL
, so
);
6522 filt_sordetach(struct knote
*kn
)
6524 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6527 if (so
->so_rcv
.sb_flags
& SB_KNOTE
) {
6528 if (KNOTE_DETACH(&so
->so_rcv
.sb_sel
.si_note
, kn
)) {
6529 so
->so_rcv
.sb_flags
&= ~SB_KNOTE
;
6532 socket_unlock(so
, 1);
6537 filt_soread(struct knote
*kn
, long hint
)
6539 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6542 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6546 retval
= filt_soread_common(kn
, NULL
, so
);
6548 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6549 socket_unlock(so
, 1);
6556 filt_sortouch(struct knote
*kn
, struct kevent_qos_s
*kev
)
6558 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6563 /* save off the new input fflags and data */
6564 kn
->kn_sfflags
= kev
->fflags
;
6565 kn
->kn_sdata
= kev
->data
;
6567 /* determine if changes result in fired events */
6568 retval
= filt_soread_common(kn
, NULL
, so
);
6570 socket_unlock(so
, 1);
6576 filt_sorprocess(struct knote
*kn
, struct kevent_qos_s
*kev
)
6578 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6582 retval
= filt_soread_common(kn
, kev
, so
);
6583 socket_unlock(so
, 1);
6589 so_wait_for_if_feedback(struct socket
*so
)
6591 if ((SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) &&
6592 (so
->so_state
& SS_ISCONNECTED
)) {
6593 struct inpcb
*inp
= sotoinpcb(so
);
6594 if (INP_WAIT_FOR_IF_FEEDBACK(inp
)) {
6602 filt_sowrite_common(struct knote
*kn
, struct kevent_qos_s
*kev
, struct socket
*so
)
6605 int64_t data
= sbspace(&so
->so_snd
);
6607 if (so
->so_state
& SS_CANTSENDMORE
) {
6608 kn
->kn_flags
|= EV_EOF
;
6609 kn
->kn_fflags
= so
->so_error
;
6614 if (so
->so_error
) { /* temporary udp error */
6619 if (!socanwrite(so
)) {
6624 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
6629 int64_t lowwat
= so
->so_snd
.sb_lowat
;
6631 if (kn
->kn_sfflags
& NOTE_LOWAT
) {
6632 if (kn
->kn_sdata
> so
->so_snd
.sb_hiwat
) {
6633 lowwat
= so
->so_snd
.sb_hiwat
;
6634 } else if (kn
->kn_sdata
> lowwat
) {
6635 lowwat
= kn
->kn_sdata
;
6639 if (data
>= lowwat
) {
6640 if ((so
->so_flags
& SOF_NOTSENT_LOWAT
)
6641 #if (DEBUG || DEVELOPMENT)
6642 && so_notsent_lowat_check
== 1
6643 #endif /* DEBUG || DEVELOPMENT */
6645 if ((SOCK_DOM(so
) == PF_INET
||
6646 SOCK_DOM(so
) == PF_INET6
) &&
6647 so
->so_type
== SOCK_STREAM
) {
6648 ret
= tcp_notsent_lowat_check(so
);
6651 else if ((SOCK_DOM(so
) == PF_MULTIPATH
) &&
6652 (SOCK_PROTO(so
) == IPPROTO_TCP
)) {
6653 ret
= mptcp_notsent_lowat_check(so
);
6664 if (so_wait_for_if_feedback(so
)) {
6670 knote_fill_kevent(kn
, kev
, data
);
6676 filt_sowattach(struct knote
*kn
, __unused
struct kevent_qos_s
*kev
)
6678 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6681 if (KNOTE_ATTACH(&so
->so_snd
.sb_sel
.si_note
, kn
)) {
6682 so
->so_snd
.sb_flags
|= SB_KNOTE
;
6685 /* determine if its already fired */
6686 return filt_sowrite_common(kn
, NULL
, so
);
6690 filt_sowdetach(struct knote
*kn
)
6692 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6695 if (so
->so_snd
.sb_flags
& SB_KNOTE
) {
6696 if (KNOTE_DETACH(&so
->so_snd
.sb_sel
.si_note
, kn
)) {
6697 so
->so_snd
.sb_flags
&= ~SB_KNOTE
;
6700 socket_unlock(so
, 1);
6705 filt_sowrite(struct knote
*kn
, long hint
)
6707 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6710 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6714 ret
= filt_sowrite_common(kn
, NULL
, so
);
6716 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6717 socket_unlock(so
, 1);
6724 filt_sowtouch(struct knote
*kn
, struct kevent_qos_s
*kev
)
6726 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6731 /*save off the new input fflags and data */
6732 kn
->kn_sfflags
= kev
->fflags
;
6733 kn
->kn_sdata
= kev
->data
;
6735 /* determine if these changes result in a triggered event */
6736 ret
= filt_sowrite_common(kn
, NULL
, so
);
6738 socket_unlock(so
, 1);
6744 filt_sowprocess(struct knote
*kn
, struct kevent_qos_s
*kev
)
6746 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6750 ret
= filt_sowrite_common(kn
, kev
, so
);
6751 socket_unlock(so
, 1);
6757 filt_sockev_common(struct knote
*kn
, struct kevent_qos_s
*kev
,
6758 struct socket
*so
, long ev_hint
)
6762 uint32_t level_trigger
= 0;
6764 if (ev_hint
& SO_FILT_HINT_CONNRESET
) {
6765 kn
->kn_fflags
|= NOTE_CONNRESET
;
6767 if (ev_hint
& SO_FILT_HINT_TIMEOUT
) {
6768 kn
->kn_fflags
|= NOTE_TIMEOUT
;
6770 if (ev_hint
& SO_FILT_HINT_NOSRCADDR
) {
6771 kn
->kn_fflags
|= NOTE_NOSRCADDR
;
6773 if (ev_hint
& SO_FILT_HINT_IFDENIED
) {
6774 kn
->kn_fflags
|= NOTE_IFDENIED
;
6776 if (ev_hint
& SO_FILT_HINT_KEEPALIVE
) {
6777 kn
->kn_fflags
|= NOTE_KEEPALIVE
;
6779 if (ev_hint
& SO_FILT_HINT_ADAPTIVE_WTIMO
) {
6780 kn
->kn_fflags
|= NOTE_ADAPTIVE_WTIMO
;
6782 if (ev_hint
& SO_FILT_HINT_ADAPTIVE_RTIMO
) {
6783 kn
->kn_fflags
|= NOTE_ADAPTIVE_RTIMO
;
6785 if ((ev_hint
& SO_FILT_HINT_CONNECTED
) ||
6786 (so
->so_state
& SS_ISCONNECTED
)) {
6787 kn
->kn_fflags
|= NOTE_CONNECTED
;
6788 level_trigger
|= NOTE_CONNECTED
;
6790 if ((ev_hint
& SO_FILT_HINT_DISCONNECTED
) ||
6791 (so
->so_state
& SS_ISDISCONNECTED
)) {
6792 kn
->kn_fflags
|= NOTE_DISCONNECTED
;
6793 level_trigger
|= NOTE_DISCONNECTED
;
6795 if (ev_hint
& SO_FILT_HINT_CONNINFO_UPDATED
) {
6796 if (so
->so_proto
!= NULL
&&
6797 (so
->so_proto
->pr_flags
& PR_EVCONNINFO
)) {
6798 kn
->kn_fflags
|= NOTE_CONNINFO_UPDATED
;
6802 if ((ev_hint
& SO_FILT_HINT_NOTIFY_ACK
) ||
6803 tcp_notify_ack_active(so
)) {
6804 kn
->kn_fflags
|= NOTE_NOTIFY_ACK
;
6807 if ((so
->so_state
& SS_CANTRCVMORE
)
6809 && cfil_sock_data_pending(&so
->so_rcv
) == 0
6810 #endif /* CONTENT_FILTER */
6812 kn
->kn_fflags
|= NOTE_READCLOSED
;
6813 level_trigger
|= NOTE_READCLOSED
;
6816 if (so
->so_state
& SS_CANTSENDMORE
) {
6817 kn
->kn_fflags
|= NOTE_WRITECLOSED
;
6818 level_trigger
|= NOTE_WRITECLOSED
;
6821 if ((ev_hint
& SO_FILT_HINT_SUSPEND
) ||
6822 (so
->so_flags
& SOF_SUSPENDED
)) {
6823 kn
->kn_fflags
&= ~(NOTE_SUSPEND
| NOTE_RESUME
);
6825 /* If resume event was delivered before, reset it */
6826 kn
->kn_hook32
&= ~NOTE_RESUME
;
6828 kn
->kn_fflags
|= NOTE_SUSPEND
;
6829 level_trigger
|= NOTE_SUSPEND
;
6832 if ((ev_hint
& SO_FILT_HINT_RESUME
) ||
6833 (so
->so_flags
& SOF_SUSPENDED
) == 0) {
6834 kn
->kn_fflags
&= ~(NOTE_SUSPEND
| NOTE_RESUME
);
6836 /* If suspend event was delivered before, reset it */
6837 kn
->kn_hook32
&= ~NOTE_SUSPEND
;
6839 kn
->kn_fflags
|= NOTE_RESUME
;
6840 level_trigger
|= NOTE_RESUME
;
6843 if (so
->so_error
!= 0) {
6845 data
= so
->so_error
;
6846 kn
->kn_flags
|= EV_EOF
;
6848 u_int32_t data32
= 0;
6849 get_sockev_state(so
, &data32
);
6853 /* Reset any events that are not requested on this knote */
6854 kn
->kn_fflags
&= (kn
->kn_sfflags
& EVFILT_SOCK_ALL_MASK
);
6855 level_trigger
&= (kn
->kn_sfflags
& EVFILT_SOCK_ALL_MASK
);
6857 /* Find the level triggerred events that are already delivered */
6858 level_trigger
&= kn
->kn_hook32
;
6859 level_trigger
&= EVFILT_SOCK_LEVEL_TRIGGER_MASK
;
6861 /* Do not deliver level triggerred events more than once */
6862 if ((kn
->kn_fflags
& ~level_trigger
) != 0) {
6868 * Store the state of the events being delivered. This
6869 * state can be used to deliver level triggered events
6870 * ateast once and still avoid waking up the application
6871 * multiple times as long as the event is active.
6873 if (kn
->kn_fflags
!= 0) {
6874 kn
->kn_hook32
|= (kn
->kn_fflags
&
6875 EVFILT_SOCK_LEVEL_TRIGGER_MASK
);
6879 * NOTE_RESUME and NOTE_SUSPEND are an exception, deliver
6880 * only one of them and remember the last one that was
6883 if (kn
->kn_fflags
& NOTE_SUSPEND
) {
6884 kn
->kn_hook32
&= ~NOTE_RESUME
;
6886 if (kn
->kn_fflags
& NOTE_RESUME
) {
6887 kn
->kn_hook32
&= ~NOTE_SUSPEND
;
6890 knote_fill_kevent(kn
, kev
, data
);
6896 filt_sockattach(struct knote
*kn
, __unused
struct kevent_qos_s
*kev
)
6898 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6902 if (KNOTE_ATTACH(&so
->so_klist
, kn
)) {
6903 so
->so_flags
|= SOF_KNOTE
;
6906 /* determine if event already fired */
6907 return filt_sockev_common(kn
, NULL
, so
, 0);
6911 filt_sockdetach(struct knote
*kn
)
6913 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6916 if ((so
->so_flags
& SOF_KNOTE
) != 0) {
6917 if (KNOTE_DETACH(&so
->so_klist
, kn
)) {
6918 so
->so_flags
&= ~SOF_KNOTE
;
6921 socket_unlock(so
, 1);
6925 filt_sockev(struct knote
*kn
, long hint
)
6927 int ret
= 0, locked
= 0;
6928 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6929 long ev_hint
= (hint
& SO_FILT_HINT_EV
);
6931 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6936 ret
= filt_sockev_common(kn
, NULL
, so
, ev_hint
);
6939 socket_unlock(so
, 1);
6948 * filt_socktouch - update event state
6953 struct kevent_qos_s
*kev
)
6955 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
6956 uint32_t changed_flags
;
6961 /* save off the [result] data and fflags */
6962 changed_flags
= (kn
->kn_sfflags
^ kn
->kn_hook32
);
6964 /* save off the new input fflags and data */
6965 kn
->kn_sfflags
= kev
->fflags
;
6966 kn
->kn_sdata
= kev
->data
;
6968 /* restrict the current results to the (smaller?) set of new interest */
6970 * For compatibility with previous implementations, we leave kn_fflags
6971 * as they were before.
6973 //kn->kn_fflags &= kev->fflags;
6976 * Since we keep track of events that are already
6977 * delivered, if any of those events are not requested
6978 * anymore the state related to them can be reset
6980 kn
->kn_hook32
&= ~(changed_flags
& EVFILT_SOCK_LEVEL_TRIGGER_MASK
);
6982 /* determine if we have events to deliver */
6983 ret
= filt_sockev_common(kn
, NULL
, so
, 0);
6985 socket_unlock(so
, 1);
6991 * filt_sockprocess - query event fired state and return data
6994 filt_sockprocess(struct knote
*kn
, struct kevent_qos_s
*kev
)
6996 struct socket
*so
= (struct socket
*)kn
->kn_fp
->fp_glob
->fg_data
;
7001 ret
= filt_sockev_common(kn
, kev
, so
, 0);
7003 socket_unlock(so
, 1);
7009 get_sockev_state(struct socket
*so
, u_int32_t
*statep
)
7011 u_int32_t state
= *(statep
);
7014 * If the state variable is already used by a previous event,
7021 if (so
->so_state
& SS_ISCONNECTED
) {
7022 state
|= SOCKEV_CONNECTED
;
7024 state
&= ~(SOCKEV_CONNECTED
);
7026 state
|= ((so
->so_state
& SS_ISDISCONNECTED
) ? SOCKEV_DISCONNECTED
: 0);
7030 #define SO_LOCK_HISTORY_STR_LEN \
7031 (2 * SO_LCKDBG_MAX * (2 + (2 * sizeof (void *)) + 1) + 1)
7033 __private_extern__
const char *
7034 solockhistory_nr(struct socket
*so
)
7038 static char lock_history_str
[SO_LOCK_HISTORY_STR_LEN
];
7040 bzero(lock_history_str
, sizeof(lock_history_str
));
7041 for (i
= SO_LCKDBG_MAX
- 1; i
>= 0; i
--) {
7042 n
+= scnprintf(lock_history_str
+ n
,
7043 SO_LOCK_HISTORY_STR_LEN
- n
, "%p:%p ",
7044 so
->lock_lr
[(so
->next_lock_lr
+ i
) % SO_LCKDBG_MAX
],
7045 so
->unlock_lr
[(so
->next_unlock_lr
+ i
) % SO_LCKDBG_MAX
]);
7047 return lock_history_str
;
7051 socket_getlock(struct socket
*so
, int flags
)
7053 if (so
->so_proto
->pr_getlock
!= NULL
) {
7054 return (*so
->so_proto
->pr_getlock
)(so
, flags
);
7056 return so
->so_proto
->pr_domain
->dom_mtx
;
7061 socket_lock(struct socket
*so
, int refcount
)
7065 lr_saved
= __builtin_return_address(0);
7067 if (so
->so_proto
->pr_lock
) {
7068 (*so
->so_proto
->pr_lock
)(so
, refcount
, lr_saved
);
7070 #ifdef MORE_LOCKING_DEBUG
7071 LCK_MTX_ASSERT(so
->so_proto
->pr_domain
->dom_mtx
,
7072 LCK_MTX_ASSERT_NOTOWNED
);
7074 lck_mtx_lock(so
->so_proto
->pr_domain
->dom_mtx
);
7078 so
->lock_lr
[so
->next_lock_lr
] = lr_saved
;
7079 so
->next_lock_lr
= (so
->next_lock_lr
+ 1) % SO_LCKDBG_MAX
;
7084 socket_lock_assert_owned(struct socket
*so
)
7086 lck_mtx_t
*mutex_held
;
7088 if (so
->so_proto
->pr_getlock
!= NULL
) {
7089 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
7091 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
7094 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
7098 socket_try_lock(struct socket
*so
)
7102 if (so
->so_proto
->pr_getlock
!= NULL
) {
7103 mtx
= (*so
->so_proto
->pr_getlock
)(so
, 0);
7105 mtx
= so
->so_proto
->pr_domain
->dom_mtx
;
7108 return lck_mtx_try_lock(mtx
);
7112 socket_unlock(struct socket
*so
, int refcount
)
7115 lck_mtx_t
*mutex_held
;
7117 lr_saved
= __builtin_return_address(0);
7119 if (so
== NULL
|| so
->so_proto
== NULL
) {
7120 panic("%s: null so_proto so=%p\n", __func__
, so
);
7124 if (so
->so_proto
->pr_unlock
) {
7125 (*so
->so_proto
->pr_unlock
)(so
, refcount
, lr_saved
);
7127 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
7128 #ifdef MORE_LOCKING_DEBUG
7129 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
7131 so
->unlock_lr
[so
->next_unlock_lr
] = lr_saved
;
7132 so
->next_unlock_lr
= (so
->next_unlock_lr
+ 1) % SO_LCKDBG_MAX
;
7135 if (so
->so_usecount
<= 0) {
7136 panic("%s: bad refcount=%d so=%p (%d, %d, %d) "
7137 "lrh=%s", __func__
, so
->so_usecount
, so
,
7138 SOCK_DOM(so
), so
->so_type
,
7139 SOCK_PROTO(so
), solockhistory_nr(so
));
7144 if (so
->so_usecount
== 0) {
7145 sofreelastref(so
, 1);
7148 lck_mtx_unlock(mutex_held
);
7152 /* Called with socket locked, will unlock socket */
7154 sofree(struct socket
*so
)
7156 lck_mtx_t
*mutex_held
;
7158 if (so
->so_proto
->pr_getlock
!= NULL
) {
7159 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
7161 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
7163 LCK_MTX_ASSERT(mutex_held
, LCK_MTX_ASSERT_OWNED
);
7165 sofreelastref(so
, 0);
7169 soreference(struct socket
*so
)
7171 socket_lock(so
, 1); /* locks & take one reference on socket */
7172 socket_unlock(so
, 0); /* unlock only */
7176 sodereference(struct socket
*so
)
7179 socket_unlock(so
, 1);
7183 * Set or clear SOF_MULTIPAGES on the socket to enable or disable the
7184 * possibility of using jumbo clusters. Caller must ensure to hold
7188 somultipages(struct socket
*so
, boolean_t set
)
7191 so
->so_flags
|= SOF_MULTIPAGES
;
7193 so
->so_flags
&= ~SOF_MULTIPAGES
;
7198 soif2kcl(struct socket
*so
, boolean_t set
)
7201 so
->so_flags1
|= SOF1_IF_2KCL
;
7203 so
->so_flags1
&= ~SOF1_IF_2KCL
;
7208 so_isdstlocal(struct socket
*so
)
7210 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
7212 if (SOCK_DOM(so
) == PF_INET
) {
7213 return inaddr_local(inp
->inp_faddr
);
7214 } else if (SOCK_DOM(so
) == PF_INET6
) {
7215 return in6addr_local(&inp
->in6p_faddr
);
7222 sosetdefunct(struct proc
*p
, struct socket
*so
, int level
, boolean_t noforce
)
7224 struct sockbuf
*rcv
, *snd
;
7225 int err
= 0, defunct
;
7230 defunct
= (so
->so_flags
& SOF_DEFUNCT
);
7232 if (!(snd
->sb_flags
& rcv
->sb_flags
& SB_DROP
)) {
7233 panic("%s: SB_DROP not set", __func__
);
7239 if (so
->so_flags
& SOF_NODEFUNCT
) {
7242 if (p
!= PROC_NULL
) {
7243 SODEFUNCTLOG("%s[%d, %s]: (target pid %d "
7244 "name %s level %d) so 0x%llx [%d,%d] "
7245 "is not eligible for defunct "
7246 "(%d)\n", __func__
, proc_selfpid(),
7247 proc_best_name(current_proc()), proc_pid(p
),
7248 proc_best_name(p
), level
,
7249 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7250 SOCK_DOM(so
), SOCK_TYPE(so
), err
);
7254 so
->so_flags
&= ~SOF_NODEFUNCT
;
7255 if (p
!= PROC_NULL
) {
7256 SODEFUNCTLOG("%s[%d, %s]: (target pid %d "
7257 "name %s level %d) so 0x%llx [%d,%d] "
7259 "(%d)\n", __func__
, proc_selfpid(),
7260 proc_best_name(current_proc()), proc_pid(p
),
7261 proc_best_name(p
), level
,
7262 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7263 SOCK_DOM(so
), SOCK_TYPE(so
), err
);
7265 } else if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) {
7266 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
7267 struct ifnet
*ifp
= inp
->inp_last_outifp
;
7269 if (ifp
&& IFNET_IS_CELLULAR(ifp
)) {
7270 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nocell
);
7271 } else if (so
->so_flags
& SOF_DELEGATED
) {
7272 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nodlgtd
);
7273 } else if (soextbkidlestat
.so_xbkidle_time
== 0) {
7274 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_notime
);
7275 } else if (noforce
&& p
!= PROC_NULL
) {
7276 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
7278 so
->so_flags1
|= SOF1_EXTEND_BK_IDLE_INPROG
;
7279 so
->so_extended_bk_start
= net_uptime();
7280 OSBitOrAtomic(P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
7282 inpcb_timer_sched(inp
->inp_pcbinfo
, INPCB_TIMER_LAZY
);
7285 SODEFUNCTLOG("%s[%d, %s]: (target pid %d "
7286 "name %s level %d) so 0x%llx [%d,%d] "
7288 "(%d)\n", __func__
, proc_selfpid(),
7289 proc_best_name(current_proc()), proc_pid(p
),
7290 proc_best_name(p
), level
,
7291 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7292 SOCK_DOM(so
), SOCK_TYPE(so
), err
);
7295 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_forced
);
7299 so
->so_flags
|= SOF_DEFUNCT
;
7301 /* Prevent further data from being appended to the socket buffers */
7302 snd
->sb_flags
|= SB_DROP
;
7303 rcv
->sb_flags
|= SB_DROP
;
7305 /* Flush any existing data in the socket buffers */
7306 if (rcv
->sb_cc
!= 0) {
7307 rcv
->sb_flags
&= ~SB_SEL
;
7308 selthreadclear(&rcv
->sb_sel
);
7311 if (snd
->sb_cc
!= 0) {
7312 snd
->sb_flags
&= ~SB_SEL
;
7313 selthreadclear(&snd
->sb_sel
);
7318 if (p
!= PROC_NULL
) {
7319 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s level %d) "
7320 "so 0x%llx [%d,%d] %s defunct%s\n", __func__
,
7321 proc_selfpid(), proc_best_name(current_proc()),
7322 proc_pid(p
), proc_best_name(p
), level
,
7323 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7324 SOCK_TYPE(so
), defunct
? "is already" : "marked as",
7325 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ?
7332 sodefunct(struct proc
*p
, struct socket
*so
, int level
)
7334 struct sockbuf
*rcv
, *snd
;
7336 if (!(so
->so_flags
& SOF_DEFUNCT
)) {
7337 panic("%s improperly called", __func__
);
7340 if (so
->so_state
& SS_DEFUNCT
) {
7347 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7348 char s
[MAX_IPv6_STR_LEN
];
7349 char d
[MAX_IPv6_STR_LEN
];
7350 struct inpcb
*inp
= sotoinpcb(so
);
7352 if (p
!= PROC_NULL
) {
7354 "%s[%d, %s]: (target pid %d name %s level %d) "
7355 "so 0x%llx [%s %s:%d -> %s:%d] is now defunct "
7356 "[rcv_si 0x%x, snd_si 0x%x, rcv_fl 0x%x, "
7357 " snd_fl 0x%x]\n", __func__
,
7358 proc_selfpid(), proc_best_name(current_proc()),
7359 proc_pid(p
), proc_best_name(p
), level
,
7360 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7361 (SOCK_TYPE(so
) == SOCK_STREAM
) ? "TCP" : "UDP",
7362 inet_ntop(SOCK_DOM(so
), ((SOCK_DOM(so
) == PF_INET
) ?
7363 (void *)&inp
->inp_laddr
.s_addr
:
7364 (void *)&inp
->in6p_laddr
),
7365 s
, sizeof(s
)), ntohs(inp
->in6p_lport
),
7366 inet_ntop(SOCK_DOM(so
), (SOCK_DOM(so
) == PF_INET
) ?
7367 (void *)&inp
->inp_faddr
.s_addr
:
7368 (void *)&inp
->in6p_faddr
,
7369 d
, sizeof(d
)), ntohs(inp
->in6p_fport
),
7370 (uint32_t)rcv
->sb_sel
.si_flags
,
7371 (uint32_t)snd
->sb_sel
.si_flags
,
7372 rcv
->sb_flags
, snd
->sb_flags
);
7374 } else if (p
!= PROC_NULL
) {
7375 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s level %d) "
7376 "so 0x%llx [%d,%d] is now defunct [rcv_si 0x%x, "
7377 "snd_si 0x%x, rcv_fl 0x%x, snd_fl 0x%x]\n", __func__
,
7378 proc_selfpid(), proc_best_name(current_proc()),
7379 proc_pid(p
), proc_best_name(p
), level
,
7380 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7381 SOCK_DOM(so
), SOCK_TYPE(so
),
7382 (uint32_t)rcv
->sb_sel
.si_flags
,
7383 (uint32_t)snd
->sb_sel
.si_flags
, rcv
->sb_flags
,
7388 * Unwedge threads blocked on sbwait() and sb_lock().
7393 so
->so_flags1
|= SOF1_DEFUNCTINPROG
;
7394 if (rcv
->sb_flags
& SB_LOCK
) {
7395 sbunlock(rcv
, TRUE
); /* keep socket locked */
7397 if (snd
->sb_flags
& SB_LOCK
) {
7398 sbunlock(snd
, TRUE
); /* keep socket locked */
7401 * Flush the buffers and disconnect. We explicitly call shutdown
7402 * on both data directions to ensure that SS_CANT{RCV,SEND}MORE
7403 * states are set for the socket. This would also flush out data
7404 * hanging off the receive list of this socket.
7406 (void) soshutdownlock_final(so
, SHUT_RD
);
7407 (void) soshutdownlock_final(so
, SHUT_WR
);
7408 (void) sodisconnectlocked(so
);
7411 * Explicitly handle connectionless-protocol disconnection
7412 * and release any remaining data in the socket buffers.
7414 if (!(so
->so_state
& SS_ISDISCONNECTED
)) {
7415 (void) soisdisconnected(so
);
7418 if (so
->so_error
== 0) {
7419 so
->so_error
= EBADF
;
7422 if (rcv
->sb_cc
!= 0) {
7423 rcv
->sb_flags
&= ~SB_SEL
;
7424 selthreadclear(&rcv
->sb_sel
);
7427 if (snd
->sb_cc
!= 0) {
7428 snd
->sb_flags
&= ~SB_SEL
;
7429 selthreadclear(&snd
->sb_sel
);
7432 so
->so_state
|= SS_DEFUNCT
;
7433 OSIncrementAtomicLong((volatile long *)&sodefunct_calls
);
7440 soresume(struct proc
*p
, struct socket
*so
, int locked
)
7446 if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
) {
7447 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s) so 0x%llx "
7448 "[%d,%d] resumed from bk idle\n",
7449 __func__
, proc_selfpid(), proc_best_name(current_proc()),
7450 proc_pid(p
), proc_best_name(p
),
7451 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7452 SOCK_DOM(so
), SOCK_TYPE(so
));
7454 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_INPROG
;
7455 so
->so_extended_bk_start
= 0;
7456 OSBitAndAtomic(~P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
7458 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_resumed
);
7459 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
7460 VERIFY(soextbkidlestat
.so_xbkidle_active
>= 0);
7463 socket_unlock(so
, 1);
7470 * Does not attempt to account for sockets that are delegated from
7471 * the current process
7474 so_set_extended_bk_idle(struct socket
*so
, int optval
)
7478 if ((SOCK_DOM(so
) != PF_INET
&& SOCK_DOM(so
) != PF_INET6
) ||
7479 SOCK_PROTO(so
) != IPPROTO_TCP
) {
7480 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_notsupp
);
7482 } else if (optval
== 0) {
7483 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_WANTED
;
7485 soresume(current_proc(), so
, 1);
7487 struct proc
*p
= current_proc();
7488 struct fileproc
*fp
;
7492 * Unlock socket to avoid lock ordering issue with
7493 * the proc fd table lock
7495 socket_unlock(so
, 0);
7498 fdt_foreach(fp
, p
) {
7501 if (FILEGLOB_DTYPE(fp
->fp_glob
) != DTYPE_SOCKET
) {
7505 so2
= (struct socket
*)fp
->fp_glob
->fg_data
;
7507 so2
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) {
7510 if (count
>= soextbkidlestat
.so_xbkidle_maxperproc
) {
7518 if (count
>= soextbkidlestat
.so_xbkidle_maxperproc
) {
7519 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_toomany
);
7521 } else if (so
->so_flags
& SOF_DELEGATED
) {
7522 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nodlgtd
);
7525 so
->so_flags1
|= SOF1_EXTEND_BK_IDLE_WANTED
;
7526 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_wantok
);
7528 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx [%d,%d] "
7529 "%s marked for extended bk idle\n",
7530 __func__
, proc_selfpid(), proc_best_name(current_proc()),
7531 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7532 SOCK_DOM(so
), SOCK_TYPE(so
),
7533 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ?
7541 so_stop_extended_bk_idle(struct socket
*so
)
7543 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_INPROG
;
7544 so
->so_extended_bk_start
= 0;
7546 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
7547 VERIFY(soextbkidlestat
.so_xbkidle_active
>= 0);
7551 sosetdefunct(current_proc(), so
,
7552 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
, FALSE
);
7553 if (so
->so_flags
& SOF_DEFUNCT
) {
7554 sodefunct(current_proc(), so
,
7555 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
);
7560 so_drain_extended_bk_idle(struct socket
*so
)
7562 if (so
&& (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
)) {
7564 * Only penalize sockets that have outstanding data
7566 if (so
->so_rcv
.sb_cc
|| so
->so_snd
.sb_cc
) {
7567 so_stop_extended_bk_idle(so
);
7569 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_drained
);
7575 * Return values tells if socket is still in extended background idle
7578 so_check_extended_bk_idle_time(struct socket
*so
)
7582 if ((so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
)) {
7583 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx [%d,%d]\n",
7584 __func__
, proc_selfpid(), proc_best_name(current_proc()),
7585 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7586 SOCK_DOM(so
), SOCK_TYPE(so
));
7587 if (net_uptime() - so
->so_extended_bk_start
>
7588 soextbkidlestat
.so_xbkidle_time
) {
7589 so_stop_extended_bk_idle(so
);
7591 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_expired
);
7595 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
7597 inpcb_timer_sched(inp
->inp_pcbinfo
, INPCB_TIMER_LAZY
);
7598 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_resched
);
7606 resume_proc_sockets(proc_t p
)
7608 if (p
->p_ladvflag
& P_LXBKIDLEINPROG
) {
7609 struct fileproc
*fp
;
7613 fdt_foreach(fp
, p
) {
7614 if (FILEGLOB_DTYPE(fp
->fp_glob
) != DTYPE_SOCKET
) {
7618 so
= (struct socket
*)fp
->fp_glob
->fg_data
;
7619 (void) soresume(p
, so
, 0);
7623 OSBitAndAtomic(~P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
7627 __private_extern__
int
7628 so_set_recv_anyif(struct socket
*so
, int optval
)
7632 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7634 sotoinpcb(so
)->inp_flags
|= INP_RECV_ANYIF
;
7636 sotoinpcb(so
)->inp_flags
&= ~INP_RECV_ANYIF
;
7644 __private_extern__
int
7645 so_get_recv_anyif(struct socket
*so
)
7649 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7650 ret
= (sotoinpcb(so
)->inp_flags
& INP_RECV_ANYIF
) ? 1 : 0;
7657 so_set_restrictions(struct socket
*so
, uint32_t vals
)
7659 int nocell_old
, nocell_new
;
7660 int noexpensive_old
, noexpensive_new
;
7661 int noconstrained_old
, noconstrained_new
;
7664 * Deny-type restrictions are trapdoors; once set they cannot be
7665 * unset for the lifetime of the socket. This allows them to be
7666 * issued by a framework on behalf of the application without
7667 * having to worry that they can be undone.
7669 * Note here that socket-level restrictions overrides any protocol
7670 * level restrictions. For instance, SO_RESTRICT_DENY_CELLULAR
7671 * socket restriction issued on the socket has a higher precendence
7672 * than INP_NO_IFT_CELLULAR. The latter is affected by the UUID
7673 * policy PROC_UUID_NO_CELLULAR for unrestricted sockets only,
7674 * i.e. when SO_RESTRICT_DENY_CELLULAR has not been issued.
7676 nocell_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_CELLULAR
);
7677 noexpensive_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_EXPENSIVE
);
7678 noconstrained_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_CONSTRAINED
);
7679 so
->so_restrictions
|= (vals
& (SO_RESTRICT_DENY_IN
|
7680 SO_RESTRICT_DENY_OUT
| SO_RESTRICT_DENY_CELLULAR
|
7681 SO_RESTRICT_DENY_EXPENSIVE
| SO_RESTRICT_DENY_CONSTRAINED
));
7682 nocell_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_CELLULAR
);
7683 noexpensive_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_EXPENSIVE
);
7684 noconstrained_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_CONSTRAINED
);
7686 /* we can only set, not clear restrictions */
7687 if ((nocell_new
- nocell_old
) == 0 &&
7688 (noexpensive_new
- noexpensive_old
) == 0 &&
7689 (noconstrained_new
- noconstrained_old
) == 0) {
7692 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7693 if (nocell_new
- nocell_old
!= 0) {
7695 * if deny cellular is now set, do what's needed
7698 inp_set_nocellular(sotoinpcb(so
));
7700 if (noexpensive_new
- noexpensive_old
!= 0) {
7701 inp_set_noexpensive(sotoinpcb(so
));
7703 if (noconstrained_new
- noconstrained_old
!= 0) {
7704 inp_set_noconstrained(sotoinpcb(so
));
7708 if (SOCK_DOM(so
) == PF_MULTIPATH
) {
7709 mptcp_set_restrictions(so
);
7716 so_get_restrictions(struct socket
*so
)
7718 return so
->so_restrictions
& (SO_RESTRICT_DENY_IN
|
7719 SO_RESTRICT_DENY_OUT
|
7720 SO_RESTRICT_DENY_CELLULAR
| SO_RESTRICT_DENY_EXPENSIVE
);
7724 so_set_effective_pid(struct socket
*so
, int epid
, struct proc
*p
, boolean_t check_cred
)
7726 struct proc
*ep
= PROC_NULL
;
7729 /* pid 0 is reserved for kernel */
7736 * If this is an in-kernel socket, prevent its delegate
7737 * association from changing unless the socket option is
7738 * coming from within the kernel itself.
7740 if (so
->last_pid
== 0 && p
!= kernproc
) {
7746 * If this is issued by a process that's recorded as the
7747 * real owner of the socket, or if the pid is the same as
7748 * the process's own pid, then proceed. Otherwise ensure
7749 * that the issuing process has the necessary privileges.
7751 if (check_cred
&& (epid
!= so
->last_pid
|| epid
!= proc_pid(p
))) {
7752 if ((error
= priv_check_cred(kauth_cred_get(),
7753 PRIV_NET_PRIVILEGED_SOCKET_DELEGATE
, 0))) {
7759 /* Find the process that corresponds to the effective pid */
7760 if ((ep
= proc_find(epid
)) == PROC_NULL
) {
7766 * If a process tries to delegate the socket to itself, then
7767 * there's really nothing to do; treat it as a way for the
7768 * delegate association to be cleared. Note that we check
7769 * the passed-in proc rather than calling proc_selfpid(),
7770 * as we need to check the process issuing the socket option
7771 * which could be kernproc. Given that we don't allow 0 for
7772 * effective pid, it means that a delegated in-kernel socket
7773 * stays delegated during its lifetime (which is probably OK.)
7775 if (epid
== proc_pid(p
)) {
7776 so
->so_flags
&= ~SOF_DELEGATED
;
7779 uuid_clear(so
->e_uuid
);
7781 so
->so_flags
|= SOF_DELEGATED
;
7782 so
->e_upid
= proc_uniqueid(ep
);
7783 so
->e_pid
= proc_pid(ep
);
7784 proc_getexecutableuuid(ep
, so
->e_uuid
, sizeof(so
->e_uuid
));
7786 #if defined(XNU_TARGET_OS_OSX)
7787 if (ep
->p_responsible_pid
!= so
->e_pid
) {
7788 proc_t rp
= proc_find(ep
->p_responsible_pid
);
7789 if (rp
!= PROC_NULL
) {
7790 proc_getexecutableuuid(rp
, so
->so_ruuid
, sizeof(so
->so_ruuid
));
7791 so
->so_rpid
= ep
->p_responsible_pid
;
7794 uuid_clear(so
->so_ruuid
);
7800 if (so
->so_proto
!= NULL
&& so
->so_proto
->pr_update_last_owner
!= NULL
) {
7801 (*so
->so_proto
->pr_update_last_owner
)(so
, NULL
, ep
);
7804 if (error
== 0 && net_io_policy_log
) {
7807 uuid_unparse(so
->e_uuid
, buf
);
7808 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d (%s) "
7809 "euuid %s%s\n", __func__
, proc_name_address(p
),
7810 proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7811 SOCK_DOM(so
), SOCK_TYPE(so
),
7812 so
->e_pid
, proc_name_address(ep
), buf
,
7813 ((so
->so_flags
& SOF_DELEGATED
) ? " [delegated]" : ""));
7814 } else if (error
!= 0 && net_io_policy_log
) {
7815 log(LOG_ERR
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d (%s) "
7816 "ERROR (%d)\n", __func__
, proc_name_address(p
),
7817 proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7818 SOCK_DOM(so
), SOCK_TYPE(so
),
7819 epid
, (ep
== PROC_NULL
) ? "PROC_NULL" :
7820 proc_name_address(ep
), error
);
7823 /* Update this socket's policy upon success */
7825 so
->so_policy_gencnt
*= -1;
7826 so_update_policy(so
);
7828 so_update_necp_policy(so
, NULL
, NULL
);
7832 if (ep
!= PROC_NULL
) {
7840 so_set_effective_uuid(struct socket
*so
, uuid_t euuid
, struct proc
*p
, boolean_t check_cred
)
7846 /* UUID must not be all-zeroes (reserved for kernel) */
7847 if (uuid_is_null(euuid
)) {
7853 * If this is an in-kernel socket, prevent its delegate
7854 * association from changing unless the socket option is
7855 * coming from within the kernel itself.
7857 if (so
->last_pid
== 0 && p
!= kernproc
) {
7862 /* Get the UUID of the issuing process */
7863 proc_getexecutableuuid(p
, uuid
, sizeof(uuid
));
7866 * If this is issued by a process that's recorded as the
7867 * real owner of the socket, or if the uuid is the same as
7868 * the process's own uuid, then proceed. Otherwise ensure
7869 * that the issuing process has the necessary privileges.
7872 (uuid_compare(euuid
, so
->last_uuid
) != 0 ||
7873 uuid_compare(euuid
, uuid
) != 0)) {
7874 if ((error
= priv_check_cred(kauth_cred_get(),
7875 PRIV_NET_PRIVILEGED_SOCKET_DELEGATE
, 0))) {
7882 * If a process tries to delegate the socket to itself, then
7883 * there's really nothing to do; treat it as a way for the
7884 * delegate association to be cleared. Note that we check
7885 * the uuid of the passed-in proc rather than that of the
7886 * current process, as we need to check the process issuing
7887 * the socket option which could be kernproc itself. Given
7888 * that we don't allow 0 for effective uuid, it means that
7889 * a delegated in-kernel socket stays delegated during its
7890 * lifetime (which is okay.)
7892 if (uuid_compare(euuid
, uuid
) == 0) {
7893 so
->so_flags
&= ~SOF_DELEGATED
;
7896 uuid_clear(so
->e_uuid
);
7898 so
->so_flags
|= SOF_DELEGATED
;
7900 * Unlike so_set_effective_pid(), we only have the UUID
7901 * here and the process ID is not known. Inherit the
7902 * real {pid,upid} of the socket.
7904 so
->e_upid
= so
->last_upid
;
7905 so
->e_pid
= so
->last_pid
;
7906 uuid_copy(so
->e_uuid
, euuid
);
7909 * The following will clear the effective process name as it's the same
7910 * as the real process
7912 if (so
->so_proto
!= NULL
&& so
->so_proto
->pr_update_last_owner
!= NULL
) {
7913 (*so
->so_proto
->pr_update_last_owner
)(so
, NULL
, NULL
);
7916 if (error
== 0 && net_io_policy_log
) {
7917 uuid_unparse(so
->e_uuid
, buf
);
7918 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d "
7919 "euuid %s%s\n", __func__
, proc_name_address(p
), proc_pid(p
),
7920 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7921 SOCK_TYPE(so
), so
->e_pid
, buf
,
7922 ((so
->so_flags
& SOF_DELEGATED
) ? " [delegated]" : ""));
7923 } else if (error
!= 0 && net_io_policy_log
) {
7924 uuid_unparse(euuid
, buf
);
7925 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] euuid %s "
7926 "ERROR (%d)\n", __func__
, proc_name_address(p
), proc_pid(p
),
7927 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7928 SOCK_TYPE(so
), buf
, error
);
7931 /* Update this socket's policy upon success */
7933 so
->so_policy_gencnt
*= -1;
7934 so_update_policy(so
);
7936 so_update_necp_policy(so
, NULL
, NULL
);
7944 netpolicy_post_msg(uint32_t ev_code
, struct netpolicy_event_data
*ev_data
,
7945 uint32_t ev_datalen
)
7947 struct kev_msg ev_msg
;
7950 * A netpolicy event always starts with a netpolicy_event_data
7951 * structure, but the caller can provide for a longer event
7952 * structure to post, depending on the event code.
7954 VERIFY(ev_data
!= NULL
&& ev_datalen
>= sizeof(*ev_data
));
7956 bzero(&ev_msg
, sizeof(ev_msg
));
7957 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7958 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
7959 ev_msg
.kev_subclass
= KEV_NETPOLICY_SUBCLASS
;
7960 ev_msg
.event_code
= ev_code
;
7962 ev_msg
.dv
[0].data_ptr
= ev_data
;
7963 ev_msg
.dv
[0].data_length
= ev_datalen
;
7965 kev_post_msg(&ev_msg
);
7969 socket_post_kev_msg(uint32_t ev_code
,
7970 struct kev_socket_event_data
*ev_data
,
7971 uint32_t ev_datalen
)
7973 struct kev_msg ev_msg
;
7975 bzero(&ev_msg
, sizeof(ev_msg
));
7976 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7977 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
7978 ev_msg
.kev_subclass
= KEV_SOCKET_SUBCLASS
;
7979 ev_msg
.event_code
= ev_code
;
7981 ev_msg
.dv
[0].data_ptr
= ev_data
;
7982 ev_msg
.dv
[0].data_length
= ev_datalen
;
7984 kev_post_msg(&ev_msg
);
7988 socket_post_kev_msg_closed(struct socket
*so
)
7990 struct kev_socket_closed ev
= {};
7991 struct sockaddr
*socksa
= NULL
, *peersa
= NULL
;
7994 if ((so
->so_flags1
& SOF1_WANT_KEV_SOCK_CLOSED
) == 0) {
7997 err
= (*so
->so_proto
->pr_usrreqs
->pru_sockaddr
)(so
, &socksa
);
7999 err
= (*so
->so_proto
->pr_usrreqs
->pru_peeraddr
)(so
,
8002 memcpy(&ev
.ev_data
.kev_sockname
, socksa
,
8004 sizeof(ev
.ev_data
.kev_sockname
)));
8005 memcpy(&ev
.ev_data
.kev_peername
, peersa
,
8007 sizeof(ev
.ev_data
.kev_peername
)));
8008 socket_post_kev_msg(KEV_SOCKET_CLOSED
,
8009 &ev
.ev_data
, sizeof(ev
));
8012 if (socksa
!= NULL
) {
8013 FREE(socksa
, M_SONAME
);
8015 if (peersa
!= NULL
) {
8016 FREE(peersa
, M_SONAME
);