2 * Copyright (c) 1998-2016 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/in_tclass.h>
106 #include <netinet/tcp_var.h>
107 #include <netinet/ip6.h>
108 #include <netinet6/ip6_var.h>
109 #include <netinet/flow_divert.h>
110 #include <kern/zalloc.h>
111 #include <kern/locks.h>
112 #include <machine/limits.h>
113 #include <libkern/OSAtomic.h>
114 #include <pexpert/pexpert.h>
115 #include <kern/assert.h>
116 #include <kern/task.h>
117 #include <kern/policy_internal.h>
119 #include <sys/kpi_mbuf.h>
120 #include <sys/mcache.h>
121 #include <sys/unpcb.h>
124 #include <security/mac.h>
125 #include <security/mac_framework.h>
129 #include <netinet/mp_pcb.h>
130 #include <netinet/mptcp_var.h>
131 #endif /* MULTIPATH */
133 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
135 #if DEBUG || DEVELOPMENT
136 #define DEBUG_KERNEL_ADDRPERM(_v) (_v)
138 #define DEBUG_KERNEL_ADDRPERM(_v) VM_KERNEL_ADDRPERM(_v)
141 /* TODO: this should be in a header file somewhere */
142 extern char *proc_name_address(void *p
);
143 extern char *proc_best_name(proc_t
);
145 static u_int32_t so_cache_hw
; /* High water mark for socache */
146 static u_int32_t so_cache_timeouts
; /* number of timeouts */
147 static u_int32_t so_cache_max_freed
; /* max freed per timeout */
148 static u_int32_t cached_sock_count
= 0;
149 STAILQ_HEAD(, socket
) so_cache_head
;
150 int max_cached_sock_count
= MAX_CACHED_SOCKETS
;
151 static u_int32_t so_cache_time
;
152 static int socketinit_done
;
153 static struct zone
*so_cache_zone
;
155 static lck_grp_t
*so_cache_mtx_grp
;
156 static lck_attr_t
*so_cache_mtx_attr
;
157 static lck_grp_attr_t
*so_cache_mtx_grp_attr
;
158 static lck_mtx_t
*so_cache_mtx
;
160 #include <machine/limits.h>
162 static int filt_sorattach(struct knote
*kn
);
163 static void filt_sordetach(struct knote
*kn
);
164 static int filt_soread(struct knote
*kn
, long hint
);
165 static int filt_sortouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
166 static int filt_sorprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
168 static int filt_sowattach(struct knote
*kn
);
169 static void filt_sowdetach(struct knote
*kn
);
170 static int filt_sowrite(struct knote
*kn
, long hint
);
171 static int filt_sowtouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
172 static int filt_sowprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
174 static int filt_sockattach(struct knote
*kn
);
175 static void filt_sockdetach(struct knote
*kn
);
176 static int filt_sockev(struct knote
*kn
, long hint
);
177 static int filt_socktouch(struct knote
*kn
, struct kevent_internal_s
*kev
);
178 static int filt_sockprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
);
180 static int sooptcopyin_timeval(struct sockopt
*, struct timeval
*);
181 static int sooptcopyout_timeval(struct sockopt
*, const struct timeval
*);
183 struct filterops soread_filtops
= {
185 .f_attach
= filt_sorattach
,
186 .f_detach
= filt_sordetach
,
187 .f_event
= filt_soread
,
188 .f_touch
= filt_sortouch
,
189 .f_process
= filt_sorprocess
,
192 struct filterops sowrite_filtops
= {
194 .f_attach
= filt_sowattach
,
195 .f_detach
= filt_sowdetach
,
196 .f_event
= filt_sowrite
,
197 .f_touch
= filt_sowtouch
,
198 .f_process
= filt_sowprocess
,
201 struct filterops sock_filtops
= {
203 .f_attach
= filt_sockattach
,
204 .f_detach
= filt_sockdetach
,
205 .f_event
= filt_sockev
,
206 .f_touch
= filt_socktouch
,
207 .f_process
= filt_sockprocess
,
210 struct filterops soexcept_filtops
= {
212 .f_attach
= filt_sorattach
,
213 .f_detach
= filt_sordetach
,
214 .f_event
= filt_soread
,
215 .f_touch
= filt_sortouch
,
216 .f_process
= filt_sorprocess
,
219 SYSCTL_DECL(_kern_ipc
);
221 #define EVEN_MORE_LOCKING_DEBUG 0
223 int socket_debug
= 0;
224 SYSCTL_INT(_kern_ipc
, OID_AUTO
, socket_debug
,
225 CTLFLAG_RW
| CTLFLAG_LOCKED
, &socket_debug
, 0, "");
227 static unsigned long sodefunct_calls
= 0;
228 SYSCTL_LONG(_kern_ipc
, OID_AUTO
, sodefunct_calls
, CTLFLAG_LOCKED
,
229 &sodefunct_calls
, "");
231 static int socket_zone
= M_SOCKET
;
232 so_gen_t so_gencnt
; /* generation count for sockets */
234 MALLOC_DEFINE(M_SONAME
, "soname", "socket name");
235 MALLOC_DEFINE(M_PCB
, "pcb", "protocol control block");
237 #define DBG_LAYER_IN_BEG NETDBG_CODE(DBG_NETSOCK, 0)
238 #define DBG_LAYER_IN_END NETDBG_CODE(DBG_NETSOCK, 2)
239 #define DBG_LAYER_OUT_BEG NETDBG_CODE(DBG_NETSOCK, 1)
240 #define DBG_LAYER_OUT_END NETDBG_CODE(DBG_NETSOCK, 3)
241 #define DBG_FNC_SOSEND NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 1)
242 #define DBG_FNC_SOSEND_LIST NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 3)
243 #define DBG_FNC_SORECEIVE NETDBG_CODE(DBG_NETSOCK, (8 << 8))
244 #define DBG_FNC_SORECEIVE_LIST NETDBG_CODE(DBG_NETSOCK, (8 << 8) | 3)
245 #define DBG_FNC_SOSHUTDOWN NETDBG_CODE(DBG_NETSOCK, (9 << 8))
247 #define MAX_SOOPTGETM_SIZE (128 * MCLBYTES)
249 int somaxconn
= SOMAXCONN
;
250 SYSCTL_INT(_kern_ipc
, KIPC_SOMAXCONN
, somaxconn
,
251 CTLFLAG_RW
| CTLFLAG_LOCKED
, &somaxconn
, 0, "");
253 /* Should we get a maximum also ??? */
254 static int sosendmaxchain
= 65536;
255 static int sosendminchain
= 16384;
256 static int sorecvmincopy
= 16384;
257 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendminchain
,
258 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendminchain
, 0, "");
259 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorecvmincopy
,
260 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sorecvmincopy
, 0, "");
263 * Set to enable jumbo clusters (if available) for large writes when
264 * the socket is marked with SOF_MULTIPAGES; see below.
267 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendjcl
,
268 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendjcl
, 0, "");
271 * Set this to ignore SOF_MULTIPAGES and use jumbo clusters for large
272 * writes on the socket for all protocols on any network interfaces,
273 * depending upon sosendjcl above. Be extra careful when setting this
274 * to 1, because sending down packets that cross physical pages down to
275 * broken drivers (those that falsely assume that the physical pages
276 * are contiguous) might lead to system panics or silent data corruption.
277 * When set to 0, the system will respect SOF_MULTIPAGES, which is set
278 * only for TCP sockets whose outgoing interface is IFNET_MULTIPAGES
279 * capable. Set this to 1 only for testing/debugging purposes.
281 int sosendjcl_ignore_capab
= 0;
282 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendjcl_ignore_capab
,
283 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendjcl_ignore_capab
, 0, "");
286 * Set this to ignore SOF1_IF_2KCL and use big clusters for large
287 * writes on the socket for all protocols on any network interfaces.
288 * Be extra careful when setting this to 1, because sending down packets with
289 * clusters larger that 2 KB might lead to system panics or data corruption.
290 * When set to 0, the system will respect SOF1_IF_2KCL, which is set
291 * on the outgoing interface
292 * Set this to 1 for testing/debugging purposes only.
294 int sosendbigcl_ignore_capab
= 0;
295 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sosendbigcl_ignore_capab
,
296 CTLFLAG_RW
| CTLFLAG_LOCKED
, &sosendbigcl_ignore_capab
, 0, "");
298 int sodefunctlog
= 0;
299 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sodefunctlog
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
300 &sodefunctlog
, 0, "");
302 int sothrottlelog
= 0;
303 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sothrottlelog
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
304 &sothrottlelog
, 0, "");
306 int sorestrictrecv
= 1;
307 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorestrictrecv
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
308 &sorestrictrecv
, 0, "Enable inbound interface restrictions");
310 int sorestrictsend
= 1;
311 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sorestrictsend
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
312 &sorestrictsend
, 0, "Enable outbound interface restrictions");
314 int soreserveheadroom
= 1;
315 SYSCTL_INT(_kern_ipc
, OID_AUTO
, soreserveheadroom
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
316 &soreserveheadroom
, 0, "To allocate contiguous datagram buffers");
318 #if (DEBUG || DEVELOPMENT)
319 int so_notsent_lowat_check
= 1;
320 SYSCTL_INT(_kern_ipc
, OID_AUTO
, notsent_lowat
, CTLFLAG_RW
|CTLFLAG_LOCKED
,
321 &so_notsent_lowat_check
, 0, "enable/disable notsnet lowat check");
322 #endif /* DEBUG || DEVELOPMENT */
324 extern struct inpcbinfo tcbinfo
;
326 /* TODO: these should be in header file */
327 extern int get_inpcb_str_size(void);
328 extern int get_tcp_str_size(void);
330 static unsigned int sl_zone_size
; /* size of sockaddr_list */
331 static struct zone
*sl_zone
; /* zone for sockaddr_list */
333 static unsigned int se_zone_size
; /* size of sockaddr_entry */
334 static struct zone
*se_zone
; /* zone for sockaddr_entry */
336 vm_size_t so_cache_zone_element_size
;
338 static int sodelayed_copy(struct socket
*, struct uio
*, struct mbuf
**,
340 static void cached_sock_alloc(struct socket
**, int);
341 static void cached_sock_free(struct socket
*);
344 * Maximum of extended background idle sockets per process
345 * Set to zero to disable further setting of the option
348 #define SO_IDLE_BK_IDLE_MAX_PER_PROC 1
349 #define SO_IDLE_BK_IDLE_TIME 600
350 #define SO_IDLE_BK_IDLE_RCV_HIWAT 131072
352 struct soextbkidlestat soextbkidlestat
;
354 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, maxextbkidleperproc
,
355 CTLFLAG_RW
| CTLFLAG_LOCKED
, &soextbkidlestat
.so_xbkidle_maxperproc
, 0,
356 "Maximum of extended background idle sockets per process");
358 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, extbkidletime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
359 &soextbkidlestat
.so_xbkidle_time
, 0,
360 "Time in seconds to keep extended background idle sockets");
362 SYSCTL_UINT(_kern_ipc
, OID_AUTO
, extbkidlercvhiwat
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
363 &soextbkidlestat
.so_xbkidle_rcvhiwat
, 0,
364 "High water mark for extended background idle sockets");
366 SYSCTL_STRUCT(_kern_ipc
, OID_AUTO
, extbkidlestat
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
367 &soextbkidlestat
, soextbkidlestat
, "");
369 int so_set_extended_bk_idle(struct socket
*, int);
372 * SOTCDB_NO_DSCP is set by default, to prevent the networking stack from
373 * setting the DSCP code on the packet based on the service class; see
374 * <rdar://problem/11277343> for details.
376 __private_extern__ u_int32_t sotcdb
= 0;
377 SYSCTL_INT(_kern_ipc
, OID_AUTO
, sotcdb
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
383 _CASSERT(sizeof(so_gencnt
) == sizeof(uint64_t));
384 VERIFY(IS_P2ALIGNED(&so_gencnt
, sizeof(uint32_t)));
387 _CASSERT(sizeof(struct sa_endpoints
) == sizeof(struct user64_sa_endpoints
));
388 _CASSERT(offsetof(struct sa_endpoints
, sae_srcif
) == offsetof(struct user64_sa_endpoints
, sae_srcif
));
389 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddr
) == offsetof(struct user64_sa_endpoints
, sae_srcaddr
));
390 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddrlen
) == offsetof(struct user64_sa_endpoints
, sae_srcaddrlen
));
391 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddr
) == offsetof(struct user64_sa_endpoints
, sae_dstaddr
));
392 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddrlen
) == offsetof(struct user64_sa_endpoints
, sae_dstaddrlen
));
394 _CASSERT(sizeof(struct sa_endpoints
) == sizeof(struct user32_sa_endpoints
));
395 _CASSERT(offsetof(struct sa_endpoints
, sae_srcif
) == offsetof(struct user32_sa_endpoints
, sae_srcif
));
396 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddr
) == offsetof(struct user32_sa_endpoints
, sae_srcaddr
));
397 _CASSERT(offsetof(struct sa_endpoints
, sae_srcaddrlen
) == offsetof(struct user32_sa_endpoints
, sae_srcaddrlen
));
398 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddr
) == offsetof(struct user32_sa_endpoints
, sae_dstaddr
));
399 _CASSERT(offsetof(struct sa_endpoints
, sae_dstaddrlen
) == offsetof(struct user32_sa_endpoints
, sae_dstaddrlen
));
402 if (socketinit_done
) {
403 printf("socketinit: already called...\n");
408 PE_parse_boot_argn("socket_debug", &socket_debug
,
409 sizeof (socket_debug
));
412 * allocate lock group attribute and group for socket cache mutex
414 so_cache_mtx_grp_attr
= lck_grp_attr_alloc_init();
415 so_cache_mtx_grp
= lck_grp_alloc_init("so_cache",
416 so_cache_mtx_grp_attr
);
419 * allocate the lock attribute for socket cache mutex
421 so_cache_mtx_attr
= lck_attr_alloc_init();
423 /* cached sockets mutex */
424 so_cache_mtx
= lck_mtx_alloc_init(so_cache_mtx_grp
, so_cache_mtx_attr
);
425 if (so_cache_mtx
== NULL
) {
426 panic("%s: unable to allocate so_cache_mtx\n", __func__
);
429 STAILQ_INIT(&so_cache_head
);
431 so_cache_zone_element_size
= (vm_size_t
)(sizeof (struct socket
) + 4
432 + get_inpcb_str_size() + 4 + get_tcp_str_size());
434 so_cache_zone
= zinit(so_cache_zone_element_size
,
435 (120000 * so_cache_zone_element_size
), 8192, "socache zone");
436 zone_change(so_cache_zone
, Z_CALLERACCT
, FALSE
);
437 zone_change(so_cache_zone
, Z_NOENCRYPT
, TRUE
);
439 sl_zone_size
= sizeof (struct sockaddr_list
);
440 if ((sl_zone
= zinit(sl_zone_size
, 1024 * sl_zone_size
, 1024,
441 "sockaddr_list")) == NULL
) {
442 panic("%s: unable to allocate sockaddr_list zone\n", __func__
);
445 zone_change(sl_zone
, Z_CALLERACCT
, FALSE
);
446 zone_change(sl_zone
, Z_EXPAND
, TRUE
);
448 se_zone_size
= sizeof (struct sockaddr_entry
);
449 if ((se_zone
= zinit(se_zone_size
, 1024 * se_zone_size
, 1024,
450 "sockaddr_entry")) == NULL
) {
451 panic("%s: unable to allocate sockaddr_entry zone\n", __func__
);
454 zone_change(se_zone
, Z_CALLERACCT
, FALSE
);
455 zone_change(se_zone
, Z_EXPAND
, TRUE
);
457 bzero(&soextbkidlestat
, sizeof(struct soextbkidlestat
));
458 soextbkidlestat
.so_xbkidle_maxperproc
= SO_IDLE_BK_IDLE_MAX_PER_PROC
;
459 soextbkidlestat
.so_xbkidle_time
= SO_IDLE_BK_IDLE_TIME
;
460 soextbkidlestat
.so_xbkidle_rcvhiwat
= SO_IDLE_BK_IDLE_RCV_HIWAT
;
464 socket_tclass_init();
467 #endif /* MULTIPATH */
471 cached_sock_alloc(struct socket
**so
, int waitok
)
476 lck_mtx_lock(so_cache_mtx
);
478 if (!STAILQ_EMPTY(&so_cache_head
)) {
479 VERIFY(cached_sock_count
> 0);
481 *so
= STAILQ_FIRST(&so_cache_head
);
482 STAILQ_REMOVE_HEAD(&so_cache_head
, so_cache_ent
);
483 STAILQ_NEXT((*so
), so_cache_ent
) = NULL
;
486 lck_mtx_unlock(so_cache_mtx
);
488 temp
= (*so
)->so_saved_pcb
;
489 bzero((caddr_t
)*so
, sizeof (struct socket
));
491 (*so
)->so_saved_pcb
= temp
;
494 lck_mtx_unlock(so_cache_mtx
);
497 *so
= (struct socket
*)zalloc(so_cache_zone
);
499 *so
= (struct socket
*)zalloc_noblock(so_cache_zone
);
504 bzero((caddr_t
)*so
, sizeof (struct socket
));
507 * Define offsets for extra structures into our
508 * single block of memory. Align extra structures
509 * on longword boundaries.
512 offset
= (uintptr_t)*so
;
513 offset
+= sizeof (struct socket
);
515 offset
= ALIGN(offset
);
517 (*so
)->so_saved_pcb
= (caddr_t
)offset
;
518 offset
+= get_inpcb_str_size();
520 offset
= ALIGN(offset
);
522 ((struct inpcb
*)(void *)(*so
)->so_saved_pcb
)->inp_saved_ppcb
=
526 OSBitOrAtomic(SOF1_CACHED_IN_SOCK_LAYER
, &(*so
)->so_flags1
);
530 cached_sock_free(struct socket
*so
)
533 lck_mtx_lock(so_cache_mtx
);
535 so_cache_time
= net_uptime();
536 if (++cached_sock_count
> max_cached_sock_count
) {
538 lck_mtx_unlock(so_cache_mtx
);
539 zfree(so_cache_zone
, so
);
541 if (so_cache_hw
< cached_sock_count
)
542 so_cache_hw
= cached_sock_count
;
544 STAILQ_INSERT_TAIL(&so_cache_head
, so
, so_cache_ent
);
546 so
->cache_timestamp
= so_cache_time
;
547 lck_mtx_unlock(so_cache_mtx
);
552 so_update_last_owner_locked(struct socket
*so
, proc_t self
)
554 if (so
->last_pid
!= 0) {
556 * last_pid and last_upid should remain zero for sockets
557 * created using sock_socket. The check above achieves that
559 if (self
== PROC_NULL
)
560 self
= current_proc();
562 if (so
->last_upid
!= proc_uniqueid(self
) ||
563 so
->last_pid
!= proc_pid(self
)) {
564 so
->last_upid
= proc_uniqueid(self
);
565 so
->last_pid
= proc_pid(self
);
566 proc_getexecutableuuid(self
, so
->last_uuid
,
567 sizeof (so
->last_uuid
));
569 proc_pidoriginatoruuid(so
->so_vuuid
, sizeof(so
->so_vuuid
));
574 so_update_policy(struct socket
*so
)
576 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
)
577 (void) inp_update_policy(sotoinpcb(so
));
582 so_update_necp_policy(struct socket
*so
, struct sockaddr
*override_local_addr
,
583 struct sockaddr
*override_remote_addr
)
585 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
)
586 inp_update_necp_policy(sotoinpcb(so
), override_local_addr
,
587 override_remote_addr
, 0);
596 boolean_t rc
= FALSE
;
598 lck_mtx_lock(so_cache_mtx
);
600 so_cache_time
= net_uptime();
602 while (!STAILQ_EMPTY(&so_cache_head
)) {
603 VERIFY(cached_sock_count
> 0);
604 p
= STAILQ_FIRST(&so_cache_head
);
605 if ((so_cache_time
- p
->cache_timestamp
) <
609 STAILQ_REMOVE_HEAD(&so_cache_head
, so_cache_ent
);
612 zfree(so_cache_zone
, p
);
614 if (++n_freed
>= SO_CACHE_MAX_FREE_BATCH
) {
615 so_cache_max_freed
++;
620 /* Schedule again if there is more to cleanup */
621 if (!STAILQ_EMPTY(&so_cache_head
))
624 lck_mtx_unlock(so_cache_mtx
);
629 * Get a socket structure from our zone, and initialize it.
630 * We don't implement `waitok' yet (see comments in uipc_domain.c).
631 * Note that it would probably be better to allocate socket
632 * and PCB at the same time, but I'm not convinced that all
633 * the protocols can be easily modified to do this.
636 soalloc(int waitok
, int dom
, int type
)
640 if ((dom
== PF_INET
) && (type
== SOCK_STREAM
)) {
641 cached_sock_alloc(&so
, waitok
);
643 MALLOC_ZONE(so
, struct socket
*, sizeof (*so
), socket_zone
,
646 bzero(so
, sizeof (*so
));
649 so
->so_gencnt
= OSIncrementAtomic64((SInt64
*)&so_gencnt
);
650 so
->so_zone
= socket_zone
;
651 #if CONFIG_MACF_SOCKET
652 /* Convert waitok to M_WAITOK/M_NOWAIT for MAC Framework. */
653 if (mac_socket_label_init(so
, !waitok
) != 0) {
657 #endif /* MAC_SOCKET */
664 socreate_internal(int dom
, struct socket
**aso
, int type
, int proto
,
665 struct proc
*p
, uint32_t flags
, struct proc
*ep
)
672 extern int tcpconsdebug
;
679 prp
= pffindproto(dom
, proto
, type
);
681 prp
= pffindtype(dom
, type
);
683 if (prp
== NULL
|| prp
->pr_usrreqs
->pru_attach
== NULL
) {
684 if (pffinddomain(dom
) == NULL
)
685 return (EAFNOSUPPORT
);
687 if (pffindprotonotype(dom
, proto
) != NULL
)
690 return (EPROTONOSUPPORT
);
692 if (prp
->pr_type
!= type
)
694 so
= soalloc(1, dom
, type
);
698 if (flags
& SOCF_ASYNC
)
699 so
->so_state
|= SS_NBIO
;
701 if (flags
& SOCF_MP_SUBFLOW
) {
703 * A multipath subflow socket is used internally in the kernel,
704 * therefore it does not have a file desciptor associated by
707 so
->so_state
|= SS_NOFDREF
;
708 so
->so_flags
|= SOF_MP_SUBFLOW
;
710 #endif /* MULTIPATH */
712 TAILQ_INIT(&so
->so_incomp
);
713 TAILQ_INIT(&so
->so_comp
);
715 so
->last_upid
= proc_uniqueid(p
);
716 so
->last_pid
= proc_pid(p
);
717 proc_getexecutableuuid(p
, so
->last_uuid
, sizeof (so
->last_uuid
));
718 proc_pidoriginatoruuid(so
->so_vuuid
, sizeof(so
->so_vuuid
));
720 if (ep
!= PROC_NULL
&& ep
!= p
) {
721 so
->e_upid
= proc_uniqueid(ep
);
722 so
->e_pid
= proc_pid(ep
);
723 proc_getexecutableuuid(ep
, so
->e_uuid
, sizeof (so
->e_uuid
));
724 so
->so_flags
|= SOF_DELEGATED
;
727 so
->so_cred
= kauth_cred_proc_ref(p
);
728 if (!suser(kauth_cred_get(), NULL
))
729 so
->so_state
|= SS_PRIV
;
732 so
->so_rcv
.sb_flags
|= SB_RECV
;
733 so
->so_rcv
.sb_so
= so
->so_snd
.sb_so
= so
;
734 so
->next_lock_lr
= 0;
735 so
->next_unlock_lr
= 0;
737 #if CONFIG_MACF_SOCKET
738 mac_socket_label_associate(kauth_cred_get(), so
);
739 #endif /* MAC_SOCKET */
742 * Attachment will create the per pcb lock if necessary and
743 * increase refcount for creation, make sure it's done before
744 * socket is inserted in lists.
748 error
= (*prp
->pr_usrreqs
->pru_attach
)(so
, proto
, p
);
752 * If so_pcb is not zero, the socket will be leaked,
753 * so protocol attachment handler must be coded carefuly
755 so
->so_state
|= SS_NOFDREF
;
757 sofreelastref(so
, 1); /* will deallocate the socket */
761 atomic_add_32(&prp
->pr_domain
->dom_refs
, 1);
762 TAILQ_INIT(&so
->so_evlist
);
764 /* Attach socket filters for this protocol */
767 if (tcpconsdebug
== 2)
768 so
->so_options
|= SO_DEBUG
;
770 so_set_default_traffic_class(so
);
773 * If this thread or task is marked to create backgrounded sockets,
774 * mark the socket as background.
776 if (proc_get_effective_thread_policy(current_thread(),
777 TASK_POLICY_NEW_SOCKETS_BG
)) {
778 socket_set_traffic_mgt_flags(so
, TRAFFIC_MGT_SO_BACKGROUND
);
779 so
->so_background_thread
= current_thread();
784 * Don't mark Unix domain, system or multipath sockets as
785 * eligible for defunct by default.
790 so
->so_flags
|= SOF_NODEFUNCT
;
797 * Entitlements can't be checked at socket creation time except if the
798 * application requested a feature guarded by a privilege (c.f., socket
800 * The priv(9) and the Sandboxing APIs are designed with the idea that
801 * a privilege check should only be triggered by a userland request.
802 * A privilege check at socket creation time is time consuming and
803 * could trigger many authorisation error messages from the security
818 * <pru_attach>:ENOBUFS[AF_UNIX]
819 * <pru_attach>:ENOBUFS[TCP]
820 * <pru_attach>:ENOMEM[TCP]
821 * <pru_attach>:??? [other protocol families, IPSEC]
824 socreate(int dom
, struct socket
**aso
, int type
, int proto
)
826 return (socreate_internal(dom
, aso
, type
, proto
, current_proc(), 0,
831 socreate_delegate(int dom
, struct socket
**aso
, int type
, int proto
, pid_t epid
)
834 struct proc
*ep
= PROC_NULL
;
836 if ((proc_selfpid() != epid
) && ((ep
= proc_find(epid
)) == PROC_NULL
)) {
841 error
= socreate_internal(dom
, aso
, type
, proto
, current_proc(), 0, ep
);
844 * It might not be wise to hold the proc reference when calling
845 * socreate_internal since it calls soalloc with M_WAITOK
856 * <pru_bind>:EINVAL Invalid argument [COMMON_START]
857 * <pru_bind>:EAFNOSUPPORT Address family not supported
858 * <pru_bind>:EADDRNOTAVAIL Address not available.
859 * <pru_bind>:EINVAL Invalid argument
860 * <pru_bind>:EAFNOSUPPORT Address family not supported [notdef]
861 * <pru_bind>:EACCES Permission denied
862 * <pru_bind>:EADDRINUSE Address in use
863 * <pru_bind>:EAGAIN Resource unavailable, try again
864 * <pru_bind>:EPERM Operation not permitted
868 * Notes: It's not possible to fully enumerate the return codes above,
869 * since socket filter authors and protocol family authors may
870 * not choose to limit their error returns to those listed, even
871 * though this may result in some software operating incorrectly.
873 * The error codes which are enumerated above are those known to
874 * be returned by the tcp_usr_bind function supplied.
877 sobindlock(struct socket
*so
, struct sockaddr
*nam
, int dolock
)
879 struct proc
*p
= current_proc();
884 VERIFY(so
->so_usecount
> 1);
886 so_update_last_owner_locked(so
, p
);
887 so_update_policy(so
);
890 so_update_necp_policy(so
, nam
, NULL
);
894 * If this is a bind request on a socket that has been marked
895 * as inactive, reject it now before we go any further.
897 if (so
->so_flags
& SOF_DEFUNCT
) {
899 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
900 __func__
, proc_pid(p
), proc_best_name(p
),
901 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
902 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
907 error
= sflt_bind(so
, nam
);
910 error
= (*so
->so_proto
->pr_usrreqs
->pru_bind
)(so
, nam
, p
);
913 socket_unlock(so
, 1);
915 if (error
== EJUSTRETURN
)
922 sodealloc(struct socket
*so
)
924 kauth_cred_unref(&so
->so_cred
);
926 /* Remove any filters */
930 cfil_sock_detach(so
);
931 #endif /* CONTENT_FILTER */
933 /* Delete the state allocated for msg queues on a socket */
934 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
935 FREE(so
->so_msg_state
, M_TEMP
);
936 so
->so_msg_state
= NULL
;
938 VERIFY(so
->so_msg_state
== NULL
);
940 so
->so_gencnt
= OSIncrementAtomic64((SInt64
*)&so_gencnt
);
942 #if CONFIG_MACF_SOCKET
943 mac_socket_label_destroy(so
);
944 #endif /* MAC_SOCKET */
946 if (so
->so_flags1
& SOF1_CACHED_IN_SOCK_LAYER
) {
947 cached_sock_free(so
);
949 FREE_ZONE(so
, sizeof (*so
), so
->so_zone
);
957 * <pru_listen>:EINVAL[AF_UNIX]
958 * <pru_listen>:EINVAL[TCP]
959 * <pru_listen>:EADDRNOTAVAIL[TCP] Address not available.
960 * <pru_listen>:EINVAL[TCP] Invalid argument
961 * <pru_listen>:EAFNOSUPPORT[TCP] Address family not supported [notdef]
962 * <pru_listen>:EACCES[TCP] Permission denied
963 * <pru_listen>:EADDRINUSE[TCP] Address in use
964 * <pru_listen>:EAGAIN[TCP] Resource unavailable, try again
965 * <pru_listen>:EPERM[TCP] Operation not permitted
968 * Notes: Other <pru_listen> returns depend on the protocol family; all
969 * <sf_listen> returns depend on what the filter author causes
970 * their filter to return.
973 solisten(struct socket
*so
, int backlog
)
975 struct proc
*p
= current_proc();
980 so_update_last_owner_locked(so
, p
);
981 so_update_policy(so
);
984 so_update_necp_policy(so
, NULL
, NULL
);
987 if (so
->so_proto
== NULL
) {
991 if ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) == 0) {
997 * If the listen request is made on a socket that is not fully
998 * disconnected, or on a socket that has been marked as inactive,
999 * reject the request now.
1002 (SS_ISCONNECTED
|SS_ISCONNECTING
|SS_ISDISCONNECTING
)) ||
1003 (so
->so_flags
& SOF_DEFUNCT
)) {
1005 if (so
->so_flags
& SOF_DEFUNCT
) {
1006 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
1007 "(%d)\n", __func__
, proc_pid(p
),
1009 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1010 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1015 if ((so
->so_restrictions
& SO_RESTRICT_DENY_IN
) != 0) {
1020 error
= sflt_listen(so
);
1022 error
= (*so
->so_proto
->pr_usrreqs
->pru_listen
)(so
, p
);
1025 if (error
== EJUSTRETURN
)
1030 if (TAILQ_EMPTY(&so
->so_comp
))
1031 so
->so_options
|= SO_ACCEPTCONN
;
1033 * POSIX: The implementation may have an upper limit on the length of
1034 * the listen queue-either global or per accepting socket. If backlog
1035 * exceeds this limit, the length of the listen queue is set to the
1038 * If listen() is called with a backlog argument value that is less
1039 * than 0, the function behaves as if it had been called with a backlog
1040 * argument value of 0.
1042 * A backlog argument of 0 may allow the socket to accept connections,
1043 * in which case the length of the listen queue may be set to an
1044 * implementation-defined minimum value.
1046 if (backlog
<= 0 || backlog
> somaxconn
)
1047 backlog
= somaxconn
;
1049 so
->so_qlimit
= backlog
;
1051 socket_unlock(so
, 1);
1056 sofreelastref(struct socket
*so
, int dealloc
)
1058 struct socket
*head
= so
->so_head
;
1060 /* Assume socket is locked */
1062 if (!(so
->so_flags
& SOF_PCBCLEARING
) || !(so
->so_state
& SS_NOFDREF
)) {
1063 selthreadclear(&so
->so_snd
.sb_sel
);
1064 selthreadclear(&so
->so_rcv
.sb_sel
);
1065 so
->so_rcv
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1066 so
->so_snd
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1067 so
->so_event
= sonullevent
;
1071 socket_lock(head
, 1);
1072 if (so
->so_state
& SS_INCOMP
) {
1073 TAILQ_REMOVE(&head
->so_incomp
, so
, so_list
);
1075 } else if (so
->so_state
& SS_COMP
) {
1077 * We must not decommission a socket that's
1078 * on the accept(2) queue. If we do, then
1079 * accept(2) may hang after select(2) indicated
1080 * that the listening socket was ready.
1082 selthreadclear(&so
->so_snd
.sb_sel
);
1083 selthreadclear(&so
->so_rcv
.sb_sel
);
1084 so
->so_rcv
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1085 so
->so_snd
.sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
1086 so
->so_event
= sonullevent
;
1087 socket_unlock(head
, 1);
1090 panic("sofree: not queued");
1093 so
->so_state
&= ~SS_INCOMP
;
1095 socket_unlock(head
, 1);
1101 if (so
->so_flags
& SOF_FLOW_DIVERT
) {
1102 flow_divert_detach(so
);
1104 #endif /* FLOW_DIVERT */
1106 /* 3932268: disable upcall */
1107 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
1108 so
->so_snd
.sb_flags
&= ~(SB_UPCALL
|SB_SNDBYTE_CNT
);
1109 so
->so_event
= sonullevent
;
1116 soclose_wait_locked(struct socket
*so
)
1118 lck_mtx_t
*mutex_held
;
1120 if (so
->so_proto
->pr_getlock
!= NULL
)
1121 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1123 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1124 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1127 * Double check here and return if there's no outstanding upcall;
1128 * otherwise proceed further only if SOF_UPCALLCLOSEWAIT is set.
1130 if (!so
->so_upcallusecount
|| !(so
->so_flags
& SOF_UPCALLCLOSEWAIT
))
1132 so
->so_rcv
.sb_flags
&= ~SB_UPCALL
;
1133 so
->so_snd
.sb_flags
&= ~SB_UPCALL
;
1134 so
->so_flags
|= SOF_CLOSEWAIT
;
1135 (void) msleep((caddr_t
)&so
->so_upcallusecount
, mutex_held
, (PZERO
- 1),
1136 "soclose_wait_locked", NULL
);
1137 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1138 so
->so_flags
&= ~SOF_CLOSEWAIT
;
1142 * Close a socket on last file table reference removal.
1143 * Initiate disconnect if connected.
1144 * Free socket when disconnect complete.
1147 soclose_locked(struct socket
*so
)
1150 lck_mtx_t
*mutex_held
;
1153 if (so
->so_usecount
== 0) {
1154 panic("soclose: so=%p refcount=0\n", so
);
1158 sflt_notify(so
, sock_evt_closing
, NULL
);
1160 if (so
->so_upcallusecount
)
1161 soclose_wait_locked(so
);
1165 * We have to wait until the content filters are done
1167 if ((so
->so_flags
& SOF_CONTENT_FILTER
) != 0) {
1168 cfil_sock_close_wait(so
);
1169 cfil_sock_is_closed(so
);
1170 cfil_sock_detach(so
);
1172 #endif /* CONTENT_FILTER */
1174 if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
) {
1175 soresume(current_proc(), so
, 1);
1176 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_WANTED
;
1179 if ((so
->so_options
& SO_ACCEPTCONN
)) {
1180 struct socket
*sp
, *sonext
;
1184 * We do not want new connection to be added
1185 * to the connection queues
1187 so
->so_options
&= ~SO_ACCEPTCONN
;
1189 for (sp
= TAILQ_FIRST(&so
->so_incomp
);
1190 sp
!= NULL
; sp
= sonext
) {
1191 sonext
= TAILQ_NEXT(sp
, so_list
);
1195 * skip sockets thrown away by tcpdropdropblreq
1196 * they will get cleanup by the garbage collection.
1197 * otherwise, remove the incomp socket from the queue
1198 * and let soabort trigger the appropriate cleanup.
1200 if (sp
->so_flags
& SOF_OVERFLOW
)
1203 if (so
->so_proto
->pr_getlock
!= NULL
) {
1205 * Lock ordering for consistency with the
1206 * rest of the stack, we lock the socket
1207 * first and then grabb the head.
1209 socket_unlock(so
, 0);
1215 TAILQ_REMOVE(&so
->so_incomp
, sp
, so_list
);
1218 if (sp
->so_state
& SS_INCOMP
) {
1219 sp
->so_state
&= ~SS_INCOMP
;
1226 socket_unlock(sp
, 1);
1229 while ((sp
= TAILQ_FIRST(&so
->so_comp
)) != NULL
) {
1230 /* Dequeue from so_comp since sofree() won't do it */
1231 TAILQ_REMOVE(&so
->so_comp
, sp
, so_list
);
1234 if (so
->so_proto
->pr_getlock
!= NULL
) {
1235 socket_unlock(so
, 0);
1239 if (sp
->so_state
& SS_COMP
) {
1240 sp
->so_state
&= ~SS_COMP
;
1246 if (so
->so_proto
->pr_getlock
!= NULL
) {
1247 socket_unlock(sp
, 1);
1252 if (so
->so_pcb
== NULL
) {
1253 /* 3915887: mark the socket as ready for dealloc */
1254 so
->so_flags
|= SOF_PCBCLEARING
;
1257 if (so
->so_state
& SS_ISCONNECTED
) {
1258 if ((so
->so_state
& SS_ISDISCONNECTING
) == 0) {
1259 error
= sodisconnectlocked(so
);
1263 if (so
->so_options
& SO_LINGER
) {
1264 if ((so
->so_state
& SS_ISDISCONNECTING
) &&
1265 (so
->so_state
& SS_NBIO
))
1267 if (so
->so_proto
->pr_getlock
!= NULL
)
1268 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1270 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1271 while (so
->so_state
& SS_ISCONNECTED
) {
1272 ts
.tv_sec
= (so
->so_linger
/100);
1273 ts
.tv_nsec
= (so
->so_linger
% 100) *
1274 NSEC_PER_USEC
* 1000 * 10;
1275 error
= msleep((caddr_t
)&so
->so_timeo
,
1276 mutex_held
, PSOCK
| PCATCH
, "soclose", &ts
);
1279 * It's OK when the time fires,
1280 * don't report an error
1282 if (error
== EWOULDBLOCK
)
1290 if (so
->so_usecount
== 0) {
1291 panic("soclose: usecount is zero so=%p\n", so
);
1294 if (so
->so_pcb
!= NULL
&& !(so
->so_flags
& SOF_PCBCLEARING
)) {
1295 int error2
= (*so
->so_proto
->pr_usrreqs
->pru_detach
)(so
);
1299 if (so
->so_usecount
<= 0) {
1300 panic("soclose: usecount is zero so=%p\n", so
);
1304 if (so
->so_pcb
!= NULL
&& !(so
->so_flags
& SOF_MP_SUBFLOW
) &&
1305 (so
->so_state
& SS_NOFDREF
)) {
1306 panic("soclose: NOFDREF");
1309 so
->so_state
|= SS_NOFDREF
;
1311 if (so
->so_flags
& SOF_MP_SUBFLOW
)
1312 so
->so_flags
&= ~SOF_MP_SUBFLOW
;
1314 if ((so
->so_flags
& SOF_KNOTE
) != 0)
1315 KNOTE(&so
->so_klist
, SO_FILT_HINT_LOCKED
);
1317 atomic_add_32(&so
->so_proto
->pr_domain
->dom_refs
, -1);
1326 soclose(struct socket
*so
)
1331 if (so
->so_retaincnt
== 0) {
1332 error
= soclose_locked(so
);
1335 * if the FD is going away, but socket is
1336 * retained in kernel remove its reference
1339 if (so
->so_usecount
< 2)
1340 panic("soclose: retaincnt non null and so=%p "
1341 "usecount=%d\n", so
, so
->so_usecount
);
1343 socket_unlock(so
, 1);
1348 * Must be called at splnet...
1350 /* Should already be locked */
1352 soabort(struct socket
*so
)
1356 #ifdef MORE_LOCKING_DEBUG
1357 lck_mtx_t
*mutex_held
;
1359 if (so
->so_proto
->pr_getlock
!= NULL
)
1360 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
1362 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
1363 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
1366 if ((so
->so_flags
& SOF_ABORTED
) == 0) {
1367 so
->so_flags
|= SOF_ABORTED
;
1368 error
= (*so
->so_proto
->pr_usrreqs
->pru_abort
)(so
);
1378 soacceptlock(struct socket
*so
, struct sockaddr
**nam
, int dolock
)
1385 so_update_last_owner_locked(so
, PROC_NULL
);
1386 so_update_policy(so
);
1388 so_update_necp_policy(so
, NULL
, NULL
);
1391 if ((so
->so_state
& SS_NOFDREF
) == 0)
1392 panic("soaccept: !NOFDREF");
1393 so
->so_state
&= ~SS_NOFDREF
;
1394 error
= (*so
->so_proto
->pr_usrreqs
->pru_accept
)(so
, nam
);
1397 socket_unlock(so
, 1);
1402 soaccept(struct socket
*so
, struct sockaddr
**nam
)
1404 return (soacceptlock(so
, nam
, 1));
1408 soacceptfilter(struct socket
*so
)
1410 struct sockaddr
*local
= NULL
, *remote
= NULL
;
1412 struct socket
*head
= so
->so_head
;
1415 * Hold the lock even if this socket has not been made visible
1416 * to the filter(s). For sockets with global locks, this protects
1417 * against the head or peer going away
1420 if (sogetaddr_locked(so
, &remote
, 1) != 0 ||
1421 sogetaddr_locked(so
, &local
, 0) != 0) {
1422 so
->so_state
&= ~(SS_NOFDREF
| SS_COMP
);
1424 socket_unlock(so
, 1);
1426 /* Out of resources; try it again next time */
1427 error
= ECONNABORTED
;
1431 error
= sflt_accept(head
, so
, local
, remote
);
1434 * If we get EJUSTRETURN from one of the filters, mark this socket
1435 * as inactive and return it anyway. This newly accepted socket
1436 * will be disconnected later before we hand it off to the caller.
1438 if (error
== EJUSTRETURN
) {
1440 (void) sosetdefunct(current_proc(), so
,
1441 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
, FALSE
);
1446 * This may seem like a duplication to the above error
1447 * handling part when we return ECONNABORTED, except
1448 * the following is done while holding the lock since
1449 * the socket has been exposed to the filter(s) earlier.
1451 so
->so_state
&= ~(SS_NOFDREF
| SS_COMP
);
1453 socket_unlock(so
, 1);
1455 /* Propagate socket filter's error code to the caller */
1457 socket_unlock(so
, 1);
1460 /* Callee checks for NULL pointer */
1461 sock_freeaddr(remote
);
1462 sock_freeaddr(local
);
1467 * Returns: 0 Success
1468 * EOPNOTSUPP Operation not supported on socket
1469 * EISCONN Socket is connected
1470 * <pru_connect>:EADDRNOTAVAIL Address not available.
1471 * <pru_connect>:EINVAL Invalid argument
1472 * <pru_connect>:EAFNOSUPPORT Address family not supported [notdef]
1473 * <pru_connect>:EACCES Permission denied
1474 * <pru_connect>:EADDRINUSE Address in use
1475 * <pru_connect>:EAGAIN Resource unavailable, try again
1476 * <pru_connect>:EPERM Operation not permitted
1477 * <sf_connect_out>:??? [anything a filter writer might set]
1480 soconnectlock(struct socket
*so
, struct sockaddr
*nam
, int dolock
)
1483 struct proc
*p
= current_proc();
1488 so_update_last_owner_locked(so
, p
);
1489 so_update_policy(so
);
1492 so_update_necp_policy(so
, NULL
, nam
);
1496 * If this is a listening socket or if this is a previously-accepted
1497 * socket that has been marked as inactive, reject the connect request.
1499 if ((so
->so_options
& SO_ACCEPTCONN
) || (so
->so_flags
& SOF_DEFUNCT
)) {
1501 if (so
->so_flags
& SOF_DEFUNCT
) {
1502 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
1503 "(%d)\n", __func__
, proc_pid(p
),
1505 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1506 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1509 socket_unlock(so
, 1);
1513 if ((so
->so_restrictions
& SO_RESTRICT_DENY_OUT
) != 0) {
1515 socket_unlock(so
, 1);
1520 * If protocol is connection-based, can only connect once.
1521 * Otherwise, if connected, try to disconnect first.
1522 * This allows user to disconnect by connecting to, e.g.,
1525 if (so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
) &&
1526 ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ||
1527 (error
= sodisconnectlocked(so
)))) {
1531 * Run connect filter before calling protocol:
1532 * - non-blocking connect returns before completion;
1534 error
= sflt_connectout(so
, nam
);
1536 if (error
== EJUSTRETURN
)
1539 error
= (*so
->so_proto
->pr_usrreqs
->pru_connect
)
1544 socket_unlock(so
, 1);
1549 soconnect(struct socket
*so
, struct sockaddr
*nam
)
1551 return (soconnectlock(so
, nam
, 1));
1555 * Returns: 0 Success
1556 * <pru_connect2>:EINVAL[AF_UNIX]
1557 * <pru_connect2>:EPROTOTYPE[AF_UNIX]
1558 * <pru_connect2>:??? [other protocol families]
1560 * Notes: <pru_connect2> is not supported by [TCP].
1563 soconnect2(struct socket
*so1
, struct socket
*so2
)
1567 socket_lock(so1
, 1);
1568 if (so2
->so_proto
->pr_lock
)
1569 socket_lock(so2
, 1);
1571 error
= (*so1
->so_proto
->pr_usrreqs
->pru_connect2
)(so1
, so2
);
1573 socket_unlock(so1
, 1);
1574 if (so2
->so_proto
->pr_lock
)
1575 socket_unlock(so2
, 1);
1580 soconnectxlocked(struct socket
*so
, struct sockaddr_list
**src_sl
,
1581 struct sockaddr_list
**dst_sl
, struct proc
*p
, uint32_t ifscope
,
1582 sae_associd_t aid
, sae_connid_t
*pcid
, uint32_t flags
, void *arg
,
1583 uint32_t arglen
, uio_t auio
, user_ssize_t
*bytes_written
)
1587 so_update_last_owner_locked(so
, p
);
1588 so_update_policy(so
);
1591 * If this is a listening socket or if this is a previously-accepted
1592 * socket that has been marked as inactive, reject the connect request.
1594 if ((so
->so_options
& SO_ACCEPTCONN
) || (so
->so_flags
& SOF_DEFUNCT
)) {
1596 if (so
->so_flags
& SOF_DEFUNCT
) {
1597 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] "
1598 "(%d)\n", __func__
, proc_pid(p
),
1600 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1601 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1606 if ((so
->so_restrictions
& SO_RESTRICT_DENY_OUT
) != 0)
1610 * If protocol is connection-based, can only connect once
1611 * unless PR_MULTICONN is set. Otherwise, if connected,
1612 * try to disconnect first. This allows user to disconnect
1613 * by connecting to, e.g., a null address.
1615 if ((so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
)) &&
1616 !(so
->so_proto
->pr_flags
& PR_MULTICONN
) &&
1617 ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ||
1618 (error
= sodisconnectlocked(so
)) != 0)) {
1622 * Run connect filter before calling protocol:
1623 * - non-blocking connect returns before completion;
1625 error
= sflt_connectxout(so
, dst_sl
);
1627 /* Disable PRECONNECT_DATA, as we don't need to send a SYN anymore. */
1628 so
->so_flags1
&= ~SOF1_PRECONNECT_DATA
;
1629 if (error
== EJUSTRETURN
)
1632 error
= (*so
->so_proto
->pr_usrreqs
->pru_connectx
)
1633 (so
, src_sl
, dst_sl
, p
, ifscope
, aid
, pcid
,
1634 flags
, arg
, arglen
, auio
, bytes_written
);
1642 sodisconnectlocked(struct socket
*so
)
1646 if ((so
->so_state
& SS_ISCONNECTED
) == 0) {
1650 if (so
->so_state
& SS_ISDISCONNECTING
) {
1655 error
= (*so
->so_proto
->pr_usrreqs
->pru_disconnect
)(so
);
1657 sflt_notify(so
, sock_evt_disconnected
, NULL
);
1663 /* Locking version */
1665 sodisconnect(struct socket
*so
)
1670 error
= sodisconnectlocked(so
);
1671 socket_unlock(so
, 1);
1676 sodisconnectxlocked(struct socket
*so
, sae_associd_t aid
, sae_connid_t cid
)
1681 * Call the protocol disconnectx handler; let it handle all
1682 * matters related to the connection state of this session.
1684 error
= (*so
->so_proto
->pr_usrreqs
->pru_disconnectx
)(so
, aid
, cid
);
1687 * The event applies only for the session, not for
1688 * the disconnection of individual subflows.
1690 if (so
->so_state
& (SS_ISDISCONNECTING
|SS_ISDISCONNECTED
))
1691 sflt_notify(so
, sock_evt_disconnected
, NULL
);
1697 sodisconnectx(struct socket
*so
, sae_associd_t aid
, sae_connid_t cid
)
1702 error
= sodisconnectxlocked(so
, aid
, cid
);
1703 socket_unlock(so
, 1);
1708 sopeelofflocked(struct socket
*so
, sae_associd_t aid
, struct socket
**psop
)
1710 return ((*so
->so_proto
->pr_usrreqs
->pru_peeloff
)(so
, aid
, psop
));
1713 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1716 * sosendcheck will lock the socket buffer if it isn't locked and
1717 * verify that there is space for the data being inserted.
1719 * Returns: 0 Success
1721 * sblock:EWOULDBLOCK
1728 sosendcheck(struct socket
*so
, struct sockaddr
*addr
, user_ssize_t resid
,
1729 int32_t clen
, int32_t atomic
, int flags
, int *sblocked
,
1730 struct mbuf
*control
)
1737 if (*sblocked
== 0) {
1738 if ((so
->so_snd
.sb_flags
& SB_LOCK
) != 0 &&
1739 so
->so_send_filt_thread
!= 0 &&
1740 so
->so_send_filt_thread
== current_thread()) {
1742 * We're being called recursively from a filter,
1743 * allow this to continue. Radar 4150520.
1744 * Don't set sblocked because we don't want
1745 * to perform an unlock later.
1749 error
= sblock(&so
->so_snd
, SBLOCKWAIT(flags
));
1751 if (so
->so_flags
& SOF_DEFUNCT
)
1760 * If a send attempt is made on a socket that has been marked
1761 * as inactive (disconnected), reject the request.
1763 if (so
->so_flags
& SOF_DEFUNCT
) {
1766 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
1767 __func__
, proc_selfpid(), proc_best_name(current_proc()),
1768 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
1769 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
1773 if (so
->so_state
& SS_CANTSENDMORE
) {
1776 * Can re-inject data of half closed connections
1778 if ((so
->so_state
& SS_ISDISCONNECTED
) == 0 &&
1779 so
->so_snd
.sb_cfil_thread
== current_thread() &&
1780 cfil_sock_data_pending(&so
->so_snd
) != 0)
1782 "so %llx ignore SS_CANTSENDMORE",
1783 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
));
1785 #endif /* CONTENT_FILTER */
1789 error
= so
->so_error
;
1794 if ((so
->so_state
& SS_ISCONNECTED
) == 0) {
1795 if ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) != 0) {
1796 if (((so
->so_state
& SS_ISCONFIRMING
) == 0) &&
1797 (resid
!= 0 || clen
== 0) &&
1798 !(so
->so_flags1
& SOF1_PRECONNECT_DATA
)) {
1801 * MPTCP Fast Join sends data before the
1802 * socket is truly connected.
1804 if ((so
->so_flags
& (SOF_MP_SUBFLOW
|
1805 SOF_MPTCP_FASTJOIN
)) !=
1806 (SOF_MP_SUBFLOW
| SOF_MPTCP_FASTJOIN
))
1810 } else if (addr
== 0 && !(flags
&MSG_HOLD
)) {
1811 return ((so
->so_proto
->pr_flags
& PR_CONNREQUIRED
) ?
1812 ENOTCONN
: EDESTADDRREQ
);
1816 if (so
->so_flags
& SOF_ENABLE_MSGS
)
1817 space
= msgq_sbspace(so
, control
);
1819 space
= sbspace(&so
->so_snd
);
1821 if (flags
& MSG_OOB
)
1823 if ((atomic
&& resid
> so
->so_snd
.sb_hiwat
) ||
1824 clen
> so
->so_snd
.sb_hiwat
)
1827 if ((space
< resid
+ clen
&&
1828 (atomic
|| (space
< (int32_t)so
->so_snd
.sb_lowat
) ||
1830 (so
->so_type
== SOCK_STREAM
&& so_wait_for_if_feedback(so
))) {
1832 * don't block the connectx call when there's more data
1833 * than can be copied.
1835 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
1837 return (EWOULDBLOCK
);
1839 if (space
< (int32_t)so
->so_snd
.sb_lowat
) {
1843 if ((so
->so_state
& SS_NBIO
) || (flags
& MSG_NBIO
) ||
1845 return (EWOULDBLOCK
);
1847 sbunlock(&so
->so_snd
, TRUE
); /* keep socket locked */
1849 error
= sbwait(&so
->so_snd
);
1851 if (so
->so_flags
& SOF_DEFUNCT
)
1862 * If send must go all at once and message is larger than
1863 * send buffering, then hard error.
1864 * Lock against other senders.
1865 * If must go all at once and not enough room now, then
1866 * inform user that this would block and do nothing.
1867 * Otherwise, if nonblocking, send as much as possible.
1868 * The data to be sent is described by "uio" if nonzero,
1869 * otherwise by the mbuf chain "top" (which must be null
1870 * if uio is not). Data provided in mbuf chain must be small
1871 * enough to send all at once.
1873 * Returns nonzero on error, timeout or signal; callers
1874 * must check for short counts if EINTR/ERESTART are returned.
1875 * Data and control buffers are freed on return.
1877 * MSG_HOLD: go thru most of sosend(), but just enqueue the mbuf
1878 * MSG_SEND: go thru as for MSG_HOLD on current fragment, then
1879 * point at the mbuf chain being constructed and go from there.
1881 * Returns: 0 Success
1887 * sosendcheck:EWOULDBLOCK
1891 * sosendcheck:??? [value from so_error]
1892 * <pru_send>:ECONNRESET[TCP]
1893 * <pru_send>:EINVAL[TCP]
1894 * <pru_send>:ENOBUFS[TCP]
1895 * <pru_send>:EADDRINUSE[TCP]
1896 * <pru_send>:EADDRNOTAVAIL[TCP]
1897 * <pru_send>:EAFNOSUPPORT[TCP]
1898 * <pru_send>:EACCES[TCP]
1899 * <pru_send>:EAGAIN[TCP]
1900 * <pru_send>:EPERM[TCP]
1901 * <pru_send>:EMSGSIZE[TCP]
1902 * <pru_send>:EHOSTUNREACH[TCP]
1903 * <pru_send>:ENETUNREACH[TCP]
1904 * <pru_send>:ENETDOWN[TCP]
1905 * <pru_send>:ENOMEM[TCP]
1906 * <pru_send>:ENOBUFS[TCP]
1907 * <pru_send>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
1908 * <pru_send>:EINVAL[AF_UNIX]
1909 * <pru_send>:EOPNOTSUPP[AF_UNIX]
1910 * <pru_send>:EPIPE[AF_UNIX]
1911 * <pru_send>:ENOTCONN[AF_UNIX]
1912 * <pru_send>:EISCONN[AF_UNIX]
1913 * <pru_send>:???[AF_UNIX] [whatever a filter author chooses]
1914 * <sf_data_out>:??? [whatever a filter author chooses]
1916 * Notes: Other <pru_send> returns depend on the protocol family; all
1917 * <sf_data_out> returns depend on what the filter author causes
1918 * their filter to return.
1921 sosend(struct socket
*so
, struct sockaddr
*addr
, struct uio
*uio
,
1922 struct mbuf
*top
, struct mbuf
*control
, int flags
)
1925 struct mbuf
*m
, *freelist
= NULL
;
1926 user_ssize_t space
, len
, resid
, orig_resid
;
1927 int clen
= 0, error
, dontroute
, mlen
, sendflags
;
1928 int atomic
= sosendallatonce(so
) || top
;
1930 struct proc
*p
= current_proc();
1931 struct mbuf
*control_copy
= NULL
;
1932 uint16_t headroom
= 0;
1933 boolean_t en_tracing
= FALSE
;
1936 resid
= uio_resid(uio
);
1938 resid
= top
->m_pkthdr
.len
;
1940 KERNEL_DEBUG((DBG_FNC_SOSEND
| DBG_FUNC_START
), so
, resid
,
1941 so
->so_snd
.sb_cc
, so
->so_snd
.sb_lowat
, so
->so_snd
.sb_hiwat
);
1946 * trace if tracing & network (vs. unix) sockets & and
1949 if (ENTR_SHOULDTRACE
&&
1950 (SOCK_CHECK_DOM(so
, AF_INET
) || SOCK_CHECK_DOM(so
, AF_INET6
))) {
1951 struct inpcb
*inp
= sotoinpcb(so
);
1952 if (inp
->inp_last_outifp
!= NULL
&&
1953 !(inp
->inp_last_outifp
->if_flags
& IFF_LOOPBACK
)) {
1955 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite
, DBG_FUNC_START
,
1956 VM_KERNEL_ADDRPERM(so
),
1957 ((so
->so_state
& SS_NBIO
) ? kEnTrFlagNonBlocking
: 0),
1964 * Re-injection should not affect process accounting
1966 if ((flags
& MSG_SKIPCFIL
) == 0) {
1967 so_update_last_owner_locked(so
, p
);
1968 so_update_policy(so
);
1971 so_update_necp_policy(so
, NULL
, addr
);
1975 if (so
->so_type
!= SOCK_STREAM
&& (flags
& MSG_OOB
) != 0) {
1977 socket_unlock(so
, 1);
1982 * In theory resid should be unsigned.
1983 * However, space must be signed, as it might be less than 0
1984 * if we over-committed, and we must use a signed comparison
1985 * of space and resid. On the other hand, a negative resid
1986 * causes us to loop sending 0-length segments to the protocol.
1988 * Usually, MSG_EOR isn't used on SOCK_STREAM type sockets.
1989 * But it will be used by sockets doing message delivery.
1991 * Note: We limit resid to be a positive int value as we use
1992 * imin() to set bytes_to_copy -- radr://14558484
1994 if (resid
< 0 || resid
> INT_MAX
|| (so
->so_type
== SOCK_STREAM
&&
1995 !(so
->so_flags
& SOF_ENABLE_MSGS
) && (flags
& MSG_EOR
))) {
1997 socket_unlock(so
, 1);
2001 dontroute
= (flags
& MSG_DONTROUTE
) &&
2002 (so
->so_options
& SO_DONTROUTE
) == 0 &&
2003 (so
->so_proto
->pr_flags
& PR_ATOMIC
);
2004 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgsnd
);
2006 if (control
!= NULL
)
2007 clen
= control
->m_len
;
2009 if (soreserveheadroom
!= 0)
2010 headroom
= so
->so_pktheadroom
;
2013 error
= sosendcheck(so
, addr
, resid
, clen
, atomic
, flags
,
2014 &sblocked
, control
);
2019 if (so
->so_flags
& SOF_ENABLE_MSGS
)
2020 space
= msgq_sbspace(so
, control
);
2022 space
= sbspace(&so
->so_snd
) - clen
;
2023 space
+= ((flags
& MSG_OOB
) ? 1024 : 0);
2028 * Data is prepackaged in "top".
2031 if (flags
& MSG_EOR
)
2032 top
->m_flags
|= M_EOR
;
2040 bytes_to_copy
= imin(resid
, space
);
2042 bytes_to_alloc
= bytes_to_copy
;
2044 bytes_to_alloc
+= headroom
;
2046 if (sosendminchain
> 0)
2049 chainlength
= sosendmaxchain
;
2052 * Use big 4 KB cluster when the outgoing interface
2053 * does not prefer 2 KB clusters
2055 bigcl
= !(so
->so_flags1
& SOF1_IF_2KCL
) ||
2056 sosendbigcl_ignore_capab
;
2059 * Attempt to use larger than system page-size
2060 * clusters for large writes only if there is
2061 * a jumbo cluster pool and if the socket is
2062 * marked accordingly.
2064 jumbocl
= sosendjcl
&& njcl
> 0 &&
2065 ((so
->so_flags
& SOF_MULTIPAGES
) ||
2066 sosendjcl_ignore_capab
) &&
2069 socket_unlock(so
, 0);
2073 int hdrs_needed
= (top
== NULL
) ? 1 : 0;
2076 * try to maintain a local cache of mbuf
2077 * clusters needed to complete this
2078 * write the list is further limited to
2079 * the number that are currently needed
2080 * to fill the socket this mechanism
2081 * allows a large number of mbufs/
2082 * clusters to be grabbed under a single
2083 * mbuf lock... if we can't get any
2084 * clusters, than fall back to trying
2085 * for mbufs if we fail early (or
2086 * miscalcluate the number needed) make
2087 * sure to release any clusters we
2088 * haven't yet consumed.
2090 if (freelist
== NULL
&&
2091 bytes_to_alloc
> MBIGCLBYTES
&&
2094 bytes_to_alloc
/ M16KCLBYTES
;
2096 if ((bytes_to_alloc
-
2097 (num_needed
* M16KCLBYTES
))
2102 m_getpackets_internal(
2103 (unsigned int *)&num_needed
,
2104 hdrs_needed
, M_WAIT
, 0,
2107 * Fall back to 4K cluster size
2108 * if allocation failed
2112 if (freelist
== NULL
&&
2113 bytes_to_alloc
> MCLBYTES
&&
2116 bytes_to_alloc
/ MBIGCLBYTES
;
2118 if ((bytes_to_alloc
-
2119 (num_needed
* MBIGCLBYTES
)) >=
2124 m_getpackets_internal(
2125 (unsigned int *)&num_needed
,
2126 hdrs_needed
, M_WAIT
, 0,
2129 * Fall back to cluster size
2130 * if allocation failed
2135 * Allocate a cluster as we want to
2136 * avoid to split the data in more
2137 * that one segment and using MINCLSIZE
2138 * would lead us to allocate two mbufs
2140 if (soreserveheadroom
!= 0 &&
2143 bytes_to_alloc
> _MHLEN
) ||
2144 bytes_to_alloc
> _MLEN
)) {
2145 num_needed
= ROUNDUP(bytes_to_alloc
, MCLBYTES
) /
2148 m_getpackets_internal(
2149 (unsigned int *)&num_needed
,
2150 hdrs_needed
, M_WAIT
, 0,
2153 * Fall back to a single mbuf
2154 * if allocation failed
2156 } else if (freelist
== NULL
&&
2157 bytes_to_alloc
> MINCLSIZE
) {
2159 bytes_to_alloc
/ MCLBYTES
;
2161 if ((bytes_to_alloc
-
2162 (num_needed
* MCLBYTES
)) >=
2167 m_getpackets_internal(
2168 (unsigned int *)&num_needed
,
2169 hdrs_needed
, M_WAIT
, 0,
2172 * Fall back to a single mbuf
2173 * if allocation failed
2177 * For datagram protocols, leave
2178 * headroom for protocol headers
2179 * in the first cluster of the chain
2181 if (freelist
!= NULL
&& atomic
&&
2182 top
== NULL
&& headroom
> 0) {
2183 freelist
->m_data
+= headroom
;
2187 * Fall back to regular mbufs without
2188 * reserving the socket headroom
2190 if (freelist
== NULL
) {
2198 if (freelist
== NULL
) {
2204 * For datagram protocols,
2205 * leave room for protocol
2206 * headers in first mbuf.
2208 if (atomic
&& top
== NULL
&&
2209 bytes_to_copy
< MHLEN
) {
2215 freelist
= m
->m_next
;
2218 if ((m
->m_flags
& M_EXT
))
2219 mlen
= m
->m_ext
.ext_size
-
2221 else if ((m
->m_flags
& M_PKTHDR
))
2223 MHLEN
- m_leadingspace(m
);
2225 mlen
= MLEN
- m_leadingspace(m
);
2226 len
= imin(mlen
, bytes_to_copy
);
2232 error
= uiomove(mtod(m
, caddr_t
),
2235 resid
= uio_resid(uio
);
2239 top
->m_pkthdr
.len
+= len
;
2244 if (flags
& MSG_EOR
)
2245 top
->m_flags
|= M_EOR
;
2248 bytes_to_copy
= min(resid
, space
);
2250 } while (space
> 0 &&
2251 (chainlength
< sosendmaxchain
|| atomic
||
2252 resid
< MINCLSIZE
));
2260 if (flags
& (MSG_HOLD
|MSG_SEND
)) {
2261 /* Enqueue for later, go away if HOLD */
2263 if (so
->so_temp
&& (flags
& MSG_FLUSH
)) {
2264 m_freem(so
->so_temp
);
2268 so
->so_tail
->m_next
= top
;
2275 if (flags
& MSG_HOLD
) {
2282 so
->so_options
|= SO_DONTROUTE
;
2285 * Compute flags here, for pru_send and NKEs
2287 * If the user set MSG_EOF, the protocol
2288 * understands this flag and nothing left to
2289 * send then use PRU_SEND_EOF instead of PRU_SEND.
2291 sendflags
= (flags
& MSG_OOB
) ? PRUS_OOB
:
2292 ((flags
& MSG_EOF
) &&
2293 (so
->so_proto
->pr_flags
& PR_IMPLOPCL
) &&
2294 (resid
<= 0)) ? PRUS_EOF
:
2295 /* If there is more to send set PRUS_MORETOCOME */
2296 (resid
> 0 && space
> 0) ? PRUS_MORETOCOME
: 0;
2298 if ((flags
& MSG_SKIPCFIL
) == 0) {
2300 * Socket filter processing
2302 error
= sflt_data_out(so
, addr
, &top
,
2303 &control
, (sendflags
& MSG_OOB
) ?
2304 sock_data_filt_flag_oob
: 0);
2306 if (error
== EJUSTRETURN
) {
2316 * Content filter processing
2318 error
= cfil_sock_data_out(so
, addr
, top
,
2319 control
, (sendflags
& MSG_OOB
) ?
2320 sock_data_filt_flag_oob
: 0);
2322 if (error
== EJUSTRETURN
) {
2330 #endif /* CONTENT_FILTER */
2332 if (so
->so_flags
& SOF_ENABLE_MSGS
) {
2334 * Make a copy of control mbuf,
2335 * so that msg priority can be
2336 * passed to subsequent mbufs.
2338 control_copy
= m_dup(control
, M_NOWAIT
);
2340 error
= (*so
->so_proto
->pr_usrreqs
->pru_send
)
2341 (so
, sendflags
, top
, addr
, control
, p
);
2343 if (flags
& MSG_SEND
)
2347 so
->so_options
&= ~SO_DONTROUTE
;
2350 control
= control_copy
;
2351 control_copy
= NULL
;
2356 } while (resid
&& space
> 0);
2361 sbunlock(&so
->so_snd
, FALSE
); /* will unlock socket */
2363 socket_unlock(so
, 1);
2367 if (control
!= NULL
)
2369 if (freelist
!= NULL
)
2370 m_freem_list(freelist
);
2371 if (control_copy
!= NULL
)
2372 m_freem(control_copy
);
2375 * One write has been done. This was enough. Get back to "normal"
2378 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
)
2379 so
->so_flags1
&= ~SOF1_PRECONNECT_DATA
;
2382 /* resid passed here is the bytes left in uio */
2383 KERNEL_ENERGYTRACE(kEnTrActKernSockWrite
, DBG_FUNC_END
,
2384 VM_KERNEL_ADDRPERM(so
),
2385 ((error
== EWOULDBLOCK
) ? kEnTrFlagNoWork
: 0),
2386 (int64_t)(orig_resid
- resid
));
2388 KERNEL_DEBUG(DBG_FNC_SOSEND
| DBG_FUNC_END
, so
, resid
,
2389 so
->so_snd
.sb_cc
, space
, error
);
2395 * Supported only connected sockets (no address) without ancillary data
2396 * (control mbuf) for atomic protocols
2399 sosend_list(struct socket
*so
, struct uio
**uioarray
, u_int uiocnt
, int flags
)
2401 struct mbuf
*m
, *freelist
= NULL
;
2402 user_ssize_t len
, resid
;
2403 int error
, dontroute
, mlen
;
2404 int atomic
= sosendallatonce(so
);
2406 struct proc
*p
= current_proc();
2409 struct mbuf
*top
= NULL
;
2410 uint16_t headroom
= 0;
2413 KERNEL_DEBUG((DBG_FNC_SOSEND_LIST
| DBG_FUNC_START
), so
, uiocnt
,
2414 so
->so_snd
.sb_cc
, so
->so_snd
.sb_lowat
, so
->so_snd
.sb_hiwat
);
2416 if (so
->so_type
!= SOCK_DGRAM
) {
2424 if (so
->so_proto
->pr_usrreqs
->pru_send_list
== NULL
) {
2425 error
= EPROTONOSUPPORT
;
2428 if (flags
& ~(MSG_DONTWAIT
| MSG_NBIO
)) {
2432 resid
= uio_array_resid(uioarray
, uiocnt
);
2435 * In theory resid should be unsigned.
2436 * However, space must be signed, as it might be less than 0
2437 * if we over-committed, and we must use a signed comparison
2438 * of space and resid. On the other hand, a negative resid
2439 * causes us to loop sending 0-length segments to the protocol.
2441 * Note: We limit resid to be a positive int value as we use
2442 * imin() to set bytes_to_copy -- radr://14558484
2444 if (resid
< 0 || resid
> INT_MAX
) {
2450 so_update_last_owner_locked(so
, p
);
2451 so_update_policy(so
);
2454 so_update_necp_policy(so
, NULL
, NULL
);
2457 dontroute
= (flags
& MSG_DONTROUTE
) &&
2458 (so
->so_options
& SO_DONTROUTE
) == 0 &&
2459 (so
->so_proto
->pr_flags
& PR_ATOMIC
);
2460 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgsnd
);
2462 error
= sosendcheck(so
, NULL
, resid
, 0, atomic
, flags
,
2468 * Use big 4 KB clusters when the outgoing interface does not prefer
2471 bigcl
= !(so
->so_flags1
& SOF1_IF_2KCL
) || sosendbigcl_ignore_capab
;
2473 if (soreserveheadroom
!= 0)
2474 headroom
= so
->so_pktheadroom
;
2480 size_t maxpktlen
= 0;
2483 if (sosendminchain
> 0)
2486 chainlength
= sosendmaxchain
;
2488 socket_unlock(so
, 0);
2491 * Find a set of uio that fit in a reasonable number
2494 for (i
= uiofirst
; i
< uiocnt
; i
++) {
2495 struct uio
*auio
= uioarray
[i
];
2497 len
= uio_resid(auio
);
2499 /* Do nothing for empty messages */
2506 if (len
> maxpktlen
)
2510 if (chainlength
> sosendmaxchain
)
2514 * Nothing left to send
2516 if (num_needed
== 0) {
2521 * Allocate buffer large enough to include headroom space for
2522 * network and link header
2525 bytes_to_alloc
= maxpktlen
+ headroom
;
2528 * Allocate a single contiguous buffer of the smallest available
2529 * size when possible
2531 if (bytes_to_alloc
> MCLBYTES
&&
2532 bytes_to_alloc
<= MBIGCLBYTES
&& bigcl
) {
2533 freelist
= m_getpackets_internal(
2534 (unsigned int *)&num_needed
,
2535 num_needed
, M_WAIT
, 1,
2537 } else if (bytes_to_alloc
> _MHLEN
&&
2538 bytes_to_alloc
<= MCLBYTES
) {
2539 freelist
= m_getpackets_internal(
2540 (unsigned int *)&num_needed
,
2541 num_needed
, M_WAIT
, 1,
2544 freelist
= m_allocpacket_internal(
2545 (unsigned int *)&num_needed
,
2546 bytes_to_alloc
, NULL
, M_WAIT
, 1, 0);
2549 if (freelist
== NULL
) {
2555 * Copy each uio of the set into its own mbuf packet
2557 for (i
= uiofirst
, m
= freelist
;
2558 i
< uiolast
&& m
!= NULL
;
2562 struct uio
*auio
= uioarray
[i
];
2564 bytes_to_copy
= uio_resid(auio
);
2566 /* Do nothing for empty messages */
2567 if (bytes_to_copy
== 0)
2570 * Leave headroom for protocol headers
2571 * in the first mbuf of the chain
2573 m
->m_data
+= headroom
;
2575 for (n
= m
; n
!= NULL
; n
= n
->m_next
) {
2576 if ((m
->m_flags
& M_EXT
))
2577 mlen
= m
->m_ext
.ext_size
-
2579 else if ((m
->m_flags
& M_PKTHDR
))
2581 MHLEN
- m_leadingspace(m
);
2583 mlen
= MLEN
- m_leadingspace(m
);
2584 len
= imin(mlen
, bytes_to_copy
);
2587 * Note: uiomove() decrements the iovec
2590 error
= uiomove(mtod(n
, caddr_t
),
2595 m
->m_pkthdr
.len
+= len
;
2597 VERIFY(m
->m_pkthdr
.len
<= maxpktlen
);
2599 bytes_to_copy
-= len
;
2602 if (m
->m_pkthdr
.len
== 0) {
2604 "%s:%d so %llx pkt %llx type %u len null\n",
2606 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
2607 (uint64_t)DEBUG_KERNEL_ADDRPERM(m
),
2623 so
->so_options
|= SO_DONTROUTE
;
2625 if ((flags
& MSG_SKIPCFIL
) == 0) {
2626 struct mbuf
**prevnextp
= NULL
;
2628 for (i
= uiofirst
, m
= top
;
2629 i
< uiolast
&& m
!= NULL
;
2631 struct mbuf
*nextpkt
= m
->m_nextpkt
;
2634 * Socket filter processing
2636 error
= sflt_data_out(so
, NULL
, &m
,
2638 if (error
!= 0 && error
!= EJUSTRETURN
)
2644 * Content filter processing
2646 error
= cfil_sock_data_out(so
, NULL
, m
,
2648 if (error
!= 0 && error
!= EJUSTRETURN
)
2651 #endif /* CONTENT_FILTER */
2653 * Remove packet from the list when
2654 * swallowed by a filter
2656 if (error
== EJUSTRETURN
) {
2658 if (prevnextp
!= NULL
)
2659 *prevnextp
= nextpkt
;
2666 prevnextp
= &m
->m_nextpkt
;
2670 error
= (*so
->so_proto
->pr_usrreqs
->pru_send_list
)
2671 (so
, 0, top
, NULL
, NULL
, p
);
2674 so
->so_options
&= ~SO_DONTROUTE
;
2678 } while (resid
> 0 && error
== 0);
2681 sbunlock(&so
->so_snd
, FALSE
); /* will unlock socket */
2683 socket_unlock(so
, 1);
2687 if (freelist
!= NULL
)
2688 m_freem_list(freelist
);
2690 KERNEL_DEBUG(DBG_FNC_SOSEND_LIST
| DBG_FUNC_END
, so
, resid
,
2691 so
->so_snd
.sb_cc
, 0, error
);
2697 * May return ERESTART when packet is dropped by MAC policy check
2700 soreceive_addr(struct proc
*p
, struct socket
*so
, struct sockaddr
**psa
,
2701 int flags
, struct mbuf
**mp
, struct mbuf
**nextrecordp
, int canwait
)
2704 struct mbuf
*m
= *mp
;
2705 struct mbuf
*nextrecord
= *nextrecordp
;
2707 KASSERT(m
->m_type
== MT_SONAME
, ("receive 1a"));
2708 #if CONFIG_MACF_SOCKET_SUBSET
2710 * Call the MAC framework for policy checking if we're in
2711 * the user process context and the socket isn't connected.
2713 if (p
!= kernproc
&& !(so
->so_state
& SS_ISCONNECTED
)) {
2714 struct mbuf
*m0
= m
;
2716 * Dequeue this record (temporarily) from the receive
2717 * list since we're about to drop the socket's lock
2718 * where a new record may arrive and be appended to
2719 * the list. Upon MAC policy failure, the record
2720 * will be freed. Otherwise, we'll add it back to
2721 * the head of the list. We cannot rely on SB_LOCK
2722 * because append operation uses the socket's lock.
2725 m
->m_nextpkt
= NULL
;
2726 sbfree(&so
->so_rcv
, m
);
2728 } while (m
!= NULL
);
2730 so
->so_rcv
.sb_mb
= nextrecord
;
2731 SB_EMPTY_FIXUP(&so
->so_rcv
);
2732 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1a");
2733 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1a");
2734 socket_unlock(so
, 0);
2736 if (mac_socket_check_received(proc_ucred(p
), so
,
2737 mtod(m
, struct sockaddr
*)) != 0) {
2739 * MAC policy failure; free this record and
2740 * process the next record (or block until
2741 * one is available). We have adjusted sb_cc
2742 * and sb_mbcnt above so there is no need to
2743 * call sbfree() again.
2747 * Clear SB_LOCK but don't unlock the socket.
2748 * Process the next record or wait for one.
2751 sbunlock(&so
->so_rcv
, TRUE
); /* stay locked */
2757 * If the socket has been defunct'd, drop it.
2759 if (so
->so_flags
& SOF_DEFUNCT
) {
2765 * Re-adjust the socket receive list and re-enqueue
2766 * the record in front of any packets which may have
2767 * been appended while we dropped the lock.
2769 for (m
= m0
; m
->m_next
!= NULL
; m
= m
->m_next
)
2770 sballoc(&so
->so_rcv
, m
);
2771 sballoc(&so
->so_rcv
, m
);
2772 if (so
->so_rcv
.sb_mb
== NULL
) {
2773 so
->so_rcv
.sb_lastrecord
= m0
;
2774 so
->so_rcv
.sb_mbtail
= m
;
2777 nextrecord
= m
->m_nextpkt
= so
->so_rcv
.sb_mb
;
2778 so
->so_rcv
.sb_mb
= m
;
2779 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1b");
2780 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1b");
2782 #endif /* CONFIG_MACF_SOCKET_SUBSET */
2784 *psa
= dup_sockaddr(mtod(m
, struct sockaddr
*), canwait
);
2785 if ((*psa
== NULL
) && (flags
& MSG_NEEDSA
)) {
2786 error
= EWOULDBLOCK
;
2790 if (flags
& MSG_PEEK
) {
2793 sbfree(&so
->so_rcv
, m
);
2794 if (m
->m_next
== NULL
&& so
->so_rcv
.sb_cc
!= 0) {
2795 panic("%s: about to create invalid socketbuf",
2799 MFREE(m
, so
->so_rcv
.sb_mb
);
2800 m
= so
->so_rcv
.sb_mb
;
2802 m
->m_nextpkt
= nextrecord
;
2804 so
->so_rcv
.sb_mb
= nextrecord
;
2805 SB_EMPTY_FIXUP(&so
->so_rcv
);
2810 *nextrecordp
= nextrecord
;
2816 * Process one or more MT_CONTROL mbufs present before any data mbufs
2817 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
2818 * just copy the data; if !MSG_PEEK, we call into the protocol to
2819 * perform externalization.
2822 soreceive_ctl(struct socket
*so
, struct mbuf
**controlp
, int flags
,
2823 struct mbuf
**mp
, struct mbuf
**nextrecordp
)
2826 struct mbuf
*cm
= NULL
, *cmn
;
2827 struct mbuf
**cme
= &cm
;
2828 struct sockbuf
*sb_rcv
= &so
->so_rcv
;
2829 struct mbuf
**msgpcm
= NULL
;
2830 struct mbuf
*m
= *mp
;
2831 struct mbuf
*nextrecord
= *nextrecordp
;
2832 struct protosw
*pr
= so
->so_proto
;
2835 * Externalizing the control messages would require us to
2836 * drop the socket's lock below. Once we re-acquire the
2837 * lock, the mbuf chain might change. In order to preserve
2838 * consistency, we unlink all control messages from the
2839 * first mbuf chain in one shot and link them separately
2840 * onto a different chain.
2843 if (flags
& MSG_PEEK
) {
2844 if (controlp
!= NULL
) {
2845 if (*controlp
== NULL
) {
2848 *controlp
= m_copy(m
, 0, m
->m_len
);
2851 * If we failed to allocate an mbuf,
2852 * release any previously allocated
2853 * mbufs for control data. Return
2854 * an error. Keep the mbufs in the
2855 * socket as this is using
2858 if (*controlp
== NULL
) {
2863 controlp
= &(*controlp
)->m_next
;
2867 m
->m_nextpkt
= NULL
;
2869 sb_rcv
->sb_mb
= m
->m_next
;
2872 cme
= &(*cme
)->m_next
;
2875 } while (m
!= NULL
&& m
->m_type
== MT_CONTROL
);
2877 if (!(flags
& MSG_PEEK
)) {
2878 if (sb_rcv
->sb_mb
!= NULL
) {
2879 sb_rcv
->sb_mb
->m_nextpkt
= nextrecord
;
2881 sb_rcv
->sb_mb
= nextrecord
;
2882 SB_EMPTY_FIXUP(sb_rcv
);
2884 if (nextrecord
== NULL
)
2885 sb_rcv
->sb_lastrecord
= m
;
2888 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive ctl");
2889 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive ctl");
2891 while (cm
!= NULL
) {
2896 cmsg_type
= mtod(cm
, struct cmsghdr
*)->cmsg_type
;
2899 * Call the protocol to externalize SCM_RIGHTS message
2900 * and return the modified message to the caller upon
2901 * success. Otherwise, all other control messages are
2902 * returned unmodified to the caller. Note that we
2903 * only get into this loop if MSG_PEEK is not set.
2905 if (pr
->pr_domain
->dom_externalize
!= NULL
&&
2906 cmsg_type
== SCM_RIGHTS
) {
2908 * Release socket lock: see 3903171. This
2909 * would also allow more records to be appended
2910 * to the socket buffer. We still have SB_LOCK
2911 * set on it, so we can be sure that the head
2912 * of the mbuf chain won't change.
2914 socket_unlock(so
, 0);
2915 error
= (*pr
->pr_domain
->dom_externalize
)(cm
);
2921 if (controlp
!= NULL
&& error
== 0) {
2923 controlp
= &(*controlp
)->m_next
;
2930 * Update the value of nextrecord in case we received new
2931 * records when the socket was unlocked above for
2932 * externalizing SCM_RIGHTS.
2935 nextrecord
= sb_rcv
->sb_mb
->m_nextpkt
;
2937 nextrecord
= sb_rcv
->sb_mb
;
2941 *nextrecordp
= nextrecord
;
2947 * Implement receive operations on a socket.
2948 * We depend on the way that records are added to the sockbuf
2949 * by sbappend*. In particular, each record (mbufs linked through m_next)
2950 * must begin with an address if the protocol so specifies,
2951 * followed by an optional mbuf or mbufs containing ancillary data,
2952 * and then zero or more mbufs of data.
2953 * In order to avoid blocking network interrupts for the entire time here,
2954 * we splx() while doing the actual copy to user space.
2955 * Although the sockbuf is locked, new data may still be appended,
2956 * and thus we must maintain consistency of the sockbuf during that time.
2958 * The caller may receive the data as a single mbuf chain by supplying
2959 * an mbuf **mp0 for use in returning the chain. The uio is then used
2960 * only for the count in uio_resid.
2962 * Returns: 0 Success
2967 * sblock:EWOULDBLOCK
2971 * sodelayed_copy:EFAULT
2972 * <pru_rcvoob>:EINVAL[TCP]
2973 * <pru_rcvoob>:EWOULDBLOCK[TCP]
2975 * <pr_domain->dom_externalize>:EMSGSIZE[AF_UNIX]
2976 * <pr_domain->dom_externalize>:ENOBUFS[AF_UNIX]
2977 * <pr_domain->dom_externalize>:???
2979 * Notes: Additional return values from calls through <pru_rcvoob> and
2980 * <pr_domain->dom_externalize> depend on protocols other than
2981 * TCP or AF_UNIX, which are documented above.
2984 soreceive(struct socket
*so
, struct sockaddr
**psa
, struct uio
*uio
,
2985 struct mbuf
**mp0
, struct mbuf
**controlp
, int *flagsp
)
2987 struct mbuf
*m
, **mp
, *ml
= NULL
;
2988 struct mbuf
*nextrecord
, *free_list
;
2989 int flags
, error
, offset
;
2991 struct protosw
*pr
= so
->so_proto
;
2993 user_ssize_t orig_resid
= uio_resid(uio
);
2994 user_ssize_t delayed_copy_len
;
2997 struct proc
*p
= current_proc();
2998 boolean_t en_tracing
= FALSE
;
3001 * Sanity check on the length passed by caller as we are making 'int'
3004 if (orig_resid
< 0 || orig_resid
> INT_MAX
)
3007 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_START
, so
,
3008 uio_resid(uio
), so
->so_rcv
.sb_cc
, so
->so_rcv
.sb_lowat
,
3009 so
->so_rcv
.sb_hiwat
);
3012 so_update_last_owner_locked(so
, p
);
3013 so_update_policy(so
);
3015 #ifdef MORE_LOCKING_DEBUG
3016 if (so
->so_usecount
== 1) {
3017 panic("%s: so=%x no other reference on socket\n", __func__
, so
);
3024 if (controlp
!= NULL
)
3027 flags
= *flagsp
&~ MSG_EOR
;
3032 * If a recv attempt is made on a previously-accepted socket
3033 * that has been marked as inactive (disconnected), reject
3036 if (so
->so_flags
& SOF_DEFUNCT
) {
3037 struct sockbuf
*sb
= &so
->so_rcv
;
3040 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
3041 __func__
, proc_pid(p
), proc_best_name(p
),
3042 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
3043 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
3045 * This socket should have been disconnected and flushed
3046 * prior to being returned from sodefunct(); there should
3047 * be no data on its receive list, so panic otherwise.
3049 if (so
->so_state
& SS_DEFUNCT
)
3050 sb_empty_assert(sb
, __func__
);
3051 socket_unlock(so
, 1);
3055 if ((so
->so_flags1
& SOF1_PRECONNECT_DATA
) &&
3056 pr
->pr_usrreqs
->pru_preconnect
) {
3058 * A user may set the CONNECT_RESUME_ON_READ_WRITE-flag but not
3059 * calling write() right after this. *If* the app calls a read
3060 * we do not want to block this read indefinetely. Thus,
3061 * we trigger a connect so that the session gets initiated.
3063 error
= (*pr
->pr_usrreqs
->pru_preconnect
)(so
);
3066 socket_unlock(so
, 1);
3071 if (ENTR_SHOULDTRACE
&&
3072 (SOCK_CHECK_DOM(so
, AF_INET
) || SOCK_CHECK_DOM(so
, AF_INET6
))) {
3074 * enable energy tracing for inet sockets that go over
3075 * non-loopback interfaces only.
3077 struct inpcb
*inp
= sotoinpcb(so
);
3078 if (inp
->inp_last_outifp
!= NULL
&&
3079 !(inp
->inp_last_outifp
->if_flags
& IFF_LOOPBACK
)) {
3081 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_START
,
3082 VM_KERNEL_ADDRPERM(so
),
3083 ((so
->so_state
& SS_NBIO
) ?
3084 kEnTrFlagNonBlocking
: 0),
3085 (int64_t)orig_resid
);
3090 * When SO_WANTOOBFLAG is set we try to get out-of-band data
3091 * regardless of the flags argument. Here is the case were
3092 * out-of-band data is not inline.
3094 if ((flags
& MSG_OOB
) ||
3095 ((so
->so_options
& SO_WANTOOBFLAG
) != 0 &&
3096 (so
->so_options
& SO_OOBINLINE
) == 0 &&
3097 (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
)))) {
3098 m
= m_get(M_WAIT
, MT_DATA
);
3100 socket_unlock(so
, 1);
3101 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
,
3102 ENOBUFS
, 0, 0, 0, 0);
3105 error
= (*pr
->pr_usrreqs
->pru_rcvoob
)(so
, m
, flags
& MSG_PEEK
);
3108 socket_unlock(so
, 0);
3110 error
= uiomove(mtod(m
, caddr_t
),
3111 imin(uio_resid(uio
), m
->m_len
), uio
);
3113 } while (uio_resid(uio
) && error
== 0 && m
!= NULL
);
3119 if ((so
->so_options
& SO_WANTOOBFLAG
) != 0) {
3120 if (error
== EWOULDBLOCK
|| error
== EINVAL
) {
3122 * Let's try to get normal data:
3123 * EWOULDBLOCK: out-of-band data not
3124 * receive yet. EINVAL: out-of-band data
3129 } else if (error
== 0 && flagsp
!= NULL
) {
3133 socket_unlock(so
, 1);
3135 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3136 VM_KERNEL_ADDRPERM(so
), 0,
3137 (int64_t)(orig_resid
- uio_resid(uio
)));
3139 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3148 if (so
->so_state
& SS_ISCONFIRMING
&& uio_resid(uio
)) {
3149 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, 0);
3153 delayed_copy_len
= 0;
3155 #ifdef MORE_LOCKING_DEBUG
3156 if (so
->so_usecount
<= 1)
3157 printf("soreceive: sblock so=0x%llx ref=%d on socket\n",
3158 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), so
->so_usecount
);
3161 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
3162 * and if so just return to the caller. This could happen when
3163 * soreceive() is called by a socket upcall function during the
3164 * time the socket is freed. The socket buffer would have been
3165 * locked across the upcall, therefore we cannot put this thread
3166 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
3167 * we may livelock), because the lock on the socket buffer will
3168 * only be released when the upcall routine returns to its caller.
3169 * Because the socket has been officially closed, there can be
3170 * no further read on it.
3172 * A multipath subflow socket would have its SS_NOFDREF set by
3173 * default, so check for SOF_MP_SUBFLOW socket flag; when the
3174 * socket is closed for real, SOF_MP_SUBFLOW would be cleared.
3176 if ((so
->so_state
& (SS_NOFDREF
| SS_CANTRCVMORE
)) ==
3177 (SS_NOFDREF
| SS_CANTRCVMORE
) && !(so
->so_flags
& SOF_MP_SUBFLOW
)) {
3178 socket_unlock(so
, 1);
3182 error
= sblock(&so
->so_rcv
, SBLOCKWAIT(flags
));
3184 socket_unlock(so
, 1);
3185 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3188 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3189 VM_KERNEL_ADDRPERM(so
), 0,
3190 (int64_t)(orig_resid
- uio_resid(uio
)));
3195 m
= so
->so_rcv
.sb_mb
;
3197 * If we have less data than requested, block awaiting more
3198 * (subject to any timeout) if:
3199 * 1. the current count is less than the low water mark, or
3200 * 2. MSG_WAITALL is set, and it is possible to do the entire
3201 * receive operation at once if we block (resid <= hiwat).
3202 * 3. MSG_DONTWAIT is not set
3203 * If MSG_WAITALL is set but resid is larger than the receive buffer,
3204 * we have to do the receive in sections, and thus risk returning
3205 * a short count if a timeout or signal occurs after we start.
3207 if (m
== NULL
|| (((flags
& MSG_DONTWAIT
) == 0 &&
3208 so
->so_rcv
.sb_cc
< uio_resid(uio
)) &&
3209 (so
->so_rcv
.sb_cc
< so
->so_rcv
.sb_lowat
||
3210 ((flags
& MSG_WAITALL
) && uio_resid(uio
) <= so
->so_rcv
.sb_hiwat
)) &&
3211 m
->m_nextpkt
== NULL
&& (pr
->pr_flags
& PR_ATOMIC
) == 0)) {
3213 * Panic if we notice inconsistencies in the socket's
3214 * receive list; both sb_mb and sb_cc should correctly
3215 * reflect the contents of the list, otherwise we may
3216 * end up with false positives during select() or poll()
3217 * which could put the application in a bad state.
3219 SB_MB_CHECK(&so
->so_rcv
);
3224 error
= so
->so_error
;
3225 if ((flags
& MSG_PEEK
) == 0)
3229 if (so
->so_state
& SS_CANTRCVMORE
) {
3232 * Deal with half closed connections
3234 if ((so
->so_state
& SS_ISDISCONNECTED
) == 0 &&
3235 cfil_sock_data_pending(&so
->so_rcv
) != 0)
3237 "so %llx ignore SS_CANTRCVMORE",
3238 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
));
3240 #endif /* CONTENT_FILTER */
3246 for (; m
!= NULL
; m
= m
->m_next
)
3247 if (m
->m_type
== MT_OOBDATA
|| (m
->m_flags
& M_EOR
)) {
3248 m
= so
->so_rcv
.sb_mb
;
3251 if ((so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
)) == 0 &&
3252 (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
)) {
3256 if (uio_resid(uio
) == 0)
3259 if ((so
->so_state
& SS_NBIO
) ||
3260 (flags
& (MSG_DONTWAIT
|MSG_NBIO
))) {
3261 error
= EWOULDBLOCK
;
3264 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 1");
3265 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 1");
3266 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3267 #if EVEN_MORE_LOCKING_DEBUG
3269 printf("Waiting for socket data\n");
3272 error
= sbwait(&so
->so_rcv
);
3273 #if EVEN_MORE_LOCKING_DEBUG
3275 printf("SORECEIVE - sbwait returned %d\n", error
);
3277 if (so
->so_usecount
< 1) {
3278 panic("%s: after 2nd sblock so=%p ref=%d on socket\n",
3279 __func__
, so
, so
->so_usecount
);
3283 socket_unlock(so
, 1);
3284 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, error
,
3287 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3288 VM_KERNEL_ADDRPERM(so
), 0,
3289 (int64_t)(orig_resid
- uio_resid(uio
)));
3296 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgrcv
);
3297 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1");
3298 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1");
3299 nextrecord
= m
->m_nextpkt
;
3301 if ((pr
->pr_flags
& PR_ADDR
) && m
->m_type
== MT_SONAME
) {
3302 error
= soreceive_addr(p
, so
, psa
, flags
, &m
, &nextrecord
,
3304 if (error
== ERESTART
)
3306 else if (error
!= 0)
3312 * Process one or more MT_CONTROL mbufs present before any data mbufs
3313 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
3314 * just copy the data; if !MSG_PEEK, we call into the protocol to
3315 * perform externalization.
3317 if (m
!= NULL
&& m
->m_type
== MT_CONTROL
) {
3318 error
= soreceive_ctl(so
, controlp
, flags
, &m
, &nextrecord
);
3325 * If the socket is a TCP socket with message delivery
3326 * enabled, then create a control msg to deliver the
3327 * relative TCP sequence number for this data. Waiting
3328 * until this point will protect against failures to
3329 * allocate an mbuf for control msgs.
3331 if (so
->so_type
== SOCK_STREAM
&& SOCK_PROTO(so
) == IPPROTO_TCP
&&
3332 (so
->so_flags
& SOF_ENABLE_MSGS
) && controlp
!= NULL
) {
3333 struct mbuf
*seq_cm
;
3335 seq_cm
= sbcreatecontrol((caddr_t
)&m
->m_pkthdr
.msg_seq
,
3336 sizeof (uint32_t), SCM_SEQNUM
, SOL_SOCKET
);
3337 if (seq_cm
== NULL
) {
3338 /* unable to allocate a control mbuf */
3343 controlp
= &seq_cm
->m_next
;
3347 if (!(flags
& MSG_PEEK
)) {
3349 * We get here because m points to an mbuf following
3350 * any MT_SONAME or MT_CONTROL mbufs which have been
3351 * processed above. In any case, m should be pointing
3352 * to the head of the mbuf chain, and the nextrecord
3353 * should be either NULL or equal to m->m_nextpkt.
3354 * See comments above about SB_LOCK.
3356 if (m
!= so
->so_rcv
.sb_mb
||
3357 m
->m_nextpkt
!= nextrecord
) {
3358 panic("%s: post-control !sync so=%p m=%p "
3359 "nextrecord=%p\n", __func__
, so
, m
,
3363 if (nextrecord
== NULL
)
3364 so
->so_rcv
.sb_lastrecord
= m
;
3367 if (type
== MT_OOBDATA
)
3370 if (!(flags
& MSG_PEEK
)) {
3371 SB_EMPTY_FIXUP(&so
->so_rcv
);
3374 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 2");
3375 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 2");
3380 if (!(flags
& MSG_PEEK
) && uio_resid(uio
) > sorecvmincopy
)
3388 (uio_resid(uio
) - delayed_copy_len
) > 0 && error
== 0) {
3389 if (m
->m_type
== MT_OOBDATA
) {
3390 if (type
!= MT_OOBDATA
)
3392 } else if (type
== MT_OOBDATA
) {
3396 * Make sure to allways set MSG_OOB event when getting
3397 * out of band data inline.
3399 if ((so
->so_options
& SO_WANTOOBFLAG
) != 0 &&
3400 (so
->so_options
& SO_OOBINLINE
) != 0 &&
3401 (so
->so_state
& SS_RCVATMARK
) != 0) {
3404 so
->so_state
&= ~SS_RCVATMARK
;
3405 len
= uio_resid(uio
) - delayed_copy_len
;
3406 if (so
->so_oobmark
&& len
> so
->so_oobmark
- offset
)
3407 len
= so
->so_oobmark
- offset
;
3408 if (len
> m
->m_len
- moff
)
3409 len
= m
->m_len
- moff
;
3411 * If mp is set, just pass back the mbufs.
3412 * Otherwise copy them out via the uio, then free.
3413 * Sockbuf must be consistent here (points to current mbuf,
3414 * it points to next record) when we drop priority;
3415 * we must note any additions to the sockbuf when we
3416 * block interrupts again.
3419 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive uiomove");
3420 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive uiomove");
3421 if (can_delay
&& len
== m
->m_len
) {
3423 * only delay the copy if we're consuming the
3424 * mbuf and we're NOT in MSG_PEEK mode
3425 * and we have enough data to make it worthwile
3426 * to drop and retake the lock... can_delay
3427 * reflects the state of the 2 latter
3428 * constraints moff should always be zero
3431 delayed_copy_len
+= len
;
3433 if (delayed_copy_len
) {
3434 error
= sodelayed_copy(so
, uio
,
3435 &free_list
, &delayed_copy_len
);
3441 * can only get here if MSG_PEEK is not
3442 * set therefore, m should point at the
3443 * head of the rcv queue; if it doesn't,
3444 * it means something drastically
3445 * changed while we were out from behind
3446 * the lock in sodelayed_copy. perhaps
3447 * a RST on the stream. in any event,
3448 * the stream has been interrupted. it's
3449 * probably best just to return whatever
3450 * data we've moved and let the caller
3453 if (m
!= so
->so_rcv
.sb_mb
) {
3457 socket_unlock(so
, 0);
3458 error
= uiomove(mtod(m
, caddr_t
) + moff
,
3466 uio_setresid(uio
, (uio_resid(uio
) - len
));
3468 if (len
== m
->m_len
- moff
) {
3469 if (m
->m_flags
& M_EOR
)
3471 if (flags
& MSG_PEEK
) {
3475 nextrecord
= m
->m_nextpkt
;
3476 sbfree(&so
->so_rcv
, m
);
3477 m
->m_nextpkt
= NULL
;
3480 * If this packet is an unordered packet
3481 * (indicated by M_UNORDERED_DATA flag), remove
3482 * the additional bytes added to the
3483 * receive socket buffer size.
3485 if ((so
->so_flags
& SOF_ENABLE_MSGS
) &&
3487 (m
->m_flags
& M_UNORDERED_DATA
) &&
3488 sbreserve(&so
->so_rcv
,
3489 so
->so_rcv
.sb_hiwat
- m
->m_len
)) {
3490 if (so
->so_msg_state
->msg_uno_bytes
>
3493 msg_uno_bytes
-= m
->m_len
;
3498 m
->m_flags
&= ~M_UNORDERED_DATA
;
3504 so
->so_rcv
.sb_mb
= m
= m
->m_next
;
3507 if (free_list
== NULL
)
3512 so
->so_rcv
.sb_mb
= m
= m
->m_next
;
3516 m
->m_nextpkt
= nextrecord
;
3517 if (nextrecord
== NULL
)
3518 so
->so_rcv
.sb_lastrecord
= m
;
3520 so
->so_rcv
.sb_mb
= nextrecord
;
3521 SB_EMPTY_FIXUP(&so
->so_rcv
);
3523 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 3");
3524 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 3");
3527 if (flags
& MSG_PEEK
) {
3533 if (flags
& MSG_DONTWAIT
)
3534 copy_flag
= M_DONTWAIT
;
3537 *mp
= m_copym(m
, 0, len
, copy_flag
);
3539 * Failed to allocate an mbuf?
3540 * Adjust uio_resid back, it was
3541 * adjusted down by len bytes which
3542 * we didn't copy over.
3546 (uio_resid(uio
) + len
));
3552 so
->so_rcv
.sb_cc
-= len
;
3555 if (so
->so_oobmark
) {
3556 if ((flags
& MSG_PEEK
) == 0) {
3557 so
->so_oobmark
-= len
;
3558 if (so
->so_oobmark
== 0) {
3559 so
->so_state
|= SS_RCVATMARK
;
3561 * delay posting the actual event until
3562 * after any delayed copy processing
3570 if (offset
== so
->so_oobmark
)
3574 if (flags
& MSG_EOR
)
3577 * If the MSG_WAITALL or MSG_WAITSTREAM flag is set
3578 * (for non-atomic socket), we must not quit until
3579 * "uio->uio_resid == 0" or an error termination.
3580 * If a signal/timeout occurs, return with a short
3581 * count but without error. Keep sockbuf locked
3582 * against other readers.
3584 while (flags
& (MSG_WAITALL
|MSG_WAITSTREAM
) && m
== NULL
&&
3585 (uio_resid(uio
) - delayed_copy_len
) > 0 &&
3586 !sosendallatonce(so
) && !nextrecord
) {
3587 if (so
->so_error
|| ((so
->so_state
& SS_CANTRCVMORE
)
3589 && cfil_sock_data_pending(&so
->so_rcv
) == 0
3590 #endif /* CONTENT_FILTER */
3595 * Depending on the protocol (e.g. TCP), the following
3596 * might cause the socket lock to be dropped and later
3597 * be reacquired, and more data could have arrived and
3598 * have been appended to the receive socket buffer by
3599 * the time it returns. Therefore, we only sleep in
3600 * sbwait() below if and only if the socket buffer is
3601 * empty, in order to avoid a false sleep.
3603 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
&&
3604 (((struct inpcb
*)so
->so_pcb
)->inp_state
!=
3606 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3608 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 2");
3609 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 2");
3611 if (so
->so_rcv
.sb_mb
== NULL
&& sbwait(&so
->so_rcv
)) {
3616 * have to wait until after we get back from the sbwait
3617 * to do the copy because we will drop the lock if we
3618 * have enough data that has been delayed... by dropping
3619 * the lock we open up a window allowing the netisr
3620 * thread to process the incoming packets and to change
3621 * the state of this socket... we're issuing the sbwait
3622 * because the socket is empty and we're expecting the
3623 * netisr thread to wake us up when more packets arrive;
3624 * if we allow that processing to happen and then sbwait
3625 * we could stall forever with packets sitting in the
3626 * socket if no further packets arrive from the remote
3629 * we want to copy before we've collected all the data
3630 * to satisfy this request to allow the copy to overlap
3631 * the incoming packet processing on an MP system
3633 if (delayed_copy_len
> sorecvmincopy
&&
3634 (delayed_copy_len
> (so
->so_rcv
.sb_hiwat
/ 2))) {
3635 error
= sodelayed_copy(so
, uio
,
3636 &free_list
, &delayed_copy_len
);
3641 m
= so
->so_rcv
.sb_mb
;
3643 nextrecord
= m
->m_nextpkt
;
3645 SB_MB_CHECK(&so
->so_rcv
);
3648 #ifdef MORE_LOCKING_DEBUG
3649 if (so
->so_usecount
<= 1) {
3650 panic("%s: after big while so=%p ref=%d on socket\n",
3651 __func__
, so
, so
->so_usecount
);
3656 if (m
!= NULL
&& pr
->pr_flags
& PR_ATOMIC
) {
3657 if (so
->so_options
& SO_DONTTRUNC
) {
3658 flags
|= MSG_RCVMORE
;
3661 if ((flags
& MSG_PEEK
) == 0)
3662 (void) sbdroprecord(&so
->so_rcv
);
3667 * pru_rcvd below (for TCP) may cause more data to be received
3668 * if the socket lock is dropped prior to sending the ACK; some
3669 * legacy OpenTransport applications don't handle this well
3670 * (if it receives less data than requested while MSG_HAVEMORE
3671 * is set), and so we set the flag now based on what we know
3672 * prior to calling pru_rcvd.
3674 if ((so
->so_options
& SO_WANTMORE
) && so
->so_rcv
.sb_cc
> 0)
3675 flags
|= MSG_HAVEMORE
;
3677 if ((flags
& MSG_PEEK
) == 0) {
3679 so
->so_rcv
.sb_mb
= nextrecord
;
3681 * First part is an inline SB_EMPTY_FIXUP(). Second
3682 * part makes sure sb_lastrecord is up-to-date if
3683 * there is still data in the socket buffer.
3685 if (so
->so_rcv
.sb_mb
== NULL
) {
3686 so
->so_rcv
.sb_mbtail
= NULL
;
3687 so
->so_rcv
.sb_lastrecord
= NULL
;
3688 } else if (nextrecord
->m_nextpkt
== NULL
) {
3689 so
->so_rcv
.sb_lastrecord
= nextrecord
;
3691 SB_MB_CHECK(&so
->so_rcv
);
3693 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 4");
3694 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 4");
3695 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
)
3696 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
3699 if (delayed_copy_len
) {
3700 error
= sodelayed_copy(so
, uio
, &free_list
, &delayed_copy_len
);
3704 if (free_list
!= NULL
) {
3705 m_freem_list(free_list
);
3709 postevent(so
, 0, EV_OOB
);
3711 if (orig_resid
== uio_resid(uio
) && orig_resid
&&
3712 (flags
& MSG_EOR
) == 0 && (so
->so_state
& SS_CANTRCVMORE
) == 0) {
3713 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3720 #ifdef MORE_LOCKING_DEBUG
3721 if (so
->so_usecount
<= 1) {
3722 panic("%s: release so=%p ref=%d on socket\n", __func__
,
3723 so
, so
->so_usecount
);
3727 if (delayed_copy_len
)
3728 error
= sodelayed_copy(so
, uio
, &free_list
, &delayed_copy_len
);
3730 if (free_list
!= NULL
)
3731 m_freem_list(free_list
);
3733 sbunlock(&so
->so_rcv
, FALSE
); /* will unlock socket */
3736 KERNEL_ENERGYTRACE(kEnTrActKernSockRead
, DBG_FUNC_END
,
3737 VM_KERNEL_ADDRPERM(so
),
3738 ((error
== EWOULDBLOCK
) ? kEnTrFlagNoWork
: 0),
3739 (int64_t)(orig_resid
- uio_resid(uio
)));
3741 KERNEL_DEBUG(DBG_FNC_SORECEIVE
| DBG_FUNC_END
, so
, uio_resid(uio
),
3742 so
->so_rcv
.sb_cc
, 0, error
);
3748 * Returns: 0 Success
3752 sodelayed_copy(struct socket
*so
, struct uio
*uio
, struct mbuf
**free_list
,
3753 user_ssize_t
*resid
)
3760 socket_unlock(so
, 0);
3762 while (m
!= NULL
&& error
== 0) {
3763 error
= uiomove(mtod(m
, caddr_t
), (int)m
->m_len
, uio
);
3766 m_freem_list(*free_list
);
3777 sodelayed_copy_list(struct socket
*so
, struct recv_msg_elem
*msgarray
,
3778 u_int uiocnt
, struct mbuf
**free_list
, user_ssize_t
*resid
)
3782 struct mbuf
*ml
, *m
;
3786 for (ml
= *free_list
, i
= 0; ml
!= NULL
&& i
< uiocnt
;
3787 ml
= ml
->m_nextpkt
, i
++) {
3788 auio
= msgarray
[i
].uio
;
3789 for (m
= ml
; m
!= NULL
; m
= m
->m_next
) {
3790 error
= uiomove(mtod(m
, caddr_t
), m
->m_len
, auio
);
3796 m_freem_list(*free_list
);
3805 soreceive_list(struct socket
*so
, struct recv_msg_elem
*msgarray
, u_int uiocnt
,
3809 struct mbuf
*nextrecord
;
3810 struct mbuf
*ml
= NULL
, *free_list
= NULL
, *free_tail
= NULL
;
3812 user_ssize_t len
, pktlen
, delayed_copy_len
= 0;
3813 struct protosw
*pr
= so
->so_proto
;
3815 struct proc
*p
= current_proc();
3816 struct uio
*auio
= NULL
;
3819 struct sockaddr
**psa
= NULL
;
3820 struct mbuf
**controlp
= NULL
;
3823 struct mbuf
*free_others
= NULL
;
3825 KERNEL_DEBUG(DBG_FNC_SORECEIVE_LIST
| DBG_FUNC_START
,
3827 so
->so_rcv
.sb_cc
, so
->so_rcv
.sb_lowat
, so
->so_rcv
.sb_hiwat
);
3831 * - Only supports don't wait flags
3832 * - Only support datagram sockets (could be extended to raw)
3834 * - Protocol must support packet chains
3835 * - The uio array is NULL (should we panic?)
3841 if (flags
& ~(MSG_PEEK
| MSG_WAITALL
| MSG_DONTWAIT
| MSG_NEEDSA
|
3843 printf("%s invalid flags 0x%x\n", __func__
, flags
);
3847 if (so
->so_type
!= SOCK_DGRAM
) {
3851 if (sosendallatonce(so
) == 0) {
3855 if (so
->so_proto
->pr_usrreqs
->pru_send_list
== NULL
) {
3856 error
= EPROTONOSUPPORT
;
3859 if (msgarray
== NULL
) {
3860 printf("%s uioarray is NULL\n", __func__
);
3865 printf("%s uiocnt is 0\n", __func__
);
3870 * Sanity check on the length passed by caller as we are making 'int'
3873 resid
= recv_msg_array_resid(msgarray
, uiocnt
);
3874 if (resid
< 0 || resid
> INT_MAX
) {
3879 if (!(flags
& MSG_PEEK
) && sorecvmincopy
> 0)
3885 so_update_last_owner_locked(so
, p
);
3886 so_update_policy(so
);
3889 so_update_necp_policy(so
, NULL
, NULL
);
3893 * If a recv attempt is made on a previously-accepted socket
3894 * that has been marked as inactive (disconnected), reject
3897 if (so
->so_flags
& SOF_DEFUNCT
) {
3898 struct sockbuf
*sb
= &so
->so_rcv
;
3901 SODEFUNCTLOG("%s[%d, %s]: defunct so 0x%llx [%d,%d] (%d)\n",
3902 __func__
, proc_pid(p
), proc_best_name(p
),
3903 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
3904 SOCK_DOM(so
), SOCK_TYPE(so
), error
);
3906 * This socket should have been disconnected and flushed
3907 * prior to being returned from sodefunct(); there should
3908 * be no data on its receive list, so panic otherwise.
3910 if (so
->so_state
& SS_DEFUNCT
)
3911 sb_empty_assert(sb
, __func__
);
3917 * The uio may be empty
3919 if (npkts
>= uiocnt
) {
3925 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
3926 * and if so just return to the caller. This could happen when
3927 * soreceive() is called by a socket upcall function during the
3928 * time the socket is freed. The socket buffer would have been
3929 * locked across the upcall, therefore we cannot put this thread
3930 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
3931 * we may livelock), because the lock on the socket buffer will
3932 * only be released when the upcall routine returns to its caller.
3933 * Because the socket has been officially closed, there can be
3934 * no further read on it.
3936 if ((so
->so_state
& (SS_NOFDREF
| SS_CANTRCVMORE
)) ==
3937 (SS_NOFDREF
| SS_CANTRCVMORE
)) {
3942 error
= sblock(&so
->so_rcv
, SBLOCKWAIT(flags
));
3948 m
= so
->so_rcv
.sb_mb
;
3950 * Block awaiting more datagram if needed
3952 if (m
== NULL
|| (((flags
& MSG_DONTWAIT
) == 0 &&
3953 (so
->so_rcv
.sb_cc
< so
->so_rcv
.sb_lowat
||
3954 ((flags
& MSG_WAITALL
) && npkts
< uiocnt
))))) {
3956 * Panic if we notice inconsistencies in the socket's
3957 * receive list; both sb_mb and sb_cc should correctly
3958 * reflect the contents of the list, otherwise we may
3959 * end up with false positives during select() or poll()
3960 * which could put the application in a bad state.
3962 SB_MB_CHECK(&so
->so_rcv
);
3965 error
= so
->so_error
;
3966 if ((flags
& MSG_PEEK
) == 0)
3970 if (so
->so_state
& SS_CANTRCVMORE
) {
3973 if ((so
->so_state
& (SS_ISCONNECTED
|SS_ISCONNECTING
)) == 0 &&
3974 (so
->so_proto
->pr_flags
& PR_CONNREQUIRED
)) {
3978 if ((so
->so_state
& SS_NBIO
) ||
3979 (flags
& (MSG_DONTWAIT
|MSG_NBIO
))) {
3980 error
= EWOULDBLOCK
;
3984 * Do not block if we got some data
3986 if (free_list
!= NULL
) {
3991 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive sbwait 1");
3992 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive sbwait 1");
3994 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
3997 error
= sbwait(&so
->so_rcv
);
4004 OSIncrementAtomicLong(&p
->p_stats
->p_ru
.ru_msgrcv
);
4005 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 1");
4006 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 1");
4009 * Consume the current uio index as we have a datagram
4011 auio
= msgarray
[npkts
].uio
;
4012 resid
= uio_resid(auio
);
4013 msgarray
[npkts
].which
|= SOCK_MSG_DATA
;
4014 psa
= (msgarray
[npkts
].which
& SOCK_MSG_SA
) ?
4015 &msgarray
[npkts
].psa
: NULL
;
4016 controlp
= (msgarray
[npkts
].which
& SOCK_MSG_CONTROL
) ?
4017 &msgarray
[npkts
].controlp
: NULL
;
4019 nextrecord
= m
->m_nextpkt
;
4021 if ((pr
->pr_flags
& PR_ADDR
) && m
->m_type
== MT_SONAME
) {
4022 error
= soreceive_addr(p
, so
, psa
, flags
, &m
, &nextrecord
, 1);
4023 if (error
== ERESTART
)
4025 else if (error
!= 0)
4029 if (m
!= NULL
&& m
->m_type
== MT_CONTROL
) {
4030 error
= soreceive_ctl(so
, controlp
, flags
, &m
, &nextrecord
);
4035 if (m
->m_pkthdr
.len
== 0) {
4036 printf("%s:%d so %llx pkt %llx type %u pktlen null\n",
4038 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
4039 (uint64_t)DEBUG_KERNEL_ADDRPERM(m
),
4044 * Loop to copy the mbufs of the current record
4045 * Support zero length packets
4049 while (m
!= NULL
&& (len
= resid
- pktlen
) >= 0 && error
== 0) {
4051 panic("%p m_len zero", m
);
4053 panic("%p m_type zero", m
);
4055 * Clip to the residual length
4061 * Copy the mbufs via the uio or delay the copy
4062 * Sockbuf must be consistent here (points to current mbuf,
4063 * it points to next record) when we drop priority;
4064 * we must note any additions to the sockbuf when we
4065 * block interrupts again.
4067 if (len
> 0 && can_delay
== 0) {
4068 socket_unlock(so
, 0);
4069 error
= uiomove(mtod(m
, caddr_t
), (int)len
, auio
);
4074 delayed_copy_len
+= len
;
4077 if (len
== m
->m_len
) {
4079 * m was entirely copied
4081 sbfree(&so
->so_rcv
, m
);
4082 nextrecord
= m
->m_nextpkt
;
4083 m
->m_nextpkt
= NULL
;
4086 * Set the first packet to the head of the free list
4088 if (free_list
== NULL
)
4091 * Link current packet to tail of free list
4094 if (free_tail
!= NULL
)
4095 free_tail
->m_nextpkt
= m
;
4099 * Link current mbuf to last mbuf of current packet
4106 * Move next buf to head of socket buffer
4108 so
->so_rcv
.sb_mb
= m
= ml
->m_next
;
4112 m
->m_nextpkt
= nextrecord
;
4113 if (nextrecord
== NULL
)
4114 so
->so_rcv
.sb_lastrecord
= m
;
4116 so
->so_rcv
.sb_mb
= nextrecord
;
4117 SB_EMPTY_FIXUP(&so
->so_rcv
);
4119 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 3");
4120 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 3");
4123 * Stop the loop on partial copy
4128 #ifdef MORE_LOCKING_DEBUG
4129 if (so
->so_usecount
<= 1) {
4130 panic("%s: after big while so=%llx ref=%d on socket\n",
4132 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), so
->so_usecount
);
4137 * Tell the caller we made a partial copy
4140 if (so
->so_options
& SO_DONTTRUNC
) {
4142 * Copyout first the freelist then the partial mbuf
4144 socket_unlock(so
, 0);
4145 if (delayed_copy_len
)
4146 error
= sodelayed_copy_list(so
, msgarray
,
4147 uiocnt
, &free_list
, &delayed_copy_len
);
4150 error
= uiomove(mtod(m
, caddr_t
), (int)len
,
4159 so
->so_rcv
.sb_cc
-= len
;
4160 flags
|= MSG_RCVMORE
;
4162 (void) sbdroprecord(&so
->so_rcv
);
4163 nextrecord
= so
->so_rcv
.sb_mb
;
4170 so
->so_rcv
.sb_mb
= nextrecord
;
4172 * First part is an inline SB_EMPTY_FIXUP(). Second
4173 * part makes sure sb_lastrecord is up-to-date if
4174 * there is still data in the socket buffer.
4176 if (so
->so_rcv
.sb_mb
== NULL
) {
4177 so
->so_rcv
.sb_mbtail
= NULL
;
4178 so
->so_rcv
.sb_lastrecord
= NULL
;
4179 } else if (nextrecord
->m_nextpkt
== NULL
) {
4180 so
->so_rcv
.sb_lastrecord
= nextrecord
;
4182 SB_MB_CHECK(&so
->so_rcv
);
4184 SBLASTRECORDCHK(&so
->so_rcv
, "soreceive 4");
4185 SBLASTMBUFCHK(&so
->so_rcv
, "soreceive 4");
4188 * We can continue to the next packet as long as:
4189 * - We haven't exhausted the uio array
4190 * - There was no error
4191 * - A packet was not truncated
4192 * - We can still receive more data
4194 if (npkts
< uiocnt
&& error
== 0 &&
4195 (flags
& (MSG_RCVMORE
| MSG_TRUNC
)) == 0 &&
4196 (so
->so_state
& SS_CANTRCVMORE
) == 0) {
4197 sbunlock(&so
->so_rcv
, TRUE
); /* keep socket locked */
4207 * pru_rcvd may cause more data to be received if the socket lock
4208 * is dropped so we set MSG_HAVEMORE now based on what we know.
4209 * That way the caller won't be surprised if it receives less data
4212 if ((so
->so_options
& SO_WANTMORE
) && so
->so_rcv
.sb_cc
> 0)
4213 flags
|= MSG_HAVEMORE
;
4215 if (pr
->pr_flags
& PR_WANTRCVD
&& so
->so_pcb
)
4216 (*pr
->pr_usrreqs
->pru_rcvd
)(so
, flags
);
4219 sbunlock(&so
->so_rcv
, FALSE
); /* will unlock socket */
4221 socket_unlock(so
, 1);
4223 if (delayed_copy_len
)
4224 error
= sodelayed_copy_list(so
, msgarray
, uiocnt
,
4225 &free_list
, &delayed_copy_len
);
4228 * Amortize the cost of freeing the mbufs
4230 if (free_list
!= NULL
)
4231 m_freem_list(free_list
);
4232 if (free_others
!= NULL
)
4233 m_freem_list(free_others
);
4235 KERNEL_DEBUG(DBG_FNC_SORECEIVE_LIST
| DBG_FUNC_END
, error
,
4241 * Returns: 0 Success
4244 * <pru_shutdown>:EINVAL
4245 * <pru_shutdown>:EADDRNOTAVAIL[TCP]
4246 * <pru_shutdown>:ENOBUFS[TCP]
4247 * <pru_shutdown>:EMSGSIZE[TCP]
4248 * <pru_shutdown>:EHOSTUNREACH[TCP]
4249 * <pru_shutdown>:ENETUNREACH[TCP]
4250 * <pru_shutdown>:ENETDOWN[TCP]
4251 * <pru_shutdown>:ENOMEM[TCP]
4252 * <pru_shutdown>:EACCES[TCP]
4253 * <pru_shutdown>:EMSGSIZE[TCP]
4254 * <pru_shutdown>:ENOBUFS[TCP]
4255 * <pru_shutdown>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
4256 * <pru_shutdown>:??? [other protocol families]
4259 soshutdown(struct socket
*so
, int how
)
4263 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
| DBG_FUNC_START
, how
, 0, 0, 0, 0);
4271 (SS_ISCONNECTED
|SS_ISCONNECTING
|SS_ISDISCONNECTING
)) == 0) {
4274 error
= soshutdownlock(so
, how
);
4276 socket_unlock(so
, 1);
4283 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
| DBG_FUNC_END
, how
, error
, 0, 0, 0);
4289 soshutdownlock_final(struct socket
*so
, int how
)
4291 struct protosw
*pr
= so
->so_proto
;
4294 sflt_notify(so
, sock_evt_shutdown
, &how
);
4296 if (how
!= SHUT_WR
) {
4297 if ((so
->so_state
& SS_CANTRCVMORE
) != 0) {
4298 /* read already shut down */
4303 postevent(so
, 0, EV_RCLOSED
);
4305 if (how
!= SHUT_RD
) {
4306 if ((so
->so_state
& SS_CANTSENDMORE
) != 0) {
4307 /* write already shut down */
4311 error
= (*pr
->pr_usrreqs
->pru_shutdown
)(so
);
4312 postevent(so
, 0, EV_WCLOSED
);
4315 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN
, how
, 1, 0, 0, 0);
4320 soshutdownlock(struct socket
*so
, int how
)
4326 * A content filter may delay the actual shutdown until it
4327 * has processed the pending data
4329 if (so
->so_flags
& SOF_CONTENT_FILTER
) {
4330 error
= cfil_sock_shutdown(so
, &how
);
4331 if (error
== EJUSTRETURN
) {
4334 } else if (error
!= 0) {
4338 #endif /* CONTENT_FILTER */
4340 error
= soshutdownlock_final(so
, how
);
4347 sowflush(struct socket
*so
)
4349 struct sockbuf
*sb
= &so
->so_snd
;
4352 * Obtain lock on the socket buffer (SB_LOCK). This is required
4353 * to prevent the socket buffer from being unexpectedly altered
4354 * while it is used by another thread in socket send/receive.
4356 * sblock() must not fail here, hence the assertion.
4358 (void) sblock(sb
, SBL_WAIT
| SBL_NOINTR
| SBL_IGNDEFUNCT
);
4359 VERIFY(sb
->sb_flags
& SB_LOCK
);
4361 sb
->sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
4362 sb
->sb_flags
|= SB_DROP
;
4363 sb
->sb_upcall
= NULL
;
4364 sb
->sb_upcallarg
= NULL
;
4366 sbunlock(sb
, TRUE
); /* keep socket locked */
4368 selthreadclear(&sb
->sb_sel
);
4373 sorflush(struct socket
*so
)
4375 struct sockbuf
*sb
= &so
->so_rcv
;
4376 struct protosw
*pr
= so
->so_proto
;
4379 lck_mtx_t
*mutex_held
;
4381 * XXX: This code is currently commented out, because we may get here
4382 * as part of sofreelastref(), and at that time, pr_getlock() may no
4383 * longer be able to return us the lock; this will be fixed in future.
4385 if (so
->so_proto
->pr_getlock
!= NULL
)
4386 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
4388 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
4390 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
4393 sflt_notify(so
, sock_evt_flush_read
, NULL
);
4398 * Obtain lock on the socket buffer (SB_LOCK). This is required
4399 * to prevent the socket buffer from being unexpectedly altered
4400 * while it is used by another thread in socket send/receive.
4402 * sblock() must not fail here, hence the assertion.
4404 (void) sblock(sb
, SBL_WAIT
| SBL_NOINTR
| SBL_IGNDEFUNCT
);
4405 VERIFY(sb
->sb_flags
& SB_LOCK
);
4408 * Copy only the relevant fields from "sb" to "asb" which we
4409 * need for sbrelease() to function. In particular, skip
4410 * sb_sel as it contains the wait queue linkage, which would
4411 * wreak havoc if we were to issue selthreadclear() on "asb".
4412 * Make sure to not carry over SB_LOCK in "asb", as we need
4413 * to acquire it later as part of sbrelease().
4415 bzero(&asb
, sizeof (asb
));
4416 asb
.sb_cc
= sb
->sb_cc
;
4417 asb
.sb_hiwat
= sb
->sb_hiwat
;
4418 asb
.sb_mbcnt
= sb
->sb_mbcnt
;
4419 asb
.sb_mbmax
= sb
->sb_mbmax
;
4420 asb
.sb_ctl
= sb
->sb_ctl
;
4421 asb
.sb_lowat
= sb
->sb_lowat
;
4422 asb
.sb_mb
= sb
->sb_mb
;
4423 asb
.sb_mbtail
= sb
->sb_mbtail
;
4424 asb
.sb_lastrecord
= sb
->sb_lastrecord
;
4425 asb
.sb_so
= sb
->sb_so
;
4426 asb
.sb_flags
= sb
->sb_flags
;
4427 asb
.sb_flags
&= ~(SB_LOCK
|SB_SEL
|SB_KNOTE
|SB_UPCALL
);
4428 asb
.sb_flags
|= SB_DROP
;
4431 * Ideally we'd bzero() these and preserve the ones we need;
4432 * but to do that we'd need to shuffle things around in the
4433 * sockbuf, and we can't do it now because there are KEXTS
4434 * that are directly referring to the socket structure.
4436 * Setting SB_DROP acts as a barrier to prevent further appends.
4437 * Clearing SB_SEL is done for selthreadclear() below.
4446 sb
->sb_mbtail
= NULL
;
4447 sb
->sb_lastrecord
= NULL
;
4448 sb
->sb_timeo
.tv_sec
= 0;
4449 sb
->sb_timeo
.tv_usec
= 0;
4450 sb
->sb_upcall
= NULL
;
4451 sb
->sb_upcallarg
= NULL
;
4452 sb
->sb_flags
&= ~(SB_SEL
|SB_UPCALL
);
4453 sb
->sb_flags
|= SB_DROP
;
4455 sbunlock(sb
, TRUE
); /* keep socket locked */
4458 * Note that selthreadclear() is called on the original "sb" and
4459 * not the local "asb" because of the way wait queue linkage is
4460 * implemented. Given that selwakeup() may be triggered, SB_SEL
4461 * should no longer be set (cleared above.)
4463 selthreadclear(&sb
->sb_sel
);
4465 if ((pr
->pr_flags
& PR_RIGHTS
) && pr
->pr_domain
->dom_dispose
)
4466 (*pr
->pr_domain
->dom_dispose
)(asb
.sb_mb
);
4472 * Perhaps this routine, and sooptcopyout(), below, ought to come in
4473 * an additional variant to handle the case where the option value needs
4474 * to be some kind of integer, but not a specific size.
4475 * In addition to their use here, these functions are also called by the
4476 * protocol-level pr_ctloutput() routines.
4478 * Returns: 0 Success
4483 sooptcopyin(struct sockopt
*sopt
, void *buf
, size_t len
, size_t minlen
)
4488 * If the user gives us more than we wanted, we ignore it,
4489 * but if we don't get the minimum length the caller
4490 * wants, we return EINVAL. On success, sopt->sopt_valsize
4491 * is set to however much we actually retrieved.
4493 if ((valsize
= sopt
->sopt_valsize
) < minlen
)
4496 sopt
->sopt_valsize
= valsize
= len
;
4498 if (sopt
->sopt_p
!= kernproc
)
4499 return (copyin(sopt
->sopt_val
, buf
, valsize
));
4501 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), buf
, valsize
);
4506 * sooptcopyin_timeval
4507 * Copy in a timeval value into tv_p, and take into account whether the
4508 * the calling process is 64-bit or 32-bit. Moved the sanity checking
4509 * code here so that we can verify the 64-bit tv_sec value before we lose
4510 * the top 32-bits assigning tv64.tv_sec to tv_p->tv_sec.
4513 sooptcopyin_timeval(struct sockopt
*sopt
, struct timeval
*tv_p
)
4517 if (proc_is64bit(sopt
->sopt_p
)) {
4518 struct user64_timeval tv64
;
4520 if (sopt
->sopt_valsize
< sizeof (tv64
))
4523 sopt
->sopt_valsize
= sizeof (tv64
);
4524 if (sopt
->sopt_p
!= kernproc
) {
4525 error
= copyin(sopt
->sopt_val
, &tv64
, sizeof (tv64
));
4529 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), &tv64
,
4532 if (tv64
.tv_sec
< 0 || tv64
.tv_sec
> LONG_MAX
||
4533 tv64
.tv_usec
< 0 || tv64
.tv_usec
>= 1000000)
4536 tv_p
->tv_sec
= tv64
.tv_sec
;
4537 tv_p
->tv_usec
= tv64
.tv_usec
;
4539 struct user32_timeval tv32
;
4541 if (sopt
->sopt_valsize
< sizeof (tv32
))
4544 sopt
->sopt_valsize
= sizeof (tv32
);
4545 if (sopt
->sopt_p
!= kernproc
) {
4546 error
= copyin(sopt
->sopt_val
, &tv32
, sizeof (tv32
));
4551 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), &tv32
,
4556 * K64todo "comparison is always false due to
4557 * limited range of data type"
4559 if (tv32
.tv_sec
< 0 || tv32
.tv_sec
> LONG_MAX
||
4560 tv32
.tv_usec
< 0 || tv32
.tv_usec
>= 1000000)
4563 tv_p
->tv_sec
= tv32
.tv_sec
;
4564 tv_p
->tv_usec
= tv32
.tv_usec
;
4570 soopt_cred_check(struct socket
*so
, int priv
)
4572 kauth_cred_t cred
= NULL
;
4573 proc_t ep
= PROC_NULL
;
4576 if (so
->so_flags
& SOF_DELEGATED
) {
4577 ep
= proc_find(so
->e_pid
);
4579 cred
= kauth_cred_proc_ref(ep
);
4581 error
= priv_check_cred(cred
? cred
: so
->so_cred
, priv
, 0);
4583 kauth_cred_unref(&cred
);
4584 if (ep
!= PROC_NULL
)
4591 * Returns: 0 Success
4596 * sooptcopyin:EINVAL
4597 * sooptcopyin:EFAULT
4598 * sooptcopyin_timeval:EINVAL
4599 * sooptcopyin_timeval:EFAULT
4600 * sooptcopyin_timeval:EDOM
4601 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
4602 * <pr_ctloutput>:???w
4603 * sflt_attach_private:??? [whatever a filter author chooses]
4604 * <sf_setoption>:??? [whatever a filter author chooses]
4606 * Notes: Other <pru_listen> returns depend on the protocol family; all
4607 * <sf_listen> returns depend on what the filter author causes
4608 * their filter to return.
4611 sosetoptlock(struct socket
*so
, struct sockopt
*sopt
, int dolock
)
4616 #if CONFIG_MACF_SOCKET
4618 #endif /* MAC_SOCKET */
4620 if (sopt
->sopt_dir
!= SOPT_SET
)
4621 sopt
->sopt_dir
= SOPT_SET
;
4626 if ((so
->so_state
& (SS_CANTRCVMORE
| SS_CANTSENDMORE
)) ==
4627 (SS_CANTRCVMORE
| SS_CANTSENDMORE
) &&
4628 (so
->so_flags
& SOF_NPX_SETOPTSHUT
) == 0) {
4629 /* the socket has been shutdown, no more sockopt's */
4634 error
= sflt_setsockopt(so
, sopt
);
4636 if (error
== EJUSTRETURN
)
4641 if (sopt
->sopt_level
!= SOL_SOCKET
) {
4642 if (so
->so_proto
!= NULL
&&
4643 so
->so_proto
->pr_ctloutput
!= NULL
) {
4644 error
= (*so
->so_proto
->pr_ctloutput
)(so
, sopt
);
4647 error
= ENOPROTOOPT
;
4650 * Allow socket-level (SOL_SOCKET) options to be filtered by
4651 * the protocol layer, if needed. A zero value returned from
4652 * the handler means use default socket-level processing as
4653 * done by the rest of this routine. Otherwise, any other
4654 * return value indicates that the option is unsupported.
4656 if (so
->so_proto
!= NULL
&& (error
= so
->so_proto
->pr_usrreqs
->
4657 pru_socheckopt(so
, sopt
)) != 0)
4661 switch (sopt
->sopt_name
) {
4664 error
= sooptcopyin(sopt
, &l
, sizeof (l
), sizeof (l
));
4668 so
->so_linger
= (sopt
->sopt_name
== SO_LINGER
) ?
4669 l
.l_linger
: l
.l_linger
* hz
;
4671 so
->so_options
|= SO_LINGER
;
4673 so
->so_options
&= ~SO_LINGER
;
4679 case SO_USELOOPBACK
:
4685 case SO_TIMESTAMP_MONOTONIC
:
4688 case SO_WANTOOBFLAG
:
4689 case SO_NOWAKEFROMSLEEP
:
4690 case SO_NOAPNFALLBK
:
4691 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4696 so
->so_options
|= sopt
->sopt_name
;
4698 so
->so_options
&= ~sopt
->sopt_name
;
4705 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4711 * Values < 1 make no sense for any of these
4712 * options, so disallow them.
4719 switch (sopt
->sopt_name
) {
4722 struct sockbuf
*sb
=
4723 (sopt
->sopt_name
== SO_SNDBUF
) ?
4724 &so
->so_snd
: &so
->so_rcv
;
4725 if (sbreserve(sb
, (u_int32_t
)optval
) == 0) {
4729 sb
->sb_flags
|= SB_USRSIZE
;
4730 sb
->sb_flags
&= ~SB_AUTOSIZE
;
4731 sb
->sb_idealsize
= (u_int32_t
)optval
;
4735 * Make sure the low-water is never greater than
4739 int space
= sbspace(&so
->so_snd
);
4740 u_int32_t hiwat
= so
->so_snd
.sb_hiwat
;
4742 if (so
->so_snd
.sb_flags
& SB_UNIX
) {
4744 (struct unpcb
*)(so
->so_pcb
);
4746 unp
->unp_conn
!= NULL
) {
4747 hiwat
+= unp
->unp_conn
->unp_cc
;
4751 so
->so_snd
.sb_lowat
=
4755 if (space
>= so
->so_snd
.sb_lowat
) {
4762 so
->so_rcv
.sb_lowat
=
4763 (optval
> so
->so_rcv
.sb_hiwat
) ?
4764 so
->so_rcv
.sb_hiwat
: optval
;
4765 data_len
= so
->so_rcv
.sb_cc
4766 - so
->so_rcv
.sb_ctl
;
4767 if (data_len
>= so
->so_rcv
.sb_lowat
)
4776 error
= sooptcopyin_timeval(sopt
, &tv
);
4780 switch (sopt
->sopt_name
) {
4782 so
->so_snd
.sb_timeo
= tv
;
4785 so
->so_rcv
.sb_timeo
= tv
;
4793 error
= sooptcopyin(sopt
, &nke
, sizeof (nke
),
4798 error
= sflt_attach_internal(so
, nke
.nke_handle
);
4803 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4808 so
->so_flags
|= SOF_NOSIGPIPE
;
4810 so
->so_flags
&= ~SOF_NOSIGPIPE
;
4814 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4819 so
->so_flags
|= SOF_NOADDRAVAIL
;
4821 so
->so_flags
&= ~SOF_NOADDRAVAIL
;
4824 case SO_REUSESHAREUID
:
4825 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4830 so
->so_flags
|= SOF_REUSESHAREUID
;
4832 so
->so_flags
&= ~SOF_REUSESHAREUID
;
4835 case SO_NOTIFYCONFLICT
:
4836 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
4840 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4845 so
->so_flags
|= SOF_NOTIFYCONFLICT
;
4847 so
->so_flags
&= ~SOF_NOTIFYCONFLICT
;
4850 case SO_RESTRICTIONS
:
4851 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4856 error
= so_set_restrictions(so
, optval
);
4859 case SO_AWDL_UNRESTRICTED
:
4860 if (SOCK_DOM(so
) != PF_INET
&&
4861 SOCK_DOM(so
) != PF_INET6
) {
4865 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
4870 error
= soopt_cred_check(so
,
4871 PRIV_NET_RESTRICTED_AWDL
);
4873 inp_set_awdl_unrestricted(
4876 inp_clear_awdl_unrestricted(sotoinpcb(so
));
4878 case SO_INTCOPROC_ALLOW
:
4879 if (SOCK_DOM(so
) != PF_INET6
) {
4883 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
4888 inp_get_intcoproc_allowed(sotoinpcb(so
)) == FALSE
) {
4889 error
= soopt_cred_check(so
,
4890 PRIV_NET_RESTRICTED_INTCOPROC
);
4892 inp_set_intcoproc_allowed(
4894 } else if (optval
== 0)
4895 inp_clear_intcoproc_allowed(sotoinpcb(so
));
4899 #if CONFIG_MACF_SOCKET
4900 if ((error
= sooptcopyin(sopt
, &extmac
, sizeof (extmac
),
4901 sizeof (extmac
))) != 0)
4904 error
= mac_setsockopt_label(proc_ucred(sopt
->sopt_p
),
4908 #endif /* MAC_SOCKET */
4911 case SO_UPCALLCLOSEWAIT
:
4912 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4917 so
->so_flags
|= SOF_UPCALLCLOSEWAIT
;
4919 so
->so_flags
&= ~SOF_UPCALLCLOSEWAIT
;
4923 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4928 so
->so_flags
|= SOF_BINDRANDOMPORT
;
4930 so
->so_flags
&= ~SOF_BINDRANDOMPORT
;
4933 case SO_NP_EXTENSIONS
: {
4934 struct so_np_extensions sonpx
;
4936 error
= sooptcopyin(sopt
, &sonpx
, sizeof (sonpx
),
4940 if (sonpx
.npx_mask
& ~SONPX_MASK_VALID
) {
4945 * Only one bit defined for now
4947 if ((sonpx
.npx_mask
& SONPX_SETOPTSHUT
)) {
4948 if ((sonpx
.npx_flags
& SONPX_SETOPTSHUT
))
4949 so
->so_flags
|= SOF_NPX_SETOPTSHUT
;
4951 so
->so_flags
&= ~SOF_NPX_SETOPTSHUT
;
4956 case SO_TRAFFIC_CLASS
: {
4957 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4961 if (optval
>= SO_TC_NET_SERVICE_OFFSET
) {
4962 int netsvc
= optval
- SO_TC_NET_SERVICE_OFFSET
;
4963 error
= so_set_net_service_type(so
, netsvc
);
4966 error
= so_set_traffic_class(so
, optval
);
4969 so
->so_flags1
&= ~SOF1_TC_NET_SERV_TYPE
;
4970 so
->so_netsvctype
= _NET_SERVICE_TYPE_UNSPEC
;
4974 case SO_RECV_TRAFFIC_CLASS
: {
4975 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
4980 so
->so_flags
&= ~SOF_RECV_TRAFFIC_CLASS
;
4982 so
->so_flags
|= SOF_RECV_TRAFFIC_CLASS
;
4986 #if (DEVELOPMENT || DEBUG)
4987 case SO_TRAFFIC_CLASS_DBG
: {
4988 struct so_tcdbg so_tcdbg
;
4990 error
= sooptcopyin(sopt
, &so_tcdbg
,
4991 sizeof (struct so_tcdbg
), sizeof (struct so_tcdbg
));
4994 error
= so_set_tcdbg(so
, &so_tcdbg
);
4999 #endif /* (DEVELOPMENT || DEBUG) */
5001 case SO_PRIVILEGED_TRAFFIC_CLASS
:
5002 error
= priv_check_cred(kauth_cred_get(),
5003 PRIV_NET_PRIVILEGED_TRAFFIC_CLASS
, 0);
5006 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5011 so
->so_flags
&= ~SOF_PRIVILEGED_TRAFFIC_CLASS
;
5013 so
->so_flags
|= SOF_PRIVILEGED_TRAFFIC_CLASS
;
5017 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5019 if (error
!= 0 || (so
->so_flags
& SOF_DEFUNCT
)) {
5025 * Any process can set SO_DEFUNCTOK (clear
5026 * SOF_NODEFUNCT), but only root can clear
5027 * SO_DEFUNCTOK (set SOF_NODEFUNCT).
5030 kauth_cred_issuser(kauth_cred_get()) == 0) {
5035 so
->so_flags
&= ~SOF_NODEFUNCT
;
5037 so
->so_flags
|= SOF_NODEFUNCT
;
5039 if (SOCK_DOM(so
) == PF_INET
||
5040 SOCK_DOM(so
) == PF_INET6
) {
5041 char s
[MAX_IPv6_STR_LEN
];
5042 char d
[MAX_IPv6_STR_LEN
];
5043 struct inpcb
*inp
= sotoinpcb(so
);
5045 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx "
5046 "[%s %s:%d -> %s:%d] is now marked "
5047 "as %seligible for "
5048 "defunct\n", __func__
, proc_selfpid(),
5049 proc_best_name(current_proc()),
5050 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
5051 (SOCK_TYPE(so
) == SOCK_STREAM
) ?
5052 "TCP" : "UDP", inet_ntop(SOCK_DOM(so
),
5053 ((SOCK_DOM(so
) == PF_INET
) ?
5054 (void *)&inp
->inp_laddr
.s_addr
:
5055 (void *)&inp
->in6p_laddr
), s
, sizeof (s
)),
5056 ntohs(inp
->in6p_lport
),
5057 inet_ntop(SOCK_DOM(so
),
5058 (SOCK_DOM(so
) == PF_INET
) ?
5059 (void *)&inp
->inp_faddr
.s_addr
:
5060 (void *)&inp
->in6p_faddr
, d
, sizeof (d
)),
5061 ntohs(inp
->in6p_fport
),
5062 (so
->so_flags
& SOF_NODEFUNCT
) ?
5065 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx [%d,%d] "
5066 "is now marked as %seligible for "
5068 __func__
, proc_selfpid(),
5069 proc_best_name(current_proc()),
5070 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
5071 SOCK_DOM(so
), SOCK_TYPE(so
),
5072 (so
->so_flags
& SOF_NODEFUNCT
) ?
5078 /* This option is not settable */
5082 case SO_OPPORTUNISTIC
:
5083 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5086 error
= so_set_opportunistic(so
, optval
);
5090 /* This option is handled by lower layer(s) */
5095 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5098 error
= so_set_recv_anyif(so
, optval
);
5101 case SO_TRAFFIC_MGT_BACKGROUND
: {
5102 /* This option is handled by lower layer(s) */
5108 case SO_FLOW_DIVERT_TOKEN
:
5109 error
= flow_divert_token_set(so
, sopt
);
5111 #endif /* FLOW_DIVERT */
5115 if ((error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5116 sizeof (optval
))) != 0)
5119 error
= so_set_effective_pid(so
, optval
, sopt
->sopt_p
);
5122 case SO_DELEGATED_UUID
: {
5125 if ((error
= sooptcopyin(sopt
, &euuid
, sizeof (euuid
),
5126 sizeof (euuid
))) != 0)
5129 error
= so_set_effective_uuid(so
, euuid
, sopt
->sopt_p
);
5134 case SO_NECP_ATTRIBUTES
:
5135 error
= necp_set_socket_attributes(so
, sopt
);
5140 case SO_MPTCP_FASTJOIN
:
5141 if (!((so
->so_flags
& SOF_MP_SUBFLOW
) ||
5142 ((SOCK_CHECK_DOM(so
, PF_MULTIPATH
)) &&
5143 (SOCK_CHECK_PROTO(so
, IPPROTO_TCP
))))) {
5144 error
= ENOPROTOOPT
;
5148 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5153 so
->so_flags
&= ~SOF_MPTCP_FASTJOIN
;
5155 so
->so_flags
|= SOF_MPTCP_FASTJOIN
;
5159 case SO_EXTENDED_BK_IDLE
:
5160 error
= sooptcopyin(sopt
, &optval
, sizeof (optval
),
5163 error
= so_set_extended_bk_idle(so
, optval
);
5166 case SO_MARK_CELLFALLBACK
:
5167 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5176 so
->so_flags1
&= ~SOF1_CELLFALLBACK
;
5178 so
->so_flags1
|= SOF1_CELLFALLBACK
;
5181 case SO_NET_SERVICE_TYPE
: {
5182 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5186 error
= so_set_net_service_type(so
, optval
);
5190 case SO_QOSMARKING_POLICY_OVERRIDE
:
5191 error
= priv_check_cred(kauth_cred_get(),
5192 PRIV_NET_QOSMARKING_POLICY_OVERRIDE
, 0);
5195 error
= sooptcopyin(sopt
, &optval
, sizeof(optval
),
5200 so
->so_flags1
&= ~SOF1_QOSMARKING_POLICY_OVERRIDE
;
5202 so
->so_flags1
|= SOF1_QOSMARKING_POLICY_OVERRIDE
;
5206 error
= ENOPROTOOPT
;
5209 if (error
== 0 && so
->so_proto
!= NULL
&&
5210 so
->so_proto
->pr_ctloutput
!= NULL
) {
5211 (void) so
->so_proto
->pr_ctloutput(so
, sopt
);
5216 socket_unlock(so
, 1);
5220 /* Helper routines for getsockopt */
5222 sooptcopyout(struct sockopt
*sopt
, void *buf
, size_t len
)
5230 * Documented get behavior is that we always return a value,
5231 * possibly truncated to fit in the user's buffer.
5232 * Traditional behavior is that we always tell the user
5233 * precisely how much we copied, rather than something useful
5234 * like the total amount we had available for her.
5235 * Note that this interface is not idempotent; the entire answer must
5236 * generated ahead of time.
5238 valsize
= min(len
, sopt
->sopt_valsize
);
5239 sopt
->sopt_valsize
= valsize
;
5240 if (sopt
->sopt_val
!= USER_ADDR_NULL
) {
5241 if (sopt
->sopt_p
!= kernproc
)
5242 error
= copyout(buf
, sopt
->sopt_val
, valsize
);
5244 bcopy(buf
, CAST_DOWN(caddr_t
, sopt
->sopt_val
), valsize
);
5250 sooptcopyout_timeval(struct sockopt
*sopt
, const struct timeval
*tv_p
)
5254 struct user64_timeval tv64
;
5255 struct user32_timeval tv32
;
5260 if (proc_is64bit(sopt
->sopt_p
)) {
5261 len
= sizeof (tv64
);
5262 tv64
.tv_sec
= tv_p
->tv_sec
;
5263 tv64
.tv_usec
= tv_p
->tv_usec
;
5266 len
= sizeof (tv32
);
5267 tv32
.tv_sec
= tv_p
->tv_sec
;
5268 tv32
.tv_usec
= tv_p
->tv_usec
;
5271 valsize
= min(len
, sopt
->sopt_valsize
);
5272 sopt
->sopt_valsize
= valsize
;
5273 if (sopt
->sopt_val
!= USER_ADDR_NULL
) {
5274 if (sopt
->sopt_p
!= kernproc
)
5275 error
= copyout(val
, sopt
->sopt_val
, valsize
);
5277 bcopy(val
, CAST_DOWN(caddr_t
, sopt
->sopt_val
), valsize
);
5285 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
5286 * <pr_ctloutput>:???
5287 * <sf_getoption>:???
5290 sogetoptlock(struct socket
*so
, struct sockopt
*sopt
, int dolock
)
5295 #if CONFIG_MACF_SOCKET
5297 #endif /* MAC_SOCKET */
5299 if (sopt
->sopt_dir
!= SOPT_GET
)
5300 sopt
->sopt_dir
= SOPT_GET
;
5305 error
= sflt_getsockopt(so
, sopt
);
5307 if (error
== EJUSTRETURN
)
5312 if (sopt
->sopt_level
!= SOL_SOCKET
) {
5313 if (so
->so_proto
!= NULL
&&
5314 so
->so_proto
->pr_ctloutput
!= NULL
) {
5315 error
= (*so
->so_proto
->pr_ctloutput
)(so
, sopt
);
5318 error
= ENOPROTOOPT
;
5321 * Allow socket-level (SOL_SOCKET) options to be filtered by
5322 * the protocol layer, if needed. A zero value returned from
5323 * the handler means use default socket-level processing as
5324 * done by the rest of this routine. Otherwise, any other
5325 * return value indicates that the option is unsupported.
5327 if (so
->so_proto
!= NULL
&& (error
= so
->so_proto
->pr_usrreqs
->
5328 pru_socheckopt(so
, sopt
)) != 0)
5332 switch (sopt
->sopt_name
) {
5335 l
.l_onoff
= ((so
->so_options
& SO_LINGER
) ? 1 : 0);
5336 l
.l_linger
= (sopt
->sopt_name
== SO_LINGER
) ?
5337 so
->so_linger
: so
->so_linger
/ hz
;
5338 error
= sooptcopyout(sopt
, &l
, sizeof (l
));
5341 case SO_USELOOPBACK
:
5350 case SO_TIMESTAMP_MONOTONIC
:
5353 case SO_WANTOOBFLAG
:
5354 case SO_NOWAKEFROMSLEEP
:
5355 case SO_NOAPNFALLBK
:
5356 optval
= so
->so_options
& sopt
->sopt_name
;
5358 error
= sooptcopyout(sopt
, &optval
, sizeof (optval
));
5362 optval
= so
->so_type
;
5366 if (so
->so_proto
->pr_flags
& PR_ATOMIC
) {
5371 m1
= so
->so_rcv
.sb_mb
;
5372 while (m1
!= NULL
) {
5373 if (m1
->m_type
== MT_DATA
||
5374 m1
->m_type
== MT_HEADER
||
5375 m1
->m_type
== MT_OOBDATA
)
5376 pkt_total
+= m1
->m_len
;
5381 optval
= so
->so_rcv
.sb_cc
- so
->so_rcv
.sb_ctl
;
5386 if (so
->so_proto
->pr_flags
& PR_ATOMIC
) {
5390 m1
= so
->so_rcv
.sb_mb
;
5391 while (m1
!= NULL
) {
5392 if (m1
->m_type
== MT_DATA
||
5393 m1
->m_type
== MT_HEADER
||
5394 m1
->m_type
== MT_OOBDATA
)
5406 optval
= so
->so_snd
.sb_cc
;
5410 optval
= so
->so_error
;
5415 u_int32_t hiwat
= so
->so_snd
.sb_hiwat
;
5417 if (so
->so_snd
.sb_flags
& SB_UNIX
) {
5419 (struct unpcb
*)(so
->so_pcb
);
5420 if (unp
!= NULL
&& unp
->unp_conn
!= NULL
) {
5421 hiwat
+= unp
->unp_conn
->unp_cc
;
5429 optval
= so
->so_rcv
.sb_hiwat
;
5433 optval
= so
->so_snd
.sb_lowat
;
5437 optval
= so
->so_rcv
.sb_lowat
;
5442 tv
= (sopt
->sopt_name
== SO_SNDTIMEO
?
5443 so
->so_snd
.sb_timeo
: so
->so_rcv
.sb_timeo
);
5445 error
= sooptcopyout_timeval(sopt
, &tv
);
5449 optval
= (so
->so_flags
& SOF_NOSIGPIPE
);
5453 optval
= (so
->so_flags
& SOF_NOADDRAVAIL
);
5456 case SO_REUSESHAREUID
:
5457 optval
= (so
->so_flags
& SOF_REUSESHAREUID
);
5461 case SO_NOTIFYCONFLICT
:
5462 optval
= (so
->so_flags
& SOF_NOTIFYCONFLICT
);
5465 case SO_RESTRICTIONS
:
5466 optval
= so_get_restrictions(so
);
5469 case SO_AWDL_UNRESTRICTED
:
5470 if (SOCK_DOM(so
) == PF_INET
||
5471 SOCK_DOM(so
) == PF_INET6
) {
5472 optval
= inp_get_awdl_unrestricted(
5479 case SO_INTCOPROC_ALLOW
:
5480 if (SOCK_DOM(so
) == PF_INET6
) {
5481 optval
= inp_get_intcoproc_allowed(
5489 #if CONFIG_MACF_SOCKET
5490 if ((error
= sooptcopyin(sopt
, &extmac
, sizeof (extmac
),
5491 sizeof (extmac
))) != 0 ||
5492 (error
= mac_socket_label_get(proc_ucred(
5493 sopt
->sopt_p
), so
, &extmac
)) != 0)
5496 error
= sooptcopyout(sopt
, &extmac
, sizeof (extmac
));
5499 #endif /* MAC_SOCKET */
5503 #if CONFIG_MACF_SOCKET
5504 if ((error
= sooptcopyin(sopt
, &extmac
, sizeof (extmac
),
5505 sizeof (extmac
))) != 0 ||
5506 (error
= mac_socketpeer_label_get(proc_ucred(
5507 sopt
->sopt_p
), so
, &extmac
)) != 0)
5510 error
= sooptcopyout(sopt
, &extmac
, sizeof (extmac
));
5513 #endif /* MAC_SOCKET */
5516 #ifdef __APPLE_API_PRIVATE
5517 case SO_UPCALLCLOSEWAIT
:
5518 optval
= (so
->so_flags
& SOF_UPCALLCLOSEWAIT
);
5522 optval
= (so
->so_flags
& SOF_BINDRANDOMPORT
);
5525 case SO_NP_EXTENSIONS
: {
5526 struct so_np_extensions sonpx
;
5528 sonpx
.npx_flags
= (so
->so_flags
& SOF_NPX_SETOPTSHUT
) ?
5529 SONPX_SETOPTSHUT
: 0;
5530 sonpx
.npx_mask
= SONPX_MASK_VALID
;
5532 error
= sooptcopyout(sopt
, &sonpx
,
5533 sizeof (struct so_np_extensions
));
5537 case SO_TRAFFIC_CLASS
:
5538 optval
= so
->so_traffic_class
;
5541 case SO_RECV_TRAFFIC_CLASS
:
5542 optval
= (so
->so_flags
& SOF_RECV_TRAFFIC_CLASS
);
5545 case SO_TRAFFIC_CLASS_STATS
:
5546 error
= sooptcopyout(sopt
, &so
->so_tc_stats
,
5547 sizeof (so
->so_tc_stats
));
5550 #if (DEVELOPMENT || DEBUG)
5551 case SO_TRAFFIC_CLASS_DBG
:
5552 error
= sogetopt_tcdbg(so
, sopt
);
5554 #endif /* (DEVELOPMENT || DEBUG) */
5556 case SO_PRIVILEGED_TRAFFIC_CLASS
:
5557 optval
= (so
->so_flags
& SOF_PRIVILEGED_TRAFFIC_CLASS
);
5561 optval
= !(so
->so_flags
& SOF_NODEFUNCT
);
5565 optval
= (so
->so_flags
& SOF_DEFUNCT
);
5568 case SO_OPPORTUNISTIC
:
5569 optval
= so_get_opportunistic(so
);
5573 /* This option is not gettable */
5578 optval
= so_get_recv_anyif(so
);
5581 case SO_TRAFFIC_MGT_BACKGROUND
:
5582 /* This option is handled by lower layer(s) */
5583 if (so
->so_proto
!= NULL
&&
5584 so
->so_proto
->pr_ctloutput
!= NULL
) {
5585 (void) so
->so_proto
->pr_ctloutput(so
, sopt
);
5590 case SO_FLOW_DIVERT_TOKEN
:
5591 error
= flow_divert_token_get(so
, sopt
);
5593 #endif /* FLOW_DIVERT */
5596 case SO_NECP_ATTRIBUTES
:
5597 error
= necp_get_socket_attributes(so
, sopt
);
5602 case SO_CFIL_SOCK_ID
: {
5603 cfil_sock_id_t sock_id
;
5605 sock_id
= cfil_sock_id_from_socket(so
);
5607 error
= sooptcopyout(sopt
, &sock_id
,
5608 sizeof(cfil_sock_id_t
));
5611 #endif /* CONTENT_FILTER */
5614 case SO_MPTCP_FASTJOIN
:
5615 if (!((so
->so_flags
& SOF_MP_SUBFLOW
) ||
5616 ((SOCK_CHECK_DOM(so
, PF_MULTIPATH
)) &&
5617 (SOCK_CHECK_PROTO(so
, IPPROTO_TCP
))))) {
5618 error
= ENOPROTOOPT
;
5621 optval
= (so
->so_flags
& SOF_MPTCP_FASTJOIN
);
5622 /* Fixed along with rdar://19391339 */
5626 case SO_EXTENDED_BK_IDLE
:
5627 optval
= (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
);
5629 case SO_MARK_CELLFALLBACK
:
5630 optval
= ((so
->so_flags1
& SOF1_CELLFALLBACK
) > 0)
5633 case SO_NET_SERVICE_TYPE
: {
5634 if ((so
->so_flags1
& SOF1_TC_NET_SERV_TYPE
))
5635 optval
= so
->so_netsvctype
;
5637 optval
= NET_SERVICE_TYPE_BE
;
5640 case SO_NETSVC_MARKING_LEVEL
:
5641 optval
= so_get_netsvc_marking_level(so
);
5645 error
= ENOPROTOOPT
;
5651 socket_unlock(so
, 1);
5656 * The size limits on our soopt_getm is different from that on FreeBSD.
5657 * We limit the size of options to MCLBYTES. This will have to change
5658 * if we need to define options that need more space than MCLBYTES.
5661 soopt_getm(struct sockopt
*sopt
, struct mbuf
**mp
)
5663 struct mbuf
*m
, *m_prev
;
5664 int sopt_size
= sopt
->sopt_valsize
;
5667 if (sopt_size
<= 0 || sopt_size
> MCLBYTES
)
5670 how
= sopt
->sopt_p
!= kernproc
? M_WAIT
: M_DONTWAIT
;
5671 MGET(m
, how
, MT_DATA
);
5674 if (sopt_size
> MLEN
) {
5676 if ((m
->m_flags
& M_EXT
) == 0) {
5680 m
->m_len
= min(MCLBYTES
, sopt_size
);
5682 m
->m_len
= min(MLEN
, sopt_size
);
5684 sopt_size
-= m
->m_len
;
5688 while (sopt_size
> 0) {
5689 MGET(m
, how
, MT_DATA
);
5694 if (sopt_size
> MLEN
) {
5696 if ((m
->m_flags
& M_EXT
) == 0) {
5701 m
->m_len
= min(MCLBYTES
, sopt_size
);
5703 m
->m_len
= min(MLEN
, sopt_size
);
5705 sopt_size
-= m
->m_len
;
5712 /* copyin sopt data into mbuf chain */
5714 soopt_mcopyin(struct sockopt
*sopt
, struct mbuf
*m
)
5716 struct mbuf
*m0
= m
;
5718 if (sopt
->sopt_val
== USER_ADDR_NULL
)
5720 while (m
!= NULL
&& sopt
->sopt_valsize
>= m
->m_len
) {
5721 if (sopt
->sopt_p
!= kernproc
) {
5724 error
= copyin(sopt
->sopt_val
, mtod(m
, char *),
5731 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
),
5732 mtod(m
, char *), m
->m_len
);
5734 sopt
->sopt_valsize
-= m
->m_len
;
5735 sopt
->sopt_val
+= m
->m_len
;
5738 /* should be allocated enoughly at ip6_sooptmcopyin() */
5740 panic("soopt_mcopyin");
5746 /* copyout mbuf chain data into soopt */
5748 soopt_mcopyout(struct sockopt
*sopt
, struct mbuf
*m
)
5750 struct mbuf
*m0
= m
;
5753 if (sopt
->sopt_val
== USER_ADDR_NULL
)
5755 while (m
!= NULL
&& sopt
->sopt_valsize
>= m
->m_len
) {
5756 if (sopt
->sopt_p
!= kernproc
) {
5759 error
= copyout(mtod(m
, char *), sopt
->sopt_val
,
5766 bcopy(mtod(m
, char *),
5767 CAST_DOWN(caddr_t
, sopt
->sopt_val
), m
->m_len
);
5769 sopt
->sopt_valsize
-= m
->m_len
;
5770 sopt
->sopt_val
+= m
->m_len
;
5771 valsize
+= m
->m_len
;
5775 /* enough soopt buffer should be given from user-land */
5779 sopt
->sopt_valsize
= valsize
;
5784 sohasoutofband(struct socket
*so
)
5786 if (so
->so_pgid
< 0)
5787 gsignal(-so
->so_pgid
, SIGURG
);
5788 else if (so
->so_pgid
> 0)
5789 proc_signal(so
->so_pgid
, SIGURG
);
5790 selwakeup(&so
->so_rcv
.sb_sel
);
5791 if (so
->so_rcv
.sb_flags
& SB_KNOTE
) {
5792 KNOTE(&so
->so_rcv
.sb_sel
.si_note
,
5793 (NOTE_OOB
| SO_FILT_HINT_LOCKED
));
5798 sopoll(struct socket
*so
, int events
, kauth_cred_t cred
, void * wql
)
5800 #pragma unused(cred)
5801 struct proc
*p
= current_proc();
5805 so_update_last_owner_locked(so
, PROC_NULL
);
5806 so_update_policy(so
);
5808 if (events
& (POLLIN
| POLLRDNORM
))
5810 revents
|= events
& (POLLIN
| POLLRDNORM
);
5812 if (events
& (POLLOUT
| POLLWRNORM
))
5813 if (sowriteable(so
))
5814 revents
|= events
& (POLLOUT
| POLLWRNORM
);
5816 if (events
& (POLLPRI
| POLLRDBAND
))
5817 if (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
))
5818 revents
|= events
& (POLLPRI
| POLLRDBAND
);
5821 if (events
& (POLLIN
| POLLPRI
| POLLRDNORM
| POLLRDBAND
)) {
5823 * Darwin sets the flag first,
5824 * BSD calls selrecord first
5826 so
->so_rcv
.sb_flags
|= SB_SEL
;
5827 selrecord(p
, &so
->so_rcv
.sb_sel
, wql
);
5830 if (events
& (POLLOUT
| POLLWRNORM
)) {
5832 * Darwin sets the flag first,
5833 * BSD calls selrecord first
5835 so
->so_snd
.sb_flags
|= SB_SEL
;
5836 selrecord(p
, &so
->so_snd
.sb_sel
, wql
);
5840 socket_unlock(so
, 1);
5845 soo_kqfilter(struct fileproc
*fp
, struct knote
*kn
, vfs_context_t ctx
)
5848 #if !CONFIG_MACF_SOCKET
5850 #endif /* MAC_SOCKET */
5851 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5855 so_update_last_owner_locked(so
, PROC_NULL
);
5856 so_update_policy(so
);
5858 #if CONFIG_MACF_SOCKET
5859 if (mac_socket_check_kqfilter(proc_ucred(vfs_context_proc(ctx
)),
5861 socket_unlock(so
, 1);
5862 kn
->kn_flags
= EV_ERROR
;
5863 kn
->kn_data
= EPERM
;
5866 #endif /* MAC_SOCKET */
5868 switch (kn
->kn_filter
) {
5870 kn
->kn_filtid
= EVFILTID_SOREAD
;
5873 kn
->kn_filtid
= EVFILTID_SOWRITE
;
5876 kn
->kn_filtid
= EVFILTID_SCK
;
5879 kn
->kn_filtid
= EVFILTID_SOEXCEPT
;
5882 socket_unlock(so
, 1);
5883 kn
->kn_flags
= EV_ERROR
;
5884 kn
->kn_data
= EINVAL
;
5889 * call the appropriate sub-filter attach
5890 * with the socket still locked
5892 result
= knote_fops(kn
)->f_attach(kn
);
5894 socket_unlock(so
, 1);
5900 filt_soread_common(struct knote
*kn
, struct socket
*so
)
5902 if (so
->so_options
& SO_ACCEPTCONN
) {
5906 * Radar 6615193 handle the listen case dynamically
5907 * for kqueue read filter. This allows to call listen()
5908 * after registering the kqueue EVFILT_READ.
5911 kn
->kn_data
= so
->so_qlen
;
5912 is_not_empty
= ! TAILQ_EMPTY(&so
->so_comp
);
5914 return (is_not_empty
);
5917 /* socket isn't a listener */
5919 * NOTE_LOWAT specifies new low water mark in data, i.e.
5920 * the bytes of protocol data. We therefore exclude any
5923 kn
->kn_data
= so
->so_rcv
.sb_cc
- so
->so_rcv
.sb_ctl
;
5925 if (kn
->kn_sfflags
& NOTE_OOB
) {
5926 if (so
->so_oobmark
|| (so
->so_state
& SS_RCVATMARK
)) {
5927 kn
->kn_fflags
|= NOTE_OOB
;
5928 kn
->kn_data
-= so
->so_oobmark
;
5933 if ((so
->so_state
& SS_CANTRCVMORE
)
5935 && cfil_sock_data_pending(&so
->so_rcv
) == 0
5936 #endif /* CONTENT_FILTER */
5938 kn
->kn_flags
|= EV_EOF
;
5939 kn
->kn_fflags
= so
->so_error
;
5943 if (so
->so_error
) { /* temporary udp error */
5947 int64_t lowwat
= so
->so_rcv
.sb_lowat
;
5949 * Ensure that when NOTE_LOWAT is used, the derived
5950 * low water mark is bounded by socket's rcv buf's
5951 * high and low water mark values.
5953 if (kn
->kn_sfflags
& NOTE_LOWAT
) {
5954 if (kn
->kn_sdata
> so
->so_rcv
.sb_hiwat
)
5955 lowwat
= so
->so_rcv
.sb_hiwat
;
5956 else if (kn
->kn_sdata
> lowwat
)
5957 lowwat
= kn
->kn_sdata
;
5961 * The order below is important. Since NOTE_LOWAT
5962 * overrides sb_lowat, check for NOTE_LOWAT case
5965 if (kn
->kn_sfflags
& NOTE_LOWAT
)
5966 return (kn
->kn_data
>= lowwat
);
5968 return (so
->so_rcv
.sb_cc
>= lowwat
);
5972 filt_sorattach(struct knote
*kn
)
5974 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
5979 * If the caller explicitly asked for OOB results (e.g. poll())
5980 * from EVFILT_READ, then save that off in the hookid field
5981 * and reserve the kn_flags EV_OOBAND bit for output only.
5983 if (kn
->kn_filter
== EVFILT_READ
&&
5984 kn
->kn_flags
& EV_OOBAND
) {
5985 kn
->kn_flags
&= ~EV_OOBAND
;
5986 kn
->kn_hookid
= EV_OOBAND
;
5990 if (KNOTE_ATTACH(&so
->so_rcv
.sb_sel
.si_note
, kn
))
5991 so
->so_rcv
.sb_flags
|= SB_KNOTE
;
5993 /* indicate if event is already fired */
5994 return filt_soread_common(kn
, so
);
5998 filt_sordetach(struct knote
*kn
)
6000 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6003 if (so
->so_rcv
.sb_flags
& SB_KNOTE
)
6004 if (KNOTE_DETACH(&so
->so_rcv
.sb_sel
.si_note
, kn
))
6005 so
->so_rcv
.sb_flags
&= ~SB_KNOTE
;
6006 socket_unlock(so
, 1);
6011 filt_soread(struct knote
*kn
, long hint
)
6013 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6016 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
6019 retval
= filt_soread_common(kn
, so
);
6021 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
6022 socket_unlock(so
, 1);
6028 filt_sortouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
6030 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6035 /* save off the new input fflags and data */
6036 kn
->kn_sfflags
= kev
->fflags
;
6037 kn
->kn_sdata
= kev
->data
;
6038 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
6039 kn
->kn_udata
= kev
->udata
;
6041 /* determine if changes result in fired events */
6042 retval
= filt_soread_common(kn
, so
);
6044 socket_unlock(so
, 1);
6050 filt_sorprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
6052 #pragma unused(data)
6053 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6057 retval
= filt_soread_common(kn
, so
);
6059 *kev
= kn
->kn_kevent
;
6060 if (kn
->kn_flags
& EV_CLEAR
) {
6065 socket_unlock(so
, 1);
6071 so_wait_for_if_feedback(struct socket
*so
)
6073 if ((SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) &&
6074 (so
->so_state
& SS_ISCONNECTED
)) {
6075 struct inpcb
*inp
= sotoinpcb(so
);
6076 if (INP_WAIT_FOR_IF_FEEDBACK(inp
))
6083 filt_sowrite_common(struct knote
*kn
, struct socket
*so
)
6087 kn
->kn_data
= sbspace(&so
->so_snd
);
6088 if (so
->so_state
& SS_CANTSENDMORE
) {
6089 kn
->kn_flags
|= EV_EOF
;
6090 kn
->kn_fflags
= so
->so_error
;
6093 if (so
->so_error
) { /* temporary udp error */
6096 if (!socanwrite(so
)) {
6099 if (so
->so_flags1
& SOF1_PRECONNECT_DATA
) {
6102 int64_t lowwat
= so
->so_snd
.sb_lowat
;
6103 if (kn
->kn_sfflags
& NOTE_LOWAT
) {
6104 if (kn
->kn_sdata
> so
->so_snd
.sb_hiwat
)
6105 lowwat
= so
->so_snd
.sb_hiwat
;
6106 else if (kn
->kn_sdata
> lowwat
)
6107 lowwat
= kn
->kn_sdata
;
6109 if (kn
->kn_data
>= lowwat
) {
6110 if ((so
->so_flags
& SOF_NOTSENT_LOWAT
)
6111 #if (DEBUG || DEVELOPMENT)
6112 && so_notsent_lowat_check
== 1
6113 #endif /* DEBUG || DEVELOPMENT */
6115 if ((SOCK_DOM(so
) == PF_INET
||
6116 SOCK_DOM(so
) == PF_INET6
) &&
6117 so
->so_type
== SOCK_STREAM
) {
6118 ret
= tcp_notsent_lowat_check(so
);
6121 else if ((SOCK_DOM(so
) == PF_MULTIPATH
) &&
6122 (SOCK_PROTO(so
) == IPPROTO_TCP
)) {
6123 ret
= mptcp_notsent_lowat_check(so
);
6133 if (so_wait_for_if_feedback(so
))
6139 filt_sowattach(struct knote
*kn
)
6141 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6144 if (KNOTE_ATTACH(&so
->so_snd
.sb_sel
.si_note
, kn
))
6145 so
->so_snd
.sb_flags
|= SB_KNOTE
;
6147 /* determine if its already fired */
6148 return filt_sowrite_common(kn
, so
);
6152 filt_sowdetach(struct knote
*kn
)
6154 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6157 if (so
->so_snd
.sb_flags
& SB_KNOTE
)
6158 if (KNOTE_DETACH(&so
->so_snd
.sb_sel
.si_note
, kn
))
6159 so
->so_snd
.sb_flags
&= ~SB_KNOTE
;
6160 socket_unlock(so
, 1);
6165 filt_sowrite(struct knote
*kn
, long hint
)
6167 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6170 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
6173 ret
= filt_sowrite_common(kn
, so
);
6175 if ((hint
& SO_FILT_HINT_LOCKED
) == 0)
6176 socket_unlock(so
, 1);
6182 filt_sowtouch(struct knote
*kn
, struct kevent_internal_s
*kev
)
6184 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6189 /*save off the new input fflags and data */
6190 kn
->kn_sfflags
= kev
->fflags
;
6191 kn
->kn_sdata
= kev
->data
;
6192 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
6193 kn
->kn_udata
= kev
->udata
;
6195 /* determine if these changes result in a triggered event */
6196 ret
= filt_sowrite_common(kn
, so
);
6198 socket_unlock(so
, 1);
6204 filt_sowprocess(struct knote
*kn
, struct filt_process_s
*data
, struct kevent_internal_s
*kev
)
6206 #pragma unused(data)
6207 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6211 ret
= filt_sowrite_common(kn
, so
);
6213 *kev
= kn
->kn_kevent
;
6214 if (kn
->kn_flags
& EV_CLEAR
) {
6219 socket_unlock(so
, 1);
6224 filt_sockev_common(struct knote
*kn
, struct socket
*so
, long ev_hint
)
6227 uint32_t level_trigger
= 0;
6229 if (ev_hint
& SO_FILT_HINT_CONNRESET
) {
6230 kn
->kn_fflags
|= NOTE_CONNRESET
;
6232 if (ev_hint
& SO_FILT_HINT_TIMEOUT
) {
6233 kn
->kn_fflags
|= NOTE_TIMEOUT
;
6235 if (ev_hint
& SO_FILT_HINT_NOSRCADDR
) {
6236 kn
->kn_fflags
|= NOTE_NOSRCADDR
;
6238 if (ev_hint
& SO_FILT_HINT_IFDENIED
) {
6239 kn
->kn_fflags
|= NOTE_IFDENIED
;
6241 if (ev_hint
& SO_FILT_HINT_KEEPALIVE
) {
6242 kn
->kn_fflags
|= NOTE_KEEPALIVE
;
6244 if (ev_hint
& SO_FILT_HINT_ADAPTIVE_WTIMO
) {
6245 kn
->kn_fflags
|= NOTE_ADAPTIVE_WTIMO
;
6247 if (ev_hint
& SO_FILT_HINT_ADAPTIVE_RTIMO
) {
6248 kn
->kn_fflags
|= NOTE_ADAPTIVE_RTIMO
;
6250 if ((ev_hint
& SO_FILT_HINT_CONNECTED
) ||
6251 (so
->so_state
& SS_ISCONNECTED
)) {
6252 kn
->kn_fflags
|= NOTE_CONNECTED
;
6253 level_trigger
|= NOTE_CONNECTED
;
6255 if ((ev_hint
& SO_FILT_HINT_DISCONNECTED
) ||
6256 (so
->so_state
& SS_ISDISCONNECTED
)) {
6257 kn
->kn_fflags
|= NOTE_DISCONNECTED
;
6258 level_trigger
|= NOTE_DISCONNECTED
;
6260 if (ev_hint
& SO_FILT_HINT_CONNINFO_UPDATED
) {
6261 if (so
->so_proto
!= NULL
&&
6262 (so
->so_proto
->pr_flags
& PR_EVCONNINFO
))
6263 kn
->kn_fflags
|= NOTE_CONNINFO_UPDATED
;
6266 if ((ev_hint
& SO_FILT_HINT_NOTIFY_ACK
) ||
6267 tcp_notify_ack_active(so
)) {
6268 kn
->kn_fflags
|= NOTE_NOTIFY_ACK
;
6271 if ((so
->so_state
& SS_CANTRCVMORE
)
6273 && cfil_sock_data_pending(&so
->so_rcv
) == 0
6274 #endif /* CONTENT_FILTER */
6276 kn
->kn_fflags
|= NOTE_READCLOSED
;
6277 level_trigger
|= NOTE_READCLOSED
;
6280 if (so
->so_state
& SS_CANTSENDMORE
) {
6281 kn
->kn_fflags
|= NOTE_WRITECLOSED
;
6282 level_trigger
|= NOTE_WRITECLOSED
;
6285 if ((ev_hint
& SO_FILT_HINT_SUSPEND
) ||
6286 (so
->so_flags
& SOF_SUSPENDED
)) {
6287 kn
->kn_fflags
&= ~(NOTE_SUSPEND
| NOTE_RESUME
);
6289 /* If resume event was delivered before, reset it */
6290 kn
->kn_hookid
&= ~NOTE_RESUME
;
6292 kn
->kn_fflags
|= NOTE_SUSPEND
;
6293 level_trigger
|= NOTE_SUSPEND
;
6296 if ((ev_hint
& SO_FILT_HINT_RESUME
) ||
6297 (so
->so_flags
& SOF_SUSPENDED
) == 0) {
6298 kn
->kn_fflags
&= ~(NOTE_SUSPEND
| NOTE_RESUME
);
6300 /* If suspend event was delivered before, reset it */
6301 kn
->kn_hookid
&= ~NOTE_SUSPEND
;
6303 kn
->kn_fflags
|= NOTE_RESUME
;
6304 level_trigger
|= NOTE_RESUME
;
6307 if (so
->so_error
!= 0) {
6309 kn
->kn_data
= so
->so_error
;
6310 kn
->kn_flags
|= EV_EOF
;
6312 get_sockev_state(so
, (u_int32_t
*)&(kn
->kn_data
));
6315 /* Reset any events that are not requested on this knote */
6316 kn
->kn_fflags
&= (kn
->kn_sfflags
& EVFILT_SOCK_ALL_MASK
);
6317 level_trigger
&= (kn
->kn_sfflags
& EVFILT_SOCK_ALL_MASK
);
6319 /* Find the level triggerred events that are already delivered */
6320 level_trigger
&= kn
->kn_hookid
;
6321 level_trigger
&= EVFILT_SOCK_LEVEL_TRIGGER_MASK
;
6323 /* Do not deliver level triggerred events more than once */
6324 if ((kn
->kn_fflags
& ~level_trigger
) != 0)
6331 filt_sockattach(struct knote
*kn
)
6333 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6337 if (KNOTE_ATTACH(&so
->so_klist
, kn
))
6338 so
->so_flags
|= SOF_KNOTE
;
6340 /* determine if event already fired */
6341 return filt_sockev_common(kn
, so
, 0);
6345 filt_sockdetach(struct knote
*kn
)
6347 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6350 if ((so
->so_flags
& SOF_KNOTE
) != 0)
6351 if (KNOTE_DETACH(&so
->so_klist
, kn
))
6352 so
->so_flags
&= ~SOF_KNOTE
;
6353 socket_unlock(so
, 1);
6357 filt_sockev(struct knote
*kn
, long hint
)
6359 int ret
= 0, locked
= 0;
6360 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6361 long ev_hint
= (hint
& SO_FILT_HINT_EV
);
6363 if ((hint
& SO_FILT_HINT_LOCKED
) == 0) {
6368 ret
= filt_sockev_common(kn
, so
, ev_hint
);
6371 socket_unlock(so
, 1);
6379 * filt_socktouch - update event state
6384 struct kevent_internal_s
*kev
)
6386 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6387 uint32_t changed_flags
;
6392 /* save off the [result] data and fflags */
6393 changed_flags
= (kn
->kn_sfflags
^ kn
->kn_hookid
);
6395 /* save off the new input fflags and data */
6396 kn
->kn_sfflags
= kev
->fflags
;
6397 kn
->kn_sdata
= kev
->data
;
6398 if ((kn
->kn_status
& KN_UDATA_SPECIFIC
) == 0)
6399 kn
->kn_udata
= kev
->udata
;
6401 /* restrict the current results to the (smaller?) set of new interest */
6403 * For compatibility with previous implementations, we leave kn_fflags
6404 * as they were before.
6406 //kn->kn_fflags &= kev->fflags;
6409 * Since we keep track of events that are already
6410 * delivered, if any of those events are not requested
6411 * anymore the state related to them can be reset
6414 ~(changed_flags
& EVFILT_SOCK_LEVEL_TRIGGER_MASK
);
6416 /* determine if we have events to deliver */
6417 ret
= filt_sockev_common(kn
, so
, 0);
6419 socket_unlock(so
, 1);
6425 * filt_sockprocess - query event fired state and return data
6430 struct filt_process_s
*data
,
6431 struct kevent_internal_s
*kev
)
6433 #pragma unused(data)
6435 struct socket
*so
= (struct socket
*)kn
->kn_fp
->f_fglob
->fg_data
;
6440 ret
= filt_sockev_common(kn
, so
, 0);
6442 *kev
= kn
->kn_kevent
;
6445 * Store the state of the events being delivered. This
6446 * state can be used to deliver level triggered events
6447 * ateast once and still avoid waking up the application
6448 * multiple times as long as the event is active.
6450 if (kn
->kn_fflags
!= 0)
6451 kn
->kn_hookid
|= (kn
->kn_fflags
&
6452 EVFILT_SOCK_LEVEL_TRIGGER_MASK
);
6455 * NOTE_RESUME and NOTE_SUSPEND are an exception, deliver
6456 * only one of them and remember the last one that was
6459 if (kn
->kn_fflags
& NOTE_SUSPEND
)
6460 kn
->kn_hookid
&= ~NOTE_RESUME
;
6461 if (kn
->kn_fflags
& NOTE_RESUME
)
6462 kn
->kn_hookid
&= ~NOTE_SUSPEND
;
6464 if (kn
->kn_flags
& EV_CLEAR
) {
6470 socket_unlock(so
, 1);
6476 get_sockev_state(struct socket
*so
, u_int32_t
*statep
)
6478 u_int32_t state
= *(statep
);
6481 * If the state variable is already used by a previous event,
6487 if (so
->so_state
& SS_ISCONNECTED
)
6488 state
|= SOCKEV_CONNECTED
;
6490 state
&= ~(SOCKEV_CONNECTED
);
6491 state
|= ((so
->so_state
& SS_ISDISCONNECTED
) ? SOCKEV_DISCONNECTED
: 0);
6495 #define SO_LOCK_HISTORY_STR_LEN \
6496 (2 * SO_LCKDBG_MAX * (2 + (2 * sizeof (void *)) + 1) + 1)
6498 __private_extern__
const char *
6499 solockhistory_nr(struct socket
*so
)
6503 static char lock_history_str
[SO_LOCK_HISTORY_STR_LEN
];
6505 bzero(lock_history_str
, sizeof (lock_history_str
));
6506 for (i
= SO_LCKDBG_MAX
- 1; i
>= 0; i
--) {
6507 n
+= snprintf(lock_history_str
+ n
,
6508 SO_LOCK_HISTORY_STR_LEN
- n
, "%p:%p ",
6509 so
->lock_lr
[(so
->next_lock_lr
+ i
) % SO_LCKDBG_MAX
],
6510 so
->unlock_lr
[(so
->next_unlock_lr
+ i
) % SO_LCKDBG_MAX
]);
6512 return (lock_history_str
);
6516 socket_lock(struct socket
*so
, int refcount
)
6521 lr_saved
= __builtin_return_address(0);
6523 if (so
->so_proto
->pr_lock
) {
6524 error
= (*so
->so_proto
->pr_lock
)(so
, refcount
, lr_saved
);
6526 #ifdef MORE_LOCKING_DEBUG
6527 lck_mtx_assert(so
->so_proto
->pr_domain
->dom_mtx
,
6528 LCK_MTX_ASSERT_NOTOWNED
);
6530 lck_mtx_lock(so
->so_proto
->pr_domain
->dom_mtx
);
6533 so
->lock_lr
[so
->next_lock_lr
] = lr_saved
;
6534 so
->next_lock_lr
= (so
->next_lock_lr
+1) % SO_LCKDBG_MAX
;
6541 socket_unlock(struct socket
*so
, int refcount
)
6545 lck_mtx_t
*mutex_held
;
6547 lr_saved
= __builtin_return_address(0);
6549 if (so
->so_proto
== NULL
) {
6550 panic("%s: null so_proto so=%p\n", __func__
, so
);
6554 if (so
&& so
->so_proto
->pr_unlock
) {
6555 error
= (*so
->so_proto
->pr_unlock
)(so
, refcount
, lr_saved
);
6557 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
6558 #ifdef MORE_LOCKING_DEBUG
6559 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
6561 so
->unlock_lr
[so
->next_unlock_lr
] = lr_saved
;
6562 so
->next_unlock_lr
= (so
->next_unlock_lr
+1) % SO_LCKDBG_MAX
;
6565 if (so
->so_usecount
<= 0) {
6566 panic("%s: bad refcount=%d so=%p (%d, %d, %d) "
6567 "lrh=%s", __func__
, so
->so_usecount
, so
,
6568 SOCK_DOM(so
), so
->so_type
,
6569 SOCK_PROTO(so
), solockhistory_nr(so
));
6574 if (so
->so_usecount
== 0)
6575 sofreelastref(so
, 1);
6577 lck_mtx_unlock(mutex_held
);
6583 /* Called with socket locked, will unlock socket */
6585 sofree(struct socket
*so
)
6587 lck_mtx_t
*mutex_held
;
6589 if (so
->so_proto
->pr_getlock
!= NULL
)
6590 mutex_held
= (*so
->so_proto
->pr_getlock
)(so
, 0);
6592 mutex_held
= so
->so_proto
->pr_domain
->dom_mtx
;
6593 lck_mtx_assert(mutex_held
, LCK_MTX_ASSERT_OWNED
);
6595 sofreelastref(so
, 0);
6599 soreference(struct socket
*so
)
6601 socket_lock(so
, 1); /* locks & take one reference on socket */
6602 socket_unlock(so
, 0); /* unlock only */
6606 sodereference(struct socket
*so
)
6609 socket_unlock(so
, 1);
6613 * Set or clear SOF_MULTIPAGES on the socket to enable or disable the
6614 * possibility of using jumbo clusters. Caller must ensure to hold
6618 somultipages(struct socket
*so
, boolean_t set
)
6621 so
->so_flags
|= SOF_MULTIPAGES
;
6623 so
->so_flags
&= ~SOF_MULTIPAGES
;
6627 soif2kcl(struct socket
*so
, boolean_t set
)
6630 so
->so_flags1
|= SOF1_IF_2KCL
;
6632 so
->so_flags1
&= ~SOF1_IF_2KCL
;
6636 so_isdstlocal(struct socket
*so
) {
6638 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
6640 if (SOCK_DOM(so
) == PF_INET
)
6641 return (inaddr_local(inp
->inp_faddr
));
6642 else if (SOCK_DOM(so
) == PF_INET6
)
6643 return (in6addr_local(&inp
->in6p_faddr
));
6649 sosetdefunct(struct proc
*p
, struct socket
*so
, int level
, boolean_t noforce
)
6651 struct sockbuf
*rcv
, *snd
;
6652 int err
= 0, defunct
;
6657 defunct
= (so
->so_flags
& SOF_DEFUNCT
);
6659 if (!(snd
->sb_flags
& rcv
->sb_flags
& SB_DROP
)) {
6660 panic("%s: SB_DROP not set", __func__
);
6666 if (so
->so_flags
& SOF_NODEFUNCT
) {
6669 SODEFUNCTLOG("%s[%d, %s]: (target pid %d "
6670 "name %s level %d) so 0x%llx [%d,%d] "
6671 "is not eligible for defunct "
6672 "(%d)\n", __func__
, proc_selfpid(),
6673 proc_best_name(current_proc()), proc_pid(p
),
6674 proc_best_name(p
), level
,
6675 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6676 SOCK_DOM(so
), SOCK_TYPE(so
), err
);
6679 so
->so_flags
&= ~SOF_NODEFUNCT
;
6680 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s level %d) "
6681 "so 0x%llx [%d,%d] defunct by force\n", __func__
,
6682 proc_selfpid(), proc_best_name(current_proc()),
6683 proc_pid(p
), proc_best_name(p
), level
,
6684 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6685 SOCK_DOM(so
), SOCK_TYPE(so
));
6686 } else if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) {
6687 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
6688 struct ifnet
*ifp
= inp
->inp_last_outifp
;
6690 if (ifp
&& IFNET_IS_CELLULAR(ifp
)) {
6691 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nocell
);
6692 } else if (so
->so_flags
& SOF_DELEGATED
) {
6693 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nodlgtd
);
6694 } else if (soextbkidlestat
.so_xbkidle_time
== 0) {
6695 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_notime
);
6696 } else if (noforce
) {
6697 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
6699 so
->so_flags1
|= SOF1_EXTEND_BK_IDLE_INPROG
;
6700 so
->so_extended_bk_start
= net_uptime();
6701 OSBitOrAtomic(P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
6703 inpcb_timer_sched(inp
->inp_pcbinfo
, INPCB_TIMER_LAZY
);
6706 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s "
6707 "level %d) extend bk idle so 0x%llx rcv hw %d "
6709 __func__
, proc_selfpid(),
6710 proc_best_name(current_proc()), proc_pid(p
),
6711 proc_best_name(p
), level
,
6712 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6713 so
->so_rcv
.sb_hiwat
, so
->so_rcv
.sb_cc
);
6716 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_forced
);
6720 so
->so_flags
|= SOF_DEFUNCT
;
6722 /* Prevent further data from being appended to the socket buffers */
6723 snd
->sb_flags
|= SB_DROP
;
6724 rcv
->sb_flags
|= SB_DROP
;
6726 /* Flush any existing data in the socket buffers */
6727 if (rcv
->sb_cc
!= 0) {
6728 rcv
->sb_flags
&= ~SB_SEL
;
6729 selthreadclear(&rcv
->sb_sel
);
6732 if (snd
->sb_cc
!= 0) {
6733 snd
->sb_flags
&= ~SB_SEL
;
6734 selthreadclear(&snd
->sb_sel
);
6739 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s level %d) "
6740 "so 0x%llx [%d,%d] %s defunct%s\n", __func__
, proc_selfpid(),
6741 proc_best_name(current_proc()), proc_pid(p
), proc_best_name(p
),
6742 level
, (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
6743 SOCK_TYPE(so
), defunct
? "is already" : "marked as",
6744 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ? " extbkidle" : "");
6750 sodefunct(struct proc
*p
, struct socket
*so
, int level
)
6752 struct sockbuf
*rcv
, *snd
;
6754 if (!(so
->so_flags
& SOF_DEFUNCT
)) {
6755 panic("%s improperly called", __func__
);
6758 if (so
->so_state
& SS_DEFUNCT
)
6764 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
6765 char s
[MAX_IPv6_STR_LEN
];
6766 char d
[MAX_IPv6_STR_LEN
];
6767 struct inpcb
*inp
= sotoinpcb(so
);
6769 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s level %d) "
6770 "so 0x%llx [%s %s:%d -> %s:%d] is now defunct "
6771 "[rcv_si 0x%x, snd_si 0x%x, rcv_fl 0x%x, snd_fl 0x%x]\n",
6772 __func__
, proc_selfpid(), proc_best_name(current_proc()),
6773 proc_pid(p
), proc_best_name(p
), level
,
6774 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6775 (SOCK_TYPE(so
) == SOCK_STREAM
) ? "TCP" : "UDP",
6776 inet_ntop(SOCK_DOM(so
), ((SOCK_DOM(so
) == PF_INET
) ?
6777 (void *)&inp
->inp_laddr
.s_addr
: (void *)&inp
->in6p_laddr
),
6778 s
, sizeof (s
)), ntohs(inp
->in6p_lport
),
6779 inet_ntop(SOCK_DOM(so
), (SOCK_DOM(so
) == PF_INET
) ?
6780 (void *)&inp
->inp_faddr
.s_addr
: (void *)&inp
->in6p_faddr
,
6781 d
, sizeof (d
)), ntohs(inp
->in6p_fport
),
6782 (uint32_t)rcv
->sb_sel
.si_flags
,
6783 (uint32_t)snd
->sb_sel
.si_flags
,
6784 rcv
->sb_flags
, snd
->sb_flags
);
6786 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s level %d) "
6787 "so 0x%llx [%d,%d] is now defunct [rcv_si 0x%x, "
6788 "snd_si 0x%x, rcv_fl 0x%x, snd_fl 0x%x]\n", __func__
,
6789 proc_selfpid(), proc_best_name(current_proc()),
6790 proc_pid(p
), proc_best_name(p
), level
,
6791 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6792 SOCK_DOM(so
), SOCK_TYPE(so
),
6793 (uint32_t)rcv
->sb_sel
.si_flags
,
6794 (uint32_t)snd
->sb_sel
.si_flags
, rcv
->sb_flags
,
6799 * Unwedge threads blocked on sbwait() and sb_lock().
6804 so
->so_flags1
|= SOF1_DEFUNCTINPROG
;
6805 if (rcv
->sb_flags
& SB_LOCK
)
6806 sbunlock(rcv
, TRUE
); /* keep socket locked */
6807 if (snd
->sb_flags
& SB_LOCK
)
6808 sbunlock(snd
, TRUE
); /* keep socket locked */
6811 * Flush the buffers and disconnect. We explicitly call shutdown
6812 * on both data directions to ensure that SS_CANT{RCV,SEND}MORE
6813 * states are set for the socket. This would also flush out data
6814 * hanging off the receive list of this socket.
6816 (void) soshutdownlock_final(so
, SHUT_RD
);
6817 (void) soshutdownlock_final(so
, SHUT_WR
);
6818 (void) sodisconnectlocked(so
);
6821 * Explicitly handle connectionless-protocol disconnection
6822 * and release any remaining data in the socket buffers.
6824 if (!(so
->so_flags
& SS_ISDISCONNECTED
))
6825 (void) soisdisconnected(so
);
6827 if (so
->so_error
== 0)
6828 so
->so_error
= EBADF
;
6830 if (rcv
->sb_cc
!= 0) {
6831 rcv
->sb_flags
&= ~SB_SEL
;
6832 selthreadclear(&rcv
->sb_sel
);
6835 if (snd
->sb_cc
!= 0) {
6836 snd
->sb_flags
&= ~SB_SEL
;
6837 selthreadclear(&snd
->sb_sel
);
6840 so
->so_state
|= SS_DEFUNCT
;
6841 OSIncrementAtomicLong((volatile long *)&sodefunct_calls
);
6848 soresume(struct proc
*p
, struct socket
*so
, int locked
)
6853 if (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
) {
6854 SODEFUNCTLOG("%s[%d, %s]: (target pid %d name %s) so 0x%llx "
6855 "[%d,%d] resumed from bk idle\n",
6856 __func__
, proc_selfpid(), proc_best_name(current_proc()),
6857 proc_pid(p
), proc_best_name(p
),
6858 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6859 SOCK_DOM(so
), SOCK_TYPE(so
));
6861 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_INPROG
;
6862 so
->so_extended_bk_start
= 0;
6863 OSBitAndAtomic(~P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
6865 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_resumed
);
6866 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
6867 VERIFY(soextbkidlestat
.so_xbkidle_active
>= 0);
6870 socket_unlock(so
, 1);
6876 * Does not attempt to account for sockets that are delegated from
6877 * the current process
6880 so_set_extended_bk_idle(struct socket
*so
, int optval
)
6884 if ((SOCK_DOM(so
) != PF_INET
&& SOCK_DOM(so
) != PF_INET6
) ||
6885 SOCK_PROTO(so
) != IPPROTO_TCP
) {
6886 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_notsupp
);
6888 } else if (optval
== 0) {
6889 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_WANTED
;
6891 soresume(current_proc(), so
, 1);
6893 struct proc
*p
= current_proc();
6895 struct filedesc
*fdp
;
6901 for (i
= 0; i
< fdp
->fd_nfiles
; i
++) {
6902 struct fileproc
*fp
= fdp
->fd_ofiles
[i
];
6906 (fdp
->fd_ofileflags
[i
] & UF_RESERVED
) != 0 ||
6907 FILEGLOB_DTYPE(fp
->f_fglob
) != DTYPE_SOCKET
)
6910 so2
= (struct socket
*)fp
->f_fglob
->fg_data
;
6912 so2
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
)
6914 if (count
>= soextbkidlestat
.so_xbkidle_maxperproc
)
6917 if (count
>= soextbkidlestat
.so_xbkidle_maxperproc
) {
6918 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_toomany
);
6920 } else if (so
->so_flags
& SOF_DELEGATED
) {
6921 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_nodlgtd
);
6924 so
->so_flags1
|= SOF1_EXTEND_BK_IDLE_WANTED
;
6925 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_wantok
);
6927 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx [%d,%d] "
6928 "%s marked for extended bk idle\n",
6929 __func__
, proc_selfpid(), proc_best_name(current_proc()),
6930 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6931 SOCK_DOM(so
), SOCK_TYPE(so
),
6932 (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_WANTED
) ?
6942 so_stop_extended_bk_idle(struct socket
*so
)
6944 so
->so_flags1
&= ~SOF1_EXTEND_BK_IDLE_INPROG
;
6945 so
->so_extended_bk_start
= 0;
6947 OSDecrementAtomic(&soextbkidlestat
.so_xbkidle_active
);
6948 VERIFY(soextbkidlestat
.so_xbkidle_active
>= 0);
6952 sosetdefunct(current_proc(), so
,
6953 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
, FALSE
);
6954 if (so
->so_flags
& SOF_DEFUNCT
) {
6955 sodefunct(current_proc(), so
,
6956 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL
);
6961 so_drain_extended_bk_idle(struct socket
*so
)
6963 if (so
&& (so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
)) {
6965 * Only penalize sockets that have outstanding data
6967 if (so
->so_rcv
.sb_cc
|| so
->so_snd
.sb_cc
) {
6968 so_stop_extended_bk_idle(so
);
6970 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_drained
);
6976 * Return values tells if socket is still in extended background idle
6979 so_check_extended_bk_idle_time(struct socket
*so
)
6983 if ((so
->so_flags1
& SOF1_EXTEND_BK_IDLE_INPROG
)) {
6984 SODEFUNCTLOG("%s[%d, %s]: so 0x%llx [%d,%d]\n",
6985 __func__
, proc_selfpid(), proc_best_name(current_proc()),
6986 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
6987 SOCK_DOM(so
), SOCK_TYPE(so
));
6988 if (net_uptime() - so
->so_extended_bk_start
>
6989 soextbkidlestat
.so_xbkidle_time
) {
6990 so_stop_extended_bk_idle(so
);
6992 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_expired
);
6996 struct inpcb
*inp
= (struct inpcb
*)so
->so_pcb
;
6998 inpcb_timer_sched(inp
->inp_pcbinfo
, INPCB_TIMER_LAZY
);
6999 OSIncrementAtomic(&soextbkidlestat
.so_xbkidle_resched
);
7007 resume_proc_sockets(proc_t p
)
7009 if (p
->p_ladvflag
& P_LXBKIDLEINPROG
) {
7010 struct filedesc
*fdp
;
7015 for (i
= 0; i
< fdp
->fd_nfiles
; i
++) {
7016 struct fileproc
*fp
;
7019 fp
= fdp
->fd_ofiles
[i
];
7021 (fdp
->fd_ofileflags
[i
] & UF_RESERVED
) != 0 ||
7022 FILEGLOB_DTYPE(fp
->f_fglob
) != DTYPE_SOCKET
)
7025 so
= (struct socket
*)fp
->f_fglob
->fg_data
;
7026 (void) soresume(p
, so
, 0);
7030 OSBitAndAtomic(~P_LXBKIDLEINPROG
, &p
->p_ladvflag
);
7034 __private_extern__
int
7035 so_set_recv_anyif(struct socket
*so
, int optval
)
7040 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7042 if (SOCK_DOM(so
) == PF_INET
) {
7045 sotoinpcb(so
)->inp_flags
|= INP_RECV_ANYIF
;
7047 sotoinpcb(so
)->inp_flags
&= ~INP_RECV_ANYIF
;
7053 __private_extern__
int
7054 so_get_recv_anyif(struct socket
*so
)
7059 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7061 if (SOCK_DOM(so
) == PF_INET
) {
7063 ret
= (sotoinpcb(so
)->inp_flags
& INP_RECV_ANYIF
) ? 1 : 0;
7070 so_set_restrictions(struct socket
*so
, uint32_t vals
)
7072 int nocell_old
, nocell_new
;
7073 int noexpensive_old
, noexpensive_new
;
7076 * Deny-type restrictions are trapdoors; once set they cannot be
7077 * unset for the lifetime of the socket. This allows them to be
7078 * issued by a framework on behalf of the application without
7079 * having to worry that they can be undone.
7081 * Note here that socket-level restrictions overrides any protocol
7082 * level restrictions. For instance, SO_RESTRICT_DENY_CELLULAR
7083 * socket restriction issued on the socket has a higher precendence
7084 * than INP_NO_IFT_CELLULAR. The latter is affected by the UUID
7085 * policy PROC_UUID_NO_CELLULAR for unrestricted sockets only,
7086 * i.e. when SO_RESTRICT_DENY_CELLULAR has not been issued.
7088 nocell_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_CELLULAR
);
7089 noexpensive_old
= (so
->so_restrictions
& SO_RESTRICT_DENY_EXPENSIVE
);
7090 so
->so_restrictions
|= (vals
& (SO_RESTRICT_DENY_IN
|
7091 SO_RESTRICT_DENY_OUT
| SO_RESTRICT_DENY_CELLULAR
|
7092 SO_RESTRICT_DENY_EXPENSIVE
));
7093 nocell_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_CELLULAR
);
7094 noexpensive_new
= (so
->so_restrictions
& SO_RESTRICT_DENY_EXPENSIVE
);
7096 /* we can only set, not clear restrictions */
7097 if ((nocell_new
- nocell_old
) == 0 &&
7098 (noexpensive_new
- noexpensive_old
) == 0)
7101 if (SOCK_DOM(so
) == PF_INET
|| SOCK_DOM(so
) == PF_INET6
) {
7103 if (SOCK_DOM(so
) == PF_INET
) {
7105 if (nocell_new
- nocell_old
!= 0) {
7107 * if deny cellular is now set, do what's needed
7110 inp_set_nocellular(sotoinpcb(so
));
7112 if (noexpensive_new
- noexpensive_old
!= 0) {
7113 inp_set_noexpensive(sotoinpcb(so
));
7121 so_get_restrictions(struct socket
*so
)
7123 return (so
->so_restrictions
& (SO_RESTRICT_DENY_IN
|
7124 SO_RESTRICT_DENY_OUT
|
7125 SO_RESTRICT_DENY_CELLULAR
| SO_RESTRICT_DENY_EXPENSIVE
));
7128 struct sockaddr_entry
*
7129 sockaddrentry_alloc(int how
)
7131 struct sockaddr_entry
*se
;
7133 se
= (how
== M_WAITOK
) ? zalloc(se_zone
) : zalloc_noblock(se_zone
);
7135 bzero(se
, se_zone_size
);
7141 sockaddrentry_free(struct sockaddr_entry
*se
)
7143 if (se
->se_addr
!= NULL
) {
7144 FREE(se
->se_addr
, M_SONAME
);
7150 struct sockaddr_entry
*
7151 sockaddrentry_dup(const struct sockaddr_entry
*src_se
, int how
)
7153 struct sockaddr_entry
*dst_se
;
7155 dst_se
= sockaddrentry_alloc(how
);
7156 if (dst_se
!= NULL
) {
7157 int len
= src_se
->se_addr
->sa_len
;
7159 MALLOC(dst_se
->se_addr
, struct sockaddr
*,
7160 len
, M_SONAME
, how
| M_ZERO
);
7161 if (dst_se
->se_addr
!= NULL
) {
7162 bcopy(src_se
->se_addr
, dst_se
->se_addr
, len
);
7164 sockaddrentry_free(dst_se
);
7172 struct sockaddr_list
*
7173 sockaddrlist_alloc(int how
)
7175 struct sockaddr_list
*sl
;
7177 sl
= (how
== M_WAITOK
) ? zalloc(sl_zone
) : zalloc_noblock(sl_zone
);
7179 bzero(sl
, sl_zone_size
);
7180 TAILQ_INIT(&sl
->sl_head
);
7186 sockaddrlist_free(struct sockaddr_list
*sl
)
7188 struct sockaddr_entry
*se
, *tse
;
7190 TAILQ_FOREACH_SAFE(se
, &sl
->sl_head
, se_link
, tse
) {
7191 sockaddrlist_remove(sl
, se
);
7192 sockaddrentry_free(se
);
7194 VERIFY(sl
->sl_cnt
== 0 && TAILQ_EMPTY(&sl
->sl_head
));
7199 sockaddrlist_insert(struct sockaddr_list
*sl
, struct sockaddr_entry
*se
)
7201 VERIFY(!(se
->se_flags
& SEF_ATTACHED
));
7202 se
->se_flags
|= SEF_ATTACHED
;
7203 TAILQ_INSERT_TAIL(&sl
->sl_head
, se
, se_link
);
7205 VERIFY(sl
->sl_cnt
!= 0);
7209 sockaddrlist_remove(struct sockaddr_list
*sl
, struct sockaddr_entry
*se
)
7211 VERIFY(se
->se_flags
& SEF_ATTACHED
);
7212 se
->se_flags
&= ~SEF_ATTACHED
;
7213 VERIFY(sl
->sl_cnt
!= 0);
7215 TAILQ_REMOVE(&sl
->sl_head
, se
, se_link
);
7218 struct sockaddr_list
*
7219 sockaddrlist_dup(const struct sockaddr_list
*src_sl
, int how
)
7221 struct sockaddr_entry
*src_se
, *tse
;
7222 struct sockaddr_list
*dst_sl
;
7224 dst_sl
= sockaddrlist_alloc(how
);
7228 TAILQ_FOREACH_SAFE(src_se
, &src_sl
->sl_head
, se_link
, tse
) {
7229 struct sockaddr_entry
*dst_se
;
7231 if (src_se
->se_addr
== NULL
)
7234 dst_se
= sockaddrentry_dup(src_se
, how
);
7235 if (dst_se
== NULL
) {
7236 sockaddrlist_free(dst_sl
);
7240 sockaddrlist_insert(dst_sl
, dst_se
);
7242 VERIFY(src_sl
->sl_cnt
== dst_sl
->sl_cnt
);
7248 so_set_effective_pid(struct socket
*so
, int epid
, struct proc
*p
)
7250 struct proc
*ep
= PROC_NULL
;
7253 /* pid 0 is reserved for kernel */
7260 * If this is an in-kernel socket, prevent its delegate
7261 * association from changing unless the socket option is
7262 * coming from within the kernel itself.
7264 if (so
->last_pid
== 0 && p
!= kernproc
) {
7270 * If this is issued by a process that's recorded as the
7271 * real owner of the socket, or if the pid is the same as
7272 * the process's own pid, then proceed. Otherwise ensure
7273 * that the issuing process has the necessary privileges.
7275 if (epid
!= so
->last_pid
|| epid
!= proc_pid(p
)) {
7276 if ((error
= priv_check_cred(kauth_cred_get(),
7277 PRIV_NET_PRIVILEGED_SOCKET_DELEGATE
, 0))) {
7283 /* Find the process that corresponds to the effective pid */
7284 if ((ep
= proc_find(epid
)) == PROC_NULL
) {
7290 * If a process tries to delegate the socket to itself, then
7291 * there's really nothing to do; treat it as a way for the
7292 * delegate association to be cleared. Note that we check
7293 * the passed-in proc rather than calling proc_selfpid(),
7294 * as we need to check the process issuing the socket option
7295 * which could be kernproc. Given that we don't allow 0 for
7296 * effective pid, it means that a delegated in-kernel socket
7297 * stays delegated during its lifetime (which is probably OK.)
7299 if (epid
== proc_pid(p
)) {
7300 so
->so_flags
&= ~SOF_DELEGATED
;
7303 uuid_clear(so
->e_uuid
);
7305 so
->so_flags
|= SOF_DELEGATED
;
7306 so
->e_upid
= proc_uniqueid(ep
);
7307 so
->e_pid
= proc_pid(ep
);
7308 proc_getexecutableuuid(ep
, so
->e_uuid
, sizeof (so
->e_uuid
));
7311 if (error
== 0 && net_io_policy_log
) {
7314 uuid_unparse(so
->e_uuid
, buf
);
7315 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d (%s) "
7316 "euuid %s%s\n", __func__
, proc_name_address(p
),
7317 proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7318 SOCK_DOM(so
), SOCK_TYPE(so
),
7319 so
->e_pid
, proc_name_address(ep
), buf
,
7320 ((so
->so_flags
& SOF_DELEGATED
) ? " [delegated]" : ""));
7321 } else if (error
!= 0 && net_io_policy_log
) {
7322 log(LOG_ERR
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d (%s) "
7323 "ERROR (%d)\n", __func__
, proc_name_address(p
),
7324 proc_pid(p
), (uint64_t)DEBUG_KERNEL_ADDRPERM(so
),
7325 SOCK_DOM(so
), SOCK_TYPE(so
),
7326 epid
, (ep
== PROC_NULL
) ? "PROC_NULL" :
7327 proc_name_address(ep
), error
);
7330 /* Update this socket's policy upon success */
7332 so
->so_policy_gencnt
*= -1;
7333 so_update_policy(so
);
7335 so_update_necp_policy(so
, NULL
, NULL
);
7339 if (ep
!= PROC_NULL
)
7346 so_set_effective_uuid(struct socket
*so
, uuid_t euuid
, struct proc
*p
)
7352 /* UUID must not be all-zeroes (reserved for kernel) */
7353 if (uuid_is_null(euuid
)) {
7359 * If this is an in-kernel socket, prevent its delegate
7360 * association from changing unless the socket option is
7361 * coming from within the kernel itself.
7363 if (so
->last_pid
== 0 && p
!= kernproc
) {
7368 /* Get the UUID of the issuing process */
7369 proc_getexecutableuuid(p
, uuid
, sizeof (uuid
));
7372 * If this is issued by a process that's recorded as the
7373 * real owner of the socket, or if the uuid is the same as
7374 * the process's own uuid, then proceed. Otherwise ensure
7375 * that the issuing process has the necessary privileges.
7377 if (uuid_compare(euuid
, so
->last_uuid
) != 0 ||
7378 uuid_compare(euuid
, uuid
) != 0) {
7379 if ((error
= priv_check_cred(kauth_cred_get(),
7380 PRIV_NET_PRIVILEGED_SOCKET_DELEGATE
, 0))) {
7387 * If a process tries to delegate the socket to itself, then
7388 * there's really nothing to do; treat it as a way for the
7389 * delegate association to be cleared. Note that we check
7390 * the uuid of the passed-in proc rather than that of the
7391 * current process, as we need to check the process issuing
7392 * the socket option which could be kernproc itself. Given
7393 * that we don't allow 0 for effective uuid, it means that
7394 * a delegated in-kernel socket stays delegated during its
7395 * lifetime (which is okay.)
7397 if (uuid_compare(euuid
, uuid
) == 0) {
7398 so
->so_flags
&= ~SOF_DELEGATED
;
7401 uuid_clear(so
->e_uuid
);
7403 so
->so_flags
|= SOF_DELEGATED
;
7405 * Unlike so_set_effective_pid(), we only have the UUID
7406 * here and the process ID is not known. Inherit the
7407 * real {pid,upid} of the socket.
7409 so
->e_upid
= so
->last_upid
;
7410 so
->e_pid
= so
->last_pid
;
7411 uuid_copy(so
->e_uuid
, euuid
);
7415 if (error
== 0 && net_io_policy_log
) {
7416 uuid_unparse(so
->e_uuid
, buf
);
7417 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] epid %d "
7418 "euuid %s%s\n", __func__
, proc_name_address(p
), proc_pid(p
),
7419 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7420 SOCK_TYPE(so
), so
->e_pid
, buf
,
7421 ((so
->so_flags
& SOF_DELEGATED
) ? " [delegated]" : ""));
7422 } else if (error
!= 0 && net_io_policy_log
) {
7423 uuid_unparse(euuid
, buf
);
7424 log(LOG_DEBUG
, "%s[%s,%d]: so 0x%llx [%d,%d] euuid %s "
7425 "ERROR (%d)\n", __func__
, proc_name_address(p
), proc_pid(p
),
7426 (uint64_t)DEBUG_KERNEL_ADDRPERM(so
), SOCK_DOM(so
),
7427 SOCK_TYPE(so
), buf
, error
);
7430 /* Update this socket's policy upon success */
7432 so
->so_policy_gencnt
*= -1;
7433 so_update_policy(so
);
7435 so_update_necp_policy(so
, NULL
, NULL
);
7443 netpolicy_post_msg(uint32_t ev_code
, struct netpolicy_event_data
*ev_data
,
7444 uint32_t ev_datalen
)
7446 struct kev_msg ev_msg
;
7449 * A netpolicy event always starts with a netpolicy_event_data
7450 * structure, but the caller can provide for a longer event
7451 * structure to post, depending on the event code.
7453 VERIFY(ev_data
!= NULL
&& ev_datalen
>= sizeof (*ev_data
));
7455 bzero(&ev_msg
, sizeof (ev_msg
));
7456 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7457 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
7458 ev_msg
.kev_subclass
= KEV_NETPOLICY_SUBCLASS
;
7459 ev_msg
.event_code
= ev_code
;
7461 ev_msg
.dv
[0].data_ptr
= ev_data
;
7462 ev_msg
.dv
[0].data_length
= ev_datalen
;
7464 kev_post_msg(&ev_msg
);
7468 socket_post_kev_msg(uint32_t ev_code
,
7469 struct kev_socket_event_data
*ev_data
,
7470 uint32_t ev_datalen
)
7472 struct kev_msg ev_msg
;
7474 bzero(&ev_msg
, sizeof(ev_msg
));
7475 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
7476 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
7477 ev_msg
.kev_subclass
= KEV_SOCKET_SUBCLASS
;
7478 ev_msg
.event_code
= ev_code
;
7480 ev_msg
.dv
[0].data_ptr
= ev_data
;
7481 ev_msg
.dv
[0]. data_length
= ev_datalen
;
7483 kev_post_msg(&ev_msg
);
7487 socket_post_kev_msg_closed(struct socket
*so
)
7489 struct kev_socket_closed ev
;
7490 struct sockaddr
*socksa
= NULL
, *peersa
= NULL
;
7492 bzero(&ev
, sizeof(ev
));
7493 err
= (*so
->so_proto
->pr_usrreqs
->pru_sockaddr
)(so
, &socksa
);
7495 err
= (*so
->so_proto
->pr_usrreqs
->pru_peeraddr
)(so
,
7498 memcpy(&ev
.ev_data
.kev_sockname
, socksa
,
7500 sizeof (ev
.ev_data
.kev_sockname
)));
7501 memcpy(&ev
.ev_data
.kev_peername
, peersa
,
7503 sizeof (ev
.ev_data
.kev_peername
)));
7504 socket_post_kev_msg(KEV_SOCKET_CLOSED
,
7505 &ev
.ev_data
, sizeof (ev
));
7509 FREE(socksa
, M_SONAME
);
7511 FREE(peersa
, M_SONAME
);