2 * Copyright (c) 1998-2015 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/ntstat.h>
102 #include <net/content_filter.h>
103 #include <netinet/in.h>
104 #include <netinet/in_pcb.h>
105 #include <netinet/ip6.h>
106 #include <netinet6/ip6_var.h>
107 #include <netinet/flow_divert.h>
108 #include <kern/zalloc.h>
109 #include <kern/locks.h>
110 #include <machine/limits.h>
111 #include <libkern/OSAtomic.h>
112 #include <pexpert/pexpert.h>
113 #include <kern/assert.h>
114 #include <kern/task.h>
115 #include <sys/kpi_mbuf.h>
116 #include <sys/mcache.h>
117 #include <sys/unpcb.h>
120 #include <security/mac.h>
121 #include <security/mac_framework.h>
125 #include <netinet/mp_pcb.h>
126 #include <netinet/mptcp_var.h>
127 #endif /* MULTIPATH */
129 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
131 #if DEBUG || DEVELOPMENT
132 #define DEBUG_KERNEL_ADDRPERM(_v) (_v)
134 #define DEBUG_KERNEL_ADDRPERM(_v) VM_KERNEL_ADDRPERM(_v)
137 /* TODO: this should be in a header file somewhere */
138 extern char *proc_name_address(void *p
);
140 static u_int32_t so_cache_hw
; /* High water mark for socache */
141 static u_int32_t so_cache_timeouts
; /* number of timeouts */
142 static u_int32_t so_cache_max_freed
; /* max freed per timeout */
143 static u_int32_t cached_sock_count
= 0;
144 STAILQ_HEAD(, socket
) so_cache_head
;
145 int max_cached_sock_count
= MAX_CACHED_SOCKETS
;
146 static u_int32_t so_cache_time
;
147 static int socketinit_done
;
148 static struct zone
*so_cache_zone
;
150 static lck_grp_t
*so_cache_mtx_grp
;
151 static lck_attr_t
*so_cache_mtx_attr
;
152 static lck_grp_attr_t
*so_cache_mtx_grp_attr
;
153 static lck_mtx_t
*so_cache_mtx
;
155 #include <machine/limits.h>
157 static void filt_sordetach(struct knote
*kn
);
158 static int filt_soread(struct knote
*kn
, long hint
);
159 static void filt_sowdetach(struct knote
*kn
);
160 static int filt_sowrite(struct knote
*kn
, long hint
);
161 static void filt_sockdetach(struct knote
*kn
);
162 static int filt_sockev(struct knote
*kn
, long hint
);
163 static void filt_socktouch(struct knote
*kn
, struct kevent_internal_s
*kev
,
166 static int sooptcopyin_timeval(struct sockopt
*, struct timeval
*);
167 static int sooptcopyout_timeval(struct sockopt
*, const struct timeval
*);
169 static struct filterops soread_filtops
= {
171 .f_detach
= filt_sordetach
,
172 .f_event
= filt_soread
,
175 static struct filterops sowrite_filtops
= {
177 .f_detach
= filt_sowdetach
,
178 .f_event
= filt_sowrite
,
181 static struct filterops sock_filtops
= {
183 .f_detach
= filt_sockdetach
,
184 .f_event
= filt_sockev
,
185 .f_touch
= filt_socktouch
,
188 SYSCTL_DECL(_kern_ipc
);
190 #define EVEN_MORE_LOCKING_DEBUG 0
192 int socket_debug
= 0;
193 SYSCTL_INT(_kern_ipc
, OID_AUTO
, socket_debug
,
194 CTLFLAG_RW
| CTLFLAG_LOCKED
, &socket_debug
, 0, "");
196 static int socket_zone
= M_SOCKET
;
197 so_gen_t so_gencnt
; /* generation count for sockets */
199 MALLOC_DEFINE(M_SONAME
, "soname", "socket name");
200 MALLOC_DEFINE(M_PCB
, "pcb", "protocol control block");
202 #define DBG_LAYER_IN_BEG NETDBG_CODE(DBG_NETSOCK, 0)
203 #define DBG_LAYER_IN_END NETDBG_CODE(DBG_NETSOCK, 2)
204 #define DBG_LAYER_OUT_BEG NETDBG_CODE(DBG_NETSOCK, 1)
205 #define DBG_LAYER_OUT_END NETDBG_CODE(DBG_NETSOCK, 3)
206 #define DBG_FNC_SOSEND NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 1)
207 #define DBG_FNC_SOSEND_LIST NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 3)
208 #define DBG_FNC_SORECEIVE NETDBG_CODE(DBG_NETSOCK, (8 << 8))
209 #define DBG_FNC_SORECEIVE_LIST NETDBG_CODE(DBG_NETSOCK, (8 << 8) | 3)
210 #define DBG_FNC_SOSHUTDOWN NETDBG_CODE(DBG_NETSOCK, (9 << 8))
212 #define MAX_SOOPTGETM_SIZE (128 * MCLBYTES)
214 int somaxconn
= SOMAXCONN
;
215 SYSCTL_INT(_kern_ipc
, KIPC_SOMAXCONN
, somaxconn
,
216 CTLFLAG_RW
| CTLFLAG_LOCKED
, &somaxconn
, 0, "");
218 /* Should we get a maximum also ??? */
219 static int sosendmaxchain
= 65536;
220 static int sosendminchain
= 16384;
221 static int sorecvmincopy
= 16384;
222 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendminchain
,
223 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendminchain
, 0, "");
224 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorecvmincopy
,
225 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sorecvmincopy
, 0, "");
228 * Set to enable jumbo clusters (if available) for large writes when
229 * the socket is marked with SOF_MULTIPAGES; see below.
232 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendjcl
,
233 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendjcl
, 0, "");
236 * Set this to ignore SOF_MULTIPAGES and use jumbo clusters for large
237 * writes on the socket for all protocols on any network interfaces,
238 * depending upon sosendjcl above. Be extra careful when setting this
239 * to 1, because sending down packets that cross physical pages down to
240 * broken drivers (those that falsely assume that the physical pages
241 * are contiguous) might lead to system panics or silent data corruption.
242 * When set to 0, the system will respect SOF_MULTIPAGES, which is set
243 * only for TCP sockets whose outgoing interface is IFNET_MULTIPAGES
244 * capable. Set this to 1 only for testing/debugging purposes.
246 int sosendjcl_ignore_capab
= 0;
247 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendjcl_ignore_capab
,
248 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendjcl_ignore_capab
, 0, "");
251 * Set this to ignore SOF1_IF_2KCL and use big clusters for large
252 * writes on the socket for all protocols on any network interfaces.
253 * Be extra careful when setting this to 1, because sending down packets with
254 * clusters larger that 2 KB might lead to system panics or data corruption.
255 * When set to 0, the system will respect SOF1_IF_2KCL, which is set
256 * on the outgoing interface
257 * Set this to 1 for testing/debugging purposes only.
259 int sosendbigcl_ignore_capab
= 0;
260 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendbigcl_ignore_capab
,
261 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendbigcl_ignore_capab
, 0, "");
263 int sodefunctlog
= 0;
264 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sodefunctlog
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
265 &sodefunctlog
, 0, "");
267 int sothrottlelog
= 0;
268 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sothrottlelog
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
269 &sothrottlelog
, 0, "");
271 int sorestrictrecv
= 1;
272 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorestrictrecv
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
273 &sorestrictrecv
, 0, "Enable inbound interface restrictions");
275 int sorestrictsend
= 1;
276 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorestrictsend
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
277 &sorestrictsend
, 0, "Enable outbound interface restrictions");
279 int soreserveheadroom
= 1;
280 SYSCTL_INT(_kern_ipc
, OID_AUTO
, soreserveheadroom
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
281 &soreserveheadroom
, 0, "To allocate contiguous datagram buffers");
283 extern struct inpcbinfo tcbinfo
;
285 /* TODO: these should be in header file */
286 extern int get_inpcb_str_size(void);
287 extern int get_tcp_str_size(void);
289 static unsigned int sl_zone_size
; /* size of sockaddr_list */
290 static struct zone
*sl_zone
; /* zone for sockaddr_list */
292 static unsigned int se_zone_size
; /* size of sockaddr_entry */
293 static struct zone
*se_zone
; /* zone for sockaddr_entry */
295 vm_size_t so_cache_zone_element_size
;
297 static int sodelayed_copy(struct socket
*, struct uio
*, struct mbuf
**,
299 static void cached_sock_alloc(struct socket
**, int);
300 static void cached_sock_free(struct socket
*);
303 * Maximum of extended background idle sockets per process
304 * Set to zero to disable further setting of the option
307 #define SO_IDLE_BK_IDLE_MAX_PER_PROC 1
308 #define SO_IDLE_BK_IDLE_TIME 600
309 #define SO_IDLE_BK_IDLE_RCV_HIWAT 131072
311 struct soextbkidlestat soextbkidlestat
;
313 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, maxextbkidleperproc
,
314 CTLFLAG_RW
| CTLFLAG_LOCKED
, &soextbkidlestat
.so_xbkidle_maxperproc
, 0,
315 "Maximum of extended background idle sockets per process");
317 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, extbkidletime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
318 &soextbkidlestat
.so_xbkidle_time
, 0,
319 "Time in seconds to keep extended background idle sockets");
321 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, extbkidlercvhiwat
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
322 &soextbkidlestat
.so_xbkidle_rcvhiwat
, 0,
323 "High water mark for extended background idle sockets");
325 SYSCTL_STRUCT(_kern_ipc
, OID_AUTO
, extbkidlestat
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
326 &soextbkidlestat
, soextbkidlestat
, "");
328 int so_set_extended_bk_idle(struct socket
*, int);
331 * SOTCDB_NO_DSCP is set by default, to prevent the networking stack from
332 * setting the DSCP code on the packet based on the service class; see
333 * <rdar://problem/11277343> for details.
335 __private_extern__ u_int32_t sotcdb
= SOTCDB_NO_DSCP
;
336 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sotcdb
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
342 _CASSERT(sizeof(so_gencnt
) == sizeof(uint64_t));
343 VERIFY(IS_P2ALIGNED(&so_gencnt
, sizeof(uint32_t)));
346 _CASSERT(sizeof(struct sa_endpoints
) == sizeof(struct user64_sa_endpoints
));
347 _CASSERT(offsetof(struct sa_endpoints
, sae_srcif
) == offsetof(struct user64_sa_endpoints
, sae_srcif
));
348 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddr
) == offsetof(struct user64_sa_endpoints
, sae_srcaddr
));
349 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddrlen
) == offsetof(struct user64_sa_endpoints
, sae_srcaddrlen
));
350 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddr
) == offsetof(struct user64_sa_endpoints
, sae_dstaddr
));
351 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddrlen
) == offsetof(struct user64_sa_endpoints
, sae_dstaddrlen
));
353 _CASSERT(sizeof(struct sa_endpoints
) == sizeof(struct user32_sa_endpoints
));
354 _CASSERT(offsetof(struct sa_endpoints
, sae_srcif
) == offsetof(struct user32_sa_endpoints
, sae_srcif
));
355 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddr
) == offsetof(struct user32_sa_endpoints
, sae_srcaddr
));
356 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddrlen
) == offsetof(struct user32_sa_endpoints
, sae_srcaddrlen
));
357 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddr
) == offsetof(struct user32_sa_endpoints
, sae_dstaddr
));
358 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddrlen
) == offsetof(struct user32_sa_endpoints
, sae_dstaddrlen
));
361 if (socketinit_done
) {
362 printf("socketinit: already called...\n");
367 PE_parse_boot_argn("socket_debug", &socket_debug
,
368 sizeof (socket_debug
));
371 * allocate lock group attribute and group for socket cache mutex
373 so_cache_mtx_grp_attr
= lck_grp_attr_alloc_init();
374 so_cache_mtx_grp
= lck_grp_alloc_init("so_cache",
375 so_cache_mtx_grp_attr
);
378 * allocate the lock attribute for socket cache mutex
380 so_cache_mtx_attr
= lck_attr_alloc_init();
382 /* cached sockets mutex */
383 so_cache_mtx
= lck_mtx_alloc_init(so_cache_mtx_grp
, so_cache_mtx_attr
);
384 if (so_cache_mtx
== NULL
) {
385 panic("%s: unable to allocate so_cache_mtx\n", __func__
);
388 STAILQ_INIT(&so_cache_head
);
390 so_cache_zone_element_size
= (vm_size_t
)(sizeof (struct socket
) + 4
391 + get_inpcb_str_size() + 4 + get_tcp_str_size());
393 so_cache_zone
= zinit(so_cache_zone_element_size
,
394 (120000 * so_cache_zone_element_size
), 8192, "socache zone");
395 zone_change(so_cache_zone
, Z_CALLERACCT
, FALSE
);
396 zone_change(so_cache_zone
, Z_NOENCRYPT
, TRUE
);
398 sl_zone_size
= sizeof (struct sockaddr_list
);
399 if ((sl_zone
= zinit(sl_zone_size
, 1024 * sl_zone_size
, 1024,
400 "sockaddr_list")) == NULL
) {
401 panic("%s: unable to allocate sockaddr_list zone\n", __func__
);
404 zone_change(sl_zone
, Z_CALLERACCT
, FALSE
);
405 zone_change(sl_zone
, Z_EXPAND
, TRUE
);
407 se_zone_size
= sizeof (struct sockaddr_entry
);
408 if ((se_zone
= zinit(se_zone_size
, 1024 * se_zone_size
, 1024,
409 "sockaddr_entry")) == NULL
) {
410 panic("%s: unable to allocate sockaddr_entry zone\n", __func__
);
413 zone_change(se_zone
, Z_CALLERACCT
, FALSE
);
414 zone_change(se_zone
, Z_EXPAND
, TRUE
);
416 bzero(&soextbkidlestat
, sizeof(struct soextbkidlestat
));
417 soextbkidlestat
.so_xbkidle_maxperproc
= SO_IDLE_BK_IDLE_MAX_PER_PROC
;
418 soextbkidlestat
.so_xbkidle_time
= SO_IDLE_BK_IDLE_TIME
;
419 soextbkidlestat
.so_xbkidle_rcvhiwat
= SO_IDLE_BK_IDLE_RCV_HIWAT
;
423 socket_tclass_init();
426 #endif /* MULTIPATH */
430 cached_sock_alloc(struct socket
**so
, int waitok
)
435 lck_mtx_lock(so_cache_mtx
);
437 if (!STAILQ_EMPTY(&so_cache_head
)) {
438 VERIFY(cached_sock_count
> 0);
440 *so
= STAILQ_FIRST(&so_cache_head
);
441 STAILQ_REMOVE_HEAD(&so_cache_head
, so_cache_ent
);
442 STAILQ_NEXT((*so
), so_cache_ent
) = NULL
;
445 lck_mtx_unlock(so_cache_mtx
);
447 temp
= (*so
)->so_saved_pcb
;
448 bzero((caddr_t
)*so
, sizeof (struct socket
));
450 (*so
)->so_saved_pcb
= temp
;
453 lck_mtx_unlock(so_cache_mtx
);
456 *so
= (struct socket
*)zalloc(so_cache_zone
);
458 *so
= (struct socket
*)zalloc_noblock(so_cache_zone
);
463 bzero((caddr_t
)*so
, sizeof (struct socket
));
466 * Define offsets for extra structures into our
467 * single block of memory. Align extra structures
468 * on longword boundaries.
471 offset
= (uintptr_t)*so
;
472 offset
+= sizeof (struct socket
);
474 offset
= ALIGN(offset
);
476 (*so
)->so_saved_pcb
= (caddr_t
)offset
;
477 offset
+= get_inpcb_str_size();
479 offset
= ALIGN(offset
);
481 ((struct inpcb
*)(void *)(*so
)->so_saved_pcb
)->inp_saved_ppcb
=
485 OSBitOrAtomic(SOF1_CACHED_IN_SOCK_LAYER
, &(*so
)->so_flags1
);
489 cached_sock_free(struct socket
*so
)
492 lck_mtx_lock(so_cache_mtx
);
494 so_cache_time
= net_uptime();
495 if (++cached_sock_count
> max_cached_sock_count
) {
497 lck_mtx_unlock(so_cache_mtx
);
498 zfree(so_cache_zone
, so
);
500 if (so_cache_hw
< cached_sock_count
)
501 so_cache_hw
= cached_sock_count
;
503 STAILQ_INSERT_TAIL(&so_cache_head
, so
, so_cache_ent
);
505 so
->cache_timestamp
= so_cache_time
;
506 lck_mtx_unlock(so_cache_mtx
);
511 so_update_last_owner_locked(struct socket
*so
, proc_t self
)
513 if (so
->last_pid
!= 0) {
515 * last_pid and last_upid should remain zero for sockets
516 * created using sock_socket. The check above achieves that
518 if (self
== PROC_NULL
)
519 self
= current_proc();
521 if (so
->last_upid
!= proc_uniqueid(self
) ||
522 so
->last_pid
!= proc_pid(self
)) {
523 so
->last_upid
= proc_uniqueid(self
);
524 so
->last_pid
= proc_pid(self
);
525 proc_getexecutableuuid(self
, so
->last_uuid
,
526 sizeof (so
->last_uuid
));
528 proc_pidoriginatoruuid(so
->so_vuuid
, sizeof(so
->so_vuuid
));
533 so_update_policy(struct socket
*so
)
535 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
)
536 (void) inp_update_policy(sotoinpcb(so
));
541 so_update_necp_policy(struct socket
*so
, struct sockaddr
*override_local_addr
,
542 struct sockaddr
*override_remote_addr
)
544 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
)
545 inp_update_necp_policy(sotoinpcb(so
), override_local_addr
,
546 override_remote_addr
, 0);
555 boolean_t rc
= FALSE
;
557 lck_mtx_lock(so_cache_mtx
);
559 so_cache_time
= net_uptime();
561 while (!STAILQ_EMPTY(&so_cache_head
)) {
562 VERIFY(cached_sock_count
> 0);
563 p
= STAILQ_FIRST(&so_cache_head
);
564 if ((so_cache_time
- p
->cache_timestamp
) <
568 STAILQ_REMOVE_HEAD(&so_cache_head
, so_cache_ent
);
571 zfree(so_cache_zone
, p
);
573 if (++n_freed
>= SO_CACHE_MAX_FREE_BATCH
) {
574 so_cache_max_freed
++;
579 /* Schedule again if there is more to cleanup */
580 if (!STAILQ_EMPTY(&so_cache_head
))
583 lck_mtx_unlock(so_cache_mtx
);
588 * Get a socket structure from our zone, and initialize it.
589 * We don't implement `waitok' yet (see comments in uipc_domain.c).
590 * Note that it would probably be better to allocate socket
591 * and PCB at the same time, but I'm not convinced that all
592 * the protocols can be easily modified to do this.
595 soalloc(int waitok
, int dom
, int type
)
599 if ((dom
== PF_INET
) && (type
== SOCK_STREAM
)) {
600 cached_sock_alloc(&so
, waitok
);
602 MALLOC_ZONE(so
, struct socket
*, sizeof (*so
), socket_zone
,
605 bzero(so
, sizeof (*so
));
608 so
->so_gencnt
= OSIncrementAtomic64((SInt64
*)&so_gencnt
);
609 so
->so_zone
= socket_zone
;
610 #if CONFIG_MACF_SOCKET
611 /* Convert waitok to M_WAITOK/M_NOWAIT for MAC Framework. */
612 if (mac_socket_label_init(so
, !waitok
) != 0) {
616 #endif /* MAC_SOCKET */
623 socreate_internal(int dom
, struct socket
**aso
, int type
, int proto
,
624 struct proc
*p
, uint32_t flags
, struct proc
*ep
)
631 extern int tcpconsdebug
;
638 prp
= pffindproto(dom
, proto
, type
);
640 prp
= pffindtype(dom
, type
);
642 if (prp
== NULL
|| prp
->pr_usrreqs
->pru_attach
== NULL
) {
643 if (pffinddomain(dom
) == NULL
)
644 return (EAFNOSUPPORT
);
646 if (pffindprotonotype(dom
, proto
) != NULL
)
649 return (EPROTONOSUPPORT
);
651 if (prp
->pr_type
!= type
)
653 so
= soalloc(1, dom
, type
);
657 if (flags
& SOCF_ASYNC
)
658 so
->so_state
|= SS_NBIO
;
660 if (flags
& SOCF_MP_SUBFLOW
) {
662 * A multipath subflow socket is used internally in the kernel,
663 * therefore it does not have a file desciptor associated by
666 so
->so_state
|= SS_NOFDREF
;
667 so
->so_flags
|= SOF_MP_SUBFLOW
;
669 #endif /* MULTIPATH */
671 TAILQ_INIT(&so
->so_incomp
);
672 TAILQ_INIT(&so
->so_comp
);
674 so
->last_upid
= proc_uniqueid(p
);
675 so
->last_pid
= proc_pid(p
);
676 proc_getexecutableuuid(p
, so
->last_uuid
, sizeof (so
->last_uuid
));
677 proc_pidoriginatoruuid(so
->so_vuuid
, sizeof(so
->so_vuuid
));
679 if (ep
!= PROC_NULL
&& ep
!= p
) {
680 so
->e_upid
= proc_uniqueid(ep
);
681 so
->e_pid
= proc_pid(ep
);
682 proc_getexecutableuuid(ep
, so
->e_uuid
, sizeof (so
->e_uuid
));
683 so
->so_flags
|= SOF_DELEGATED
;
686 so
->so_cred
= kauth_cred_proc_ref(p
);
687 if (!suser(kauth_cred_get(), NULL
))
688 so
->so_state
|= SS_PRIV
;
691 so
->so_rcv
.sb_flags
|= SB_RECV
;
692 so
->so_rcv
.sb_so
= so
->so_snd
.sb_so
= so
;
693 so
->next_lock_lr
= 0;
694 so
->next_unlock_lr
= 0;
696 #if CONFIG_MACF_SOCKET
697 mac_socket_label_associate(kauth_cred_get(), so
);
698 #endif /* MAC_SOCKET */
701 * Attachment will create the per pcb lock if necessary and
702 * increase refcount for creation, make sure it's done before
703 * socket is inserted in lists.
707 error
= (*prp
->pr_usrreqs
->pru_attach
)(so
, proto
, p
);
711 * If so_pcb is not zero, the socket will be leaked,
712 * so protocol attachment handler must be coded carefuly
714 so
->so_state
|= SS_NOFDREF
;
716 sofreelastref(so
, 1); /* will deallocate the socket */
720 atomic_add_32(&prp
->pr_domain
->dom_refs
, 1);
721 TAILQ_INIT(&so
->so_evlist
);
723 /* Attach socket filters for this protocol */
726 if (tcpconsdebug
== 2)
727 so
->so_options
|= SO_DEBUG
;
729 so_set_default_traffic_class(so
);
732 * If this thread or task is marked to create backgrounded sockets,
733 * mark the socket as background.
735 if (proc_get_effective_thread_policy(current_thread(),
736 TASK_POLICY_NEW_SOCKETS_BG
)) {
737 socket_set_traffic_mgt_flags(so
, TRAFFIC_MGT_SO_BACKGROUND
);
738 so
->so_background_thread
= current_thread();
743 * Don't mark Unix domain, system or multipath sockets as
744 * eligible for defunct by default.
749 so
->so_flags
|= SOF_NODEFUNCT
;
756 * Entitlements can't be checked at socket creation time except if the
757 * application requested a feature guarded by a privilege (c.f., socket
759 * The priv(9) and the Sandboxing APIs are designed with the idea that
760 * a privilege check should only be triggered by a userland request.
761 * A privilege check at socket creation time is time consuming and
762 * could trigger many authorisation error messages from the security
777 * <pru_attach>:ENOBUFS[AF_UNIX]
778 * <pru_attach>:ENOBUFS[TCP]
779 * <pru_attach>:ENOMEM[TCP]
780 * <pru_attach>:??? [other protocol families, IPSEC]
783 socreate(int dom
, struct socket
**aso
, int type
, int proto
)
785 return (socreate_internal(dom
, aso
, type
, proto
, current_proc(), 0,
790 socreate_delegate(int dom
, struct socket
**aso
, int type
, int proto
, pid_t epid
)
793 struct proc
*ep
= PROC_NULL
;
795 if ((proc_selfpid() != epid
) && ((ep
= proc_find(epid
)) == PROC_NULL
)) {
800 error
= socreate_internal(dom
, aso
, type
, proto
, current_proc(), 0, ep
);
803 * It might not be wise to hold the proc reference when calling
804 * socreate_internal since it calls soalloc with M_WAITOK
815 * <pru_bind>:EINVAL Invalid argument [COMMON_START]
816 * <pru_bind>:EAFNOSUPPORT Address family not supported
817 * <pru_bind>:EADDRNOTAVAIL Address not available.
818 * <pru_bind>:EINVAL Invalid argument
819 * <pru_bind>:EAFNOSUPPORT Address family not supported [notdef]
820 * <pru_bind>:EACCES Permission denied
821 * <pru_bind>:EADDRINUSE Address in use
822 * <pru_bind>:EAGAIN Resource unavailable, try again
823 * <pru_bind>:EPERM Operation not permitted
827 * Notes: It's not possible to fully enumerate the return codes above,
828 * since socket filter authors and protocol family authors may
829 * not choose to limit their error returns to those listed, even
830 * though this may result in some software operating incorrectly.
832 * The error codes which are enumerated above are those known to
833 * be returned by the tcp_usr_bind function supplied.
836 sobindlock(struct socket
*so
, struct sockaddr
*nam
, int dolock
)
838 struct proc
*p
= current_proc();
843 VERIFY(so
->so_usecount
> 1);
845 so_update_last_owner_locked(so
, p
);
846 so_update_policy(so
);
849 so_update_necp_policy(so
, nam
, NULL
);
853 * If this is a bind request on a socket that has been marked
854 * as inactive, reject it now before we go any further.
856 if (so
->so_flags
& SOF_DEFUNCT
) {
858 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] (%d)\n",
859 __func__
, proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
860 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
865 error
= sflt_bind(so
, nam
);
868 error
= (*so
->so_proto
->pr_usrreqs
->pru_bind
)(so
, nam
, p
);
871 socket_unlock(so
, 1);
873 if (error
== EJUSTRETURN
)
880 sodealloc(struct socket
*so
)
882 kauth_cred_unref(&so
->so_cred
);
884 /* Remove any filters */
888 cfil_sock_detach(so
);
889 #endif /* CONTENT_FILTER */
891 /* Delete the state allocated for msg queues on a socket */
892 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
893 FREE(so
->so_msg_state
, M_TEMP
);
894 so
->so_msg_state
= NULL
;
896 VERIFY(so
->so_msg_state
== NULL
);
898 so
->so_gencnt
= OSIncrementAtomic64((SInt64
*)&so_gencnt
);
900 #if CONFIG_MACF_SOCKET
901 mac_socket_label_destroy(so
);
902 #endif /* MAC_SOCKET */
904 if (so
->so_flags1
& SOF1_CACHED_IN_SOCK_LAYER
) {
905 cached_sock_free(so
);
907 FREE_ZONE(so
, sizeof (*so
), so
->so_zone
);
915 * <pru_listen>:EINVAL[AF_UNIX]
916 * <pru_listen>:EINVAL[TCP]
917 * <pru_listen>:EADDRNOTAVAIL[TCP] Address not available.
918 * <pru_listen>:EINVAL[TCP] Invalid argument
919 * <pru_listen>:EAFNOSUPPORT[TCP] Address family not supported [notdef]
920 * <pru_listen>:EACCES[TCP] Permission denied
921 * <pru_listen>:EADDRINUSE[TCP] Address in use
922 * <pru_listen>:EAGAIN[TCP] Resource unavailable, try again
923 * <pru_listen>:EPERM[TCP] Operation not permitted
926 * Notes: Other <pru_listen> returns depend on the protocol family; all
927 * <sf_listen> returns depend on what the filter author causes
928 * their filter to return.
931 solisten(struct socket
*so
, int backlog
)
933 struct proc
*p
= current_proc();
938 so_update_last_owner_locked(so
, p
);
939 so_update_policy(so
);
942 so_update_necp_policy(so
, NULL
, NULL
);
945 if (so
->so_proto
== NULL
) {
949 if ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) == 0) {
955 * If the listen request is made on a socket that is not fully
956 * disconnected, or on a socket that has been marked as inactive,
957 * reject the request now.
960 (SS_ISCONNECTED
|SS_ISCONNECTING
|SS_ISDISCONNECTING
)) ||
961 (so
->so_flags
& SOF_DEFUNCT
)) {
963 if (so
->so_flags
& SOF_DEFUNCT
) {
964 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] "
965 "(%d)\n", __func__
, proc_pid(p
),
966 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
967 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
972 if ((so
->so_restrictions
& SO_RESTRICT_DENY_IN
) != 0) {
977 error
= sflt_listen(so
);
979 error
= (*so
->so_proto
->pr_usrreqs
->pru_listen
)(so
, p
);
982 if (error
== EJUSTRETURN
)
987 if (TAILQ_EMPTY(&so
->so_comp
))
988 so
->so_options
|= SO_ACCEPTCONN
;
990 * POSIX: The implementation may have an upper limit on the length of
991 * the listen queue-either global or per accepting socket. If backlog
992 * exceeds this limit, the length of the listen queue is set to the
995 * If listen() is called with a backlog argument value that is less
996 * than 0, the function behaves as if it had been called with a backlog
997 * argument value of 0.
999 * A backlog argument of 0 may allow the socket to accept connections,
1000 * in which case the length of the listen queue may be set to an
1001 * implementation-defined minimum value.
1003 if (backlog
<= 0 || backlog
> somaxconn
)
1004 backlog
= somaxconn
;
1006 so
->so_qlimit
= backlog
;
1008 socket_unlock(so
, 1);
1013 sofreelastref(struct socket
*so
, int dealloc
)
1015 struct socket
*head
= so
->so_head
;
1017 /* Assume socket is locked */
1019 if (!(so
->so_flags
& SOF_PCBCLEARING
) || !(so
->so_state
& SS_NOFDREF
)) {
1020 selthreadclear(&so
->so_snd
.sb_sel
);
1021 selthreadclear(&so
->so_rcv
.sb_sel
);
1022 so
->so_rcv
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1023 so
->so_snd
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1024 so
->so_event
= sonullevent
;
1028 socket_lock(head
, 1);
1029 if (so
->so_state
& SS_INCOMP
) {
1030 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
1032 } else if (so
->so_state
& SS_COMP
) {
1034 * We must not decommission a socket that's
1035 * on the accept(2) queue. If we do, then
1036 * accept(2) may hang after select(2) indicated
1037 * that the listening socket was ready.
1039 selthreadclear(&so
->so_snd
.sb_sel
);
1040 selthreadclear(&so
->so_rcv
.sb_sel
);
1041 so
->so_rcv
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1042 so
->so_snd
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1043 so
->so_event
= sonullevent
;
1044 socket_unlock(head
, 1);
1047 panic("sofree: not queued");
1050 so
->so_state
&= ~SS_INCOMP
;
1052 socket_unlock(head
, 1);
1058 if (so
->so_flags
& SOF_FLOW_DIVERT
) {
1059 flow_divert_detach(so
);
1061 #endif /* FLOW_DIVERT */
1063 /* 3932268: disable upcall */
1064 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
1065 so
->so_snd
.sb_flags
&= ~SB_UPCALL
;
1066 so
->so_event
= sonullevent
;
1073 soclose_wait_locked(struct socket
*so
)
1075 lck_mtx_t
*mutex_held
;
1077 if (so
->so_proto
->pr_getlock
!= NULL
)
1078 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1080 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1081 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1084 * Double check here and return if there's no outstanding upcall;
1085 * otherwise proceed further only if SOF_UPCALLCLOSEWAIT is set.
1087 if (!so
->so_upcallusecount
|| !(so
->so_flags
& SOF_UPCALLCLOSEWAIT
))
1089 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
1090 so
->so_snd
.sb_flags
&= ~SB_UPCALL
;
1091 so
->so_flags
|= SOF_CLOSEWAIT
;
1092 (void) msleep((caddr_t
)&so
->so_upcallusecount
, mutex_held
, (PZERO
- 1),
1093 "soclose_wait_locked", NULL
);
1094 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1095 so
->so_flags
&= ~SOF_CLOSEWAIT
;
1099 * Close a socket on last file table reference removal.
1100 * Initiate disconnect if connected.
1101 * Free socket when disconnect complete.
1104 soclose_locked(struct socket
*so
)
1107 lck_mtx_t
*mutex_held
;
1110 if (so
->so_usecount
== 0) {
1111 panic("soclose: so=%p refcount=0\n", so
);
1115 sflt_notify(so
, sock_evt_closing
, NULL
);
1117 if (so
->so_upcallusecount
)
1118 soclose_wait_locked(so
);
1122 * We have to wait until the content filters are done
1124 if ((so
->so_flags
& SOF_CONTENT_FILTER
) != 0) {
1125 cfil_sock_close_wait(so
);
1126 cfil_sock_is_closed(so
);
1127 cfil_sock_detach(so
);
1129 #endif /* CONTENT_FILTER */
1131 if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
) {
1132 soresume(current_proc(), so
, 1);
1133 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_WANTED
;
1136 if ((so
->so_options
& SO_ACCEPTCONN
)) {
1137 struct socket
*sp
, *sonext
;
1141 * We do not want new connection to be added
1142 * to the connection queues
1144 so
->so_options
&= ~SO_ACCEPTCONN
;
1146 for (sp
= TAILQ_FIRST(&so
->so_incomp
);
1147 sp
!= NULL
; sp
= sonext
) {
1148 sonext
= TAILQ_NEXT(sp
, so_list
);
1152 * skip sockets thrown away by tcpdropdropblreq
1153 * they will get cleanup by the garbage collection.
1154 * otherwise, remove the incomp socket from the queue
1155 * and let soabort trigger the appropriate cleanup.
1157 if (sp
->so_flags
& SOF_OVERFLOW
)
1160 if (so
->so_proto
->pr_getlock
!= NULL
) {
1162 * Lock ordering for consistency with the
1163 * rest of the stack, we lock the socket
1164 * first and then grabb the head.
1166 socket_unlock(so
, 0);
1172 TAILQ_REMOVE(&so
->so_incomp
, sp
, so_list
);
1175 if (sp
->so_state
& SS_INCOMP
) {
1176 sp
->so_state
&= ~SS_INCOMP
;
1183 socket_unlock(sp
, 1);
1186 while ((sp
= TAILQ_FIRST(&so
->so_comp
)) != NULL
) {
1187 /* Dequeue from so_comp since sofree() won't do it */
1188 TAILQ_REMOVE(&so
->so_comp
, sp
, so_list
);
1191 if (so
->so_proto
->pr_getlock
!= NULL
) {
1192 socket_unlock(so
, 0);
1196 if (sp
->so_state
& SS_COMP
) {
1197 sp
->so_state
&= ~SS_COMP
;
1203 if (so
->so_proto
->pr_getlock
!= NULL
) {
1204 socket_unlock(sp
, 1);
1209 if (so
->so_pcb
== NULL
) {
1210 /* 3915887: mark the socket as ready for dealloc */
1211 so
->so_flags
|= SOF_PCBCLEARING
;
1214 if (so
->so_state
& SS_ISCONNECTED
) {
1215 if ((so
->so_state
& SS_ISDISCONNECTING
) == 0) {
1216 error
= sodisconnectlocked(so
);
1220 if (so
->so_options
& SO_LINGER
) {
1221 if ((so
->so_state
& SS_ISDISCONNECTING
) &&
1222 (so
->so_state
& SS_NBIO
))
1224 if (so
->so_proto
->pr_getlock
!= NULL
)
1225 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1227 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1228 while (so
->so_state
& SS_ISCONNECTED
) {
1229 ts
.tv_sec
= (so
->so_linger
/100);
1230 ts
.tv_nsec
= (so
->so_linger
% 100) *
1231 NSEC_PER_USEC
* 1000 * 10;
1232 error
= msleep((caddr_t
)&so
->so_timeo
,
1233 mutex_held
, PSOCK
| PCATCH
, "soclose", &ts
);
1236 * It's OK when the time fires,
1237 * don't report an error
1239 if (error
== EWOULDBLOCK
)
1247 if (so
->so_usecount
== 0) {
1248 panic("soclose: usecount is zero so=%p\n", so
);
1251 if (so
->so_pcb
!= NULL
&& !(so
->so_flags
& SOF_PCBCLEARING
)) {
1252 int error2
= (*so
->so_proto
->pr_usrreqs
->pru_detach
)(so
);
1256 if (so
->so_usecount
<= 0) {
1257 panic("soclose: usecount is zero so=%p\n", so
);
1261 if (so
->so_pcb
!= NULL
&& !(so
->so_flags
& SOF_MP_SUBFLOW
) &&
1262 (so
->so_state
& SS_NOFDREF
)) {
1263 panic("soclose: NOFDREF");
1266 so
->so_state
|= SS_NOFDREF
;
1268 if (so
->so_flags
& SOF_MP_SUBFLOW
)
1269 so
->so_flags
&= ~SOF_MP_SUBFLOW
;
1271 if ((so
->so_flags
& SOF_KNOTE
) != 0)
1272 KNOTE(&so
->so_klist
, SO_FILT_HINT_LOCKED
);
1274 atomic_add_32(&so
->so_proto
->pr_domain
->dom_refs
, -1);
1283 soclose(struct socket
*so
)
1288 if (so
->so_retaincnt
== 0) {
1289 error
= soclose_locked(so
);
1292 * if the FD is going away, but socket is
1293 * retained in kernel remove its reference
1296 if (so
->so_usecount
< 2)
1297 panic("soclose: retaincnt non null and so=%p "
1298 "usecount=%d\n", so
, so
->so_usecount
);
1300 socket_unlock(so
, 1);
1305 * Must be called at splnet...
1307 /* Should already be locked */
1309 soabort(struct socket
*so
)
1313 #ifdef MORE_LOCKING_DEBUG
1314 lck_mtx_t
*mutex_held
;
1316 if (so
->so_proto
->pr_getlock
!= NULL
)
1317 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1319 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1320 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1323 if ((so
->so_flags
& SOF_ABORTED
) == 0) {
1324 so
->so_flags
|= SOF_ABORTED
;
1325 error
= (*so
->so_proto
->pr_usrreqs
->pru_abort
)(so
);
1335 soacceptlock(struct socket
*so
, struct sockaddr
**nam
, int dolock
)
1342 so_update_last_owner_locked(so
, PROC_NULL
);
1343 so_update_policy(so
);
1345 so_update_necp_policy(so
, NULL
, NULL
);
1348 if ((so
->so_state
& SS_NOFDREF
) == 0)
1349 panic("soaccept: !NOFDREF");
1350 so
->so_state
&= ~SS_NOFDREF
;
1351 error
= (*so
->so_proto
->pr_usrreqs
->pru_accept
)(so
, nam
);
1354 socket_unlock(so
, 1);
1359 soaccept(struct socket
*so
, struct sockaddr
**nam
)
1361 return (soacceptlock(so
, nam
, 1));
1365 soacceptfilter(struct socket
*so
)
1367 struct sockaddr
*local
= NULL
, *remote
= NULL
;
1369 struct socket
*head
= so
->so_head
;
1372 * Hold the lock even if this socket has not been made visible
1373 * to the filter(s). For sockets with global locks, this protects
1374 * against the head or peer going away
1377 if (sogetaddr_locked(so
, &remote
, 1) != 0 ||
1378 sogetaddr_locked(so
, &local
, 0) != 0) {
1379 so
->so_state
&= ~(SS_NOFDREF
| SS_COMP
);
1381 socket_unlock(so
, 1);
1383 /* Out of resources; try it again next time */
1384 error
= ECONNABORTED
;
1388 error
= sflt_accept(head
, so
, local
, remote
);
1391 * If we get EJUSTRETURN from one of the filters, mark this socket
1392 * as inactive and return it anyway. This newly accepted socket
1393 * will be disconnected later before we hand it off to the caller.
1395 if (error
== EJUSTRETURN
) {
1397 (void) sosetdefunct(current_proc(), so
,
1398 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
, FALSE
);
1403 * This may seem like a duplication to the above error
1404 * handling part when we return ECONNABORTED, except
1405 * the following is done while holding the lock since
1406 * the socket has been exposed to the filter(s) earlier.
1408 so
->so_state
&= ~(SS_NOFDREF
| SS_COMP
);
1410 socket_unlock(so
, 1);
1412 /* Propagate socket filter's error code to the caller */
1414 socket_unlock(so
, 1);
1417 /* Callee checks for NULL pointer */
1418 sock_freeaddr(remote
);
1419 sock_freeaddr(local
);
1424 * Returns: 0 Success
1425 * EOPNOTSUPP Operation not supported on socket
1426 * EISCONN Socket is connected
1427 * <pru_connect>:EADDRNOTAVAIL Address not available.
1428 * <pru_connect>:EINVAL Invalid argument
1429 * <pru_connect>:EAFNOSUPPORT Address family not supported [notdef]
1430 * <pru_connect>:EACCES Permission denied
1431 * <pru_connect>:EADDRINUSE Address in use
1432 * <pru_connect>:EAGAIN Resource unavailable, try again
1433 * <pru_connect>:EPERM Operation not permitted
1434 * <sf_connect_out>:??? [anything a filter writer might set]
1437 soconnectlock(struct socket
*so
, struct sockaddr
*nam
, int dolock
)
1440 struct proc
*p
= current_proc();
1445 so_update_last_owner_locked(so
, p
);
1446 so_update_policy(so
);
1449 so_update_necp_policy(so
, NULL
, nam
);
1453 * If this is a listening socket or if this is a previously-accepted
1454 * socket that has been marked as inactive, reject the connect request.
1456 if ((so
->so_options
& SO_ACCEPTCONN
) || (so
->so_flags
& SOF_DEFUNCT
)) {
1458 if (so
->so_flags
& SOF_DEFUNCT
) {
1459 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] "
1460 "(%d)\n", __func__
, proc_pid(p
),
1461 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1462 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
1465 socket_unlock(so
, 1);
1469 if ((so
->so_restrictions
& SO_RESTRICT_DENY_OUT
) != 0) {
1471 socket_unlock(so
, 1);
1476 * If protocol is connection-based, can only connect once.
1477 * Otherwise, if connected, try to disconnect first.
1478 * This allows user to disconnect by connecting to, e.g.,
1481 if (so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
) &&
1482 ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ||
1483 (error
= sodisconnectlocked(so
)))) {
1487 * Run connect filter before calling protocol:
1488 * - non-blocking connect returns before completion;
1490 error
= sflt_connectout(so
, nam
);
1492 if (error
== EJUSTRETURN
)
1495 error
= (*so
->so_proto
->pr_usrreqs
->pru_connect
)
1500 socket_unlock(so
, 1);
1505 soconnect(struct socket
*so
, struct sockaddr
*nam
)
1507 return (soconnectlock(so
, nam
, 1));
1511 * Returns: 0 Success
1512 * <pru_connect2>:EINVAL[AF_UNIX]
1513 * <pru_connect2>:EPROTOTYPE[AF_UNIX]
1514 * <pru_connect2>:??? [other protocol families]
1516 * Notes: <pru_connect2> is not supported by [TCP].
1519 soconnect2(struct socket
*so1
, struct socket
*so2
)
1523 socket_lock(so1
, 1);
1524 if (so2
->so_proto
->pr_lock
)
1525 socket_lock(so2
, 1);
1527 error
= (*so1
->so_proto
->pr_usrreqs
->pru_connect2
)(so1
, so2
);
1529 socket_unlock(so1
, 1);
1530 if (so2
->so_proto
->pr_lock
)
1531 socket_unlock(so2
, 1);
1536 soconnectxlocked(struct socket
*so
, struct sockaddr_list
**src_sl
,
1537 struct sockaddr_list
**dst_sl
, struct proc
*p
, uint32_t ifscope
,
1538 sae_associd_t aid
, sae_connid_t
*pcid
, uint32_t flags
, void *arg
,
1539 uint32_t arglen
, uio_t auio
, user_ssize_t
*bytes_written
)
1543 so_update_last_owner_locked(so
, p
);
1544 so_update_policy(so
);
1547 * If this is a listening socket or if this is a previously-accepted
1548 * socket that has been marked as inactive, reject the connect request.
1550 if ((so
->so_options
& SO_ACCEPTCONN
) || (so
->so_flags
& SOF_DEFUNCT
)) {
1552 if (so
->so_flags
& SOF_DEFUNCT
) {
1553 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] "
1554 "(%d)\n", __func__
, proc_pid(p
),
1555 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1556 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
1561 if ((so
->so_restrictions
& SO_RESTRICT_DENY_OUT
) != 0)
1565 * If protocol is connection-based, can only connect once
1566 * unless PR_MULTICONN is set. Otherwise, if connected,
1567 * try to disconnect first. This allows user to disconnect
1568 * by connecting to, e.g., a null address.
1570 if ((so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
)) &&
1571 !(so
->so_proto
->pr_flags
& PR_MULTICONN
) &&
1572 ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ||
1573 (error
= sodisconnectlocked(so
)) != 0)) {
1577 * Run connect filter before calling protocol:
1578 * - non-blocking connect returns before completion;
1580 error
= sflt_connectxout(so
, dst_sl
);
1582 if (error
== EJUSTRETURN
)
1585 error
= (*so
->so_proto
->pr_usrreqs
->pru_connectx
)
1586 (so
, src_sl
, dst_sl
, p
, ifscope
, aid
, pcid
,
1587 flags
, arg
, arglen
, auio
, bytes_written
);
1595 sodisconnectlocked(struct socket
*so
)
1599 if ((so
->so_state
& SS_ISCONNECTED
) == 0) {
1603 if (so
->so_state
& SS_ISDISCONNECTING
) {
1608 error
= (*so
->so_proto
->pr_usrreqs
->pru_disconnect
)(so
);
1610 sflt_notify(so
, sock_evt_disconnected
, NULL
);
1616 /* Locking version */
1618 sodisconnect(struct socket
*so
)
1623 error
= sodisconnectlocked(so
);
1624 socket_unlock(so
, 1);
1629 sodisconnectxlocked(struct socket
*so
, sae_associd_t aid
, sae_connid_t cid
)
1634 * Call the protocol disconnectx handler; let it handle all
1635 * matters related to the connection state of this session.
1637 error
= (*so
->so_proto
->pr_usrreqs
->pru_disconnectx
)(so
, aid
, cid
);
1640 * The event applies only for the session, not for
1641 * the disconnection of individual subflows.
1643 if (so
->so_state
& (SS_ISDISCONNECTING
|SS_ISDISCONNECTED
))
1644 sflt_notify(so
, sock_evt_disconnected
, NULL
);
1650 sodisconnectx(struct socket
*so
, sae_associd_t aid
, sae_connid_t cid
)
1655 error
= sodisconnectxlocked(so
, aid
, cid
);
1656 socket_unlock(so
, 1);
1661 sopeelofflocked(struct socket
*so
, sae_associd_t aid
, struct socket
**psop
)
1663 return ((*so
->so_proto
->pr_usrreqs
->pru_peeloff
)(so
, aid
, psop
));
1666 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1669 * sosendcheck will lock the socket buffer if it isn't locked and
1670 * verify that there is space for the data being inserted.
1672 * Returns: 0 Success
1674 * sblock:EWOULDBLOCK
1681 sosendcheck(struct socket
*so
, struct sockaddr
*addr
, user_ssize_t resid
,
1682 int32_t clen
, int32_t atomic
, int flags
, int *sblocked
,
1683 struct mbuf
*control
)
1690 if (*sblocked
== 0) {
1691 if ((so
->so_snd
.sb_flags
& SB_LOCK
) != 0 &&
1692 so
->so_send_filt_thread
!= 0 &&
1693 so
->so_send_filt_thread
== current_thread()) {
1695 * We're being called recursively from a filter,
1696 * allow this to continue. Radar 4150520.
1697 * Don't set sblocked because we don't want
1698 * to perform an unlock later.
1702 error
= sblock(&so
->so_snd
, SBLOCKWAIT(flags
));
1704 if (so
->so_flags
& SOF_DEFUNCT
)
1713 * If a send attempt is made on a socket that has been marked
1714 * as inactive (disconnected), reject the request.
1716 if (so
->so_flags
& SOF_DEFUNCT
) {
1719 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] (%d)\n",
1720 __func__
, proc_selfpid(),
1721 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1722 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
1726 if (so
->so_state
& SS_CANTSENDMORE
) {
1729 * Can re-inject data of half closed connections
1731 if ((so
->so_state
& SS_ISDISCONNECTED
) == 0 &&
1732 so
->so_snd
.sb_cfil_thread
== current_thread() &&
1733 cfil_sock_data_pending(&so
->so_snd
) != 0)
1735 "so %llx ignore SS_CANTSENDMORE",
1736 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
));
1738 #endif /* CONTENT_FILTER */
1742 error
= so
->so_error
;
1747 if ((so
->so_state
& SS_ISCONNECTED
) == 0) {
1748 if ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) != 0) {
1749 if (((so
->so_state
& SS_ISCONFIRMING
) == 0) &&
1750 (resid
!= 0 || clen
== 0) &&
1751 !(so
->so_flags1
& SOF1_PRECONNECT_DATA
)) {
1754 * MPTCP Fast Join sends data before the
1755 * socket is truly connected.
1757 if ((so
->so_flags
& (SOF_MP_SUBFLOW
|
1758 SOF_MPTCP_FASTJOIN
)) !=
1759 (SOF_MP_SUBFLOW
| SOF_MPTCP_FASTJOIN
))
1763 } else if (addr
== 0 && !(flags
&MSG_HOLD
)) {
1764 return ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ?
1765 ENOTCONN
: EDESTADDRREQ
);
1769 if (so
->so_flags
& SOF_ENABLE_MSGS
)
1770 space
= msgq_sbspace(so
, control
);
1772 space
= sbspace(&so
->so_snd
);
1774 if (flags
& MSG_OOB
)
1776 if ((atomic
&& resid
> so
->so_snd
.sb_hiwat
) ||
1777 clen
> so
->so_snd
.sb_hiwat
)
1780 if ((space
< resid
+ clen
&&
1781 (atomic
|| (space
< (int32_t)so
->so_snd
.sb_lowat
) ||
1783 (so
->so_type
== SOCK_STREAM
&& so_wait_for_if_feedback(so
))) {
1785 * don't block the connectx call when there's more data
1786 * than can be copied.
1788 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
1790 return (EWOULDBLOCK
);
1792 if (space
< (int32_t)so
->so_snd
.sb_lowat
) {
1796 if ((so
->so_state
& SS_NBIO
) || (flags
& MSG_NBIO
) ||
1798 return (EWOULDBLOCK
);
1800 sbunlock(&so
->so_snd
, TRUE
); /* keep socket locked */
1802 error
= sbwait(&so
->so_snd
);
1804 if (so
->so_flags
& SOF_DEFUNCT
)
1815 * If send must go all at once and message is larger than
1816 * send buffering, then hard error.
1817 * Lock against other senders.
1818 * If must go all at once and not enough room now, then
1819 * inform user that this would block and do nothing.
1820 * Otherwise, if nonblocking, send as much as possible.
1821 * The data to be sent is described by "uio" if nonzero,
1822 * otherwise by the mbuf chain "top" (which must be null
1823 * if uio is not). Data provided in mbuf chain must be small
1824 * enough to send all at once.
1826 * Returns nonzero on error, timeout or signal; callers
1827 * must check for short counts if EINTR/ERESTART are returned.
1828 * Data and control buffers are freed on return.
1830 * MSG_HOLD: go thru most of sosend(), but just enqueue the mbuf
1831 * MSG_SEND: go thru as for MSG_HOLD on current fragment, then
1832 * point at the mbuf chain being constructed and go from there.
1834 * Returns: 0 Success
1840 * sosendcheck:EWOULDBLOCK
1844 * sosendcheck:??? [value from so_error]
1845 * <pru_send>:ECONNRESET[TCP]
1846 * <pru_send>:EINVAL[TCP]
1847 * <pru_send>:ENOBUFS[TCP]
1848 * <pru_send>:EADDRINUSE[TCP]
1849 * <pru_send>:EADDRNOTAVAIL[TCP]
1850 * <pru_send>:EAFNOSUPPORT[TCP]
1851 * <pru_send>:EACCES[TCP]
1852 * <pru_send>:EAGAIN[TCP]
1853 * <pru_send>:EPERM[TCP]
1854 * <pru_send>:EMSGSIZE[TCP]
1855 * <pru_send>:EHOSTUNREACH[TCP]
1856 * <pru_send>:ENETUNREACH[TCP]
1857 * <pru_send>:ENETDOWN[TCP]
1858 * <pru_send>:ENOMEM[TCP]
1859 * <pru_send>:ENOBUFS[TCP]
1860 * <pru_send>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
1861 * <pru_send>:EINVAL[AF_UNIX]
1862 * <pru_send>:EOPNOTSUPP[AF_UNIX]
1863 * <pru_send>:EPIPE[AF_UNIX]
1864 * <pru_send>:ENOTCONN[AF_UNIX]
1865 * <pru_send>:EISCONN[AF_UNIX]
1866 * <pru_send>:???[AF_UNIX] [whatever a filter author chooses]
1867 * <sf_data_out>:??? [whatever a filter author chooses]
1869 * Notes: Other <pru_send> returns depend on the protocol family; all
1870 * <sf_data_out> returns depend on what the filter author causes
1871 * their filter to return.
1874 sosend(struct socket
*so
, struct sockaddr
*addr
, struct uio
*uio
,
1875 struct mbuf
*top
, struct mbuf
*control
, int flags
)
1878 struct mbuf
*m
, *freelist
= NULL
;
1879 user_ssize_t space
, len
, resid
, orig_resid
;
1880 int clen
= 0, error
, dontroute
, mlen
, sendflags
;
1881 int atomic
= sosendallatonce(so
) || top
;
1883 struct proc
*p
= current_proc();
1884 struct mbuf
*control_copy
= NULL
;
1885 uint16_t headroom
= 0;
1886 boolean_t en_tracing
= FALSE
;
1889 resid
= uio_resid(uio
);
1891 resid
= top
->m_pkthdr
.len
;
1893 KERNEL_DEBUG((DBG_FNC_SOSEND
| DBG_FUNC_START
), so
, resid
,
1894 so
->so_snd
.sb_cc
, so
->so_snd
.sb_lowat
, so
->so_snd
.sb_hiwat
);
1899 * trace if tracing & network (vs. unix) sockets & and
1902 if (ENTR_SHOULDTRACE
&&
1903 (SOCK_CHECK_DOM(so
, AF_INET
) || SOCK_CHECK_DOM(so
, AF_INET6
))) {
1904 struct inpcb
*inp
= sotoinpcb(so
);
1905 if (inp
->inp_last_outifp
!= NULL
&&
1906 !(inp
->inp_last_outifp
->if_flags
& IFF_LOOPBACK
)) {
1908 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite
, DBG_FUNC_START
,
1909 VM_KERNEL_ADDRPERM(so
),
1910 ((so
->so_state
& SS_NBIO
) ? kEnTrFlagNonBlocking
: 0),
1917 * Re-injection should not affect process accounting
1919 if ((flags
& MSG_SKIPCFIL
) == 0) {
1920 so_update_last_owner_locked(so
, p
);
1921 so_update_policy(so
);
1924 so_update_necp_policy(so
, NULL
, addr
);
1928 if (so
->so_type
!= SOCK_STREAM
&& (flags
& MSG_OOB
) != 0) {
1930 socket_unlock(so
, 1);
1935 * In theory resid should be unsigned.
1936 * However, space must be signed, as it might be less than 0
1937 * if we over-committed, and we must use a signed comparison
1938 * of space and resid. On the other hand, a negative resid
1939 * causes us to loop sending 0-length segments to the protocol.
1941 * Usually, MSG_EOR isn't used on SOCK_STREAM type sockets.
1942 * But it will be used by sockets doing message delivery.
1944 * Note: We limit resid to be a positive int value as we use
1945 * imin() to set bytes_to_copy -- radr://14558484
1947 if (resid
< 0 || resid
> INT_MAX
|| (so
->so_type
== SOCK_STREAM
&&
1948 !(so
->so_flags
& SOF_ENABLE_MSGS
) && (flags
& MSG_EOR
))) {
1950 socket_unlock(so
, 1);
1954 dontroute
= (flags
& MSG_DONTROUTE
) &&
1955 (so
->so_options
& SO_DONTROUTE
) == 0 &&
1956 (so
->so_proto
->pr_flags
& PR_ATOMIC
);
1957 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgsnd
);
1959 if (control
!= NULL
)
1960 clen
= control
->m_len
;
1962 if (soreserveheadroom
!= 0)
1963 headroom
= so
->so_pktheadroom
;
1966 error
= sosendcheck(so
, addr
, resid
, clen
, atomic
, flags
,
1967 &sblocked
, control
);
1972 if (so
->so_flags
& SOF_ENABLE_MSGS
)
1973 space
= msgq_sbspace(so
, control
);
1975 space
= sbspace(&so
->so_snd
) - clen
;
1976 space
+= ((flags
& MSG_OOB
) ? 1024 : 0);
1981 * Data is prepackaged in "top".
1984 if (flags
& MSG_EOR
)
1985 top
->m_flags
|= M_EOR
;
1993 bytes_to_copy
= imin(resid
, space
);
1995 bytes_to_alloc
= bytes_to_copy
;
1997 bytes_to_alloc
+= headroom
;
1999 if (sosendminchain
> 0)
2002 chainlength
= sosendmaxchain
;
2005 * Use big 4 KB cluster when the outgoing interface
2006 * does not prefer 2 KB clusters
2008 bigcl
= !(so
->so_flags1
& SOF1_IF_2KCL
) ||
2009 sosendbigcl_ignore_capab
;
2012 * Attempt to use larger than system page-size
2013 * clusters for large writes only if there is
2014 * a jumbo cluster pool and if the socket is
2015 * marked accordingly.
2017 jumbocl
= sosendjcl
&& njcl
> 0 &&
2018 ((so
->so_flags
& SOF_MULTIPAGES
) ||
2019 sosendjcl_ignore_capab
) &&
2022 socket_unlock(so
, 0);
2026 int hdrs_needed
= (top
== NULL
) ? 1 : 0;
2029 * try to maintain a local cache of mbuf
2030 * clusters needed to complete this
2031 * write the list is further limited to
2032 * the number that are currently needed
2033 * to fill the socket this mechanism
2034 * allows a large number of mbufs/
2035 * clusters to be grabbed under a single
2036 * mbuf lock... if we can't get any
2037 * clusters, than fall back to trying
2038 * for mbufs if we fail early (or
2039 * miscalcluate the number needed) make
2040 * sure to release any clusters we
2041 * haven't yet consumed.
2043 if (freelist
== NULL
&&
2044 bytes_to_alloc
> MBIGCLBYTES
&&
2047 bytes_to_alloc
/ M16KCLBYTES
;
2049 if ((bytes_to_alloc
-
2050 (num_needed
* M16KCLBYTES
))
2055 m_getpackets_internal(
2056 (unsigned int *)&num_needed
,
2057 hdrs_needed
, M_WAIT
, 0,
2060 * Fall back to 4K cluster size
2061 * if allocation failed
2065 if (freelist
== NULL
&&
2066 bytes_to_alloc
> MCLBYTES
&&
2069 bytes_to_alloc
/ MBIGCLBYTES
;
2071 if ((bytes_to_alloc
-
2072 (num_needed
* MBIGCLBYTES
)) >=
2077 m_getpackets_internal(
2078 (unsigned int *)&num_needed
,
2079 hdrs_needed
, M_WAIT
, 0,
2082 * Fall back to cluster size
2083 * if allocation failed
2088 * Allocate a cluster as we want to
2089 * avoid to split the data in more
2090 * that one segment and using MINCLSIZE
2091 * would lead us to allocate two mbufs
2093 if (soreserveheadroom
!= 0 &&
2096 bytes_to_alloc
> _MHLEN
) ||
2097 bytes_to_alloc
> _MLEN
)) {
2098 num_needed
= ROUNDUP(bytes_to_alloc
, MCLBYTES
) /
2101 m_getpackets_internal(
2102 (unsigned int *)&num_needed
,
2103 hdrs_needed
, M_WAIT
, 0,
2106 * Fall back to a single mbuf
2107 * if allocation failed
2109 } else if (freelist
== NULL
&&
2110 bytes_to_alloc
> MINCLSIZE
) {
2112 bytes_to_alloc
/ MCLBYTES
;
2114 if ((bytes_to_alloc
-
2115 (num_needed
* MCLBYTES
)) >=
2120 m_getpackets_internal(
2121 (unsigned int *)&num_needed
,
2122 hdrs_needed
, M_WAIT
, 0,
2125 * Fall back to a single mbuf
2126 * if allocation failed
2130 * For datagram protocols, leave
2131 * headroom for protocol headers
2132 * in the first cluster of the chain
2134 if (freelist
!= NULL
&& atomic
&&
2135 top
== NULL
&& headroom
> 0) {
2136 freelist
->m_data
+= headroom
;
2140 * Fall back to regular mbufs without
2141 * reserving the socket headroom
2143 if (freelist
== NULL
) {
2151 if (freelist
== NULL
) {
2157 * For datagram protocols,
2158 * leave room for protocol
2159 * headers in first mbuf.
2161 if (atomic
&& top
== NULL
&&
2162 bytes_to_copy
< MHLEN
) {
2168 freelist
= m
->m_next
;
2171 if ((m
->m_flags
& M_EXT
))
2172 mlen
= m
->m_ext
.ext_size
-
2174 else if ((m
->m_flags
& M_PKTHDR
))
2176 MHLEN
- m_leadingspace(m
);
2178 mlen
= MLEN
- m_leadingspace(m
);
2179 len
= imin(mlen
, bytes_to_copy
);
2185 error
= uiomove(mtod(m
, caddr_t
),
2188 resid
= uio_resid(uio
);
2192 top
->m_pkthdr
.len
+= len
;
2197 if (flags
& MSG_EOR
)
2198 top
->m_flags
|= M_EOR
;
2201 bytes_to_copy
= min(resid
, space
);
2203 } while (space
> 0 &&
2204 (chainlength
< sosendmaxchain
|| atomic
||
2205 resid
< MINCLSIZE
));
2213 if (flags
& (MSG_HOLD
|MSG_SEND
)) {
2214 /* Enqueue for later, go away if HOLD */
2216 if (so
->so_temp
&& (flags
& MSG_FLUSH
)) {
2217 m_freem(so
->so_temp
);
2221 so
->so_tail
->m_next
= top
;
2228 if (flags
& MSG_HOLD
) {
2235 so
->so_options
|= SO_DONTROUTE
;
2238 * Compute flags here, for pru_send and NKEs
2240 * If the user set MSG_EOF, the protocol
2241 * understands this flag and nothing left to
2242 * send then use PRU_SEND_EOF instead of PRU_SEND.
2244 sendflags
= (flags
& MSG_OOB
) ? PRUS_OOB
:
2245 ((flags
& MSG_EOF
) &&
2246 (so
->so_proto
->pr_flags
& PR_IMPLOPCL
) &&
2247 (resid
<= 0)) ? PRUS_EOF
:
2248 /* If there is more to send set PRUS_MORETOCOME */
2249 (resid
> 0 && space
> 0) ? PRUS_MORETOCOME
: 0;
2251 if ((flags
& MSG_SKIPCFIL
) == 0) {
2253 * Socket filter processing
2255 error
= sflt_data_out(so
, addr
, &top
,
2256 &control
, (sendflags
& MSG_OOB
) ?
2257 sock_data_filt_flag_oob
: 0);
2259 if (error
== EJUSTRETURN
) {
2269 * Content filter processing
2271 error
= cfil_sock_data_out(so
, addr
, top
,
2272 control
, (sendflags
& MSG_OOB
) ?
2273 sock_data_filt_flag_oob
: 0);
2275 if (error
== EJUSTRETURN
) {
2283 #endif /* CONTENT_FILTER */
2285 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
2287 * Make a copy of control mbuf,
2288 * so that msg priority can be
2289 * passed to subsequent mbufs.
2291 control_copy
= m_dup(control
, M_NOWAIT
);
2293 error
= (*so
->so_proto
->pr_usrreqs
->pru_send
)
2294 (so
, sendflags
, top
, addr
, control
, p
);
2296 if (flags
& MSG_SEND
)
2300 so
->so_options
&= ~SO_DONTROUTE
;
2303 control
= control_copy
;
2304 control_copy
= NULL
;
2309 } while (resid
&& space
> 0);
2314 sbunlock(&so
->so_snd
, FALSE
); /* will unlock socket */
2316 socket_unlock(so
, 1);
2320 if (control
!= NULL
)
2322 if (freelist
!= NULL
)
2323 m_freem_list(freelist
);
2324 if (control_copy
!= NULL
)
2325 m_freem(control_copy
);
2328 * One write has been done. This was enough. Get back to "normal"
2331 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
)
2332 so
->so_flags1
&= ~SOF1_PRECONNECT_DATA
;
2335 /* resid passed here is the bytes left in uio */
2336 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite
, DBG_FUNC_END
,
2337 VM_KERNEL_ADDRPERM(so
),
2338 ((error
== EWOULDBLOCK
) ? kEnTrFlagNoWork
: 0),
2339 (int64_t)(orig_resid
- resid
));
2341 KERNEL_DEBUG(DBG_FNC_SOSEND
| DBG_FUNC_END
, so
, resid
,
2342 so
->so_snd
.sb_cc
, space
, error
);
2348 * Supported only connected sockets (no address) without ancillary data
2349 * (control mbuf) for atomic protocols
2352 sosend_list(struct socket
*so
, struct uio
**uioarray
, u_int uiocnt
, int flags
)
2354 struct mbuf
*m
, *freelist
= NULL
;
2355 user_ssize_t len
, resid
;
2356 int error
, dontroute
, mlen
;
2357 int atomic
= sosendallatonce(so
);
2359 struct proc
*p
= current_proc();
2362 struct mbuf
*top
= NULL
;
2363 uint16_t headroom
= 0;
2366 KERNEL_DEBUG((DBG_FNC_SOSEND_LIST
| DBG_FUNC_START
), so
, uiocnt
,
2367 so
->so_snd
.sb_cc
, so
->so_snd
.sb_lowat
, so
->so_snd
.sb_hiwat
);
2369 if (so
->so_type
!= SOCK_DGRAM
) {
2377 if (so
->so_proto
->pr_usrreqs
->pru_send_list
== NULL
) {
2378 error
= EPROTONOSUPPORT
;
2381 if (flags
& ~(MSG_DONTWAIT
| MSG_NBIO
)) {
2385 resid
= uio_array_resid(uioarray
, uiocnt
);
2388 * In theory resid should be unsigned.
2389 * However, space must be signed, as it might be less than 0
2390 * if we over-committed, and we must use a signed comparison
2391 * of space and resid. On the other hand, a negative resid
2392 * causes us to loop sending 0-length segments to the protocol.
2394 * Note: We limit resid to be a positive int value as we use
2395 * imin() to set bytes_to_copy -- radr://14558484
2397 if (resid
< 0 || resid
> INT_MAX
) {
2403 so_update_last_owner_locked(so
, p
);
2404 so_update_policy(so
);
2407 so_update_necp_policy(so
, NULL
, NULL
);
2410 dontroute
= (flags
& MSG_DONTROUTE
) &&
2411 (so
->so_options
& SO_DONTROUTE
) == 0 &&
2412 (so
->so_proto
->pr_flags
& PR_ATOMIC
);
2413 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgsnd
);
2415 error
= sosendcheck(so
, NULL
, resid
, 0, atomic
, flags
,
2421 * Use big 4 KB clusters when the outgoing interface does not prefer
2424 bigcl
= !(so
->so_flags1
& SOF1_IF_2KCL
) || sosendbigcl_ignore_capab
;
2426 if (soreserveheadroom
!= 0)
2427 headroom
= so
->so_pktheadroom
;
2433 size_t maxpktlen
= 0;
2436 if (sosendminchain
> 0)
2439 chainlength
= sosendmaxchain
;
2441 socket_unlock(so
, 0);
2444 * Find a set of uio that fit in a reasonable number
2447 for (i
= uiofirst
; i
< uiocnt
; i
++) {
2448 struct uio
*auio
= uioarray
[i
];
2450 len
= uio_resid(auio
);
2452 /* Do nothing for empty messages */
2459 if (len
> maxpktlen
)
2463 if (chainlength
> sosendmaxchain
)
2467 * Nothing left to send
2469 if (num_needed
== 0) {
2474 * Allocate buffer large enough to include headroom space for
2475 * network and link header
2478 bytes_to_alloc
= maxpktlen
+ headroom
;
2481 * Allocate a single contiguous buffer of the smallest available
2482 * size when possible
2484 if (bytes_to_alloc
> MCLBYTES
&&
2485 bytes_to_alloc
<= MBIGCLBYTES
&& bigcl
) {
2486 freelist
= m_getpackets_internal(
2487 (unsigned int *)&num_needed
,
2488 num_needed
, M_WAIT
, 1,
2490 } else if (bytes_to_alloc
> _MHLEN
&&
2491 bytes_to_alloc
<= MCLBYTES
) {
2492 freelist
= m_getpackets_internal(
2493 (unsigned int *)&num_needed
,
2494 num_needed
, M_WAIT
, 1,
2497 freelist
= m_allocpacket_internal(
2498 (unsigned int *)&num_needed
,
2499 bytes_to_alloc
, NULL
, M_WAIT
, 1, 0);
2502 if (freelist
== NULL
) {
2508 * Copy each uio of the set into its own mbuf packet
2510 for (i
= uiofirst
, m
= freelist
;
2511 i
< uiolast
&& m
!= NULL
;
2515 struct uio
*auio
= uioarray
[i
];
2517 bytes_to_copy
= uio_resid(auio
);
2519 /* Do nothing for empty messages */
2520 if (bytes_to_copy
== 0)
2523 * Leave headroom for protocol headers
2524 * in the first mbuf of the chain
2526 m
->m_data
+= headroom
;
2528 for (n
= m
; n
!= NULL
; n
= n
->m_next
) {
2529 if ((m
->m_flags
& M_EXT
))
2530 mlen
= m
->m_ext
.ext_size
-
2532 else if ((m
->m_flags
& M_PKTHDR
))
2534 MHLEN
- m_leadingspace(m
);
2536 mlen
= MLEN
- m_leadingspace(m
);
2537 len
= imin(mlen
, bytes_to_copy
);
2540 * Note: uiomove() decrements the iovec
2543 error
= uiomove(mtod(n
, caddr_t
),
2548 m
->m_pkthdr
.len
+= len
;
2550 VERIFY(m
->m_pkthdr
.len
<= maxpktlen
);
2552 bytes_to_copy
-= len
;
2555 if (m
->m_pkthdr
.len
== 0) {
2557 "%s:%d so %llx pkt %llx type %u len null\n",
2559 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
2560 (uint64_t)DEBUG_KERNEL_ADDRPERM(m
),
2576 so
->so_options
|= SO_DONTROUTE
;
2578 if ((flags
& MSG_SKIPCFIL
) == 0) {
2579 struct mbuf
**prevnextp
= NULL
;
2581 for (i
= uiofirst
, m
= top
;
2582 i
< uiolast
&& m
!= NULL
;
2584 struct mbuf
*nextpkt
= m
->m_nextpkt
;
2587 * Socket filter processing
2589 error
= sflt_data_out(so
, NULL
, &m
,
2591 if (error
!= 0 && error
!= EJUSTRETURN
)
2597 * Content filter processing
2599 error
= cfil_sock_data_out(so
, NULL
, m
,
2601 if (error
!= 0 && error
!= EJUSTRETURN
)
2604 #endif /* CONTENT_FILTER */
2606 * Remove packet from the list when
2607 * swallowed by a filter
2609 if (error
== EJUSTRETURN
) {
2611 if (prevnextp
!= NULL
)
2612 *prevnextp
= nextpkt
;
2619 prevnextp
= &m
->m_nextpkt
;
2623 error
= (*so
->so_proto
->pr_usrreqs
->pru_send_list
)
2624 (so
, 0, top
, NULL
, NULL
, p
);
2627 so
->so_options
&= ~SO_DONTROUTE
;
2631 } while (resid
> 0 && error
== 0);
2634 sbunlock(&so
->so_snd
, FALSE
); /* will unlock socket */
2636 socket_unlock(so
, 1);
2640 if (freelist
!= NULL
)
2641 m_freem_list(freelist
);
2643 KERNEL_DEBUG(DBG_FNC_SOSEND_LIST
| DBG_FUNC_END
, so
, resid
,
2644 so
->so_snd
.sb_cc
, 0, error
);
2650 * May return ERESTART when packet is dropped by MAC policy check
2653 soreceive_addr(struct proc
*p
, struct socket
*so
, struct sockaddr
**psa
,
2654 int flags
, struct mbuf
**mp
, struct mbuf
**nextrecordp
, int canwait
)
2657 struct mbuf
*m
= *mp
;
2658 struct mbuf
*nextrecord
= *nextrecordp
;
2660 KASSERT(m
->m_type
== MT_SONAME
, ("receive 1a"));
2661 #if CONFIG_MACF_SOCKET_SUBSET
2663 * Call the MAC framework for policy checking if we're in
2664 * the user process context and the socket isn't connected.
2666 if (p
!= kernproc
&& !(so
->so_state
& SS_ISCONNECTED
)) {
2667 struct mbuf
*m0
= m
;
2669 * Dequeue this record (temporarily) from the receive
2670 * list since we're about to drop the socket's lock
2671 * where a new record may arrive and be appended to
2672 * the list. Upon MAC policy failure, the record
2673 * will be freed. Otherwise, we'll add it back to
2674 * the head of the list. We cannot rely on SB_LOCK
2675 * because append operation uses the socket's lock.
2678 m
->m_nextpkt
= NULL
;
2679 sbfree(&so
->so_rcv
, m
);
2681 } while (m
!= NULL
);
2683 so
->so_rcv
.sb_mb
= nextrecord
;
2684 SB_EMPTY_FIXUP(&so
->so_rcv
);
2685 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1a");
2686 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1a");
2687 socket_unlock(so
, 0);
2689 if (mac_socket_check_received(proc_ucred(p
), so
,
2690 mtod(m
, struct sockaddr
*)) != 0) {
2692 * MAC policy failure; free this record and
2693 * process the next record (or block until
2694 * one is available). We have adjusted sb_cc
2695 * and sb_mbcnt above so there is no need to
2696 * call sbfree() again.
2700 * Clear SB_LOCK but don't unlock the socket.
2701 * Process the next record or wait for one.
2704 sbunlock(&so
->so_rcv
, TRUE
); /* stay locked */
2710 * If the socket has been defunct'd, drop it.
2712 if (so
->so_flags
& SOF_DEFUNCT
) {
2718 * Re-adjust the socket receive list and re-enqueue
2719 * the record in front of any packets which may have
2720 * been appended while we dropped the lock.
2722 for (m
= m0
; m
->m_next
!= NULL
; m
= m
->m_next
)
2723 sballoc(&so
->so_rcv
, m
);
2724 sballoc(&so
->so_rcv
, m
);
2725 if (so
->so_rcv
.sb_mb
== NULL
) {
2726 so
->so_rcv
.sb_lastrecord
= m0
;
2727 so
->so_rcv
.sb_mbtail
= m
;
2730 nextrecord
= m
->m_nextpkt
= so
->so_rcv
.sb_mb
;
2731 so
->so_rcv
.sb_mb
= m
;
2732 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1b");
2733 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1b");
2735 #endif /* CONFIG_MACF_SOCKET_SUBSET */
2737 *psa
= dup_sockaddr(mtod(m
, struct sockaddr
*), canwait
);
2738 if ((*psa
== NULL
) && (flags
& MSG_NEEDSA
)) {
2739 error
= EWOULDBLOCK
;
2743 if (flags
& MSG_PEEK
) {
2746 sbfree(&so
->so_rcv
, m
);
2747 if (m
->m_next
== NULL
&& so
->so_rcv
.sb_cc
!= 0) {
2748 panic("%s: about to create invalid socketbuf",
2752 MFREE(m
, so
->so_rcv
.sb_mb
);
2753 m
= so
->so_rcv
.sb_mb
;
2755 m
->m_nextpkt
= nextrecord
;
2757 so
->so_rcv
.sb_mb
= nextrecord
;
2758 SB_EMPTY_FIXUP(&so
->so_rcv
);
2763 *nextrecordp
= nextrecord
;
2769 * Process one or more MT_CONTROL mbufs present before any data mbufs
2770 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
2771 * just copy the data; if !MSG_PEEK, we call into the protocol to
2772 * perform externalization.
2775 soreceive_ctl(struct socket
*so
, struct mbuf
**controlp
, int flags
,
2776 struct mbuf
**mp
, struct mbuf
**nextrecordp
)
2779 struct mbuf
*cm
= NULL
, *cmn
;
2780 struct mbuf
**cme
= &cm
;
2781 struct sockbuf
*sb_rcv
= &so
->so_rcv
;
2782 struct mbuf
**msgpcm
= NULL
;
2783 struct mbuf
*m
= *mp
;
2784 struct mbuf
*nextrecord
= *nextrecordp
;
2785 struct protosw
*pr
= so
->so_proto
;
2788 * Externalizing the control messages would require us to
2789 * drop the socket's lock below. Once we re-acquire the
2790 * lock, the mbuf chain might change. In order to preserve
2791 * consistency, we unlink all control messages from the
2792 * first mbuf chain in one shot and link them separately
2793 * onto a different chain.
2796 if (flags
& MSG_PEEK
) {
2797 if (controlp
!= NULL
) {
2798 if (*controlp
== NULL
) {
2801 *controlp
= m_copy(m
, 0, m
->m_len
);
2804 * If we failed to allocate an mbuf,
2805 * release any previously allocated
2806 * mbufs for control data. Return
2807 * an error. Keep the mbufs in the
2808 * socket as this is using
2811 if (*controlp
== NULL
) {
2816 controlp
= &(*controlp
)->m_next
;
2820 m
->m_nextpkt
= NULL
;
2822 sb_rcv
->sb_mb
= m
->m_next
;
2825 cme
= &(*cme
)->m_next
;
2828 } while (m
!= NULL
&& m
->m_type
== MT_CONTROL
);
2830 if (!(flags
& MSG_PEEK
)) {
2831 if (sb_rcv
->sb_mb
!= NULL
) {
2832 sb_rcv
->sb_mb
->m_nextpkt
= nextrecord
;
2834 sb_rcv
->sb_mb
= nextrecord
;
2835 SB_EMPTY_FIXUP(sb_rcv
);
2837 if (nextrecord
== NULL
)
2838 sb_rcv
->sb_lastrecord
= m
;
2841 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive ctl");
2842 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive ctl");
2844 while (cm
!= NULL
) {
2849 cmsg_type
= mtod(cm
, struct cmsghdr
*)->cmsg_type
;
2852 * Call the protocol to externalize SCM_RIGHTS message
2853 * and return the modified message to the caller upon
2854 * success. Otherwise, all other control messages are
2855 * returned unmodified to the caller. Note that we
2856 * only get into this loop if MSG_PEEK is not set.
2858 if (pr
->pr_domain
->dom_externalize
!= NULL
&&
2859 cmsg_type
== SCM_RIGHTS
) {
2861 * Release socket lock: see 3903171. This
2862 * would also allow more records to be appended
2863 * to the socket buffer. We still have SB_LOCK
2864 * set on it, so we can be sure that the head
2865 * of the mbuf chain won't change.
2867 socket_unlock(so
, 0);
2868 error
= (*pr
->pr_domain
->dom_externalize
)(cm
);
2874 if (controlp
!= NULL
&& error
== 0) {
2876 controlp
= &(*controlp
)->m_next
;
2883 * Update the value of nextrecord in case we received new
2884 * records when the socket was unlocked above for
2885 * externalizing SCM_RIGHTS.
2888 nextrecord
= sb_rcv
->sb_mb
->m_nextpkt
;
2890 nextrecord
= sb_rcv
->sb_mb
;
2894 *nextrecordp
= nextrecord
;
2900 * Implement receive operations on a socket.
2901 * We depend on the way that records are added to the sockbuf
2902 * by sbappend*. In particular, each record (mbufs linked through m_next)
2903 * must begin with an address if the protocol so specifies,
2904 * followed by an optional mbuf or mbufs containing ancillary data,
2905 * and then zero or more mbufs of data.
2906 * In order to avoid blocking network interrupts for the entire time here,
2907 * we splx() while doing the actual copy to user space.
2908 * Although the sockbuf is locked, new data may still be appended,
2909 * and thus we must maintain consistency of the sockbuf during that time.
2911 * The caller may receive the data as a single mbuf chain by supplying
2912 * an mbuf **mp0 for use in returning the chain. The uio is then used
2913 * only for the count in uio_resid.
2915 * Returns: 0 Success
2920 * sblock:EWOULDBLOCK
2924 * sodelayed_copy:EFAULT
2925 * <pru_rcvoob>:EINVAL[TCP]
2926 * <pru_rcvoob>:EWOULDBLOCK[TCP]
2928 * <pr_domain->dom_externalize>:EMSGSIZE[AF_UNIX]
2929 * <pr_domain->dom_externalize>:ENOBUFS[AF_UNIX]
2930 * <pr_domain->dom_externalize>:???
2932 * Notes: Additional return values from calls through <pru_rcvoob> and
2933 * <pr_domain->dom_externalize> depend on protocols other than
2934 * TCP or AF_UNIX, which are documented above.
2937 soreceive(struct socket
*so
, struct sockaddr
**psa
, struct uio
*uio
,
2938 struct mbuf
**mp0
, struct mbuf
**controlp
, int *flagsp
)
2940 struct mbuf
*m
, **mp
, *ml
= NULL
;
2941 struct mbuf
*nextrecord
, *free_list
;
2942 int flags
, error
, offset
;
2944 struct protosw
*pr
= so
->so_proto
;
2946 user_ssize_t orig_resid
= uio_resid(uio
);
2947 user_ssize_t delayed_copy_len
;
2950 struct proc
*p
= current_proc();
2951 boolean_t en_tracing
= FALSE
;
2954 * Sanity check on the length passed by caller as we are making 'int'
2957 if (orig_resid
< 0 || orig_resid
> INT_MAX
)
2960 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_START
, so
,
2961 uio_resid(uio
), so
->so_rcv
.sb_cc
, so
->so_rcv
.sb_lowat
,
2962 so
->so_rcv
.sb_hiwat
);
2965 so_update_last_owner_locked(so
, p
);
2966 so_update_policy(so
);
2968 #ifdef MORE_LOCKING_DEBUG
2969 if (so
->so_usecount
== 1) {
2970 panic("%s: so=%x no other reference on socket\n", __func__
, so
);
2977 if (controlp
!= NULL
)
2980 flags
= *flagsp
&~ MSG_EOR
;
2985 * If a recv attempt is made on a previously-accepted socket
2986 * that has been marked as inactive (disconnected), reject
2989 if (so
->so_flags
& SOF_DEFUNCT
) {
2990 struct sockbuf
*sb
= &so
->so_rcv
;
2993 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] (%d)\n",
2994 __func__
, proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
2995 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
2997 * This socket should have been disconnected and flushed
2998 * prior to being returned from sodefunct(); there should
2999 * be no data on its receive list, so panic otherwise.
3001 if (so
->so_state
& SS_DEFUNCT
)
3002 sb_empty_assert(sb
, __func__
);
3003 socket_unlock(so
, 1);
3007 if ((so
->so_flags1
& SOF1_PRECONNECT_DATA
) &&
3008 pr
->pr_usrreqs
->pru_preconnect
) {
3010 * A user may set the CONNECT_RESUME_ON_READ_WRITE-flag but not
3011 * calling write() right after this. *If* the app calls a read
3012 * we do not want to block this read indefinetely. Thus,
3013 * we trigger a connect so that the session gets initiated.
3015 error
= (*pr
->pr_usrreqs
->pru_preconnect
)(so
);
3018 socket_unlock(so
, 1);
3023 if (ENTR_SHOULDTRACE
&&
3024 (SOCK_CHECK_DOM(so
, AF_INET
) || SOCK_CHECK_DOM(so
, AF_INET6
))) {
3026 * enable energy tracing for inet sockets that go over
3027 * non-loopback interfaces only.
3029 struct inpcb
*inp
= sotoinpcb(so
);
3030 if (inp
->inp_last_outifp
!= NULL
&&
3031 !(inp
->inp_last_outifp
->if_flags
& IFF_LOOPBACK
)) {
3033 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_START
,
3034 VM_KERNEL_ADDRPERM(so
),
3035 ((so
->so_state
& SS_NBIO
) ?
3036 kEnTrFlagNonBlocking
: 0),
3037 (int64_t)orig_resid
);
3042 * When SO_WANTOOBFLAG is set we try to get out-of-band data
3043 * regardless of the flags argument. Here is the case were
3044 * out-of-band data is not inline.
3046 if ((flags
& MSG_OOB
) ||
3047 ((so
->so_options
& SO_WANTOOBFLAG
) != 0 &&
3048 (so
->so_options
& SO_OOBINLINE
) == 0 &&
3049 (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
)))) {
3050 m
= m_get(M_WAIT
, MT_DATA
);
3052 socket_unlock(so
, 1);
3053 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
,
3054 ENOBUFS
, 0, 0, 0, 0);
3057 error
= (*pr
->pr_usrreqs
->pru_rcvoob
)(so
, m
, flags
& MSG_PEEK
);
3060 socket_unlock(so
, 0);
3062 error
= uiomove(mtod(m
, caddr_t
),
3063 imin(uio_resid(uio
), m
->m_len
), uio
);
3065 } while (uio_resid(uio
) && error
== 0 && m
!= NULL
);
3071 if ((so
->so_options
& SO_WANTOOBFLAG
) != 0) {
3072 if (error
== EWOULDBLOCK
|| error
== EINVAL
) {
3074 * Let's try to get normal data:
3075 * EWOULDBLOCK: out-of-band data not
3076 * receive yet. EINVAL: out-of-band data
3081 } else if (error
== 0 && flagsp
!= NULL
) {
3085 socket_unlock(so
, 1);
3087 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3088 VM_KERNEL_ADDRPERM(so
), 0,
3089 (int64_t)(orig_resid
- uio_resid(uio
)));
3091 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3100 if (so
->so_state
& SS_ISCONFIRMING
&& uio_resid(uio
)) {
3101 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, 0);
3105 delayed_copy_len
= 0;
3107 #ifdef MORE_LOCKING_DEBUG
3108 if (so
->so_usecount
<= 1)
3109 printf("soreceive: sblock so=0x%llx ref=%d on socket\n",
3110 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), so
->so_usecount
);
3113 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
3114 * and if so just return to the caller. This could happen when
3115 * soreceive() is called by a socket upcall function during the
3116 * time the socket is freed. The socket buffer would have been
3117 * locked across the upcall, therefore we cannot put this thread
3118 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
3119 * we may livelock), because the lock on the socket buffer will
3120 * only be released when the upcall routine returns to its caller.
3121 * Because the socket has been officially closed, there can be
3122 * no further read on it.
3124 * A multipath subflow socket would have its SS_NOFDREF set by
3125 * default, so check for SOF_MP_SUBFLOW socket flag; when the
3126 * socket is closed for real, SOF_MP_SUBFLOW would be cleared.
3128 if ((so
->so_state
& (SS_NOFDREF
| SS_CANTRCVMORE
)) ==
3129 (SS_NOFDREF
| SS_CANTRCVMORE
) && !(so
->so_flags
& SOF_MP_SUBFLOW
)) {
3130 socket_unlock(so
, 1);
3134 error
= sblock(&so
->so_rcv
, SBLOCKWAIT(flags
));
3136 socket_unlock(so
, 1);
3137 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3140 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3141 VM_KERNEL_ADDRPERM(so
), 0,
3142 (int64_t)(orig_resid
- uio_resid(uio
)));
3147 m
= so
->so_rcv
.sb_mb
;
3149 * If we have less data than requested, block awaiting more
3150 * (subject to any timeout) if:
3151 * 1. the current count is less than the low water mark, or
3152 * 2. MSG_WAITALL is set, and it is possible to do the entire
3153 * receive operation at once if we block (resid <= hiwat).
3154 * 3. MSG_DONTWAIT is not set
3155 * If MSG_WAITALL is set but resid is larger than the receive buffer,
3156 * we have to do the receive in sections, and thus risk returning
3157 * a short count if a timeout or signal occurs after we start.
3159 if (m
== NULL
|| (((flags
& MSG_DONTWAIT
) == 0 &&
3160 so
->so_rcv
.sb_cc
< uio_resid(uio
)) &&
3161 (so
->so_rcv
.sb_cc
< so
->so_rcv
.sb_lowat
||
3162 ((flags
& MSG_WAITALL
) && uio_resid(uio
) <= so
->so_rcv
.sb_hiwat
)) &&
3163 m
->m_nextpkt
== NULL
&& (pr
->pr_flags
& PR_ATOMIC
) == 0)) {
3165 * Panic if we notice inconsistencies in the socket's
3166 * receive list; both sb_mb and sb_cc should correctly
3167 * reflect the contents of the list, otherwise we may
3168 * end up with false positives during select() or poll()
3169 * which could put the application in a bad state.
3171 SB_MB_CHECK(&so
->so_rcv
);
3176 error
= so
->so_error
;
3177 if ((flags
& MSG_PEEK
) == 0)
3181 if (so
->so_state
& SS_CANTRCVMORE
) {
3184 * Deal with half closed connections
3186 if ((so
->so_state
& SS_ISDISCONNECTED
) == 0 &&
3187 cfil_sock_data_pending(&so
->so_rcv
) != 0)
3189 "so %llx ignore SS_CANTRCVMORE",
3190 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
));
3192 #endif /* CONTENT_FILTER */
3198 for (; m
!= NULL
; m
= m
->m_next
)
3199 if (m
->m_type
== MT_OOBDATA
|| (m
->m_flags
& M_EOR
)) {
3200 m
= so
->so_rcv
.sb_mb
;
3203 if ((so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
)) == 0 &&
3204 (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
)) {
3208 if (uio_resid(uio
) == 0)
3211 if ((so
->so_state
& SS_NBIO
) ||
3212 (flags
& (MSG_DONTWAIT
|MSG_NBIO
))) {
3213 error
= EWOULDBLOCK
;
3216 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 1");
3217 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 1");
3218 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3219 #if EVEN_MORE_LOCKING_DEBUG
3221 printf("Waiting for socket data\n");
3224 error
= sbwait(&so
->so_rcv
);
3225 #if EVEN_MORE_LOCKING_DEBUG
3227 printf("SORECEIVE - sbwait returned %d\n", error
);
3229 if (so
->so_usecount
< 1) {
3230 panic("%s: after 2nd sblock so=%p ref=%d on socket\n",
3231 __func__
, so
, so
->so_usecount
);
3235 socket_unlock(so
, 1);
3236 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3239 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3240 VM_KERNEL_ADDRPERM(so
), 0,
3241 (int64_t)(orig_resid
- uio_resid(uio
)));
3248 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgrcv
);
3249 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1");
3250 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1");
3251 nextrecord
= m
->m_nextpkt
;
3253 if ((pr
->pr_flags
& PR_ADDR
) && m
->m_type
== MT_SONAME
) {
3254 error
= soreceive_addr(p
, so
, psa
, flags
, &m
, &nextrecord
,
3256 if (error
== ERESTART
)
3258 else if (error
!= 0)
3264 * Process one or more MT_CONTROL mbufs present before any data mbufs
3265 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
3266 * just copy the data; if !MSG_PEEK, we call into the protocol to
3267 * perform externalization.
3269 if (m
!= NULL
&& m
->m_type
== MT_CONTROL
) {
3270 error
= soreceive_ctl(so
, controlp
, flags
, &m
, &nextrecord
);
3277 * If the socket is a TCP socket with message delivery
3278 * enabled, then create a control msg to deliver the
3279 * relative TCP sequence number for this data. Waiting
3280 * until this point will protect against failures to
3281 * allocate an mbuf for control msgs.
3283 if (so
->so_type
== SOCK_STREAM
&& SOCK_PROTO(so
) == IPPROTO_TCP
&&
3284 (so
->so_flags
& SOF_ENABLE_MSGS
) && controlp
!= NULL
) {
3285 struct mbuf
*seq_cm
;
3287 seq_cm
= sbcreatecontrol((caddr_t
)&m
->m_pkthdr
.msg_seq
,
3288 sizeof (uint32_t), SCM_SEQNUM
, SOL_SOCKET
);
3289 if (seq_cm
== NULL
) {
3290 /* unable to allocate a control mbuf */
3295 controlp
= &seq_cm
->m_next
;
3299 if (!(flags
& MSG_PEEK
)) {
3301 * We get here because m points to an mbuf following
3302 * any MT_SONAME or MT_CONTROL mbufs which have been
3303 * processed above. In any case, m should be pointing
3304 * to the head of the mbuf chain, and the nextrecord
3305 * should be either NULL or equal to m->m_nextpkt.
3306 * See comments above about SB_LOCK.
3308 if (m
!= so
->so_rcv
.sb_mb
||
3309 m
->m_nextpkt
!= nextrecord
) {
3310 panic("%s: post-control !sync so=%p m=%p "
3311 "nextrecord=%p\n", __func__
, so
, m
,
3315 if (nextrecord
== NULL
)
3316 so
->so_rcv
.sb_lastrecord
= m
;
3319 if (type
== MT_OOBDATA
)
3322 if (!(flags
& MSG_PEEK
)) {
3323 SB_EMPTY_FIXUP(&so
->so_rcv
);
3326 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 2");
3327 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 2");
3332 if (!(flags
& MSG_PEEK
) && uio_resid(uio
) > sorecvmincopy
)
3340 (uio_resid(uio
) - delayed_copy_len
) > 0 && error
== 0) {
3341 if (m
->m_type
== MT_OOBDATA
) {
3342 if (type
!= MT_OOBDATA
)
3344 } else if (type
== MT_OOBDATA
) {
3348 * Make sure to allways set MSG_OOB event when getting
3349 * out of band data inline.
3351 if ((so
->so_options
& SO_WANTOOBFLAG
) != 0 &&
3352 (so
->so_options
& SO_OOBINLINE
) != 0 &&
3353 (so
->so_state
& SS_RCVATMARK
) != 0) {
3356 so
->so_state
&= ~SS_RCVATMARK
;
3357 len
= uio_resid(uio
) - delayed_copy_len
;
3358 if (so
->so_oobmark
&& len
> so
->so_oobmark
- offset
)
3359 len
= so
->so_oobmark
- offset
;
3360 if (len
> m
->m_len
- moff
)
3361 len
= m
->m_len
- moff
;
3363 * If mp is set, just pass back the mbufs.
3364 * Otherwise copy them out via the uio, then free.
3365 * Sockbuf must be consistent here (points to current mbuf,
3366 * it points to next record) when we drop priority;
3367 * we must note any additions to the sockbuf when we
3368 * block interrupts again.
3371 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive uiomove");
3372 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive uiomove");
3373 if (can_delay
&& len
== m
->m_len
) {
3375 * only delay the copy if we're consuming the
3376 * mbuf and we're NOT in MSG_PEEK mode
3377 * and we have enough data to make it worthwile
3378 * to drop and retake the lock... can_delay
3379 * reflects the state of the 2 latter
3380 * constraints moff should always be zero
3383 delayed_copy_len
+= len
;
3385 if (delayed_copy_len
) {
3386 error
= sodelayed_copy(so
, uio
,
3387 &free_list
, &delayed_copy_len
);
3393 * can only get here if MSG_PEEK is not
3394 * set therefore, m should point at the
3395 * head of the rcv queue; if it doesn't,
3396 * it means something drastically
3397 * changed while we were out from behind
3398 * the lock in sodelayed_copy. perhaps
3399 * a RST on the stream. in any event,
3400 * the stream has been interrupted. it's
3401 * probably best just to return whatever
3402 * data we've moved and let the caller
3405 if (m
!= so
->so_rcv
.sb_mb
) {
3409 socket_unlock(so
, 0);
3410 error
= uiomove(mtod(m
, caddr_t
) + moff
,
3418 uio_setresid(uio
, (uio_resid(uio
) - len
));
3420 if (len
== m
->m_len
- moff
) {
3421 if (m
->m_flags
& M_EOR
)
3423 if (flags
& MSG_PEEK
) {
3427 nextrecord
= m
->m_nextpkt
;
3428 sbfree(&so
->so_rcv
, m
);
3429 m
->m_nextpkt
= NULL
;
3432 * If this packet is an unordered packet
3433 * (indicated by M_UNORDERED_DATA flag), remove
3434 * the additional bytes added to the
3435 * receive socket buffer size.
3437 if ((so
->so_flags
& SOF_ENABLE_MSGS
) &&
3439 (m
->m_flags
& M_UNORDERED_DATA
) &&
3440 sbreserve(&so
->so_rcv
,
3441 so
->so_rcv
.sb_hiwat
- m
->m_len
)) {
3442 if (so
->so_msg_state
->msg_uno_bytes
>
3445 msg_uno_bytes
-= m
->m_len
;
3450 m
->m_flags
&= ~M_UNORDERED_DATA
;
3456 so
->so_rcv
.sb_mb
= m
= m
->m_next
;
3459 if (free_list
== NULL
)
3464 so
->so_rcv
.sb_mb
= m
= m
->m_next
;
3468 m
->m_nextpkt
= nextrecord
;
3469 if (nextrecord
== NULL
)
3470 so
->so_rcv
.sb_lastrecord
= m
;
3472 so
->so_rcv
.sb_mb
= nextrecord
;
3473 SB_EMPTY_FIXUP(&so
->so_rcv
);
3475 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 3");
3476 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 3");
3479 if (flags
& MSG_PEEK
) {
3485 if (flags
& MSG_DONTWAIT
)
3486 copy_flag
= M_DONTWAIT
;
3489 *mp
= m_copym(m
, 0, len
, copy_flag
);
3491 * Failed to allocate an mbuf?
3492 * Adjust uio_resid back, it was
3493 * adjusted down by len bytes which
3494 * we didn't copy over.
3498 (uio_resid(uio
) + len
));
3504 so
->so_rcv
.sb_cc
-= len
;
3507 if (so
->so_oobmark
) {
3508 if ((flags
& MSG_PEEK
) == 0) {
3509 so
->so_oobmark
-= len
;
3510 if (so
->so_oobmark
== 0) {
3511 so
->so_state
|= SS_RCVATMARK
;
3513 * delay posting the actual event until
3514 * after any delayed copy processing
3522 if (offset
== so
->so_oobmark
)
3526 if (flags
& MSG_EOR
)
3529 * If the MSG_WAITALL or MSG_WAITSTREAM flag is set
3530 * (for non-atomic socket), we must not quit until
3531 * "uio->uio_resid == 0" or an error termination.
3532 * If a signal/timeout occurs, return with a short
3533 * count but without error. Keep sockbuf locked
3534 * against other readers.
3536 while (flags
& (MSG_WAITALL
|MSG_WAITSTREAM
) && m
== NULL
&&
3537 (uio_resid(uio
) - delayed_copy_len
) > 0 &&
3538 !sosendallatonce(so
) && !nextrecord
) {
3539 if (so
->so_error
|| ((so
->so_state
& SS_CANTRCVMORE
)
3541 && cfil_sock_data_pending(&so
->so_rcv
) == 0
3542 #endif /* CONTENT_FILTER */
3547 * Depending on the protocol (e.g. TCP), the following
3548 * might cause the socket lock to be dropped and later
3549 * be reacquired, and more data could have arrived and
3550 * have been appended to the receive socket buffer by
3551 * the time it returns. Therefore, we only sleep in
3552 * sbwait() below if and only if the socket buffer is
3553 * empty, in order to avoid a false sleep.
3555 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
&&
3556 (((struct inpcb
*)so
->so_pcb
)->inp_state
!=
3558 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3560 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 2");
3561 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 2");
3563 if (so
->so_rcv
.sb_mb
== NULL
&& sbwait(&so
->so_rcv
)) {
3568 * have to wait until after we get back from the sbwait
3569 * to do the copy because we will drop the lock if we
3570 * have enough data that has been delayed... by dropping
3571 * the lock we open up a window allowing the netisr
3572 * thread to process the incoming packets and to change
3573 * the state of this socket... we're issuing the sbwait
3574 * because the socket is empty and we're expecting the
3575 * netisr thread to wake us up when more packets arrive;
3576 * if we allow that processing to happen and then sbwait
3577 * we could stall forever with packets sitting in the
3578 * socket if no further packets arrive from the remote
3581 * we want to copy before we've collected all the data
3582 * to satisfy this request to allow the copy to overlap
3583 * the incoming packet processing on an MP system
3585 if (delayed_copy_len
> sorecvmincopy
&&
3586 (delayed_copy_len
> (so
->so_rcv
.sb_hiwat
/ 2))) {
3587 error
= sodelayed_copy(so
, uio
,
3588 &free_list
, &delayed_copy_len
);
3593 m
= so
->so_rcv
.sb_mb
;
3595 nextrecord
= m
->m_nextpkt
;
3597 SB_MB_CHECK(&so
->so_rcv
);
3600 #ifdef MORE_LOCKING_DEBUG
3601 if (so
->so_usecount
<= 1) {
3602 panic("%s: after big while so=%p ref=%d on socket\n",
3603 __func__
, so
, so
->so_usecount
);
3608 if (m
!= NULL
&& pr
->pr_flags
& PR_ATOMIC
) {
3609 if (so
->so_options
& SO_DONTTRUNC
) {
3610 flags
|= MSG_RCVMORE
;
3613 if ((flags
& MSG_PEEK
) == 0)
3614 (void) sbdroprecord(&so
->so_rcv
);
3619 * pru_rcvd below (for TCP) may cause more data to be received
3620 * if the socket lock is dropped prior to sending the ACK; some
3621 * legacy OpenTransport applications don't handle this well
3622 * (if it receives less data than requested while MSG_HAVEMORE
3623 * is set), and so we set the flag now based on what we know
3624 * prior to calling pru_rcvd.
3626 if ((so
->so_options
& SO_WANTMORE
) && so
->so_rcv
.sb_cc
> 0)
3627 flags
|= MSG_HAVEMORE
;
3629 if ((flags
& MSG_PEEK
) == 0) {
3631 so
->so_rcv
.sb_mb
= nextrecord
;
3633 * First part is an inline SB_EMPTY_FIXUP(). Second
3634 * part makes sure sb_lastrecord is up-to-date if
3635 * there is still data in the socket buffer.
3637 if (so
->so_rcv
.sb_mb
== NULL
) {
3638 so
->so_rcv
.sb_mbtail
= NULL
;
3639 so
->so_rcv
.sb_lastrecord
= NULL
;
3640 } else if (nextrecord
->m_nextpkt
== NULL
) {
3641 so
->so_rcv
.sb_lastrecord
= nextrecord
;
3643 SB_MB_CHECK(&so
->so_rcv
);
3645 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 4");
3646 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 4");
3647 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
)
3648 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3651 if (delayed_copy_len
) {
3652 error
= sodelayed_copy(so
, uio
, &free_list
, &delayed_copy_len
);
3656 if (free_list
!= NULL
) {
3657 m_freem_list(free_list
);
3661 postevent(so
, 0, EV_OOB
);
3663 if (orig_resid
== uio_resid(uio
) && orig_resid
&&
3664 (flags
& MSG_EOR
) == 0 && (so
->so_state
& SS_CANTRCVMORE
) == 0) {
3665 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3672 #ifdef MORE_LOCKING_DEBUG
3673 if (so
->so_usecount
<= 1) {
3674 panic("%s: release so=%p ref=%d on socket\n", __func__
,
3675 so
, so
->so_usecount
);
3679 if (delayed_copy_len
)
3680 error
= sodelayed_copy(so
, uio
, &free_list
, &delayed_copy_len
);
3682 if (free_list
!= NULL
)
3683 m_freem_list(free_list
);
3685 sbunlock(&so
->so_rcv
, FALSE
); /* will unlock socket */
3688 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3689 VM_KERNEL_ADDRPERM(so
),
3690 ((error
== EWOULDBLOCK
) ? kEnTrFlagNoWork
: 0),
3691 (int64_t)(orig_resid
- uio_resid(uio
)));
3693 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, so
, uio_resid(uio
),
3694 so
->so_rcv
.sb_cc
, 0, error
);
3700 * Returns: 0 Success
3704 sodelayed_copy(struct socket
*so
, struct uio
*uio
, struct mbuf
**free_list
,
3705 user_ssize_t
*resid
)
3712 socket_unlock(so
, 0);
3714 while (m
!= NULL
&& error
== 0) {
3715 error
= uiomove(mtod(m
, caddr_t
), (int)m
->m_len
, uio
);
3718 m_freem_list(*free_list
);
3729 sodelayed_copy_list(struct socket
*so
, struct recv_msg_elem
*msgarray
,
3730 u_int uiocnt
, struct mbuf
**free_list
, user_ssize_t
*resid
)
3734 struct mbuf
*ml
, *m
;
3738 for (ml
= *free_list
, i
= 0; ml
!= NULL
&& i
< uiocnt
;
3739 ml
= ml
->m_nextpkt
, i
++) {
3740 auio
= msgarray
[i
].uio
;
3741 for (m
= ml
; m
!= NULL
; m
= m
->m_next
) {
3742 error
= uiomove(mtod(m
, caddr_t
), m
->m_len
, auio
);
3748 m_freem_list(*free_list
);
3757 soreceive_list(struct socket
*so
, struct recv_msg_elem
*msgarray
, u_int uiocnt
,
3761 struct mbuf
*nextrecord
;
3762 struct mbuf
*ml
= NULL
, *free_list
= NULL
, *free_tail
= NULL
;
3764 user_ssize_t len
, pktlen
, delayed_copy_len
= 0;
3765 struct protosw
*pr
= so
->so_proto
;
3767 struct proc
*p
= current_proc();
3768 struct uio
*auio
= NULL
;
3771 struct sockaddr
**psa
= NULL
;
3772 struct mbuf
**controlp
= NULL
;
3775 struct mbuf
*free_others
= NULL
;
3777 KERNEL_DEBUG(DBG_FNC_SORECEIVE_LIST
| DBG_FUNC_START
,
3779 so
->so_rcv
.sb_cc
, so
->so_rcv
.sb_lowat
, so
->so_rcv
.sb_hiwat
);
3783 * - Only supports don't wait flags
3784 * - Only support datagram sockets (could be extended to raw)
3786 * - Protocol must support packet chains
3787 * - The uio array is NULL (should we panic?)
3793 if (flags
& ~(MSG_PEEK
| MSG_WAITALL
| MSG_DONTWAIT
| MSG_NEEDSA
|
3795 printf("%s invalid flags 0x%x\n", __func__
, flags
);
3799 if (so
->so_type
!= SOCK_DGRAM
) {
3803 if (sosendallatonce(so
) == 0) {
3807 if (so
->so_proto
->pr_usrreqs
->pru_send_list
== NULL
) {
3808 error
= EPROTONOSUPPORT
;
3811 if (msgarray
== NULL
) {
3812 printf("%s uioarray is NULL\n", __func__
);
3817 printf("%s uiocnt is 0\n", __func__
);
3822 * Sanity check on the length passed by caller as we are making 'int'
3825 resid
= recv_msg_array_resid(msgarray
, uiocnt
);
3826 if (resid
< 0 || resid
> INT_MAX
) {
3831 if (!(flags
& MSG_PEEK
) && sorecvmincopy
> 0)
3837 so_update_last_owner_locked(so
, p
);
3838 so_update_policy(so
);
3841 so_update_necp_policy(so
, NULL
, NULL
);
3845 * If a recv attempt is made on a previously-accepted socket
3846 * that has been marked as inactive (disconnected), reject
3849 if (so
->so_flags
& SOF_DEFUNCT
) {
3850 struct sockbuf
*sb
= &so
->so_rcv
;
3853 SODEFUNCTLOG(("%s[%d]: defunct so 0x%llx [%d,%d] (%d)\n",
3854 __func__
, proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
3855 SOCK_DOM(so
), SOCK_TYPE(so
), error
));
3857 * This socket should have been disconnected and flushed
3858 * prior to being returned from sodefunct(); there should
3859 * be no data on its receive list, so panic otherwise.
3861 if (so
->so_state
& SS_DEFUNCT
)
3862 sb_empty_assert(sb
, __func__
);
3868 * The uio may be empty
3870 if (npkts
>= uiocnt
) {
3876 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
3877 * and if so just return to the caller. This could happen when
3878 * soreceive() is called by a socket upcall function during the
3879 * time the socket is freed. The socket buffer would have been
3880 * locked across the upcall, therefore we cannot put this thread
3881 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
3882 * we may livelock), because the lock on the socket buffer will
3883 * only be released when the upcall routine returns to its caller.
3884 * Because the socket has been officially closed, there can be
3885 * no further read on it.
3887 if ((so
->so_state
& (SS_NOFDREF
| SS_CANTRCVMORE
)) ==
3888 (SS_NOFDREF
| SS_CANTRCVMORE
)) {
3893 error
= sblock(&so
->so_rcv
, SBLOCKWAIT(flags
));
3899 m
= so
->so_rcv
.sb_mb
;
3901 * Block awaiting more datagram if needed
3903 if (m
== NULL
|| (((flags
& MSG_DONTWAIT
) == 0 &&
3904 (so
->so_rcv
.sb_cc
< so
->so_rcv
.sb_lowat
||
3905 ((flags
& MSG_WAITALL
) && npkts
< uiocnt
))))) {
3907 * Panic if we notice inconsistencies in the socket's
3908 * receive list; both sb_mb and sb_cc should correctly
3909 * reflect the contents of the list, otherwise we may
3910 * end up with false positives during select() or poll()
3911 * which could put the application in a bad state.
3913 SB_MB_CHECK(&so
->so_rcv
);
3916 error
= so
->so_error
;
3917 if ((flags
& MSG_PEEK
) == 0)
3921 if (so
->so_state
& SS_CANTRCVMORE
) {
3924 if ((so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
)) == 0 &&
3925 (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
)) {
3929 if ((so
->so_state
& SS_NBIO
) ||
3930 (flags
& (MSG_DONTWAIT
|MSG_NBIO
))) {
3931 error
= EWOULDBLOCK
;
3935 * Do not block if we got some data
3937 if (free_list
!= NULL
) {
3942 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 1");
3943 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 1");
3945 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3948 error
= sbwait(&so
->so_rcv
);
3955 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgrcv
);
3956 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1");
3957 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1");
3960 * Consume the current uio index as we have a datagram
3962 auio
= msgarray
[npkts
].uio
;
3963 resid
= uio_resid(auio
);
3964 msgarray
[npkts
].which
|= SOCK_MSG_DATA
;
3965 psa
= (msgarray
[npkts
].which
& SOCK_MSG_SA
) ?
3966 &msgarray
[npkts
].psa
: NULL
;
3967 controlp
= (msgarray
[npkts
].which
& SOCK_MSG_CONTROL
) ?
3968 &msgarray
[npkts
].controlp
: NULL
;
3970 nextrecord
= m
->m_nextpkt
;
3972 if ((pr
->pr_flags
& PR_ADDR
) && m
->m_type
== MT_SONAME
) {
3973 error
= soreceive_addr(p
, so
, psa
, flags
, &m
, &nextrecord
, 1);
3974 if (error
== ERESTART
)
3976 else if (error
!= 0)
3980 if (m
!= NULL
&& m
->m_type
== MT_CONTROL
) {
3981 error
= soreceive_ctl(so
, controlp
, flags
, &m
, &nextrecord
);
3986 if (m
->m_pkthdr
.len
== 0) {
3987 printf("%s:%d so %llx pkt %llx type %u pktlen null\n",
3989 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
3990 (uint64_t)DEBUG_KERNEL_ADDRPERM(m
),
3995 * Loop to copy the mbufs of the current record
3996 * Support zero length packets
4000 while (m
!= NULL
&& (len
= resid
- pktlen
) >= 0 && error
== 0) {
4002 panic("%p m_len zero", m
);
4004 panic("%p m_type zero", m
);
4006 * Clip to the residual length
4012 * Copy the mbufs via the uio or delay the copy
4013 * Sockbuf must be consistent here (points to current mbuf,
4014 * it points to next record) when we drop priority;
4015 * we must note any additions to the sockbuf when we
4016 * block interrupts again.
4018 if (len
> 0 && can_delay
== 0) {
4019 socket_unlock(so
, 0);
4020 error
= uiomove(mtod(m
, caddr_t
), (int)len
, auio
);
4025 delayed_copy_len
+= len
;
4028 if (len
== m
->m_len
) {
4030 * m was entirely copied
4032 sbfree(&so
->so_rcv
, m
);
4033 nextrecord
= m
->m_nextpkt
;
4034 m
->m_nextpkt
= NULL
;
4037 * Set the first packet to the head of the free list
4039 if (free_list
== NULL
)
4042 * Link current packet to tail of free list
4045 if (free_tail
!= NULL
)
4046 free_tail
->m_nextpkt
= m
;
4050 * Link current mbuf to last mbuf of current packet
4057 * Move next buf to head of socket buffer
4059 so
->so_rcv
.sb_mb
= m
= ml
->m_next
;
4063 m
->m_nextpkt
= nextrecord
;
4064 if (nextrecord
== NULL
)
4065 so
->so_rcv
.sb_lastrecord
= m
;
4067 so
->so_rcv
.sb_mb
= nextrecord
;
4068 SB_EMPTY_FIXUP(&so
->so_rcv
);
4070 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 3");
4071 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 3");
4074 * Stop the loop on partial copy
4079 #ifdef MORE_LOCKING_DEBUG
4080 if (so
->so_usecount
<= 1) {
4081 panic("%s: after big while so=%llx ref=%d on socket\n",
4083 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), so
->so_usecount
);
4088 * Tell the caller we made a partial copy
4091 if (so
->so_options
& SO_DONTTRUNC
) {
4093 * Copyout first the freelist then the partial mbuf
4095 socket_unlock(so
, 0);
4096 if (delayed_copy_len
)
4097 error
= sodelayed_copy_list(so
, msgarray
,
4098 uiocnt
, &free_list
, &delayed_copy_len
);
4101 error
= uiomove(mtod(m
, caddr_t
), (int)len
,
4110 so
->so_rcv
.sb_cc
-= len
;
4111 flags
|= MSG_RCVMORE
;
4113 (void) sbdroprecord(&so
->so_rcv
);
4114 nextrecord
= so
->so_rcv
.sb_mb
;
4121 so
->so_rcv
.sb_mb
= nextrecord
;
4123 * First part is an inline SB_EMPTY_FIXUP(). Second
4124 * part makes sure sb_lastrecord is up-to-date if
4125 * there is still data in the socket buffer.
4127 if (so
->so_rcv
.sb_mb
== NULL
) {
4128 so
->so_rcv
.sb_mbtail
= NULL
;
4129 so
->so_rcv
.sb_lastrecord
= NULL
;
4130 } else if (nextrecord
->m_nextpkt
== NULL
) {
4131 so
->so_rcv
.sb_lastrecord
= nextrecord
;
4133 SB_MB_CHECK(&so
->so_rcv
);
4135 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 4");
4136 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 4");
4139 * We can continue to the next packet as long as:
4140 * - We haven't exhausted the uio array
4141 * - There was no error
4142 * - A packet was not truncated
4143 * - We can still receive more data
4145 if (npkts
< uiocnt
&& error
== 0 &&
4146 (flags
& (MSG_RCVMORE
| MSG_TRUNC
)) == 0 &&
4147 (so
->so_state
& SS_CANTRCVMORE
) == 0) {
4148 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
4158 * pru_rcvd may cause more data to be received if the socket lock
4159 * is dropped so we set MSG_HAVEMORE now based on what we know.
4160 * That way the caller won't be surprised if it receives less data
4163 if ((so
->so_options
& SO_WANTMORE
) && so
->so_rcv
.sb_cc
> 0)
4164 flags
|= MSG_HAVEMORE
;
4166 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
)
4167 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
4170 sbunlock(&so
->so_rcv
, FALSE
); /* will unlock socket */
4172 socket_unlock(so
, 1);
4174 if (delayed_copy_len
)
4175 error
= sodelayed_copy_list(so
, msgarray
, uiocnt
,
4176 &free_list
, &delayed_copy_len
);
4179 * Amortize the cost of freeing the mbufs
4181 if (free_list
!= NULL
)
4182 m_freem_list(free_list
);
4183 if (free_others
!= NULL
)
4184 m_freem_list(free_others
);
4186 KERNEL_DEBUG(DBG_FNC_SORECEIVE_LIST
| DBG_FUNC_END
, error
,
4192 * Returns: 0 Success
4195 * <pru_shutdown>:EINVAL
4196 * <pru_shutdown>:EADDRNOTAVAIL[TCP]
4197 * <pru_shutdown>:ENOBUFS[TCP]
4198 * <pru_shutdown>:EMSGSIZE[TCP]
4199 * <pru_shutdown>:EHOSTUNREACH[TCP]
4200 * <pru_shutdown>:ENETUNREACH[TCP]
4201 * <pru_shutdown>:ENETDOWN[TCP]
4202 * <pru_shutdown>:ENOMEM[TCP]
4203 * <pru_shutdown>:EACCES[TCP]
4204 * <pru_shutdown>:EMSGSIZE[TCP]
4205 * <pru_shutdown>:ENOBUFS[TCP]
4206 * <pru_shutdown>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
4207 * <pru_shutdown>:??? [other protocol families]
4210 soshutdown(struct socket
*so
, int how
)
4214 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
| DBG_FUNC_START
, how
, 0, 0, 0, 0);
4222 (SS_ISCONNECTED
|SS_ISCONNECTING
|SS_ISDISCONNECTING
)) == 0) {
4225 error
= soshutdownlock(so
, how
);
4227 socket_unlock(so
, 1);
4234 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
| DBG_FUNC_END
, how
, error
, 0, 0, 0);
4240 soshutdownlock_final(struct socket
*so
, int how
)
4242 struct protosw
*pr
= so
->so_proto
;
4245 sflt_notify(so
, sock_evt_shutdown
, &how
);
4247 if (how
!= SHUT_WR
) {
4248 if ((so
->so_state
& SS_CANTRCVMORE
) != 0) {
4249 /* read already shut down */
4254 postevent(so
, 0, EV_RCLOSED
);
4256 if (how
!= SHUT_RD
) {
4257 if ((so
->so_state
& SS_CANTSENDMORE
) != 0) {
4258 /* write already shut down */
4262 error
= (*pr
->pr_usrreqs
->pru_shutdown
)(so
);
4263 postevent(so
, 0, EV_WCLOSED
);
4266 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
, how
, 1, 0, 0, 0);
4271 soshutdownlock(struct socket
*so
, int how
)
4277 * A content filter may delay the actual shutdown until it
4278 * has processed the pending data
4280 if (so
->so_flags
& SOF_CONTENT_FILTER
) {
4281 error
= cfil_sock_shutdown(so
, &how
);
4282 if (error
== EJUSTRETURN
) {
4285 } else if (error
!= 0) {
4289 #endif /* CONTENT_FILTER */
4291 error
= soshutdownlock_final(so
, how
);
4298 sowflush(struct socket
*so
)
4300 struct sockbuf
*sb
= &so
->so_snd
;
4302 lck_mtx_t
*mutex_held
;
4304 * XXX: This code is currently commented out, because we may get here
4305 * as part of sofreelastref(), and at that time, pr_getlock() may no
4306 * longer be able to return us the lock; this will be fixed in future.
4308 if (so
->so_proto
->pr_getlock
!= NULL
)
4309 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
4311 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
4313 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
4317 * Obtain lock on the socket buffer (SB_LOCK). This is required
4318 * to prevent the socket buffer from being unexpectedly altered
4319 * while it is used by another thread in socket send/receive.
4321 * sblock() must not fail here, hence the assertion.
4323 (void) sblock(sb
, SBL_WAIT
| SBL_NOINTR
| SBL_IGNDEFUNCT
);
4324 VERIFY(sb
->sb_flags
& SB_LOCK
);
4326 sb
->sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
4327 sb
->sb_flags
|= SB_DROP
;
4328 sb
->sb_upcall
= NULL
;
4329 sb
->sb_upcallarg
= NULL
;
4331 sbunlock(sb
, TRUE
); /* keep socket locked */
4333 selthreadclear(&sb
->sb_sel
);
4338 sorflush(struct socket
*so
)
4340 struct sockbuf
*sb
= &so
->so_rcv
;
4341 struct protosw
*pr
= so
->so_proto
;
4344 lck_mtx_t
*mutex_held
;
4346 * XXX: This code is currently commented out, because we may get here
4347 * as part of sofreelastref(), and at that time, pr_getlock() may no
4348 * longer be able to return us the lock; this will be fixed in future.
4350 if (so
->so_proto
->pr_getlock
!= NULL
)
4351 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
4353 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
4355 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
4358 sflt_notify(so
, sock_evt_flush_read
, NULL
);
4363 * Obtain lock on the socket buffer (SB_LOCK). This is required
4364 * to prevent the socket buffer from being unexpectedly altered
4365 * while it is used by another thread in socket send/receive.
4367 * sblock() must not fail here, hence the assertion.
4369 (void) sblock(sb
, SBL_WAIT
| SBL_NOINTR
| SBL_IGNDEFUNCT
);
4370 VERIFY(sb
->sb_flags
& SB_LOCK
);
4373 * Copy only the relevant fields from "sb" to "asb" which we
4374 * need for sbrelease() to function. In particular, skip
4375 * sb_sel as it contains the wait queue linkage, which would
4376 * wreak havoc if we were to issue selthreadclear() on "asb".
4377 * Make sure to not carry over SB_LOCK in "asb", as we need
4378 * to acquire it later as part of sbrelease().
4380 bzero(&asb
, sizeof (asb
));
4381 asb
.sb_cc
= sb
->sb_cc
;
4382 asb
.sb_hiwat
= sb
->sb_hiwat
;
4383 asb
.sb_mbcnt
= sb
->sb_mbcnt
;
4384 asb
.sb_mbmax
= sb
->sb_mbmax
;
4385 asb
.sb_ctl
= sb
->sb_ctl
;
4386 asb
.sb_lowat
= sb
->sb_lowat
;
4387 asb
.sb_mb
= sb
->sb_mb
;
4388 asb
.sb_mbtail
= sb
->sb_mbtail
;
4389 asb
.sb_lastrecord
= sb
->sb_lastrecord
;
4390 asb
.sb_so
= sb
->sb_so
;
4391 asb
.sb_flags
= sb
->sb_flags
;
4392 asb
.sb_flags
&= ~(SB_LOCK
|SB_SEL
|SB_KNOTE
|SB_UPCALL
);
4393 asb
.sb_flags
|= SB_DROP
;
4396 * Ideally we'd bzero() these and preserve the ones we need;
4397 * but to do that we'd need to shuffle things around in the
4398 * sockbuf, and we can't do it now because there are KEXTS
4399 * that are directly referring to the socket structure.
4401 * Setting SB_DROP acts as a barrier to prevent further appends.
4402 * Clearing SB_SEL is done for selthreadclear() below.
4411 sb
->sb_mbtail
= NULL
;
4412 sb
->sb_lastrecord
= NULL
;
4413 sb
->sb_timeo
.tv_sec
= 0;
4414 sb
->sb_timeo
.tv_usec
= 0;
4415 sb
->sb_upcall
= NULL
;
4416 sb
->sb_upcallarg
= NULL
;
4417 sb
->sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
4418 sb
->sb_flags
|= SB_DROP
;
4420 sbunlock(sb
, TRUE
); /* keep socket locked */
4423 * Note that selthreadclear() is called on the original "sb" and
4424 * not the local "asb" because of the way wait queue linkage is
4425 * implemented. Given that selwakeup() may be triggered, SB_SEL
4426 * should no longer be set (cleared above.)
4428 selthreadclear(&sb
->sb_sel
);
4430 if ((pr
->pr_flags
& PR_RIGHTS
) && pr
->pr_domain
->dom_dispose
)
4431 (*pr
->pr_domain
->dom_dispose
)(asb
.sb_mb
);
4437 * Perhaps this routine, and sooptcopyout(), below, ought to come in
4438 * an additional variant to handle the case where the option value needs
4439 * to be some kind of integer, but not a specific size.
4440 * In addition to their use here, these functions are also called by the
4441 * protocol-level pr_ctloutput() routines.
4443 * Returns: 0 Success
4448 sooptcopyin(struct sockopt
*sopt
, void *buf
, size_t len
, size_t minlen
)
4453 * If the user gives us more than we wanted, we ignore it,
4454 * but if we don't get the minimum length the caller
4455 * wants, we return EINVAL. On success, sopt->sopt_valsize
4456 * is set to however much we actually retrieved.
4458 if ((valsize
= sopt
->sopt_valsize
) < minlen
)
4461 sopt
->sopt_valsize
= valsize
= len
;
4463 if (sopt
->sopt_p
!= kernproc
)
4464 return (copyin(sopt
->sopt_val
, buf
, valsize
));
4466 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), buf
, valsize
);
4471 * sooptcopyin_timeval
4472 * Copy in a timeval value into tv_p, and take into account whether the
4473 * the calling process is 64-bit or 32-bit. Moved the sanity checking
4474 * code here so that we can verify the 64-bit tv_sec value before we lose
4475 * the top 32-bits assigning tv64.tv_sec to tv_p->tv_sec.
4478 sooptcopyin_timeval(struct sockopt
*sopt
, struct timeval
*tv_p
)
4482 if (proc_is64bit(sopt
->sopt_p
)) {
4483 struct user64_timeval tv64
;
4485 if (sopt
->sopt_valsize
< sizeof (tv64
))
4488 sopt
->sopt_valsize
= sizeof (tv64
);
4489 if (sopt
->sopt_p
!= kernproc
) {
4490 error
= copyin(sopt
->sopt_val
, &tv64
, sizeof (tv64
));
4494 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), &tv64
,
4497 if (tv64
.tv_sec
< 0 || tv64
.tv_sec
> LONG_MAX
||
4498 tv64
.tv_usec
< 0 || tv64
.tv_usec
>= 1000000)
4501 tv_p
->tv_sec
= tv64
.tv_sec
;
4502 tv_p
->tv_usec
= tv64
.tv_usec
;
4504 struct user32_timeval tv32
;
4506 if (sopt
->sopt_valsize
< sizeof (tv32
))
4509 sopt
->sopt_valsize
= sizeof (tv32
);
4510 if (sopt
->sopt_p
!= kernproc
) {
4511 error
= copyin(sopt
->sopt_val
, &tv32
, sizeof (tv32
));
4516 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), &tv32
,
4521 * K64todo "comparison is always false due to
4522 * limited range of data type"
4524 if (tv32
.tv_sec
< 0 || tv32
.tv_sec
> LONG_MAX
||
4525 tv32
.tv_usec
< 0 || tv32
.tv_usec
>= 1000000)
4528 tv_p
->tv_sec
= tv32
.tv_sec
;
4529 tv_p
->tv_usec
= tv32
.tv_usec
;
4535 * Returns: 0 Success
4540 * sooptcopyin:EINVAL
4541 * sooptcopyin:EFAULT
4542 * sooptcopyin_timeval:EINVAL
4543 * sooptcopyin_timeval:EFAULT
4544 * sooptcopyin_timeval:EDOM
4545 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
4546 * <pr_ctloutput>:???w
4547 * sflt_attach_private:??? [whatever a filter author chooses]
4548 * <sf_setoption>:??? [whatever a filter author chooses]
4550 * Notes: Other <pru_listen> returns depend on the protocol family; all
4551 * <sf_listen> returns depend on what the filter author causes
4552 * their filter to return.
4555 sosetoptlock(struct socket
*so
, struct sockopt
*sopt
, int dolock
)
4560 #if CONFIG_MACF_SOCKET
4562 #endif /* MAC_SOCKET */
4564 if (sopt
->sopt_dir
!= SOPT_SET
)
4565 sopt
->sopt_dir
= SOPT_SET
;
4570 if ((so
->so_state
& (SS_CANTRCVMORE
| SS_CANTSENDMORE
)) ==
4571 (SS_CANTRCVMORE
| SS_CANTSENDMORE
) &&
4572 (so
->so_flags
& SOF_NPX_SETOPTSHUT
) == 0) {
4573 /* the socket has been shutdown, no more sockopt's */
4578 error
= sflt_setsockopt(so
, sopt
);
4580 if (error
== EJUSTRETURN
)
4585 if (sopt
->sopt_level
!= SOL_SOCKET
) {
4586 if (so
->so_proto
!= NULL
&&
4587 so
->so_proto
->pr_ctloutput
!= NULL
) {
4588 error
= (*so
->so_proto
->pr_ctloutput
)(so
, sopt
);
4591 error
= ENOPROTOOPT
;
4594 * Allow socket-level (SOL_SOCKET) options to be filtered by
4595 * the protocol layer, if needed. A zero value returned from
4596 * the handler means use default socket-level processing as
4597 * done by the rest of this routine. Otherwise, any other
4598 * return value indicates that the option is unsupported.
4600 if (so
->so_proto
!= NULL
&& (error
= so
->so_proto
->pr_usrreqs
->
4601 pru_socheckopt(so
, sopt
)) != 0)
4605 switch (sopt
->sopt_name
) {
4608 error
= sooptcopyin(sopt
, &l
, sizeof (l
), sizeof (l
));
4612 so
->so_linger
= (sopt
->sopt_name
== SO_LINGER
) ?
4613 l
.l_linger
: l
.l_linger
* hz
;
4615 so
->so_options
|= SO_LINGER
;
4617 so
->so_options
&= ~SO_LINGER
;
4623 case SO_USELOOPBACK
:
4629 case SO_TIMESTAMP_MONOTONIC
:
4632 case SO_WANTOOBFLAG
:
4633 case SO_NOWAKEFROMSLEEP
:
4634 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4639 so
->so_options
|= sopt
->sopt_name
;
4641 so
->so_options
&= ~sopt
->sopt_name
;
4648 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4654 * Values < 1 make no sense for any of these
4655 * options, so disallow them.
4662 switch (sopt
->sopt_name
) {
4665 struct sockbuf
*sb
=
4666 (sopt
->sopt_name
== SO_SNDBUF
) ?
4667 &so
->so_snd
: &so
->so_rcv
;
4668 if (sbreserve(sb
, (u_int32_t
)optval
) == 0) {
4672 sb
->sb_flags
|= SB_USRSIZE
;
4673 sb
->sb_flags
&= ~SB_AUTOSIZE
;
4674 sb
->sb_idealsize
= (u_int32_t
)optval
;
4678 * Make sure the low-water is never greater than
4682 int space
= sbspace(&so
->so_snd
);
4683 u_int32_t hiwat
= so
->so_snd
.sb_hiwat
;
4685 if (so
->so_snd
.sb_flags
& SB_UNIX
) {
4687 (struct unpcb
*)(so
->so_pcb
);
4689 unp
->unp_conn
!= NULL
) {
4690 hiwat
+= unp
->unp_conn
->unp_cc
;
4694 so
->so_snd
.sb_lowat
=
4698 if (space
>= so
->so_snd
.sb_lowat
) {
4705 so
->so_rcv
.sb_lowat
=
4706 (optval
> so
->so_rcv
.sb_hiwat
) ?
4707 so
->so_rcv
.sb_hiwat
: optval
;
4708 data_len
= so
->so_rcv
.sb_cc
4709 - so
->so_rcv
.sb_ctl
;
4710 if (data_len
>= so
->so_rcv
.sb_lowat
)
4719 error
= sooptcopyin_timeval(sopt
, &tv
);
4723 switch (sopt
->sopt_name
) {
4725 so
->so_snd
.sb_timeo
= tv
;
4728 so
->so_rcv
.sb_timeo
= tv
;
4736 error
= sooptcopyin(sopt
, &nke
, sizeof (nke
),
4741 error
= sflt_attach_internal(so
, nke
.nke_handle
);
4746 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4751 so
->so_flags
|= SOF_NOSIGPIPE
;
4753 so
->so_flags
&= ~SOF_NOSIGPIPE
;
4757 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4762 so
->so_flags
|= SOF_NOADDRAVAIL
;
4764 so
->so_flags
&= ~SOF_NOADDRAVAIL
;
4767 case SO_REUSESHAREUID
:
4768 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4773 so
->so_flags
|= SOF_REUSESHAREUID
;
4775 so
->so_flags
&= ~SOF_REUSESHAREUID
;
4778 case SO_NOTIFYCONFLICT
:
4779 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
4783 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4788 so
->so_flags
|= SOF_NOTIFYCONFLICT
;
4790 so
->so_flags
&= ~SOF_NOTIFYCONFLICT
;
4793 case SO_RESTRICTIONS
:
4794 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4799 error
= so_set_restrictions(so
, optval
);
4802 case SO_AWDL_UNRESTRICTED
:
4803 if (SOCK_DOM(so
) != PF_INET
&&
4804 SOCK_DOM(so
) != PF_INET6
) {
4808 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
4813 kauth_cred_t cred
= NULL
;
4814 proc_t ep
= PROC_NULL
;
4816 if (so
->so_flags
& SOF_DELEGATED
) {
4817 ep
= proc_find(so
->e_pid
);
4819 cred
= kauth_cred_proc_ref(ep
);
4821 error
= priv_check_cred(
4822 cred
? cred
: so
->so_cred
,
4823 PRIV_NET_RESTRICTED_AWDL
, 0);
4825 inp_set_awdl_unrestricted(
4828 kauth_cred_unref(&cred
);
4829 if (ep
!= PROC_NULL
)
4832 inp_clear_awdl_unrestricted(sotoinpcb(so
));
4836 #if CONFIG_MACF_SOCKET
4837 if ((error
= sooptcopyin(sopt
, &extmac
, sizeof (extmac
),
4838 sizeof (extmac
))) != 0)
4841 error
= mac_setsockopt_label(proc_ucred(sopt
->sopt_p
),
4845 #endif /* MAC_SOCKET */
4848 case SO_UPCALLCLOSEWAIT
:
4849 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4854 so
->so_flags
|= SOF_UPCALLCLOSEWAIT
;
4856 so
->so_flags
&= ~SOF_UPCALLCLOSEWAIT
;
4860 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4865 so
->so_flags
|= SOF_BINDRANDOMPORT
;
4867 so
->so_flags
&= ~SOF_BINDRANDOMPORT
;
4870 case SO_NP_EXTENSIONS
: {
4871 struct so_np_extensions sonpx
;
4873 error
= sooptcopyin(sopt
, &sonpx
, sizeof (sonpx
),
4877 if (sonpx
.npx_mask
& ~SONPX_MASK_VALID
) {
4882 * Only one bit defined for now
4884 if ((sonpx
.npx_mask
& SONPX_SETOPTSHUT
)) {
4885 if ((sonpx
.npx_flags
& SONPX_SETOPTSHUT
))
4886 so
->so_flags
|= SOF_NPX_SETOPTSHUT
;
4888 so
->so_flags
&= ~SOF_NPX_SETOPTSHUT
;
4893 case SO_TRAFFIC_CLASS
: {
4894 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4898 error
= so_set_traffic_class(so
, optval
);
4904 case SO_RECV_TRAFFIC_CLASS
: {
4905 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4910 so
->so_flags
&= ~SOF_RECV_TRAFFIC_CLASS
;
4912 so
->so_flags
|= SOF_RECV_TRAFFIC_CLASS
;
4916 case SO_TRAFFIC_CLASS_DBG
: {
4917 struct so_tcdbg so_tcdbg
;
4919 error
= sooptcopyin(sopt
, &so_tcdbg
,
4920 sizeof (struct so_tcdbg
), sizeof (struct so_tcdbg
));
4923 error
= so_set_tcdbg(so
, &so_tcdbg
);
4929 case SO_PRIVILEGED_TRAFFIC_CLASS
:
4930 error
= priv_check_cred(kauth_cred_get(),
4931 PRIV_NET_PRIVILEGED_TRAFFIC_CLASS
, 0);
4934 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4939 so
->so_flags
&= ~SOF_PRIVILEGED_TRAFFIC_CLASS
;
4941 so
->so_flags
|= SOF_PRIVILEGED_TRAFFIC_CLASS
;
4945 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4947 if (error
!= 0 || (so
->so_flags
& SOF_DEFUNCT
)) {
4953 * Any process can set SO_DEFUNCTOK (clear
4954 * SOF_NODEFUNCT), but only root can clear
4955 * SO_DEFUNCTOK (set SOF_NODEFUNCT).
4958 kauth_cred_issuser(kauth_cred_get()) == 0) {
4963 so
->so_flags
&= ~SOF_NODEFUNCT
;
4965 so
->so_flags
|= SOF_NODEFUNCT
;
4967 if (SOCK_DOM(so
) == PF_INET
||
4968 SOCK_DOM(so
) == PF_INET6
) {
4969 char s
[MAX_IPv6_STR_LEN
];
4970 char d
[MAX_IPv6_STR_LEN
];
4971 struct inpcb
*inp
= sotoinpcb(so
);
4973 SODEFUNCTLOG(("%s[%d]: so 0x%llx [%s %s:%d -> "
4974 "%s:%d] is now marked as %seligible for "
4975 "defunct\n", __func__
, proc_selfpid(),
4976 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
4977 (SOCK_TYPE(so
) == SOCK_STREAM
) ?
4978 "TCP" : "UDP", inet_ntop(SOCK_DOM(so
),
4979 ((SOCK_DOM(so
) == PF_INET
) ?
4980 (void *)&inp
->inp_laddr
.s_addr
:
4981 (void *)&inp
->in6p_laddr
), s
, sizeof (s
)),
4982 ntohs(inp
->in6p_lport
),
4983 inet_ntop(SOCK_DOM(so
),
4984 (SOCK_DOM(so
) == PF_INET
) ?
4985 (void *)&inp
->inp_faddr
.s_addr
:
4986 (void *)&inp
->in6p_faddr
, d
, sizeof (d
)),
4987 ntohs(inp
->in6p_fport
),
4988 (so
->so_flags
& SOF_NODEFUNCT
) ?
4991 SODEFUNCTLOG(("%s[%d]: so 0x%llx [%d,%d] is "
4992 "now marked as %seligible for defunct\n",
4993 __func__
, proc_selfpid(),
4994 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
4995 SOCK_DOM(so
), SOCK_TYPE(so
),
4996 (so
->so_flags
& SOF_NODEFUNCT
) ?
5002 /* This option is not settable */
5006 case SO_OPPORTUNISTIC
:
5007 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5010 error
= so_set_opportunistic(so
, optval
);
5014 /* This option is handled by lower layer(s) */
5019 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5022 error
= so_set_recv_anyif(so
, optval
);
5025 case SO_TRAFFIC_MGT_BACKGROUND
: {
5026 /* This option is handled by lower layer(s) */
5032 case SO_FLOW_DIVERT_TOKEN
:
5033 error
= flow_divert_token_set(so
, sopt
);
5035 #endif /* FLOW_DIVERT */
5039 if ((error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5040 sizeof (optval
))) != 0)
5043 error
= so_set_effective_pid(so
, optval
, sopt
->sopt_p
);
5046 case SO_DELEGATED_UUID
: {
5049 if ((error
= sooptcopyin(sopt
, &euuid
, sizeof (euuid
),
5050 sizeof (euuid
))) != 0)
5053 error
= so_set_effective_uuid(so
, euuid
, sopt
->sopt_p
);
5058 case SO_NECP_ATTRIBUTES
:
5059 error
= necp_set_socket_attributes(so
, sopt
);
5064 case SO_MPTCP_FASTJOIN
:
5065 if (!((so
->so_flags
& SOF_MP_SUBFLOW
) ||
5066 ((SOCK_CHECK_DOM(so
, PF_MULTIPATH
)) &&
5067 (SOCK_CHECK_PROTO(so
, IPPROTO_TCP
))))) {
5068 error
= ENOPROTOOPT
;
5072 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5077 so
->so_flags
&= ~SOF_MPTCP_FASTJOIN
;
5079 so
->so_flags
|= SOF_MPTCP_FASTJOIN
;
5083 case SO_EXTENDED_BK_IDLE
:
5084 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5087 error
= so_set_extended_bk_idle(so
, optval
);
5091 error
= ENOPROTOOPT
;
5094 if (error
== 0 && so
->so_proto
!= NULL
&&
5095 so
->so_proto
->pr_ctloutput
!= NULL
) {
5096 (void) so
->so_proto
->pr_ctloutput(so
, sopt
);
5101 socket_unlock(so
, 1);
5105 /* Helper routines for getsockopt */
5107 sooptcopyout(struct sockopt
*sopt
, void *buf
, size_t len
)
5115 * Documented get behavior is that we always return a value,
5116 * possibly truncated to fit in the user's buffer.
5117 * Traditional behavior is that we always tell the user
5118 * precisely how much we copied, rather than something useful
5119 * like the total amount we had available for her.
5120 * Note that this interface is not idempotent; the entire answer must
5121 * generated ahead of time.
5123 valsize
= min(len
, sopt
->sopt_valsize
);
5124 sopt
->sopt_valsize
= valsize
;
5125 if (sopt
->sopt_val
!= USER_ADDR_NULL
) {
5126 if (sopt
->sopt_p
!= kernproc
)
5127 error
= copyout(buf
, sopt
->sopt_val
, valsize
);
5129 bcopy(buf
, CAST_DOWN(caddr_t
, sopt
->sopt_val
), valsize
);
5135 sooptcopyout_timeval(struct sockopt
*sopt
, const struct timeval
*tv_p
)
5139 struct user64_timeval tv64
;
5140 struct user32_timeval tv32
;
5145 if (proc_is64bit(sopt
->sopt_p
)) {
5146 len
= sizeof (tv64
);
5147 tv64
.tv_sec
= tv_p
->tv_sec
;
5148 tv64
.tv_usec
= tv_p
->tv_usec
;
5151 len
= sizeof (tv32
);
5152 tv32
.tv_sec
= tv_p
->tv_sec
;
5153 tv32
.tv_usec
= tv_p
->tv_usec
;
5156 valsize
= min(len
, sopt
->sopt_valsize
);
5157 sopt
->sopt_valsize
= valsize
;
5158 if (sopt
->sopt_val
!= USER_ADDR_NULL
) {
5159 if (sopt
->sopt_p
!= kernproc
)
5160 error
= copyout(val
, sopt
->sopt_val
, valsize
);
5162 bcopy(val
, CAST_DOWN(caddr_t
, sopt
->sopt_val
), valsize
);
5170 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
5171 * <pr_ctloutput>:???
5172 * <sf_getoption>:???
5175 sogetoptlock(struct socket
*so
, struct sockopt
*sopt
, int dolock
)
5180 #if CONFIG_MACF_SOCKET
5182 #endif /* MAC_SOCKET */
5184 if (sopt
->sopt_dir
!= SOPT_GET
)
5185 sopt
->sopt_dir
= SOPT_GET
;
5190 error
= sflt_getsockopt(so
, sopt
);
5192 if (error
== EJUSTRETURN
)
5197 if (sopt
->sopt_level
!= SOL_SOCKET
) {
5198 if (so
->so_proto
!= NULL
&&
5199 so
->so_proto
->pr_ctloutput
!= NULL
) {
5200 error
= (*so
->so_proto
->pr_ctloutput
)(so
, sopt
);
5203 error
= ENOPROTOOPT
;
5206 * Allow socket-level (SOL_SOCKET) options to be filtered by
5207 * the protocol layer, if needed. A zero value returned from
5208 * the handler means use default socket-level processing as
5209 * done by the rest of this routine. Otherwise, any other
5210 * return value indicates that the option is unsupported.
5212 if (so
->so_proto
!= NULL
&& (error
= so
->so_proto
->pr_usrreqs
->
5213 pru_socheckopt(so
, sopt
)) != 0)
5217 switch (sopt
->sopt_name
) {
5220 l
.l_onoff
= ((so
->so_options
& SO_LINGER
) ? 1 : 0);
5221 l
.l_linger
= (sopt
->sopt_name
== SO_LINGER
) ?
5222 so
->so_linger
: so
->so_linger
/ hz
;
5223 error
= sooptcopyout(sopt
, &l
, sizeof (l
));
5226 case SO_USELOOPBACK
:
5235 case SO_TIMESTAMP_MONOTONIC
:
5238 case SO_WANTOOBFLAG
:
5239 case SO_NOWAKEFROMSLEEP
:
5240 optval
= so
->so_options
& sopt
->sopt_name
;
5242 error
= sooptcopyout(sopt
, &optval
, sizeof (optval
));
5246 optval
= so
->so_type
;
5250 if (so
->so_proto
->pr_flags
& PR_ATOMIC
) {
5255 m1
= so
->so_rcv
.sb_mb
;
5256 while (m1
!= NULL
) {
5257 if (m1
->m_type
== MT_DATA
||
5258 m1
->m_type
== MT_HEADER
||
5259 m1
->m_type
== MT_OOBDATA
)
5260 pkt_total
+= m1
->m_len
;
5265 optval
= so
->so_rcv
.sb_cc
- so
->so_rcv
.sb_ctl
;
5270 if (so
->so_proto
->pr_flags
& PR_ATOMIC
) {
5274 m1
= so
->so_rcv
.sb_mb
;
5275 while (m1
!= NULL
) {
5276 if (m1
->m_type
== MT_DATA
||
5277 m1
->m_type
== MT_HEADER
||
5278 m1
->m_type
== MT_OOBDATA
)
5290 optval
= so
->so_snd
.sb_cc
;
5294 optval
= so
->so_error
;
5299 u_int32_t hiwat
= so
->so_snd
.sb_hiwat
;
5301 if (so
->so_snd
.sb_flags
& SB_UNIX
) {
5303 (struct unpcb
*)(so
->so_pcb
);
5304 if (unp
!= NULL
&& unp
->unp_conn
!= NULL
) {
5305 hiwat
+= unp
->unp_conn
->unp_cc
;
5313 optval
= so
->so_rcv
.sb_hiwat
;
5317 optval
= so
->so_snd
.sb_lowat
;
5321 optval
= so
->so_rcv
.sb_lowat
;
5326 tv
= (sopt
->sopt_name
== SO_SNDTIMEO
?
5327 so
->so_snd
.sb_timeo
: so
->so_rcv
.sb_timeo
);
5329 error
= sooptcopyout_timeval(sopt
, &tv
);
5333 optval
= (so
->so_flags
& SOF_NOSIGPIPE
);
5337 optval
= (so
->so_flags
& SOF_NOADDRAVAIL
);
5340 case SO_REUSESHAREUID
:
5341 optval
= (so
->so_flags
& SOF_REUSESHAREUID
);
5345 case SO_NOTIFYCONFLICT
:
5346 optval
= (so
->so_flags
& SOF_NOTIFYCONFLICT
);
5349 case SO_RESTRICTIONS
:
5350 optval
= so_get_restrictions(so
);
5353 case SO_AWDL_UNRESTRICTED
:
5354 if (SOCK_DOM(so
) == PF_INET
||
5355 SOCK_DOM(so
) == PF_INET6
) {
5356 optval
= inp_get_awdl_unrestricted(
5364 #if CONFIG_MACF_SOCKET
5365 if ((error
= sooptcopyin(sopt
, &extmac
, sizeof (extmac
),
5366 sizeof (extmac
))) != 0 ||
5367 (error
= mac_socket_label_get(proc_ucred(
5368 sopt
->sopt_p
), so
, &extmac
)) != 0)
5371 error
= sooptcopyout(sopt
, &extmac
, sizeof (extmac
));
5374 #endif /* MAC_SOCKET */
5378 #if CONFIG_MACF_SOCKET
5379 if ((error
= sooptcopyin(sopt
, &extmac
, sizeof (extmac
),
5380 sizeof (extmac
))) != 0 ||
5381 (error
= mac_socketpeer_label_get(proc_ucred(
5382 sopt
->sopt_p
), so
, &extmac
)) != 0)
5385 error
= sooptcopyout(sopt
, &extmac
, sizeof (extmac
));
5388 #endif /* MAC_SOCKET */
5391 #ifdef __APPLE_API_PRIVATE
5392 case SO_UPCALLCLOSEWAIT
:
5393 optval
= (so
->so_flags
& SOF_UPCALLCLOSEWAIT
);
5397 optval
= (so
->so_flags
& SOF_BINDRANDOMPORT
);
5400 case SO_NP_EXTENSIONS
: {
5401 struct so_np_extensions sonpx
;
5403 sonpx
.npx_flags
= (so
->so_flags
& SOF_NPX_SETOPTSHUT
) ?
5404 SONPX_SETOPTSHUT
: 0;
5405 sonpx
.npx_mask
= SONPX_MASK_VALID
;
5407 error
= sooptcopyout(sopt
, &sonpx
,
5408 sizeof (struct so_np_extensions
));
5412 case SO_TRAFFIC_CLASS
:
5413 optval
= so
->so_traffic_class
;
5416 case SO_RECV_TRAFFIC_CLASS
:
5417 optval
= (so
->so_flags
& SOF_RECV_TRAFFIC_CLASS
);
5420 case SO_TRAFFIC_CLASS_STATS
:
5421 error
= sooptcopyout(sopt
, &so
->so_tc_stats
,
5422 sizeof (so
->so_tc_stats
));
5425 case SO_TRAFFIC_CLASS_DBG
:
5426 error
= sogetopt_tcdbg(so
, sopt
);
5429 case SO_PRIVILEGED_TRAFFIC_CLASS
:
5430 optval
= (so
->so_flags
& SOF_PRIVILEGED_TRAFFIC_CLASS
);
5434 optval
= !(so
->so_flags
& SOF_NODEFUNCT
);
5438 optval
= (so
->so_flags
& SOF_DEFUNCT
);
5441 case SO_OPPORTUNISTIC
:
5442 optval
= so_get_opportunistic(so
);
5446 /* This option is not gettable */
5451 optval
= so_get_recv_anyif(so
);
5454 case SO_TRAFFIC_MGT_BACKGROUND
:
5455 /* This option is handled by lower layer(s) */
5456 if (so
->so_proto
!= NULL
&&
5457 so
->so_proto
->pr_ctloutput
!= NULL
) {
5458 (void) so
->so_proto
->pr_ctloutput(so
, sopt
);
5463 case SO_FLOW_DIVERT_TOKEN
:
5464 error
= flow_divert_token_get(so
, sopt
);
5466 #endif /* FLOW_DIVERT */
5469 case SO_NECP_ATTRIBUTES
:
5470 error
= necp_get_socket_attributes(so
, sopt
);
5475 case SO_CFIL_SOCK_ID
: {
5476 cfil_sock_id_t sock_id
;
5478 sock_id
= cfil_sock_id_from_socket(so
);
5480 error
= sooptcopyout(sopt
, &sock_id
,
5481 sizeof(cfil_sock_id_t
));
5484 #endif /* CONTENT_FILTER */
5487 case SO_MPTCP_FASTJOIN
:
5488 if (!((so
->so_flags
& SOF_MP_SUBFLOW
) ||
5489 ((SOCK_CHECK_DOM(so
, PF_MULTIPATH
)) &&
5490 (SOCK_CHECK_PROTO(so
, IPPROTO_TCP
))))) {
5491 error
= ENOPROTOOPT
;
5494 optval
= (so
->so_flags
& SOF_MPTCP_FASTJOIN
);
5495 /* Fixed along with rdar://19391339 */
5499 case SO_EXTENDED_BK_IDLE
:
5500 optval
= (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
);
5504 error
= ENOPROTOOPT
;
5510 socket_unlock(so
, 1);
5515 * The size limits on our soopt_getm is different from that on FreeBSD.
5516 * We limit the size of options to MCLBYTES. This will have to change
5517 * if we need to define options that need more space than MCLBYTES.
5520 soopt_getm(struct sockopt
*sopt
, struct mbuf
**mp
)
5522 struct mbuf
*m
, *m_prev
;
5523 int sopt_size
= sopt
->sopt_valsize
;
5526 if (sopt_size
<= 0 || sopt_size
> MCLBYTES
)
5529 how
= sopt
->sopt_p
!= kernproc
? M_WAIT
: M_DONTWAIT
;
5530 MGET(m
, how
, MT_DATA
);
5533 if (sopt_size
> MLEN
) {
5535 if ((m
->m_flags
& M_EXT
) == 0) {
5539 m
->m_len
= min(MCLBYTES
, sopt_size
);
5541 m
->m_len
= min(MLEN
, sopt_size
);
5543 sopt_size
-= m
->m_len
;
5547 while (sopt_size
> 0) {
5548 MGET(m
, how
, MT_DATA
);
5553 if (sopt_size
> MLEN
) {
5555 if ((m
->m_flags
& M_EXT
) == 0) {
5560 m
->m_len
= min(MCLBYTES
, sopt_size
);
5562 m
->m_len
= min(MLEN
, sopt_size
);
5564 sopt_size
-= m
->m_len
;
5571 /* copyin sopt data into mbuf chain */
5573 soopt_mcopyin(struct sockopt
*sopt
, struct mbuf
*m
)
5575 struct mbuf
*m0
= m
;
5577 if (sopt
->sopt_val
== USER_ADDR_NULL
)
5579 while (m
!= NULL
&& sopt
->sopt_valsize
>= m
->m_len
) {
5580 if (sopt
->sopt_p
!= kernproc
) {
5583 error
= copyin(sopt
->sopt_val
, mtod(m
, char *),
5590 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
),
5591 mtod(m
, char *), m
->m_len
);
5593 sopt
->sopt_valsize
-= m
->m_len
;
5594 sopt
->sopt_val
+= m
->m_len
;
5597 /* should be allocated enoughly at ip6_sooptmcopyin() */
5599 panic("soopt_mcopyin");
5605 /* copyout mbuf chain data into soopt */
5607 soopt_mcopyout(struct sockopt
*sopt
, struct mbuf
*m
)
5609 struct mbuf
*m0
= m
;
5612 if (sopt
->sopt_val
== USER_ADDR_NULL
)
5614 while (m
!= NULL
&& sopt
->sopt_valsize
>= m
->m_len
) {
5615 if (sopt
->sopt_p
!= kernproc
) {
5618 error
= copyout(mtod(m
, char *), sopt
->sopt_val
,
5625 bcopy(mtod(m
, char *),
5626 CAST_DOWN(caddr_t
, sopt
->sopt_val
), m
->m_len
);
5628 sopt
->sopt_valsize
-= m
->m_len
;
5629 sopt
->sopt_val
+= m
->m_len
;
5630 valsize
+= m
->m_len
;
5634 /* enough soopt buffer should be given from user-land */
5638 sopt
->sopt_valsize
= valsize
;
5643 sohasoutofband(struct socket
*so
)
5645 if (so
->so_pgid
< 0)
5646 gsignal(-so
->so_pgid
, SIGURG
);
5647 else if (so
->so_pgid
> 0)
5648 proc_signal(so
->so_pgid
, SIGURG
);
5649 selwakeup(&so
->so_rcv
.sb_sel
);
5653 sopoll(struct socket
*so
, int events
, kauth_cred_t cred
, void * wql
)
5655 #pragma unused(cred)
5656 struct proc
*p
= current_proc();
5660 so_update_last_owner_locked(so
, PROC_NULL
);
5661 so_update_policy(so
);
5663 if (events
& (POLLIN
| POLLRDNORM
))
5665 revents
|= events
& (POLLIN
| POLLRDNORM
);
5667 if (events
& (POLLOUT
| POLLWRNORM
))
5668 if (sowriteable(so
))
5669 revents
|= events
& (POLLOUT
| POLLWRNORM
);
5671 if (events
& (POLLPRI
| POLLRDBAND
))
5672 if (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
))
5673 revents
|= events
& (POLLPRI
| POLLRDBAND
);
5676 if (events
& (POLLIN
| POLLPRI
| POLLRDNORM
| POLLRDBAND
)) {
5678 * Darwin sets the flag first,
5679 * BSD calls selrecord first
5681 so
->so_rcv
.sb_flags
|= SB_SEL
;
5682 selrecord(p
, &so
->so_rcv
.sb_sel
, wql
);
5685 if (events
& (POLLOUT
| POLLWRNORM
)) {
5687 * Darwin sets the flag first,
5688 * BSD calls selrecord first
5690 so
->so_snd
.sb_flags
|= SB_SEL
;
5691 selrecord(p
, &so
->so_snd
.sb_sel
, wql
);
5695 socket_unlock(so
, 1);
5700 soo_kqfilter(struct fileproc
*fp
, struct knote
*kn
, vfs_context_t ctx
)
5703 #if !CONFIG_MACF_SOCKET
5705 #endif /* MAC_SOCKET */
5706 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5710 so_update_last_owner_locked(so
, PROC_NULL
);
5711 so_update_policy(so
);
5713 #if CONFIG_MACF_SOCKET
5714 if (mac_socket_check_kqfilter(proc_ucred(vfs_context_proc(ctx
)),
5716 socket_unlock(so
, 1);
5719 #endif /* MAC_SOCKET */
5721 switch (kn
->kn_filter
) {
5723 kn
->kn_fop
= &soread_filtops
;
5725 * If the caller explicitly asked for OOB results (e.g. poll()),
5726 * save that off in the hookid field and reserve the kn_flags
5727 * EV_OOBAND bit for output only.
5729 if (kn
->kn_flags
& EV_OOBAND
) {
5730 kn
->kn_flags
&= ~EV_OOBAND
;
5731 kn
->kn_hookid
= EV_OOBAND
;
5735 skl
= &so
->so_rcv
.sb_sel
.si_note
;
5738 kn
->kn_fop
= &sowrite_filtops
;
5739 skl
= &so
->so_snd
.sb_sel
.si_note
;
5742 kn
->kn_fop
= &sock_filtops
;
5743 skl
= &so
->so_klist
;
5745 kn
->kn_status
|= KN_TOUCH
;
5748 socket_unlock(so
, 1);
5752 if (KNOTE_ATTACH(skl
, kn
)) {
5753 switch (kn
->kn_filter
) {
5755 so
->so_rcv
.sb_flags
|= SB_KNOTE
;
5758 so
->so_snd
.sb_flags
|= SB_KNOTE
;
5761 so
->so_flags
|= SOF_KNOTE
;
5764 socket_unlock(so
, 1);
5768 socket_unlock(so
, 1);
5773 filt_sordetach(struct knote
*kn
)
5775 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5778 if (so
->so_rcv
.sb_flags
& SB_KNOTE
)
5779 if (KNOTE_DETACH(&so
->so_rcv
.sb_sel
.si_note
, kn
))
5780 so
->so_rcv
.sb_flags
&= ~SB_KNOTE
;
5781 socket_unlock(so
, 1);
5786 filt_soread(struct knote
*kn
, long hint
)
5788 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5790 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5793 if (so
->so_options
& SO_ACCEPTCONN
) {
5797 * Radar 6615193 handle the listen case dynamically
5798 * for kqueue read filter. This allows to call listen()
5799 * after registering the kqueue EVFILT_READ.
5802 kn
->kn_data
= so
->so_qlen
;
5803 isempty
= ! TAILQ_EMPTY(&so
->so_comp
);
5805 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5806 socket_unlock(so
, 1);
5811 /* socket isn't a listener */
5813 * NOTE_LOWAT specifies new low water mark in data, i.e.
5814 * the bytes of protocol data. We therefore exclude any
5817 kn
->kn_data
= so
->so_rcv
.sb_cc
- so
->so_rcv
.sb_ctl
;
5820 * Clear out EV_OOBAND that filt_soread may have set in the
5823 kn
->kn_flags
&= ~EV_OOBAND
;
5824 if ((so
->so_oobmark
) || (so
->so_state
& SS_RCVATMARK
)) {
5825 kn
->kn_flags
|= EV_OOBAND
;
5827 * If caller registered explicit interest in OOB data,
5828 * return immediately (data == amount beyond mark, for
5829 * legacy reasons - that should be changed later).
5831 if (kn
->kn_hookid
== EV_OOBAND
) {
5833 * When so_state is SS_RCVATMARK, so_oobmark
5836 kn
->kn_data
-= so
->so_oobmark
;
5837 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5838 socket_unlock(so
, 1);
5843 if ((so
->so_state
& SS_CANTRCVMORE
)
5845 && cfil_sock_data_pending(&so
->so_rcv
) == 0
5846 #endif /* CONTENT_FILTER */
5848 kn
->kn_flags
|= EV_EOF
;
5849 kn
->kn_fflags
= so
->so_error
;
5850 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5851 socket_unlock(so
, 1);
5855 if (so
->so_error
) { /* temporary udp error */
5856 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5857 socket_unlock(so
, 1);
5861 int64_t lowwat
= so
->so_rcv
.sb_lowat
;
5863 * Ensure that when NOTE_LOWAT is used, the derived
5864 * low water mark is bounded by socket's rcv buf's
5865 * high and low water mark values.
5867 if (kn
->kn_sfflags
& NOTE_LOWAT
) {
5868 if (kn
->kn_sdata
> so
->so_rcv
.sb_hiwat
)
5869 lowwat
= so
->so_rcv
.sb_hiwat
;
5870 else if (kn
->kn_sdata
> lowwat
)
5871 lowwat
= kn
->kn_sdata
;
5874 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5875 socket_unlock(so
, 1);
5878 * The order below is important. Since NOTE_LOWAT
5879 * overrides sb_lowat, check for NOTE_LOWAT case
5882 if (kn
->kn_sfflags
& NOTE_LOWAT
)
5883 return (kn
->kn_data
>= lowwat
);
5885 return (so
->so_rcv
.sb_cc
>= lowwat
);
5889 filt_sowdetach(struct knote
*kn
)
5891 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5894 if (so
->so_snd
.sb_flags
& SB_KNOTE
)
5895 if (KNOTE_DETACH(&so
->so_snd
.sb_sel
.si_note
, kn
))
5896 so
->so_snd
.sb_flags
&= ~SB_KNOTE
;
5897 socket_unlock(so
, 1);
5901 so_wait_for_if_feedback(struct socket
*so
)
5903 if ((SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) &&
5904 (so
->so_state
& SS_ISCONNECTED
)) {
5905 struct inpcb
*inp
= sotoinpcb(so
);
5906 if (INP_WAIT_FOR_IF_FEEDBACK(inp
))
5914 filt_sowrite(struct knote
*kn
, long hint
)
5916 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5919 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5922 kn
->kn_data
= sbspace(&so
->so_snd
);
5923 if (so
->so_state
& SS_CANTSENDMORE
) {
5924 kn
->kn_flags
|= EV_EOF
;
5925 kn
->kn_fflags
= so
->so_error
;
5929 if (so
->so_error
) { /* temporary udp error */
5933 if (!socanwrite(so
)) {
5937 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
5941 int64_t lowwat
= so
->so_snd
.sb_lowat
;
5942 if (kn
->kn_sfflags
& NOTE_LOWAT
) {
5943 if (kn
->kn_sdata
> so
->so_snd
.sb_hiwat
)
5944 lowwat
= so
->so_snd
.sb_hiwat
;
5945 else if (kn
->kn_sdata
> lowwat
)
5946 lowwat
= kn
->kn_sdata
;
5948 if (kn
->kn_data
>= lowwat
) {
5949 if (so
->so_flags
& SOF_NOTSENT_LOWAT
) {
5950 if ((SOCK_DOM(so
) == PF_INET
5951 || SOCK_DOM(so
) == PF_INET6
)
5952 && so
->so_type
== SOCK_STREAM
) {
5953 ret
= tcp_notsent_lowat_check(so
);
5956 else if ((SOCK_DOM(so
) == PF_MULTIPATH
) &&
5957 (SOCK_PROTO(so
) == IPPROTO_TCP
)) {
5958 ret
= mptcp_notsent_lowat_check(so
);
5969 if (so_wait_for_if_feedback(so
))
5972 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
5973 socket_unlock(so
, 1);
5978 filt_sockdetach(struct knote
*kn
)
5980 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5983 if ((so
->so_flags
& SOF_KNOTE
) != 0)
5984 if (KNOTE_DETACH(&so
->so_klist
, kn
))
5985 so
->so_flags
&= ~SOF_KNOTE
;
5986 socket_unlock(so
, 1);
5990 filt_sockev(struct knote
*kn
, long hint
)
5992 int ret
= 0, locked
= 0;
5993 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5994 long ev_hint
= (hint
& SO_FILT_HINT_EV
);
5995 uint32_t level_trigger
= 0;
5997 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6002 if (ev_hint
& SO_FILT_HINT_CONNRESET
) {
6003 kn
->kn_fflags
|= NOTE_CONNRESET
;
6005 if (ev_hint
& SO_FILT_HINT_TIMEOUT
) {
6006 kn
->kn_fflags
|= NOTE_TIMEOUT
;
6008 if (ev_hint
& SO_FILT_HINT_NOSRCADDR
) {
6009 kn
->kn_fflags
|= NOTE_NOSRCADDR
;
6011 if (ev_hint
& SO_FILT_HINT_IFDENIED
) {
6012 kn
->kn_fflags
|= NOTE_IFDENIED
;
6014 if (ev_hint
& SO_FILT_HINT_KEEPALIVE
) {
6015 kn
->kn_fflags
|= NOTE_KEEPALIVE
;
6017 if (ev_hint
& SO_FILT_HINT_ADAPTIVE_WTIMO
) {
6018 kn
->kn_fflags
|= NOTE_ADAPTIVE_WTIMO
;
6020 if (ev_hint
& SO_FILT_HINT_ADAPTIVE_RTIMO
) {
6021 kn
->kn_fflags
|= NOTE_ADAPTIVE_RTIMO
;
6023 if ((ev_hint
& SO_FILT_HINT_CONNECTED
) ||
6024 (so
->so_state
& SS_ISCONNECTED
)) {
6025 kn
->kn_fflags
|= NOTE_CONNECTED
;
6026 level_trigger
|= NOTE_CONNECTED
;
6028 if ((ev_hint
& SO_FILT_HINT_DISCONNECTED
) ||
6029 (so
->so_state
& SS_ISDISCONNECTED
)) {
6030 kn
->kn_fflags
|= NOTE_DISCONNECTED
;
6031 level_trigger
|= NOTE_DISCONNECTED
;
6033 if (ev_hint
& SO_FILT_HINT_CONNINFO_UPDATED
) {
6034 if (so
->so_proto
!= NULL
&&
6035 (so
->so_proto
->pr_flags
& PR_EVCONNINFO
))
6036 kn
->kn_fflags
|= NOTE_CONNINFO_UPDATED
;
6039 if ((so
->so_state
& SS_CANTRCVMORE
)
6041 && cfil_sock_data_pending(&so
->so_rcv
) == 0
6042 #endif /* CONTENT_FILTER */
6044 kn
->kn_fflags
|= NOTE_READCLOSED
;
6045 level_trigger
|= NOTE_READCLOSED
;
6048 if (so
->so_state
& SS_CANTSENDMORE
) {
6049 kn
->kn_fflags
|= NOTE_WRITECLOSED
;
6050 level_trigger
|= NOTE_WRITECLOSED
;
6053 if ((ev_hint
& SO_FILT_HINT_SUSPEND
) ||
6054 (so
->so_flags
& SOF_SUSPENDED
)) {
6055 kn
->kn_fflags
&= ~(NOTE_SUSPEND
| NOTE_RESUME
);
6057 /* If resume event was delivered before, reset it */
6058 kn
->kn_hookid
&= ~NOTE_RESUME
;
6060 kn
->kn_fflags
|= NOTE_SUSPEND
;
6061 level_trigger
|= NOTE_SUSPEND
;
6064 if ((ev_hint
& SO_FILT_HINT_RESUME
) ||
6065 (so
->so_flags
& SOF_SUSPENDED
) == 0) {
6066 kn
->kn_fflags
&= ~(NOTE_SUSPEND
| NOTE_RESUME
);
6068 /* If suspend event was delivered before, reset it */
6069 kn
->kn_hookid
&= ~NOTE_SUSPEND
;
6071 kn
->kn_fflags
|= NOTE_RESUME
;
6072 level_trigger
|= NOTE_RESUME
;
6075 if (so
->so_error
!= 0) {
6077 kn
->kn_data
= so
->so_error
;
6078 kn
->kn_flags
|= EV_EOF
;
6080 get_sockev_state(so
, (u_int32_t
*)&(kn
->kn_data
));
6083 /* Reset any events that are not requested on this knote */
6084 kn
->kn_fflags
&= (kn
->kn_sfflags
& EVFILT_SOCK_ALL_MASK
);
6085 level_trigger
&= (kn
->kn_sfflags
& EVFILT_SOCK_ALL_MASK
);
6087 /* Find the level triggerred events that are already delivered */
6088 level_trigger
&= kn
->kn_hookid
;
6089 level_trigger
&= EVFILT_SOCK_LEVEL_TRIGGER_MASK
;
6091 /* Do not deliver level triggerred events more than once */
6092 if ((kn
->kn_fflags
& ~level_trigger
) != 0)
6096 socket_unlock(so
, 1);
6102 filt_socktouch(struct knote
*kn
, struct kevent_internal_s
*kev
, long type
)
6106 case EVENT_REGISTER
:
6108 uint32_t changed_flags
;
6109 changed_flags
= (kn
->kn_sfflags
^ kn
->kn_hookid
);
6112 * Since we keep track of events that are already
6113 * delivered, if any of those events are not requested
6114 * anymore the state related to them can be reset
6117 ~(changed_flags
& EVFILT_SOCK_LEVEL_TRIGGER_MASK
);
6122 * Store the state of the events being delivered. This
6123 * state can be used to deliver level triggered events
6124 * ateast once and still avoid waking up the application
6125 * multiple times as long as the event is active.
6127 if (kn
->kn_fflags
!= 0)
6128 kn
->kn_hookid
|= (kn
->kn_fflags
&
6129 EVFILT_SOCK_LEVEL_TRIGGER_MASK
);
6132 * NOTE_RESUME and NOTE_SUSPEND are an exception, deliver
6133 * only one of them and remember the last one that was
6136 if (kn
->kn_fflags
& NOTE_SUSPEND
)
6137 kn
->kn_hookid
&= ~NOTE_RESUME
;
6138 if (kn
->kn_fflags
& NOTE_RESUME
)
6139 kn
->kn_hookid
&= ~NOTE_SUSPEND
;
6147 get_sockev_state(struct socket
*so
, u_int32_t
*statep
)
6149 u_int32_t state
= *(statep
);
6151 if (so
->so_state
& SS_ISCONNECTED
)
6152 state
|= SOCKEV_CONNECTED
;
6154 state
&= ~(SOCKEV_CONNECTED
);
6155 state
|= ((so
->so_state
& SS_ISDISCONNECTED
) ? SOCKEV_DISCONNECTED
: 0);
6159 #define SO_LOCK_HISTORY_STR_LEN \
6160 (2 * SO_LCKDBG_MAX * (2 + (2 * sizeof (void *)) + 1) + 1)
6162 __private_extern__
const char *
6163 solockhistory_nr(struct socket
*so
)
6167 static char lock_history_str
[SO_LOCK_HISTORY_STR_LEN
];
6169 bzero(lock_history_str
, sizeof (lock_history_str
));
6170 for (i
= SO_LCKDBG_MAX
- 1; i
>= 0; i
--) {
6171 n
+= snprintf(lock_history_str
+ n
,
6172 SO_LOCK_HISTORY_STR_LEN
- n
, "%p:%p ",
6173 so
->lock_lr
[(so
->next_lock_lr
+ i
) % SO_LCKDBG_MAX
],
6174 so
->unlock_lr
[(so
->next_unlock_lr
+ i
) % SO_LCKDBG_MAX
]);
6176 return (lock_history_str
);
6180 socket_lock(struct socket
*so
, int refcount
)
6185 lr_saved
= __builtin_return_address(0);
6187 if (so
->so_proto
->pr_lock
) {
6188 error
= (*so
->so_proto
->pr_lock
)(so
, refcount
, lr_saved
);
6190 #ifdef MORE_LOCKING_DEBUG
6191 lck_mtx_assert(so
->so_proto
->pr_domain
->dom_mtx
,
6192 LCK_MTX_ASSERT_NOTOWNED
);
6194 lck_mtx_lock(so
->so_proto
->pr_domain
->dom_mtx
);
6197 so
->lock_lr
[so
->next_lock_lr
] = lr_saved
;
6198 so
->next_lock_lr
= (so
->next_lock_lr
+1) % SO_LCKDBG_MAX
;
6205 socket_unlock(struct socket
*so
, int refcount
)
6209 lck_mtx_t
*mutex_held
;
6211 lr_saved
= __builtin_return_address(0);
6213 if (so
->so_proto
== NULL
) {
6214 panic("%s: null so_proto so=%p\n", __func__
, so
);
6218 if (so
&& so
->so_proto
->pr_unlock
) {
6219 error
= (*so
->so_proto
->pr_unlock
)(so
, refcount
, lr_saved
);
6221 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
6222 #ifdef MORE_LOCKING_DEBUG
6223 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
6225 so
->unlock_lr
[so
->next_unlock_lr
] = lr_saved
;
6226 so
->next_unlock_lr
= (so
->next_unlock_lr
+1) % SO_LCKDBG_MAX
;
6229 if (so
->so_usecount
<= 0) {
6230 panic("%s: bad refcount=%d so=%p (%d, %d, %d) "
6231 "lrh=%s", __func__
, so
->so_usecount
, so
,
6232 SOCK_DOM(so
), so
->so_type
,
6233 SOCK_PROTO(so
), solockhistory_nr(so
));
6238 if (so
->so_usecount
== 0)
6239 sofreelastref(so
, 1);
6241 lck_mtx_unlock(mutex_held
);
6247 /* Called with socket locked, will unlock socket */
6249 sofree(struct socket
*so
)
6251 lck_mtx_t
*mutex_held
;
6253 if (so
->so_proto
->pr_getlock
!= NULL
)
6254 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
6256 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
6257 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
6259 sofreelastref(so
, 0);
6263 soreference(struct socket
*so
)
6265 socket_lock(so
, 1); /* locks & take one reference on socket */
6266 socket_unlock(so
, 0); /* unlock only */
6270 sodereference(struct socket
*so
)
6273 socket_unlock(so
, 1);
6277 * Set or clear SOF_MULTIPAGES on the socket to enable or disable the
6278 * possibility of using jumbo clusters. Caller must ensure to hold
6282 somultipages(struct socket
*so
, boolean_t set
)
6285 so
->so_flags
|= SOF_MULTIPAGES
;
6287 so
->so_flags
&= ~SOF_MULTIPAGES
;
6291 soif2kcl(struct socket
*so
, boolean_t set
)
6294 so
->so_flags1
|= SOF1_IF_2KCL
;
6296 so
->so_flags1
&= ~SOF1_IF_2KCL
;
6300 so_isdstlocal(struct socket
*so
) {
6302 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
6304 if (SOCK_DOM(so
) == PF_INET
)
6305 return (inaddr_local(inp
->inp_faddr
));
6306 else if (SOCK_DOM(so
) == PF_INET6
)
6307 return (in6addr_local(&inp
->in6p_faddr
));
6313 sosetdefunct(struct proc
*p
, struct socket
*so
, int level
, boolean_t noforce
)
6315 struct sockbuf
*rcv
, *snd
;
6316 int err
= 0, defunct
;
6321 defunct
= (so
->so_flags
& SOF_DEFUNCT
);
6323 if (!(snd
->sb_flags
& rcv
->sb_flags
& SB_DROP
)) {
6324 panic("%s: SB_DROP not set", __func__
);
6330 if (so
->so_flags
& SOF_NODEFUNCT
) {
6333 SODEFUNCTLOG(("%s[%d]: (target pid %d level %d) "
6334 "so 0x%llx [%d,%d] is not eligible for defunct "
6335 "(%d)\n", __func__
, proc_selfpid(), proc_pid(p
),
6336 level
, (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6337 SOCK_DOM(so
), SOCK_TYPE(so
), err
));
6340 so
->so_flags
&= ~SOF_NODEFUNCT
;
6341 SODEFUNCTLOG(("%s[%d]: (target pid %d level %d) so 0x%llx "
6342 "[%d,%d] defunct by force\n", __func__
, proc_selfpid(),
6343 proc_pid(p
), level
, (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6344 SOCK_DOM(so
), SOCK_TYPE(so
)));
6345 } else if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) {
6346 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
6347 struct ifnet
*ifp
= inp
->inp_last_outifp
;
6349 if (ifp
&& IFNET_IS_CELLULAR(ifp
)) {
6350 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nocell
);
6351 } else if (so
->so_flags
& SOF_DELEGATED
) {
6352 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nodlgtd
);
6353 } else if (soextbkidlestat
.so_xbkidle_time
== 0) {
6354 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_notime
);
6355 } else if (noforce
) {
6356 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
6358 so
->so_flags1
|= SOF1_EXTEND_BK_IDLE_INPROG
;
6359 so
->so_extended_bk_start
= net_uptime();
6360 OSBitOrAtomic(P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
6362 inpcb_timer_sched(inp
->inp_pcbinfo
, INPCB_TIMER_LAZY
);
6365 SODEFUNCTLOG(("%s[%d]: (target pid %d level %d) "
6367 "so 0x%llx rcv hw %d cc %d\n",
6368 __func__
, proc_selfpid(), proc_pid(p
),
6369 level
, (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6370 so
->so_rcv
.sb_hiwat
, so
->so_rcv
.sb_cc
));
6373 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_forced
);
6377 so
->so_flags
|= SOF_DEFUNCT
;
6379 /* Prevent further data from being appended to the socket buffers */
6380 snd
->sb_flags
|= SB_DROP
;
6381 rcv
->sb_flags
|= SB_DROP
;
6383 /* Flush any existing data in the socket buffers */
6384 if (rcv
->sb_cc
!= 0) {
6385 rcv
->sb_flags
&= ~SB_SEL
;
6386 selthreadclear(&rcv
->sb_sel
);
6389 if (snd
->sb_cc
!= 0) {
6390 snd
->sb_flags
&= ~SB_SEL
;
6391 selthreadclear(&snd
->sb_sel
);
6396 SODEFUNCTLOG(("%s[%d]: (target pid %d level %d) so 0x%llx [%d,%d] %s "
6397 "defunct%s\n", __func__
, proc_selfpid(), proc_pid(p
), level
,
6398 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
), SOCK_TYPE(so
),
6399 defunct
? "is already" : "marked as",
6400 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ? " extbkidle" : ""));
6406 sodefunct(struct proc
*p
, struct socket
*so
, int level
)
6408 struct sockbuf
*rcv
, *snd
;
6410 if (!(so
->so_flags
& SOF_DEFUNCT
)) {
6411 panic("%s improperly called", __func__
);
6414 if (so
->so_state
& SS_DEFUNCT
)
6420 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6421 char s
[MAX_IPv6_STR_LEN
];
6422 char d
[MAX_IPv6_STR_LEN
];
6423 struct inpcb
*inp
= sotoinpcb(so
);
6425 SODEFUNCTLOG(("%s[%d]: (target pid %d level %d) so 0x%llx [%s "
6426 "%s:%d -> %s:%d] is now defunct [rcv_si 0x%x, snd_si 0x%x, "
6427 "rcv_fl 0x%x, snd_fl 0x%x]\n", __func__
, proc_selfpid(),
6428 proc_pid(p
), level
, (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6429 (SOCK_TYPE(so
) == SOCK_STREAM
) ? "TCP" : "UDP",
6430 inet_ntop(SOCK_DOM(so
), ((SOCK_DOM(so
) == PF_INET
) ?
6431 (void *)&inp
->inp_laddr
.s_addr
: (void *)&inp
->in6p_laddr
),
6432 s
, sizeof (s
)), ntohs(inp
->in6p_lport
),
6433 inet_ntop(SOCK_DOM(so
), (SOCK_DOM(so
) == PF_INET
) ?
6434 (void *)&inp
->inp_faddr
.s_addr
: (void *)&inp
->in6p_faddr
,
6435 d
, sizeof (d
)), ntohs(inp
->in6p_fport
),
6436 (uint32_t)rcv
->sb_sel
.si_flags
,
6437 (uint32_t)snd
->sb_sel
.si_flags
,
6438 rcv
->sb_flags
, snd
->sb_flags
));
6440 SODEFUNCTLOG(("%s[%d]: (target pid %d level %d) so 0x%llx "
6441 "[%d,%d] is now defunct [rcv_si 0x%x, snd_si 0x%x, "
6442 "rcv_fl 0x%x, snd_fl 0x%x]\n", __func__
, proc_selfpid(),
6443 proc_pid(p
), level
, (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6444 SOCK_DOM(so
), SOCK_TYPE(so
), (uint32_t)rcv
->sb_sel
.si_flags
,
6445 (uint32_t)snd
->sb_sel
.si_flags
, rcv
->sb_flags
,
6450 * Unwedge threads blocked on sbwait() and sb_lock().
6455 so
->so_flags1
|= SOF1_DEFUNCTINPROG
;
6456 if (rcv
->sb_flags
& SB_LOCK
)
6457 sbunlock(rcv
, TRUE
); /* keep socket locked */
6458 if (snd
->sb_flags
& SB_LOCK
)
6459 sbunlock(snd
, TRUE
); /* keep socket locked */
6462 * Flush the buffers and disconnect. We explicitly call shutdown
6463 * on both data directions to ensure that SS_CANT{RCV,SEND}MORE
6464 * states are set for the socket. This would also flush out data
6465 * hanging off the receive list of this socket.
6467 (void) soshutdownlock_final(so
, SHUT_RD
);
6468 (void) soshutdownlock_final(so
, SHUT_WR
);
6469 (void) sodisconnectlocked(so
);
6472 * Explicitly handle connectionless-protocol disconnection
6473 * and release any remaining data in the socket buffers.
6475 if (!(so
->so_flags
& SS_ISDISCONNECTED
))
6476 (void) soisdisconnected(so
);
6478 if (so
->so_error
== 0)
6479 so
->so_error
= EBADF
;
6481 if (rcv
->sb_cc
!= 0) {
6482 rcv
->sb_flags
&= ~SB_SEL
;
6483 selthreadclear(&rcv
->sb_sel
);
6486 if (snd
->sb_cc
!= 0) {
6487 snd
->sb_flags
&= ~SB_SEL
;
6488 selthreadclear(&snd
->sb_sel
);
6491 so
->so_state
|= SS_DEFUNCT
;
6498 soresume(struct proc
*p
, struct socket
*so
, int locked
)
6503 if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
) {
6504 SODEFUNCTLOG(("%s[%d]: )target pid %d) so 0x%llx [%d,%d] "
6505 "resumed from bk idle\n",
6506 __func__
, proc_selfpid(), proc_pid(p
),
6507 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6508 SOCK_DOM(so
), SOCK_TYPE(so
)));
6510 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_INPROG
;
6511 so
->so_extended_bk_start
= 0;
6512 OSBitAndAtomic(~P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
6514 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_resumed
);
6515 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
6516 VERIFY(soextbkidlestat
.so_xbkidle_active
>= 0);
6519 socket_unlock(so
, 1);
6525 * Does not attempt to account for sockets that are delegated from
6526 * the current process
6529 so_set_extended_bk_idle(struct socket
*so
, int optval
)
6533 if ((SOCK_DOM(so
) != PF_INET
&& SOCK_DOM(so
) != PF_INET6
) ||
6534 SOCK_PROTO(so
) != IPPROTO_TCP
) {
6535 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_notsupp
);
6537 } else if (optval
== 0) {
6538 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_WANTED
;
6540 soresume(current_proc(), so
, 1);
6542 struct proc
*p
= current_proc();
6544 struct filedesc
*fdp
;
6550 for (i
= 0; i
< fdp
->fd_nfiles
; i
++) {
6551 struct fileproc
*fp
= fdp
->fd_ofiles
[i
];
6555 (fdp
->fd_ofileflags
[i
] & UF_RESERVED
) != 0 ||
6556 FILEGLOB_DTYPE(fp
->f_fglob
) != DTYPE_SOCKET
)
6559 so2
= (struct socket
*)fp
->f_fglob
->fg_data
;
6561 so2
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
)
6563 if (count
>= soextbkidlestat
.so_xbkidle_maxperproc
)
6566 if (count
>= soextbkidlestat
.so_xbkidle_maxperproc
) {
6567 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_toomany
);
6569 } else if (so
->so_flags
& SOF_DELEGATED
) {
6570 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nodlgtd
);
6573 so
->so_flags1
|= SOF1_EXTEND_BK_IDLE_WANTED
;
6574 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_wantok
);
6576 SODEFUNCTLOG(("%s[%d]: so 0x%llx [%d,%d] "
6577 "%s marked for extended bk idle\n",
6578 __func__
, proc_selfpid(),
6579 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6580 SOCK_DOM(so
), SOCK_TYPE(so
),
6581 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ?
6591 so_stop_extended_bk_idle(struct socket
*so
)
6593 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_INPROG
;
6594 so
->so_extended_bk_start
= 0;
6596 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
6597 VERIFY(soextbkidlestat
.so_xbkidle_active
>= 0);
6601 sosetdefunct(current_proc(), so
,
6602 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
, FALSE
);
6603 if (so
->so_flags
& SOF_DEFUNCT
) {
6604 sodefunct(current_proc(), so
,
6605 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
);
6610 so_drain_extended_bk_idle(struct socket
*so
)
6612 if (so
&& (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
)) {
6614 * Only penalize sockets that have outstanding data
6616 if (so
->so_rcv
.sb_cc
|| so
->so_snd
.sb_cc
) {
6617 so_stop_extended_bk_idle(so
);
6619 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_drained
);
6625 * Return values tells if socket is still in extended background idle
6628 so_check_extended_bk_idle_time(struct socket
*so
)
6632 if ((so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
)) {
6633 SODEFUNCTLOG(("%s[%d]: so 0x%llx [%d,%d]\n",
6634 __func__
, proc_selfpid(),
6635 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6636 SOCK_DOM(so
), SOCK_TYPE(so
)));
6637 if (net_uptime() - so
->so_extended_bk_start
>
6638 soextbkidlestat
.so_xbkidle_time
) {
6639 so_stop_extended_bk_idle(so
);
6641 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_expired
);
6645 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
6647 inpcb_timer_sched(inp
->inp_pcbinfo
, INPCB_TIMER_LAZY
);
6648 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_resched
);
6656 resume_proc_sockets(proc_t p
)
6658 if (p
->p_ladvflag
& P_LXBKIDLEINPROG
) {
6659 struct filedesc
*fdp
;
6664 for (i
= 0; i
< fdp
->fd_nfiles
; i
++) {
6665 struct fileproc
*fp
;
6668 fp
= fdp
->fd_ofiles
[i
];
6670 (fdp
->fd_ofileflags
[i
] & UF_RESERVED
) != 0 ||
6671 FILEGLOB_DTYPE(fp
->f_fglob
) != DTYPE_SOCKET
)
6674 so
= (struct socket
*)fp
->f_fglob
->fg_data
;
6675 (void) soresume(p
, so
, 0);
6679 OSBitAndAtomic(~P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
6683 __private_extern__
int
6684 so_set_recv_anyif(struct socket
*so
, int optval
)
6689 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6691 if (SOCK_DOM(so
) == PF_INET
) {
6694 sotoinpcb(so
)->inp_flags
|= INP_RECV_ANYIF
;
6696 sotoinpcb(so
)->inp_flags
&= ~INP_RECV_ANYIF
;
6702 __private_extern__
int
6703 so_get_recv_anyif(struct socket
*so
)
6708 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6710 if (SOCK_DOM(so
) == PF_INET
) {
6712 ret
= (sotoinpcb(so
)->inp_flags
& INP_RECV_ANYIF
) ? 1 : 0;
6719 so_set_restrictions(struct socket
*so
, uint32_t vals
)
6721 int nocell_old
, nocell_new
;
6722 int noexpensive_old
, noexpensive_new
;
6725 * Deny-type restrictions are trapdoors; once set they cannot be
6726 * unset for the lifetime of the socket. This allows them to be
6727 * issued by a framework on behalf of the application without
6728 * having to worry that they can be undone.
6730 * Note here that socket-level restrictions overrides any protocol
6731 * level restrictions. For instance, SO_RESTRICT_DENY_CELLULAR
6732 * socket restriction issued on the socket has a higher precendence
6733 * than INP_NO_IFT_CELLULAR. The latter is affected by the UUID
6734 * policy PROC_UUID_NO_CELLULAR for unrestricted sockets only,
6735 * i.e. when SO_RESTRICT_DENY_CELLULAR has not been issued.
6737 nocell_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_CELLULAR
);
6738 noexpensive_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_EXPENSIVE
);
6739 so
->so_restrictions
|= (vals
& (SO_RESTRICT_DENY_IN
|
6740 SO_RESTRICT_DENY_OUT
| SO_RESTRICT_DENY_CELLULAR
|
6741 SO_RESTRICT_DENY_EXPENSIVE
));
6742 nocell_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_CELLULAR
);
6743 noexpensive_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_EXPENSIVE
);
6745 /* we can only set, not clear restrictions */
6746 if ((nocell_new
- nocell_old
) == 0 &&
6747 (noexpensive_new
- noexpensive_old
) == 0)
6750 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6752 if (SOCK_DOM(so
) == PF_INET
) {
6754 if (nocell_new
- nocell_old
!= 0) {
6756 * if deny cellular is now set, do what's needed
6759 inp_set_nocellular(sotoinpcb(so
));
6761 if (noexpensive_new
- noexpensive_old
!= 0) {
6762 inp_set_noexpensive(sotoinpcb(so
));
6770 so_get_restrictions(struct socket
*so
)
6772 return (so
->so_restrictions
& (SO_RESTRICT_DENY_IN
|
6773 SO_RESTRICT_DENY_OUT
|
6774 SO_RESTRICT_DENY_CELLULAR
| SO_RESTRICT_DENY_EXPENSIVE
));
6777 struct sockaddr_entry
*
6778 sockaddrentry_alloc(int how
)
6780 struct sockaddr_entry
*se
;
6782 se
= (how
== M_WAITOK
) ? zalloc(se_zone
) : zalloc_noblock(se_zone
);
6784 bzero(se
, se_zone_size
);
6790 sockaddrentry_free(struct sockaddr_entry
*se
)
6792 if (se
->se_addr
!= NULL
) {
6793 FREE(se
->se_addr
, M_SONAME
);
6799 struct sockaddr_entry
*
6800 sockaddrentry_dup(const struct sockaddr_entry
*src_se
, int how
)
6802 struct sockaddr_entry
*dst_se
;
6804 dst_se
= sockaddrentry_alloc(how
);
6805 if (dst_se
!= NULL
) {
6806 int len
= src_se
->se_addr
->sa_len
;
6808 MALLOC(dst_se
->se_addr
, struct sockaddr
*,
6809 len
, M_SONAME
, how
| M_ZERO
);
6810 if (dst_se
->se_addr
!= NULL
) {
6811 bcopy(src_se
->se_addr
, dst_se
->se_addr
, len
);
6813 sockaddrentry_free(dst_se
);
6821 struct sockaddr_list
*
6822 sockaddrlist_alloc(int how
)
6824 struct sockaddr_list
*sl
;
6826 sl
= (how
== M_WAITOK
) ? zalloc(sl_zone
) : zalloc_noblock(sl_zone
);
6828 bzero(sl
, sl_zone_size
);
6829 TAILQ_INIT(&sl
->sl_head
);
6835 sockaddrlist_free(struct sockaddr_list
*sl
)
6837 struct sockaddr_entry
*se
, *tse
;
6839 TAILQ_FOREACH_SAFE(se
, &sl
->sl_head
, se_link
, tse
) {
6840 sockaddrlist_remove(sl
, se
);
6841 sockaddrentry_free(se
);
6843 VERIFY(sl
->sl_cnt
== 0 && TAILQ_EMPTY(&sl
->sl_head
));
6848 sockaddrlist_insert(struct sockaddr_list
*sl
, struct sockaddr_entry
*se
)
6850 VERIFY(!(se
->se_flags
& SEF_ATTACHED
));
6851 se
->se_flags
|= SEF_ATTACHED
;
6852 TAILQ_INSERT_TAIL(&sl
->sl_head
, se
, se_link
);
6854 VERIFY(sl
->sl_cnt
!= 0);
6858 sockaddrlist_remove(struct sockaddr_list
*sl
, struct sockaddr_entry
*se
)
6860 VERIFY(se
->se_flags
& SEF_ATTACHED
);
6861 se
->se_flags
&= ~SEF_ATTACHED
;
6862 VERIFY(sl
->sl_cnt
!= 0);
6864 TAILQ_REMOVE(&sl
->sl_head
, se
, se_link
);
6867 struct sockaddr_list
*
6868 sockaddrlist_dup(const struct sockaddr_list
*src_sl
, int how
)
6870 struct sockaddr_entry
*src_se
, *tse
;
6871 struct sockaddr_list
*dst_sl
;
6873 dst_sl
= sockaddrlist_alloc(how
);
6877 TAILQ_FOREACH_SAFE(src_se
, &src_sl
->sl_head
, se_link
, tse
) {
6878 struct sockaddr_entry
*dst_se
;
6880 if (src_se
->se_addr
== NULL
)
6883 dst_se
= sockaddrentry_dup(src_se
, how
);
6884 if (dst_se
== NULL
) {
6885 sockaddrlist_free(dst_sl
);
6889 sockaddrlist_insert(dst_sl
, dst_se
);
6891 VERIFY(src_sl
->sl_cnt
== dst_sl
->sl_cnt
);
6897 so_set_effective_pid(struct socket
*so
, int epid
, struct proc
*p
)
6899 struct proc
*ep
= PROC_NULL
;
6902 /* pid 0 is reserved for kernel */
6909 * If this is an in-kernel socket, prevent its delegate
6910 * association from changing unless the socket option is
6911 * coming from within the kernel itself.
6913 if (so
->last_pid
== 0 && p
!= kernproc
) {
6919 * If this is issued by a process that's recorded as the
6920 * real owner of the socket, or if the pid is the same as
6921 * the process's own pid, then proceed. Otherwise ensure
6922 * that the issuing process has the necessary privileges.
6924 if (epid
!= so
->last_pid
|| epid
!= proc_pid(p
)) {
6925 if ((error
= priv_check_cred(kauth_cred_get(),
6926 PRIV_NET_PRIVILEGED_SOCKET_DELEGATE
, 0))) {
6932 /* Find the process that corresponds to the effective pid */
6933 if ((ep
= proc_find(epid
)) == PROC_NULL
) {
6939 * If a process tries to delegate the socket to itself, then
6940 * there's really nothing to do; treat it as a way for the
6941 * delegate association to be cleared. Note that we check
6942 * the passed-in proc rather than calling proc_selfpid(),
6943 * as we need to check the process issuing the socket option
6944 * which could be kernproc. Given that we don't allow 0 for
6945 * effective pid, it means that a delegated in-kernel socket
6946 * stays delegated during its lifetime (which is probably OK.)
6948 if (epid
== proc_pid(p
)) {
6949 so
->so_flags
&= ~SOF_DELEGATED
;
6952 uuid_clear(so
->e_uuid
);
6954 so
->so_flags
|= SOF_DELEGATED
;
6955 so
->e_upid
= proc_uniqueid(ep
);
6956 so
->e_pid
= proc_pid(ep
);
6957 proc_getexecutableuuid(ep
, so
->e_uuid
, sizeof (so
->e_uuid
));
6960 if (error
== 0 && net_io_policy_log
) {
6963 uuid_unparse(so
->e_uuid
, buf
);
6964 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d (%s) "
6965 "euuid %s%s\n", __func__
, proc_name_address(p
),
6966 proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6967 SOCK_DOM(so
), SOCK_TYPE(so
),
6968 so
->e_pid
, proc_name_address(ep
), buf
,
6969 ((so
->so_flags
& SOF_DELEGATED
) ? " [delegated]" : ""));
6970 } else if (error
!= 0 && net_io_policy_log
) {
6971 log(LOG_ERR
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d (%s) "
6972 "ERROR (%d)\n", __func__
, proc_name_address(p
),
6973 proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6974 SOCK_DOM(so
), SOCK_TYPE(so
),
6975 epid
, (ep
== PROC_NULL
) ? "PROC_NULL" :
6976 proc_name_address(ep
), error
);
6979 /* Update this socket's policy upon success */
6981 so
->so_policy_gencnt
*= -1;
6982 so_update_policy(so
);
6984 so_update_necp_policy(so
, NULL
, NULL
);
6988 if (ep
!= PROC_NULL
)
6995 so_set_effective_uuid(struct socket
*so
, uuid_t euuid
, struct proc
*p
)
7001 /* UUID must not be all-zeroes (reserved for kernel) */
7002 if (uuid_is_null(euuid
)) {
7008 * If this is an in-kernel socket, prevent its delegate
7009 * association from changing unless the socket option is
7010 * coming from within the kernel itself.
7012 if (so
->last_pid
== 0 && p
!= kernproc
) {
7017 /* Get the UUID of the issuing process */
7018 proc_getexecutableuuid(p
, uuid
, sizeof (uuid
));
7021 * If this is issued by a process that's recorded as the
7022 * real owner of the socket, or if the uuid is the same as
7023 * the process's own uuid, then proceed. Otherwise ensure
7024 * that the issuing process has the necessary privileges.
7026 if (uuid_compare(euuid
, so
->last_uuid
) != 0 ||
7027 uuid_compare(euuid
, uuid
) != 0) {
7028 if ((error
= priv_check_cred(kauth_cred_get(),
7029 PRIV_NET_PRIVILEGED_SOCKET_DELEGATE
, 0))) {
7036 * If a process tries to delegate the socket to itself, then
7037 * there's really nothing to do; treat it as a way for the
7038 * delegate association to be cleared. Note that we check
7039 * the uuid of the passed-in proc rather than that of the
7040 * current process, as we need to check the process issuing
7041 * the socket option which could be kernproc itself. Given
7042 * that we don't allow 0 for effective uuid, it means that
7043 * a delegated in-kernel socket stays delegated during its
7044 * lifetime (which is okay.)
7046 if (uuid_compare(euuid
, uuid
) == 0) {
7047 so
->so_flags
&= ~SOF_DELEGATED
;
7050 uuid_clear(so
->e_uuid
);
7052 so
->so_flags
|= SOF_DELEGATED
;
7054 * Unlike so_set_effective_pid(), we only have the UUID
7055 * here and the process ID is not known. Inherit the
7056 * real {pid,upid} of the socket.
7058 so
->e_upid
= so
->last_upid
;
7059 so
->e_pid
= so
->last_pid
;
7060 uuid_copy(so
->e_uuid
, euuid
);
7064 if (error
== 0 && net_io_policy_log
) {
7065 uuid_unparse(so
->e_uuid
, buf
);
7066 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d "
7067 "euuid %s%s\n", __func__
, proc_name_address(p
), proc_pid(p
),
7068 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7069 SOCK_TYPE(so
), so
->e_pid
, buf
,
7070 ((so
->so_flags
& SOF_DELEGATED
) ? " [delegated]" : ""));
7071 } else if (error
!= 0 && net_io_policy_log
) {
7072 uuid_unparse(euuid
, buf
);
7073 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] euuid %s "
7074 "ERROR (%d)\n", __func__
, proc_name_address(p
), proc_pid(p
),
7075 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7076 SOCK_TYPE(so
), buf
, error
);
7079 /* Update this socket's policy upon success */
7081 so
->so_policy_gencnt
*= -1;
7082 so_update_policy(so
);
7084 so_update_necp_policy(so
, NULL
, NULL
);
7092 netpolicy_post_msg(uint32_t ev_code
, struct netpolicy_event_data
*ev_data
,
7093 uint32_t ev_datalen
)
7095 struct kev_msg ev_msg
;
7098 * A netpolicy event always starts with a netpolicy_event_data
7099 * structure, but the caller can provide for a longer event
7100 * structure to post, depending on the event code.
7102 VERIFY(ev_data
!= NULL
&& ev_datalen
>= sizeof (*ev_data
));
7104 bzero(&ev_msg
, sizeof (ev_msg
));
7105 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7106 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
7107 ev_msg
.kev_subclass
= KEV_NETPOLICY_SUBCLASS
;
7108 ev_msg
.event_code
= ev_code
;
7110 ev_msg
.dv
[0].data_ptr
= ev_data
;
7111 ev_msg
.dv
[0].data_length
= ev_datalen
;
7113 kev_post_msg(&ev_msg
);
7117 socket_post_kev_msg(uint32_t ev_code
,
7118 struct kev_socket_event_data
*ev_data
,
7119 uint32_t ev_datalen
)
7121 struct kev_msg ev_msg
;
7123 bzero(&ev_msg
, sizeof(ev_msg
));
7124 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7125 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
7126 ev_msg
.kev_subclass
= KEV_SOCKET_SUBCLASS
;
7127 ev_msg
.event_code
= ev_code
;
7129 ev_msg
.dv
[0].data_ptr
= ev_data
;
7130 ev_msg
.dv
[0]. data_length
= ev_datalen
;
7132 kev_post_msg(&ev_msg
);
7136 socket_post_kev_msg_closed(struct socket
*so
)
7138 struct kev_socket_closed ev
;
7139 struct sockaddr
*socksa
= NULL
, *peersa
= NULL
;
7141 bzero(&ev
, sizeof(ev
));
7142 err
= (*so
->so_proto
->pr_usrreqs
->pru_sockaddr
)(so
, &socksa
);
7144 err
= (*so
->so_proto
->pr_usrreqs
->pru_peeraddr
)(so
,
7147 memcpy(&ev
.ev_data
.kev_sockname
, socksa
,
7149 sizeof (ev
.ev_data
.kev_sockname
)));
7150 memcpy(&ev
.ev_data
.kev_peername
, peersa
,
7152 sizeof (ev
.ev_data
.kev_peername
)));
7153 socket_post_kev_msg(KEV_SOCKET_CLOSED
,
7154 &ev
.ev_data
, sizeof (ev
));
7158 FREE(socksa
, M_SONAME
);
7160 FREE(peersa
, M_SONAME
);