]> git.saurik.com Git - apple/xnu.git/blame - bsd/kern/uipc_socket.c
xnu-1504.3.12.tar.gz
[apple/xnu.git] / bsd / kern / uipc_socket.c
CommitLineData
1c79356b 1/*
b0d623f7 2 * Copyright (c) 1998-2008 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
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.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b 27 */
1c79356b
A
28/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29/*
30 * Copyright (c) 1982, 1986, 1988, 1990, 1993
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 *
9bccf70c
A
61 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
62 * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.16 2001/06/14 20:46:06 ume Exp $
1c79356b 63 */
2d21ac55
A
64/*
65 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
66 * support for mandatory and extensible security protections. This notice
67 * is included in support of clause 2.2 (b) of the Apple Public License,
68 * Version 2.0.
69 */
1c79356b
A
70
71#include <sys/param.h>
72#include <sys/systm.h>
55e303ae 73#include <sys/filedesc.h>
2d21ac55 74#include <sys/proc.h>
91447636
A
75#include <sys/proc_internal.h>
76#include <sys/kauth.h>
77#include <sys/file_internal.h>
1c79356b
A
78#include <sys/fcntl.h>
79#include <sys/malloc.h>
80#include <sys/mbuf.h>
81#include <sys/domain.h>
82#include <sys/kernel.h>
55e303ae 83#include <sys/event.h>
1c79356b
A
84#include <sys/poll.h>
85#include <sys/protosw.h>
86#include <sys/socket.h>
87#include <sys/socketvar.h>
88#include <sys/resourcevar.h>
89#include <sys/signalvar.h>
90#include <sys/sysctl.h>
91#include <sys/uio.h>
92#include <sys/ev.h>
93#include <sys/kdebug.h>
2d21ac55 94#include <sys/un.h>
1c79356b
A
95#include <net/route.h>
96#include <netinet/in.h>
97#include <netinet/in_pcb.h>
98#include <kern/zalloc.h>
91447636 99#include <kern/locks.h>
1c79356b 100#include <machine/limits.h>
2d21ac55
A
101#include <libkern/OSAtomic.h>
102#include <pexpert/pexpert.h>
b0d623f7 103#include <kern/assert.h>
2d21ac55
A
104
105#if CONFIG_MACF
106#include <security/mac.h>
107#include <security/mac_framework.h>
108#endif /* MAC */
109
1c79356b
A
110int so_cache_hw = 0;
111int so_cache_timeouts = 0;
112int so_cache_max_freed = 0;
113int cached_sock_count = 0;
b0d623f7 114__private_extern__ int max_cached_sock_count = MAX_CACHED_SOCKETS;
1c79356b
A
115struct socket *socket_cache_head = 0;
116struct socket *socket_cache_tail = 0;
b0d623f7 117u_int32_t so_cache_time = 0;
1c79356b
A
118int so_cache_init_done = 0;
119struct zone *so_cache_zone;
1c79356b 120
91447636
A
121static lck_grp_t *so_cache_mtx_grp;
122static lck_attr_t *so_cache_mtx_attr;
123static lck_grp_attr_t *so_cache_mtx_grp_attr;
124lck_mtx_t *so_cache_mtx;
125
1c79356b
A
126#include <machine/limits.h>
127
2d21ac55
A
128static void filt_sordetach(struct knote *kn);
129static int filt_soread(struct knote *kn, long hint);
130static void filt_sowdetach(struct knote *kn);
131static int filt_sowrite(struct knote *kn, long hint);
2d21ac55
A
132
133static int
134sooptcopyin_timeval(struct sockopt *sopt, struct timeval * tv_p);
135
136static int
137sooptcopyout_timeval(struct sockopt *sopt, const struct timeval * tv_p);
55e303ae 138
b0d623f7
A
139static struct filterops soread_filtops = {
140 .f_isfd = 1,
141 .f_detach = filt_sordetach,
142 .f_event = filt_soread,
143};
144static struct filterops sowrite_filtops = {
145 .f_isfd = 1,
146 .f_detach = filt_sowdetach,
147 .f_event = filt_sowrite,
148};
55e303ae 149
2d21ac55 150#define EVEN_MORE_LOCKING_DEBUG 0
1c79356b
A
151int socket_debug = 0;
152int socket_zone = M_SOCKET;
153so_gen_t so_gencnt; /* generation count for sockets */
154
155MALLOC_DEFINE(M_SONAME, "soname", "socket name");
156MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
157
2d21ac55
A
158#define DBG_LAYER_IN_BEG NETDBG_CODE(DBG_NETSOCK, 0)
159#define DBG_LAYER_IN_END NETDBG_CODE(DBG_NETSOCK, 2)
160#define DBG_LAYER_OUT_BEG NETDBG_CODE(DBG_NETSOCK, 1)
161#define DBG_LAYER_OUT_END NETDBG_CODE(DBG_NETSOCK, 3)
162#define DBG_FNC_SOSEND NETDBG_CODE(DBG_NETSOCK, (4 << 8) | 1)
163#define DBG_FNC_SORECEIVE NETDBG_CODE(DBG_NETSOCK, (8 << 8))
164#define DBG_FNC_SOSHUTDOWN NETDBG_CODE(DBG_NETSOCK, (9 << 8))
1c79356b 165
2d21ac55 166#define MAX_SOOPTGETM_SIZE (128 * MCLBYTES)
1c79356b 167
91447636 168
1c79356b
A
169SYSCTL_DECL(_kern_ipc);
170
2d21ac55
A
171int somaxconn = SOMAXCONN;
172SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW, &somaxconn, 0, "");
1c79356b
A
173
174/* Should we get a maximum also ??? */
fa4905b1 175static int sosendmaxchain = 65536;
1c79356b 176static int sosendminchain = 16384;
55e303ae 177static int sorecvmincopy = 16384;
1c79356b 178SYSCTL_INT(_kern_ipc, OID_AUTO, sosendminchain, CTLFLAG_RW, &sosendminchain,
2d21ac55 179 0, "");
55e303ae 180SYSCTL_INT(_kern_ipc, OID_AUTO, sorecvmincopy, CTLFLAG_RW, &sorecvmincopy,
2d21ac55
A
181 0, "");
182
183/*
184 * Set to enable jumbo clusters (if available) for large writes when
185 * the socket is marked with SOF_MULTIPAGES; see below.
186 */
187int sosendjcl = 1;
188SYSCTL_INT(_kern_ipc, OID_AUTO, sosendjcl, CTLFLAG_RW, &sosendjcl, 0, "");
1c79356b 189
2d21ac55
A
190/*
191 * Set this to ignore SOF_MULTIPAGES and use jumbo clusters for large
192 * writes on the socket for all protocols on any network interfaces,
193 * depending upon sosendjcl above. Be extra careful when setting this
194 * to 1, because sending down packets that cross physical pages down to
195 * broken drivers (those that falsely assume that the physical pages
196 * are contiguous) might lead to system panics or silent data corruption.
197 * When set to 0, the system will respect SOF_MULTIPAGES, which is set
198 * only for TCP sockets whose outgoing interface is IFNET_MULTIPAGES
199 * capable. Set this to 1 only for testing/debugging purposes.
200 */
201int sosendjcl_ignore_capab = 0;
202SYSCTL_INT(_kern_ipc, OID_AUTO, sosendjcl_ignore_capab, CTLFLAG_RW,
203 &sosendjcl_ignore_capab, 0, "");
1c79356b
A
204
205/*
206 * Socket operation routines.
207 * These routines are called by the routines in
208 * sys_socket.c or from a system process, and
209 * implement the semantics of socket operations by
210 * switching out to the protocol specific routines.
211 */
212
2d21ac55
A
213/* sys_generic.c */
214extern void postevent(struct socket *, struct sockbuf *, int);
215extern void evsofree(struct socket *);
216
217/* TODO: these should be in header file */
218extern int get_inpcb_str_size(void);
219extern int get_tcp_str_size(void);
220extern struct domain *pffinddomain(int);
221extern struct protosw *pffindprotonotype(int, int);
222extern int soclose_locked(struct socket *);
223extern int soo_kqfilter(struct fileproc *, struct knote *, struct proc *);
224
9bccf70c 225#ifdef __APPLE__
91447636
A
226
227vm_size_t so_cache_zone_element_size;
228
2d21ac55
A
229static int sodelayed_copy(struct socket *, struct uio *, struct mbuf **, int *);
230static void cached_sock_alloc(struct socket **, int);
231static void cached_sock_free(struct socket *);
232static void so_cache_timer(void *);
233
234void soclose_wait_locked(struct socket *so);
b0d623f7 235int so_isdstlocal(struct socket *so);
91447636
A
236
237
2d21ac55
A
238void
239socketinit(void)
1c79356b 240{
2d21ac55 241 vm_size_t str_size;
1c79356b 242
91447636
A
243 if (so_cache_init_done) {
244 printf("socketinit: already called...\n");
245 return;
246 }
247
593a1d5f 248 PE_parse_boot_argn("socket_debug", &socket_debug, sizeof (socket_debug));
2d21ac55 249
91447636
A
250 /*
251 * allocate lock group attribute and group for socket cache mutex
252 */
253 so_cache_mtx_grp_attr = lck_grp_attr_alloc_init();
91447636 254
2d21ac55
A
255 so_cache_mtx_grp = lck_grp_alloc_init("so_cache",
256 so_cache_mtx_grp_attr);
257
91447636
A
258 /*
259 * allocate the lock attribute for socket cache mutex
260 */
261 so_cache_mtx_attr = lck_attr_alloc_init();
91447636 262
2d21ac55
A
263 so_cache_init_done = 1;
264
265 /* cached sockets mutex */
266 so_cache_mtx = lck_mtx_alloc_init(so_cache_mtx_grp, so_cache_mtx_attr);
1c79356b 267
2d21ac55 268 if (so_cache_mtx == NULL)
91447636
A
269 return; /* we're hosed... */
270
2d21ac55
A
271 str_size = (vm_size_t)(sizeof (struct socket) + 4 +
272 get_inpcb_str_size() + 4 + get_tcp_str_size());
273
274 so_cache_zone = zinit(str_size, 120000*str_size, 8192, "socache zone");
1c79356b 275#if TEMPDEBUG
2d21ac55 276 printf("cached_sock_alloc -- so_cache_zone size is %x\n", str_size);
1c79356b 277#endif
2d21ac55 278 timeout(so_cache_timer, NULL, (SO_CACHE_FLUSH_INTERVAL * hz));
91447636 279
2d21ac55 280 so_cache_zone_element_size = str_size;
1c79356b 281
2d21ac55 282 sflt_init();
1c79356b
A
283}
284
2d21ac55
A
285static void
286cached_sock_alloc(struct socket **so, int waitok)
1c79356b 287{
2d21ac55 288 caddr_t temp;
b0d623f7 289 register uintptr_t offset;
1c79356b 290
91447636
A
291 lck_mtx_lock(so_cache_mtx);
292
2d21ac55
A
293 if (cached_sock_count) {
294 cached_sock_count--;
295 *so = socket_cache_head;
296 if (*so == 0)
297 panic("cached_sock_alloc: cached sock is null");
1c79356b 298
2d21ac55
A
299 socket_cache_head = socket_cache_head->cache_next;
300 if (socket_cache_head)
301 socket_cache_head->cache_prev = 0;
302 else
303 socket_cache_tail = 0;
91447636
A
304
305 lck_mtx_unlock(so_cache_mtx);
1c79356b 306
2d21ac55
A
307 temp = (*so)->so_saved_pcb;
308 bzero((caddr_t)*so, sizeof (struct socket));
1c79356b 309#if TEMPDEBUG
2d21ac55
A
310 kprintf("cached_sock_alloc - retreiving cached sock %p - "
311 "count == %d\n", *so, cached_sock_count);
1c79356b 312#endif
2d21ac55
A
313 (*so)->so_saved_pcb = temp;
314 (*so)->cached_in_sock_layer = 1;
315 } else {
1c79356b 316#if TEMPDEBUG
2d21ac55 317 kprintf("Allocating cached sock %p from memory\n", *so);
1c79356b
A
318#endif
319
2d21ac55 320 lck_mtx_unlock(so_cache_mtx);
1c79356b 321
2d21ac55
A
322 if (waitok)
323 *so = (struct socket *)zalloc(so_cache_zone);
324 else
325 *so = (struct socket *)zalloc_noblock(so_cache_zone);
1c79356b 326
2d21ac55
A
327 if (*so == 0)
328 return;
1c79356b 329
2d21ac55 330 bzero((caddr_t)*so, sizeof (struct socket));
1c79356b 331
2d21ac55
A
332 /*
333 * Define offsets for extra structures into our single block of
334 * memory. Align extra structures on longword boundaries.
335 */
b0d623f7
A
336
337 offset = (uintptr_t) *so;
2d21ac55 338 offset += sizeof (struct socket);
b0d623f7
A
339
340 offset = ALIGN(offset);
341
2d21ac55
A
342 (*so)->so_saved_pcb = (caddr_t)offset;
343 offset += get_inpcb_str_size();
b0d623f7
A
344
345 offset = ALIGN(offset);
1c79356b 346
2d21ac55
A
347 ((struct inpcb *)(*so)->so_saved_pcb)->inp_saved_ppcb =
348 (caddr_t)offset;
1c79356b 349#if TEMPDEBUG
2d21ac55
A
350 kprintf("Allocating cached socket - %p, pcb=%p tcpcb=%p\n",
351 *so, (*so)->so_saved_pcb,
1c79356b
A
352 ((struct inpcb *)(*so)->so_saved_pcb)->inp_saved_ppcb);
353#endif
2d21ac55 354 }
1c79356b 355
2d21ac55 356 (*so)->cached_in_sock_layer = 1;
1c79356b
A
357}
358
2d21ac55
A
359static void
360cached_sock_free(struct socket *so)
1c79356b 361{
1c79356b 362
91447636 363 lck_mtx_lock(so_cache_mtx);
1c79356b 364
b0d623f7 365 if (++cached_sock_count > max_cached_sock_count) {
1c79356b 366 --cached_sock_count;
91447636 367 lck_mtx_unlock(so_cache_mtx);
1c79356b 368#if TEMPDEBUG
2d21ac55 369 kprintf("Freeing overflowed cached socket %p\n", so);
1c79356b 370#endif
91447636 371 zfree(so_cache_zone, so);
2d21ac55 372 } else {
1c79356b 373#if TEMPDEBUG
2d21ac55 374 kprintf("Freeing socket %p into cache\n", so);
1c79356b
A
375#endif
376 if (so_cache_hw < cached_sock_count)
377 so_cache_hw = cached_sock_count;
378
379 so->cache_next = socket_cache_head;
380 so->cache_prev = 0;
381 if (socket_cache_head)
382 socket_cache_head->cache_prev = so;
383 else
384 socket_cache_tail = so;
385
386 so->cache_timestamp = so_cache_time;
387 socket_cache_head = so;
91447636 388 lck_mtx_unlock(so_cache_mtx);
1c79356b
A
389 }
390
391#if TEMPDEBUG
2d21ac55
A
392 kprintf("Freed cached sock %p into cache - count is %d\n",
393 so, cached_sock_count);
1c79356b 394#endif
1c79356b
A
395}
396
2d21ac55
A
397static void
398so_cache_timer(__unused void *dummy)
1c79356b
A
399{
400 register struct socket *p;
1c79356b 401 register int n_freed = 0;
1c79356b 402
91447636 403 lck_mtx_lock(so_cache_mtx);
1c79356b 404
91447636 405 ++so_cache_time;
1c79356b 406
2d21ac55 407 while ((p = socket_cache_tail)) {
1c79356b 408 if ((so_cache_time - p->cache_timestamp) < SO_CACHE_TIME_LIMIT)
2d21ac55 409 break;
1c79356b
A
410
411 so_cache_timeouts++;
1c79356b 412
2d21ac55
A
413 if ((socket_cache_tail = p->cache_prev))
414 p->cache_prev->cache_next = 0;
415 if (--cached_sock_count == 0)
416 socket_cache_head = 0;
1c79356b 417
91447636 418 zfree(so_cache_zone, p);
2d21ac55
A
419
420 if (++n_freed >= SO_CACHE_MAX_FREE_BATCH) {
421 so_cache_max_freed++;
1c79356b
A
422 break;
423 }
424 }
91447636 425 lck_mtx_unlock(so_cache_mtx);
1c79356b
A
426
427 timeout(so_cache_timer, NULL, (SO_CACHE_FLUSH_INTERVAL * hz));
1c79356b 428}
9bccf70c 429#endif /* __APPLE__ */
1c79356b
A
430
431/*
432 * Get a socket structure from our zone, and initialize it.
433 * We don't implement `waitok' yet (see comments in uipc_domain.c).
434 * Note that it would probably be better to allocate socket
435 * and PCB at the same time, but I'm not convinced that all
436 * the protocols can be easily modified to do this.
437 */
438struct socket *
2d21ac55 439soalloc(int waitok, int dom, int type)
1c79356b
A
440{
441 struct socket *so;
442
2d21ac55
A
443 if ((dom == PF_INET) && (type == SOCK_STREAM)) {
444 cached_sock_alloc(&so, waitok);
445 } else {
446 MALLOC_ZONE(so, struct socket *, sizeof (*so), socket_zone,
447 M_WAITOK);
448 if (so != NULL)
449 bzero(so, sizeof (*so));
1c79356b
A
450 }
451 /* XXX race condition for reentrant kernel */
91447636 452//###LD Atomic add for so_gencnt
2d21ac55
A
453 if (so != NULL) {
454 so->so_gencnt = ++so_gencnt;
455 so->so_zone = socket_zone;
456#if CONFIG_MACF_SOCKET
457 /* Convert waitok to M_WAITOK/M_NOWAIT for MAC Framework. */
458 if (mac_socket_label_init(so, !waitok) != 0) {
459 sodealloc(so);
460 return (NULL);
461 }
462#endif /* MAC_SOCKET */
1c79356b
A
463 }
464
2d21ac55 465 return (so);
1c79356b
A
466}
467
2d21ac55
A
468/*
469 * Returns: 0 Success
470 * EAFNOSUPPORT
471 * EPROTOTYPE
472 * EPROTONOSUPPORT
473 * ENOBUFS
474 * <pru_attach>:ENOBUFS[AF_UNIX]
475 * <pru_attach>:ENOBUFS[TCP]
476 * <pru_attach>:ENOMEM[TCP]
477 * <pru_attach>:EISCONN[TCP]
478 * <pru_attach>:??? [other protocol families, IPSEC]
479 */
1c79356b 480int
2d21ac55 481socreate(int dom, struct socket **aso, int type, int proto)
1c79356b
A
482{
483 struct proc *p = current_proc();
484 register struct protosw *prp;
9bccf70c 485 register struct socket *so;
1c79356b 486 register int error = 0;
55e303ae
A
487#if TCPDEBUG
488 extern int tcpconsdebug;
489#endif
1c79356b
A
490 if (proto)
491 prp = pffindproto(dom, proto, type);
492 else
493 prp = pffindtype(dom, type);
9bccf70c 494
2d21ac55
A
495 if (prp == 0 || prp->pr_usrreqs->pru_attach == 0) {
496 if (pffinddomain(dom) == NULL) {
497 return (EAFNOSUPPORT);
498 }
499 if (proto != 0) {
500 if (pffindprotonotype(dom, proto) != NULL) {
501 return (EPROTOTYPE);
502 }
503 }
9bccf70c
A
504 return (EPROTONOSUPPORT);
505 }
1c79356b
A
506 if (prp->pr_type != type)
507 return (EPROTOTYPE);
b0d623f7 508 so = soalloc(1, dom, type);
1c79356b
A
509 if (so == 0)
510 return (ENOBUFS);
511
512 TAILQ_INIT(&so->so_incomp);
513 TAILQ_INIT(&so->so_comp);
514 so->so_type = type;
515
b0d623f7
A
516 so->so_uid = kauth_cred_getuid(kauth_cred_get());
517 if (!suser(kauth_cred_get(), NULL))
518 so->so_state = SS_PRIV;
519
1c79356b 520 so->so_proto = prp;
9bccf70c 521#ifdef __APPLE__
1c79356b 522 so->so_rcv.sb_flags |= SB_RECV; /* XXX */
91447636 523 so->so_rcv.sb_so = so->so_snd.sb_so = so;
9bccf70c 524#endif
0c530ab8
A
525 so->next_lock_lr = 0;
526 so->next_unlock_lr = 0;
2d21ac55
A
527
528#if CONFIG_MACF_SOCKET
529 mac_socket_label_associate(kauth_cred_get(), so);
530#endif /* MAC_SOCKET */
531
91447636 532//### Attachement will create the per pcb lock if necessary and increase refcount
2d21ac55
A
533 /*
534 * for creation, make sure it's done before
535 * socket is inserted in lists
536 */
537 so->so_usecount++;
91447636
A
538
539 error = (*prp->pr_usrreqs->pru_attach)(so, proto, p);
1c79356b 540 if (error) {
2d21ac55
A
541 /*
542 * Warning:
543 * If so_pcb is not zero, the socket will be leaked,
544 * so protocol attachment handler must be coded carefuly
55e303ae 545 */
1c79356b 546 so->so_state |= SS_NOFDREF;
37839358
A
547 so->so_usecount--;
548 sofreelastref(so, 1); /* will deallocate the socket */
1c79356b
A
549 return (error);
550 }
9bccf70c 551#ifdef __APPLE__
1c79356b 552 prp->pr_domain->dom_refs++;
1c79356b 553 TAILQ_INIT(&so->so_evlist);
91447636
A
554
555 /* Attach socket filters for this protocol */
556 sflt_initsock(so);
55e303ae
A
557#if TCPDEBUG
558 if (tcpconsdebug == 2)
559 so->so_options |= SO_DEBUG;
560#endif
9bccf70c 561#endif
1c79356b
A
562 *aso = so;
563 return (0);
564}
565
2d21ac55
A
566/*
567 * Returns: 0 Success
568 * <pru_bind>:EINVAL Invalid argument [COMMON_START]
569 * <pru_bind>:EAFNOSUPPORT Address family not supported
570 * <pru_bind>:EADDRNOTAVAIL Address not available.
571 * <pru_bind>:EINVAL Invalid argument
572 * <pru_bind>:EAFNOSUPPORT Address family not supported [notdef]
573 * <pru_bind>:EACCES Permission denied
574 * <pru_bind>:EADDRINUSE Address in use
575 * <pru_bind>:EAGAIN Resource unavailable, try again
576 * <pru_bind>:EPERM Operation not permitted
577 * <pru_bind>:???
578 * <sf_bind>:???
579 *
580 * Notes: It's not possible to fully enumerate the return codes above,
581 * since socket filter authors and protocol family authors may
582 * not choose to limit their error returns to those listed, even
583 * though this may result in some software operating incorrectly.
584 *
585 * The error codes which are enumerated above are those known to
586 * be returned by the tcp_usr_bind function supplied.
587 */
1c79356b 588int
2d21ac55 589sobind(struct socket *so, struct sockaddr *nam)
1c79356b
A
590{
591 struct proc *p = current_proc();
91447636 592 int error = 0;
2d21ac55
A
593 struct socket_filter_entry *filter;
594 int filtered = 0;
1c79356b 595
91447636
A
596 socket_lock(so, 1);
597
2d21ac55
A
598 /*
599 * If this is a bind request on a previously-accepted socket
600 * that has been marked as inactive, reject it now before
601 * we go any further.
602 */
603 if (so->so_flags & SOF_DEFUNCT) {
604 error = EINVAL;
605 goto out;
606 }
607
91447636
A
608 /* Socket filter */
609 error = 0;
610 for (filter = so->so_filt; filter && (error == 0);
2d21ac55 611 filter = filter->sfe_next_onsocket) {
91447636
A
612 if (filter->sfe_filter->sf_filter.sf_bind) {
613 if (filtered == 0) {
614 filtered = 1;
615 sflt_use(so);
616 socket_unlock(so, 0);
1c79356b 617 }
2d21ac55
A
618 error = filter->sfe_filter->sf_filter.
619 sf_bind(filter->sfe_cookie, so, nam);
1c79356b
A
620 }
621 }
91447636
A
622 if (filtered != 0) {
623 socket_lock(so, 0);
624 sflt_unuse(so);
625 }
626 /* End socket filter */
2d21ac55 627
91447636
A
628 if (error == 0)
629 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, p);
2d21ac55 630out:
91447636 631 socket_unlock(so, 1);
2d21ac55 632
91447636
A
633 if (error == EJUSTRETURN)
634 error = 0;
2d21ac55 635
1c79356b
A
636 return (error);
637}
638
639void
2d21ac55 640sodealloc(struct socket *so)
1c79356b
A
641{
642 so->so_gencnt = ++so_gencnt;
643
2d21ac55
A
644#if CONFIG_MACF_SOCKET
645 mac_socket_label_destroy(so);
646#endif /* MAC_SOCKET */
647 if (so->cached_in_sock_layer == 1) {
648 cached_sock_free(so);
649 } else {
650 if (so->cached_in_sock_layer == -1)
651 panic("sodealloc: double dealloc: so=%p\n", so);
652 so->cached_in_sock_layer = -1;
653 FREE_ZONE(so, sizeof (*so), so->so_zone);
91447636 654 }
1c79356b
A
655}
656
2d21ac55
A
657/*
658 * Returns: 0 Success
659 * EINVAL
660 * EOPNOTSUPP
661 * <pru_listen>:EINVAL[AF_UNIX]
662 * <pru_listen>:EINVAL[TCP]
663 * <pru_listen>:EADDRNOTAVAIL[TCP] Address not available.
664 * <pru_listen>:EINVAL[TCP] Invalid argument
665 * <pru_listen>:EAFNOSUPPORT[TCP] Address family not supported [notdef]
666 * <pru_listen>:EACCES[TCP] Permission denied
667 * <pru_listen>:EADDRINUSE[TCP] Address in use
668 * <pru_listen>:EAGAIN[TCP] Resource unavailable, try again
669 * <pru_listen>:EPERM[TCP] Operation not permitted
670 * <sf_listen>:???
671 *
672 * Notes: Other <pru_listen> returns depend on the protocol family; all
673 * <sf_listen> returns depend on what the filter author causes
674 * their filter to return.
675 */
1c79356b 676int
2d21ac55 677solisten(struct socket *so, int backlog)
1c79356b 678{
1c79356b 679 struct proc *p = current_proc();
2d21ac55
A
680 int error = 0;
681 struct socket_filter_entry *filter;
682 int filtered = 0;
1c79356b 683
91447636 684 socket_lock(so, 1);
2d21ac55
A
685 if (so->so_proto == NULL) {
686 error = EINVAL;
687 goto out;
688 }
689 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0) {
690 error = EOPNOTSUPP;
691 goto out;
692 }
693
694 /*
695 * If the listen request is made on a socket that is not fully
696 * disconnected, or on a previously-accepted socket that has
697 * been marked as inactive, reject the request now.
698 */
699 if ((so->so_state &
700 (SS_ISCONNECTED|SS_ISCONNECTING|SS_ISDISCONNECTING)) ||
701 (so->so_flags & SOF_DEFUNCT)) {
702 error = EINVAL;
703 goto out;
704 }
705
706 if ((so->so_restrictions & SO_RESTRICT_DENYIN) != 0) {
707 error = EPERM;
708 goto out;
709 }
710
711 error = 0;
712 for (filter = so->so_filt; filter && (error == 0);
713 filter = filter->sfe_next_onsocket) {
714 if (filter->sfe_filter->sf_filter.sf_listen) {
715 if (filtered == 0) {
716 filtered = 1;
717 sflt_use(so);
718 socket_unlock(so, 0);
91447636 719 }
2d21ac55
A
720 error = filter->sfe_filter->sf_filter.
721 sf_listen(filter->sfe_cookie, so);
91447636 722 }
2d21ac55
A
723 }
724 if (filtered != 0) {
725 socket_lock(so, 0);
726 sflt_unuse(so);
91447636
A
727 }
728
729 if (error == 0) {
730 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, p);
731 }
2d21ac55 732
1c79356b 733 if (error) {
91447636
A
734 if (error == EJUSTRETURN)
735 error = 0;
2d21ac55 736 goto out;
1c79356b 737 }
2d21ac55 738
91447636 739 if (TAILQ_EMPTY(&so->so_comp))
1c79356b 740 so->so_options |= SO_ACCEPTCONN;
2d21ac55
A
741 /*
742 * POSIX: The implementation may have an upper limit on the length of
743 * the listen queue-either global or per accepting socket. If backlog
744 * exceeds this limit, the length of the listen queue is set to the
745 * limit.
746 *
747 * If listen() is called with a backlog argument value that is less
748 * than 0, the function behaves as if it had been called with a backlog
749 * argument value of 0.
750 *
751 * A backlog argument of 0 may allow the socket to accept connections,
752 * in which case the length of the listen queue may be set to an
753 * implementation-defined minimum value.
754 */
755 if (backlog <= 0 || backlog > somaxconn)
1c79356b 756 backlog = somaxconn;
1c79356b 757
2d21ac55
A
758 so->so_qlimit = backlog;
759out:
91447636 760 socket_unlock(so, 1);
2d21ac55 761 return (error);
1c79356b
A
762}
763
1c79356b 764void
2d21ac55 765sofreelastref(struct socket *so, int dealloc)
9bccf70c 766{
1c79356b
A
767 struct socket *head = so->so_head;
768
2d21ac55 769 /* Assume socket is locked */
1c79356b 770
3a60a9f5
A
771 /* Remove any filters - may be called more than once */
772 sflt_termsock(so);
2d21ac55
A
773
774 if ((!(so->so_flags & SOF_PCBCLEARING)) ||
775 ((so->so_state & SS_NOFDREF) == 0)) {
9bccf70c 776#ifdef __APPLE__
0b4e3aa0
A
777 selthreadclear(&so->so_snd.sb_sel);
778 selthreadclear(&so->so_rcv.sb_sel);
cc9f6e38
A
779 so->so_rcv.sb_flags &= ~SB_UPCALL;
780 so->so_snd.sb_flags &= ~SB_UPCALL;
9bccf70c 781#endif
1c79356b 782 return;
0b4e3aa0 783 }
9bccf70c 784 if (head != NULL) {
91447636 785 socket_lock(head, 1);
9bccf70c
A
786 if (so->so_state & SS_INCOMP) {
787 TAILQ_REMOVE(&head->so_incomp, so, so_list);
788 head->so_incqlen--;
789 } else if (so->so_state & SS_COMP) {
790 /*
791 * We must not decommission a socket that's
792 * on the accept(2) queue. If we do, then
793 * accept(2) may hang after select(2) indicated
794 * that the listening socket was ready.
795 */
796#ifdef __APPLE__
797 selthreadclear(&so->so_snd.sb_sel);
798 selthreadclear(&so->so_rcv.sb_sel);
cc9f6e38
A
799 so->so_rcv.sb_flags &= ~SB_UPCALL;
800 so->so_snd.sb_flags &= ~SB_UPCALL;
9bccf70c 801#endif
91447636 802 socket_unlock(head, 1);
9bccf70c
A
803 return;
804 } else {
805 panic("sofree: not queued");
806 }
1c79356b 807 head->so_qlen--;
9bccf70c 808 so->so_state &= ~SS_INCOMP;
1c79356b 809 so->so_head = NULL;
91447636 810 socket_unlock(head, 1);
1c79356b 811 }
9bccf70c 812#ifdef __APPLE__
0b4e3aa0 813 selthreadclear(&so->so_snd.sb_sel);
1c79356b 814 sbrelease(&so->so_snd);
9bccf70c 815#endif
1c79356b 816 sorflush(so);
2d21ac55 817
91447636
A
818 /* 3932268: disable upcall */
819 so->so_rcv.sb_flags &= ~SB_UPCALL;
820 so->so_snd.sb_flags &= ~SB_UPCALL;
2d21ac55 821
91447636
A
822 if (dealloc)
823 sodealloc(so);
1c79356b
A
824}
825
2d21ac55
A
826void
827soclose_wait_locked(struct socket *so)
828{
829 lck_mtx_t *mutex_held;
830
831 if (so->so_proto->pr_getlock != NULL)
832 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
833 else
834 mutex_held = so->so_proto->pr_domain->dom_mtx;
835 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
836
4a3eedf9
A
837 /*
838 * Double check here and return if there's no outstanding upcall;
839 * otherwise proceed further only if SOF_UPCALLCLOSEWAIT is set.
840 */
841 if (!(so->so_flags & SOF_UPCALLINUSE) ||
842 !(so->so_flags & SOF_UPCALLCLOSEWAIT))
2d21ac55
A
843 return;
844
845 so->so_flags |= SOF_CLOSEWAIT;
846 (void) msleep((caddr_t)&so->so_upcall, mutex_held, (PZERO - 1),
847 "soclose_wait_locked", NULL);
848 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
849 so->so_flags &= ~SOF_CLOSEWAIT;
850}
851
1c79356b
A
852/*
853 * Close a socket on last file table reference removal.
854 * Initiate disconnect if connected.
855 * Free socket when disconnect complete.
856 */
857int
2d21ac55 858soclose_locked(struct socket *so)
1c79356b 859{
1c79356b 860 int error = 0;
2d21ac55 861 lck_mtx_t *mutex_held;
91447636 862 struct timespec ts;
1c79356b 863
91447636 864 if (so->so_usecount == 0) {
2d21ac55 865 panic("soclose: so=%p refcount=0\n", so);
1c79356b
A
866 }
867
91447636 868 sflt_notify(so, sock_evt_closing, NULL);
2d21ac55 869
91447636 870 if ((so->so_options & SO_ACCEPTCONN)) {
2d21ac55
A
871 struct socket *sp, *sonext;
872 int socklock = 0;
873
874 /*
875 * We do not want new connection to be added
876 * to the connection queues
877 */
91447636 878 so->so_options &= ~SO_ACCEPTCONN;
2d21ac55
A
879
880 for (sp = TAILQ_FIRST(&so->so_incomp); sp != NULL; sp = sonext) {
881 sonext = TAILQ_NEXT(sp, so_list);
882
883 /* Radar 5350314
884 * skip sockets thrown away by tcpdropdropblreq
885 * they will get cleanup by the garbage collection.
886 * otherwise, remove the incomp socket from the queue
887 * and let soabort trigger the appropriate cleanup.
91447636 888 */
2d21ac55
A
889 if (sp->so_flags & SOF_OVERFLOW)
890 continue;
891
ff6e181a 892 if (so->so_proto->pr_getlock != NULL) {
2d21ac55
A
893 /* lock ordering for consistency with the rest of the stack,
894 * we lock the socket first and then grabb the head.
895 */
91447636 896 socket_unlock(so, 0);
ff6e181a 897 socket_lock(sp, 1);
ff6e181a 898 socket_lock(so, 0);
2d21ac55
A
899 socklock = 1;
900 }
901
902 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
903 so->so_incqlen--;
904
905 if (sp->so_state & SS_INCOMP) {
906 sp->so_state &= ~SS_INCOMP;
907 sp->so_head = NULL;
908
909 (void) soabort(sp);
ff6e181a 910 }
2d21ac55
A
911
912 if (socklock)
913 socket_unlock(sp, 1);
91447636
A
914 }
915
916 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
91447636 917 /* Dequeue from so_comp since sofree() won't do it */
2d21ac55 918 TAILQ_REMOVE(&so->so_comp, sp, so_list);
91447636 919 so->so_qlen--;
ff6e181a
A
920
921 if (so->so_proto->pr_getlock != NULL) {
922 socket_unlock(so, 0);
923 socket_lock(sp, 1);
924 }
925
2d21ac55
A
926 if (sp->so_state & SS_COMP) {
927 sp->so_state &= ~SS_COMP;
928 sp->so_head = NULL;
929
930 (void) soabort(sp);
931 }
91447636 932
ff6e181a 933 if (so->so_proto->pr_getlock != NULL) {
91447636 934 socket_unlock(sp, 1);
ff6e181a
A
935 socket_lock(so, 0);
936 }
91447636
A
937 }
938 }
939 if (so->so_pcb == 0) {
940 /* 3915887: mark the socket as ready for dealloc */
941 so->so_flags |= SOF_PCBCLEARING;
1c79356b 942 goto discard;
91447636 943 }
1c79356b
A
944 if (so->so_state & SS_ISCONNECTED) {
945 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
91447636 946 error = sodisconnectlocked(so);
1c79356b
A
947 if (error)
948 goto drop;
949 }
950 if (so->so_options & SO_LINGER) {
951 if ((so->so_state & SS_ISDISCONNECTING) &&
952 (so->so_state & SS_NBIO))
953 goto drop;
2d21ac55 954 if (so->so_proto->pr_getlock != NULL)
91447636 955 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
2d21ac55 956 else
91447636 957 mutex_held = so->so_proto->pr_domain->dom_mtx;
1c79356b 958 while (so->so_state & SS_ISCONNECTED) {
91447636 959 ts.tv_sec = (so->so_linger/100);
2d21ac55
A
960 ts.tv_nsec = (so->so_linger % 100) *
961 NSEC_PER_USEC * 1000 * 10;
962 error = msleep((caddr_t)&so->so_timeo,
963 mutex_held, PSOCK | PCATCH, "soclose", &ts);
91447636 964 if (error) {
2d21ac55
A
965 /*
966 * It's OK when the time fires,
967 * don't report an error
968 */
91447636
A
969 if (error == EWOULDBLOCK)
970 error = 0;
1c79356b 971 break;
91447636 972 }
1c79356b
A
973 }
974 }
975 }
976drop:
91447636 977 if (so->so_usecount == 0)
2d21ac55 978 panic("soclose: usecount is zero so=%p\n", so);
91447636 979 if (so->so_pcb && !(so->so_flags & SOF_PCBCLEARING)) {
1c79356b
A
980 int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
981 if (error == 0)
982 error = error2;
983 }
91447636 984 if (so->so_usecount <= 0)
2d21ac55 985 panic("soclose: usecount is zero so=%p\n", so);
1c79356b 986discard:
e3027f41 987 if (so->so_pcb && so->so_state & SS_NOFDREF)
1c79356b
A
988 panic("soclose: NOFDREF");
989 so->so_state |= SS_NOFDREF;
9bccf70c 990#ifdef __APPLE__
1c79356b
A
991 so->so_proto->pr_domain->dom_refs--;
992 evsofree(so);
9bccf70c 993#endif
91447636 994 so->so_usecount--;
1c79356b 995 sofree(so);
1c79356b
A
996 return (error);
997}
998
91447636 999int
2d21ac55 1000soclose(struct socket *so)
91447636
A
1001{
1002 int error = 0;
1003 socket_lock(so, 1);
2d21ac55
A
1004
1005 if (so->so_flags & SOF_UPCALLINUSE)
1006 soclose_wait_locked(so);
1007
1008 if (so->so_retaincnt == 0) {
91447636 1009 error = soclose_locked(so);
2d21ac55
A
1010 } else {
1011 /*
1012 * if the FD is going away, but socket is
1013 * retained in kernel remove its reference
1014 */
91447636
A
1015 so->so_usecount--;
1016 if (so->so_usecount < 2)
2d21ac55
A
1017 panic("soclose: retaincnt non null and so=%p "
1018 "usecount=%d\n", so, so->so_usecount);
91447636
A
1019 }
1020 socket_unlock(so, 1);
1021 return (error);
1022}
1023
1c79356b
A
1024/*
1025 * Must be called at splnet...
1026 */
2d21ac55 1027/* Should already be locked */
1c79356b 1028int
2d21ac55 1029soabort(struct socket *so)
1c79356b 1030{
9bccf70c 1031 int error;
1c79356b 1032
91447636 1033#ifdef MORE_LOCKING_DEBUG
2d21ac55 1034 lck_mtx_t *mutex_held;
91447636 1035
2d21ac55 1036 if (so->so_proto->pr_getlock != NULL)
91447636 1037 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
2d21ac55 1038 else
91447636
A
1039 mutex_held = so->so_proto->pr_domain->dom_mtx;
1040 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
1041#endif
1042
2d21ac55
A
1043 if ((so->so_flags & SOF_ABORTED) == 0) {
1044 so->so_flags |= SOF_ABORTED;
1045 error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
1046 if (error) {
1047 sofree(so);
1048 return (error);
1049 }
9bccf70c
A
1050 }
1051 return (0);
1c79356b
A
1052}
1053
1054int
2d21ac55 1055soacceptlock(struct socket *so, struct sockaddr **nam, int dolock)
9bccf70c 1056{
1c79356b 1057 int error;
91447636 1058
2d21ac55
A
1059 if (dolock)
1060 socket_lock(so, 1);
1c79356b
A
1061
1062 if ((so->so_state & SS_NOFDREF) == 0)
1063 panic("soaccept: !NOFDREF");
1064 so->so_state &= ~SS_NOFDREF;
1065 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
2d21ac55
A
1066
1067 if (dolock)
1068 socket_unlock(so, 1);
1c79356b
A
1069 return (error);
1070}
2d21ac55 1071
91447636 1072int
2d21ac55 1073soaccept(struct socket *so, struct sockaddr **nam)
91447636
A
1074{
1075 return (soacceptlock(so, nam, 1));
1076}
1c79356b
A
1077
1078int
2d21ac55
A
1079soacceptfilter(struct socket *so)
1080{
1081 struct sockaddr *local = NULL, *remote = NULL;
1082 struct socket_filter_entry *filter;
1083 int error = 0, filtered = 0;
1084 struct socket *head = so->so_head;
1085
1086 /*
b0d623f7 1087 * Hold the lock even if this socket
2d21ac55 1088 * has not been made visible to the filter(s).
b0d623f7
A
1089 * For sockets with global locks, this protect against the
1090 * head or peer going away
2d21ac55 1091 */
b0d623f7
A
1092 socket_lock(so, 1);
1093 if (sogetaddr_locked(so, &remote, 1) != 0 ||
1094 sogetaddr_locked(so, &local, 0) != 0) {
2d21ac55
A
1095 so->so_state &= ~(SS_NOFDREF | SS_COMP);
1096 so->so_head = NULL;
b0d623f7 1097 socket_unlock(so, 1);
2d21ac55
A
1098 soclose(so);
1099 /* Out of resources; try it again next time */
1100 error = ECONNABORTED;
1101 goto done;
1102 }
1103
1104 /*
1105 * At this point, we have a reference on the listening socket
1106 * so we know it won't be going away. Do the same for the newly
1107 * accepted socket while we invoke the accept callback routine.
1108 */
2d21ac55
A
1109 for (filter = so->so_filt; filter != NULL && error == 0;
1110 filter = filter->sfe_next_onsocket) {
1111 if (filter->sfe_filter->sf_filter.sf_accept != NULL) {
1112 if (!filtered) {
1113 filtered = 1;
1114 sflt_use(so);
1115 socket_unlock(so, 0);
1116 }
1117 error = filter->sfe_filter->sf_filter.
1118 sf_accept(filter->sfe_cookie,
1119 head, so, local, remote);
1120 }
1121 }
1122
1123 if (filtered) {
1124 socket_lock(so, 0);
1125 sflt_unuse(so);
1126 }
1127
1128 /*
1129 * If we get EJUSTRETURN from one of the filters, mark this socket
1130 * as inactive and return it anyway. This newly accepted socket
1131 * will be disconnected later before we hand it off to the caller.
1132 */
1133 if (error == EJUSTRETURN) {
1134 error = 0;
1135 so->so_flags |= SOF_DEFUNCT;
1136 /* Prevent data from being appended to the socket buffers */
1137 so->so_snd.sb_flags |= SB_DROP;
1138 so->so_rcv.sb_flags |= SB_DROP;
1139 }
1140
1141 if (error != 0) {
1142 /*
1143 * This may seem like a duplication to the above error
1144 * handling part when we return ECONNABORTED, except
1145 * the following is done while holding the lock since
1146 * the socket has been exposed to the filter(s) earlier.
1147 */
1148 so->so_state &= ~(SS_NOFDREF | SS_COMP);
1149 so->so_head = NULL;
1150 socket_unlock(so, 1);
1151 soclose(so);
1152 /* Propagate socket filter's error code to the caller */
1153 } else {
1154 socket_unlock(so, 1);
1155 }
1156done:
1157 /* Callee checks for NULL pointer */
1158 sock_freeaddr(remote);
1159 sock_freeaddr(local);
1160 return (error);
1161}
1c79356b 1162
2d21ac55
A
1163/*
1164 * Returns: 0 Success
1165 * EOPNOTSUPP Operation not supported on socket
1166 * EISCONN Socket is connected
1167 * <pru_connect>:EADDRNOTAVAIL Address not available.
1168 * <pru_connect>:EINVAL Invalid argument
1169 * <pru_connect>:EAFNOSUPPORT Address family not supported [notdef]
1170 * <pru_connect>:EACCES Permission denied
1171 * <pru_connect>:EADDRINUSE Address in use
1172 * <pru_connect>:EAGAIN Resource unavailable, try again
1173 * <pru_connect>:EPERM Operation not permitted
1174 * <sf_connect_out>:??? [anything a filter writer might set]
1175 */
1176int
1177soconnectlock(struct socket *so, struct sockaddr *nam, int dolock)
1c79356b 1178{
1c79356b
A
1179 int error;
1180 struct proc *p = current_proc();
1c79356b 1181
2d21ac55
A
1182 if (dolock)
1183 socket_lock(so, 1);
91447636 1184
2d21ac55
A
1185 /*
1186 * If this is a listening socket or if this is a previously-accepted
1187 * socket that has been marked as inactive, reject the connect request.
1188 */
1189 if ((so->so_options & SO_ACCEPTCONN) || (so->so_flags & SOF_DEFUNCT)) {
1190 if (dolock)
1191 socket_unlock(so, 1);
1c79356b 1192 return (EOPNOTSUPP);
91447636 1193 }
2d21ac55
A
1194
1195 if ((so->so_restrictions & SO_RESTRICT_DENYOUT) != 0) {
1196 if (dolock)
1197 socket_unlock(so, 1);
1198 return (EPERM);
1199 }
1200
1c79356b
A
1201 /*
1202 * If protocol is connection-based, can only connect once.
1203 * Otherwise, if connected, try to disconnect first.
1204 * This allows user to disconnect by connecting to, e.g.,
1205 * a null address.
1206 */
1207 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1208 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
2d21ac55 1209 (error = sodisconnectlocked(so)))) {
1c79356b 1210 error = EISCONN;
2d21ac55 1211 } else {
91447636
A
1212 /*
1213 * Run connect filter before calling protocol:
1214 * - non-blocking connect returns before completion;
1215 */
2d21ac55
A
1216 struct socket_filter_entry *filter;
1217 int filtered = 0;
1218
1219 error = 0;
1220 for (filter = so->so_filt; filter && (error == 0);
1221 filter = filter->sfe_next_onsocket) {
1222 if (filter->sfe_filter->sf_filter.sf_connect_out) {
1223 if (filtered == 0) {
1224 filtered = 1;
1225 sflt_use(so);
1226 socket_unlock(so, 0);
91447636 1227 }
2d21ac55
A
1228 error = filter->sfe_filter->sf_filter.
1229 sf_connect_out(filter->sfe_cookie, so, nam);
91447636 1230 }
91447636 1231 }
2d21ac55
A
1232 if (filtered != 0) {
1233 socket_lock(so, 0);
1234 sflt_unuse(so);
1235 }
1236
91447636
A
1237 if (error) {
1238 if (error == EJUSTRETURN)
1239 error = 0;
2d21ac55
A
1240 if (dolock)
1241 socket_unlock(so, 1);
1242 return (error);
91447636 1243 }
2d21ac55 1244
1c79356b 1245 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, p);
1c79356b 1246 }
2d21ac55
A
1247 if (dolock)
1248 socket_unlock(so, 1);
1c79356b
A
1249 return (error);
1250}
1251
91447636 1252int
2d21ac55 1253soconnect(struct socket *so, struct sockaddr *nam)
91447636
A
1254{
1255 return (soconnectlock(so, nam, 1));
1256}
1257
2d21ac55
A
1258/*
1259 * Returns: 0 Success
1260 * <pru_connect2>:EINVAL[AF_UNIX]
1261 * <pru_connect2>:EPROTOTYPE[AF_UNIX]
1262 * <pru_connect2>:??? [other protocol families]
1263 *
1264 * Notes: <pru_connect2> is not supported by [TCP].
1265 */
1c79356b 1266int
2d21ac55 1267soconnect2(struct socket *so1, struct socket *so2)
1c79356b 1268{
1c79356b 1269 int error;
91447636 1270
0c530ab8 1271 socket_lock(so1, 1);
2d21ac55 1272 if (so2->so_proto->pr_lock)
0c530ab8 1273 socket_lock(so2, 1);
1c79356b
A
1274
1275 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
2d21ac55 1276
0c530ab8 1277 socket_unlock(so1, 1);
2d21ac55 1278 if (so2->so_proto->pr_lock)
0c530ab8 1279 socket_unlock(so2, 1);
1c79356b
A
1280 return (error);
1281}
1282
1283int
2d21ac55 1284sodisconnectlocked(struct socket *so)
1c79356b 1285{
1c79356b 1286 int error;
1c79356b
A
1287
1288 if ((so->so_state & SS_ISCONNECTED) == 0) {
1289 error = ENOTCONN;
1290 goto bad;
1291 }
1292 if (so->so_state & SS_ISDISCONNECTING) {
1293 error = EALREADY;
1294 goto bad;
1295 }
2d21ac55 1296
1c79356b 1297 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
2d21ac55 1298
9bccf70c 1299 if (error == 0) {
91447636 1300 sflt_notify(so, sock_evt_disconnected, NULL);
1c79356b 1301 }
1c79356b 1302bad:
1c79356b
A
1303 return (error);
1304}
2d21ac55
A
1305
1306/* Locking version */
91447636 1307int
2d21ac55 1308sodisconnect(struct socket *so)
91447636 1309{
2d21ac55 1310 int error;
91447636
A
1311
1312 socket_lock(so, 1);
1313 error = sodisconnectlocked(so);
1314 socket_unlock(so, 1);
2d21ac55 1315 return (error);
91447636 1316}
1c79356b
A
1317
1318#define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_DONTWAIT : M_WAIT)
91447636
A
1319
1320/*
1321 * sosendcheck will lock the socket buffer if it isn't locked and
1322 * verify that there is space for the data being inserted.
2d21ac55
A
1323 *
1324 * Returns: 0 Success
1325 * EPIPE
1326 * sblock:EWOULDBLOCK
1327 * sblock:EINTR
1328 * sbwait:EBADF
1329 * sbwait:EINTR
1330 * [so_error]:???
91447636 1331 */
91447636 1332static int
b0d623f7
A
1333sosendcheck(struct socket *so, struct sockaddr *addr, int32_t resid, int32_t clen,
1334 int32_t atomic, int flags, int *sblocked)
91447636 1335{
b0d623f7
A
1336 int error = 0;
1337 int32_t space;
3a60a9f5 1338 int assumelock = 0;
91447636
A
1339
1340restart:
1341 if (*sblocked == 0) {
3a60a9f5 1342 if ((so->so_snd.sb_flags & SB_LOCK) != 0 &&
2d21ac55
A
1343 so->so_send_filt_thread != 0 &&
1344 so->so_send_filt_thread == current_thread()) {
3a60a9f5
A
1345 /*
1346 * We're being called recursively from a filter,
1347 * allow this to continue. Radar 4150520.
1348 * Don't set sblocked because we don't want
1349 * to perform an unlock later.
1350 */
1351 assumelock = 1;
2d21ac55 1352 } else {
3a60a9f5
A
1353 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1354 if (error) {
2d21ac55 1355 return (error);
3a60a9f5
A
1356 }
1357 *sblocked = 1;
1358 }
91447636 1359 }
2d21ac55
A
1360
1361 /*
1362 * If a send attempt is made on a previously-accepted socket
1363 * that has been marked as inactive (disconnected), reject
1364 * the request.
1365 */
1366 if (so->so_flags & SOF_DEFUNCT)
1367 return (ENOTCONN);
1368
1369 if (so->so_state & SS_CANTSENDMORE)
1370 return (EPIPE);
1371
91447636
A
1372 if (so->so_error) {
1373 error = so->so_error;
1374 so->so_error = 0;
2d21ac55 1375 return (error);
91447636 1376 }
2d21ac55 1377
91447636 1378 if ((so->so_state & SS_ISCONNECTED) == 0) {
2d21ac55 1379 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) {
91447636 1380 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
2d21ac55
A
1381 !(resid == 0 && clen != 0))
1382 return (ENOTCONN);
1383 } else if (addr == 0 && !(flags&MSG_HOLD)) {
1384 return ((so->so_proto->pr_flags & PR_CONNREQUIRED) ?
1385 ENOTCONN : EDESTADDRREQ);
1386 }
91447636
A
1387 }
1388 space = sbspace(&so->so_snd);
1389 if (flags & MSG_OOB)
1390 space += 1024;
1391 if ((atomic && resid > so->so_snd.sb_hiwat) ||
2d21ac55
A
1392 clen > so->so_snd.sb_hiwat)
1393 return (EMSGSIZE);
1394 if (space < resid + clen &&
b0d623f7 1395 (atomic || space < (int32_t)so->so_snd.sb_lowat || space < clen)) {
2d21ac55
A
1396 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO) ||
1397 assumelock) {
1398 return (EWOULDBLOCK);
3a60a9f5 1399 }
91447636
A
1400 sbunlock(&so->so_snd, 1);
1401 error = sbwait(&so->so_snd);
1402 if (error) {
2d21ac55 1403 return (error);
91447636
A
1404 }
1405 goto restart;
1406 }
2d21ac55
A
1407
1408 return (0);
91447636
A
1409}
1410
1c79356b
A
1411/*
1412 * Send on a socket.
1413 * If send must go all at once and message is larger than
1414 * send buffering, then hard error.
1415 * Lock against other senders.
1416 * If must go all at once and not enough room now, then
1417 * inform user that this would block and do nothing.
1418 * Otherwise, if nonblocking, send as much as possible.
1419 * The data to be sent is described by "uio" if nonzero,
1420 * otherwise by the mbuf chain "top" (which must be null
1421 * if uio is not). Data provided in mbuf chain must be small
1422 * enough to send all at once.
1423 *
1424 * Returns nonzero on error, timeout or signal; callers
1425 * must check for short counts if EINTR/ERESTART are returned.
1426 * Data and control buffers are freed on return.
1427 * Experiment:
1428 * MSG_HOLD: go thru most of sosend(), but just enqueue the mbuf
1429 * MSG_SEND: go thru as for MSG_HOLD on current fragment, then
1430 * point at the mbuf chain being constructed and go from there.
2d21ac55
A
1431 *
1432 * Returns: 0 Success
1433 * EOPNOTSUPP
1434 * EINVAL
1435 * ENOBUFS
1436 * uiomove:EFAULT
1437 * sosendcheck:EPIPE
1438 * sosendcheck:EWOULDBLOCK
1439 * sosendcheck:EINTR
1440 * sosendcheck:EBADF
1441 * sosendcheck:EINTR
1442 * sosendcheck:??? [value from so_error]
1443 * <pru_send>:ECONNRESET[TCP]
1444 * <pru_send>:EINVAL[TCP]
1445 * <pru_send>:ENOBUFS[TCP]
1446 * <pru_send>:EADDRINUSE[TCP]
1447 * <pru_send>:EADDRNOTAVAIL[TCP]
1448 * <pru_send>:EAFNOSUPPORT[TCP]
1449 * <pru_send>:EACCES[TCP]
1450 * <pru_send>:EAGAIN[TCP]
1451 * <pru_send>:EPERM[TCP]
1452 * <pru_send>:EMSGSIZE[TCP]
1453 * <pru_send>:EHOSTUNREACH[TCP]
1454 * <pru_send>:ENETUNREACH[TCP]
1455 * <pru_send>:ENETDOWN[TCP]
1456 * <pru_send>:ENOMEM[TCP]
1457 * <pru_send>:ENOBUFS[TCP]
1458 * <pru_send>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
1459 * <pru_send>:EINVAL[AF_UNIX]
1460 * <pru_send>:EOPNOTSUPP[AF_UNIX]
1461 * <pru_send>:EPIPE[AF_UNIX]
1462 * <pru_send>:ENOTCONN[AF_UNIX]
1463 * <pru_send>:EISCONN[AF_UNIX]
1464 * <pru_send>:???[AF_UNIX] [whatever a filter author chooses]
1465 * <sf_data_out>:??? [whatever a filter author chooses]
1466 *
1467 * Notes: Other <pru_send> returns depend on the protocol family; all
1468 * <sf_data_out> returns depend on what the filter author causes
1469 * their filter to return.
1c79356b
A
1470 */
1471int
2d21ac55
A
1472sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1473 struct mbuf *top, struct mbuf *control, int flags)
1c79356b
A
1474{
1475 struct mbuf **mp;
fa4905b1 1476 register struct mbuf *m, *freelist = NULL;
b0d623f7 1477 register int32_t space, len, resid;
91447636 1478 int clen = 0, error, dontroute, mlen, sendflags;
1c79356b 1479 int atomic = sosendallatonce(so) || top;
91447636 1480 int sblocked = 0;
1c79356b 1481 struct proc *p = current_proc();
1c79356b 1482
2d21ac55 1483 if (uio) {
91447636
A
1484 // LP64todo - fix this!
1485 resid = uio_resid(uio);
2d21ac55 1486 } else {
1c79356b 1487 resid = top->m_pkthdr.len;
2d21ac55
A
1488 }
1489 KERNEL_DEBUG((DBG_FNC_SOSEND | DBG_FUNC_START), so, resid,
1490 so->so_snd.sb_cc, so->so_snd.sb_lowat, so->so_snd.sb_hiwat);
1c79356b 1491
91447636 1492 socket_lock(so, 1);
2d21ac55
A
1493 if (so->so_type != SOCK_STREAM && (flags & MSG_OOB) != 0) {
1494 error = EOPNOTSUPP;
1495 socket_unlock(so, 1);
1496 goto out;
1497 }
91447636 1498
1c79356b
A
1499 /*
1500 * In theory resid should be unsigned.
1501 * However, space must be signed, as it might be less than 0
1502 * if we over-committed, and we must use a signed comparison
1503 * of space and resid. On the other hand, a negative resid
1504 * causes us to loop sending 0-length segments to the protocol.
1505 *
1506 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1507 * type sockets since that's an error.
1508 */
91447636 1509 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1c79356b 1510 error = EINVAL;
91447636 1511 socket_unlock(so, 1);
1c79356b
A
1512 goto out;
1513 }
1514
1515 dontroute =
1516 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1517 (so->so_proto->pr_flags & PR_ATOMIC);
b0d623f7 1518 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_msgsnd);
1c79356b
A
1519 if (control)
1520 clen = control->m_len;
1c79356b 1521
1c79356b 1522 do {
2d21ac55
A
1523 error = sosendcheck(so, addr, resid, clen, atomic, flags,
1524 &sblocked);
91447636 1525 if (error) {
3a60a9f5 1526 goto release;
1c79356b 1527 }
1c79356b 1528 mp = &top;
2d21ac55
A
1529 space = sbspace(&so->so_snd) - clen + ((flags & MSG_OOB) ?
1530 1024 : 0);
fa4905b1 1531
1c79356b 1532 do {
2d21ac55
A
1533 struct socket_filter_entry *filter;
1534 int filtered;
1535 boolean_t recursive;
1536
1537 if (uio == NULL) {
91447636
A
1538 /*
1539 * Data is prepackaged in "top".
1540 */
1541 resid = 0;
1c79356b
A
1542 if (flags & MSG_EOR)
1543 top->m_flags |= M_EOR;
91447636 1544 } else {
2d21ac55
A
1545 int chainlength;
1546 int bytes_to_copy;
1547 boolean_t jumbocl;
1548
b0d623f7 1549 bytes_to_copy = imin(resid, space);
2d21ac55 1550
91447636
A
1551 if (sosendminchain > 0) {
1552 chainlength = 0;
2d21ac55 1553 } else {
91447636 1554 chainlength = sosendmaxchain;
2d21ac55
A
1555 }
1556
1557 /*
1558 * Attempt to use larger than system page-size
1559 * clusters for large writes only if there is
1560 * a jumbo cluster pool and if the socket is
1561 * marked accordingly.
1562 */
1563 jumbocl = sosendjcl && njcl > 0 &&
1564 ((so->so_flags & SOF_MULTIPAGES) ||
1565 sosendjcl_ignore_capab);
1566
91447636 1567 socket_unlock(so, 0);
2d21ac55 1568
91447636
A
1569 do {
1570 int num_needed;
1571 int hdrs_needed = (top == 0) ? 1 : 0;
2d21ac55 1572
91447636 1573 /*
2d21ac55
A
1574 * try to maintain a local cache of mbuf
1575 * clusters needed to complete this
1576 * write the list is further limited to
1577 * the number that are currently needed
1578 * to fill the socket this mechanism
1579 * allows a large number of mbufs/
1580 * clusters to be grabbed under a single
1581 * mbuf lock... if we can't get any
1582 * clusters, than fall back to trying
1583 * for mbufs if we fail early (or
1584 * miscalcluate the number needed) make
1585 * sure to release any clusters we
1586 * haven't yet consumed.
91447636 1587 */
2d21ac55
A
1588 if (freelist == NULL &&
1589 bytes_to_copy > NBPG && jumbocl) {
1590 num_needed =
1591 bytes_to_copy / M16KCLBYTES;
1592
1593 if ((bytes_to_copy -
1594 (num_needed * M16KCLBYTES))
1595 >= MINCLSIZE)
1596 num_needed++;
91447636 1597
2d21ac55
A
1598 freelist =
1599 m_getpackets_internal(
1600 (unsigned int *)&num_needed,
1601 hdrs_needed, M_WAIT, 0,
1602 M16KCLBYTES);
1603 /*
1604 * Fall back to 4K cluster size
1605 * if allocation failed
1606 */
1607 }
1608
1609 if (freelist == NULL &&
1610 bytes_to_copy > MCLBYTES) {
1611 num_needed =
1612 bytes_to_copy / NBPG;
1613
1614 if ((bytes_to_copy -
1615 (num_needed * NBPG)) >=
1616 MINCLSIZE)
91447636 1617 num_needed++;
2d21ac55
A
1618
1619 freelist =
1620 m_getpackets_internal(
1621 (unsigned int *)&num_needed,
1622 hdrs_needed, M_WAIT, 0,
1623 NBPG);
1624 /*
1625 * Fall back to cluster size
1626 * if allocation failed
1627 */
91447636 1628 }
2d21ac55
A
1629
1630 if (freelist == NULL &&
1631 bytes_to_copy > MINCLSIZE) {
1632 num_needed =
1633 bytes_to_copy / MCLBYTES;
1634
1635 if ((bytes_to_copy -
1636 (num_needed * MCLBYTES)) >=
1637 MINCLSIZE)
91447636 1638 num_needed++;
2d21ac55
A
1639
1640 freelist =
1641 m_getpackets_internal(
1642 (unsigned int *)&num_needed,
1643 hdrs_needed, M_WAIT, 0,
1644 MCLBYTES);
1645 /*
1646 * Fall back to a single mbuf
1647 * if allocation failed
1648 */
91447636 1649 }
2d21ac55 1650
91447636
A
1651 if (freelist == NULL) {
1652 if (top == 0)
2d21ac55
A
1653 MGETHDR(freelist,
1654 M_WAIT, MT_DATA);
91447636 1655 else
2d21ac55
A
1656 MGET(freelist,
1657 M_WAIT, MT_DATA);
91447636
A
1658
1659 if (freelist == NULL) {
1660 error = ENOBUFS;
1661 socket_lock(so, 0);
3a60a9f5 1662 goto release;
91447636
A
1663 }
1664 /*
2d21ac55
A
1665 * For datagram protocols,
1666 * leave room for protocol
1667 * headers in first mbuf.
91447636 1668 */
2d21ac55
A
1669 if (atomic && top == 0 &&
1670 bytes_to_copy < MHLEN) {
1671 MH_ALIGN(freelist,
1672 bytes_to_copy);
1673 }
91447636
A
1674 }
1675 m = freelist;
1676 freelist = m->m_next;
1677 m->m_next = NULL;
2d21ac55 1678
91447636
A
1679 if ((m->m_flags & M_EXT))
1680 mlen = m->m_ext.ext_size;
1681 else if ((m->m_flags & M_PKTHDR))
2d21ac55
A
1682 mlen =
1683 MHLEN - m_leadingspace(m);
91447636
A
1684 else
1685 mlen = MLEN;
b0d623f7 1686 len = imin(mlen, bytes_to_copy);
91447636
A
1687
1688 chainlength += len;
2d21ac55 1689
91447636 1690 space -= len;
fa4905b1 1691
2d21ac55 1692 error = uiomove(mtod(m, caddr_t),
b0d623f7 1693 len, uio);
2d21ac55 1694
91447636 1695 resid = uio_resid(uio);
2d21ac55 1696
91447636
A
1697 m->m_len = len;
1698 *mp = m;
1699 top->m_pkthdr.len += len;
2d21ac55 1700 if (error)
91447636
A
1701 break;
1702 mp = &m->m_next;
1703 if (resid <= 0) {
1704 if (flags & MSG_EOR)
1705 top->m_flags |= M_EOR;
1706 break;
1707 }
1708 bytes_to_copy = min(resid, space);
2d21ac55
A
1709
1710 } while (space > 0 &&
1711 (chainlength < sosendmaxchain || atomic ||
1712 resid < MINCLSIZE));
1713
91447636 1714 socket_lock(so, 0);
2d21ac55 1715
91447636
A
1716 if (error)
1717 goto release;
1718 }
2d21ac55
A
1719
1720 if (flags & (MSG_HOLD|MSG_SEND)) {
3a60a9f5
A
1721 /* Enqueue for later, go away if HOLD */
1722 register struct mbuf *mb1;
2d21ac55 1723 if (so->so_temp && (flags & MSG_FLUSH)) {
3a60a9f5
A
1724 m_freem(so->so_temp);
1725 so->so_temp = NULL;
1726 }
1727 if (so->so_temp)
1728 so->so_tail->m_next = top;
1729 else
1730 so->so_temp = top;
1731 mb1 = top;
1732 while (mb1->m_next)
2d21ac55 1733 mb1 = mb1->m_next;
3a60a9f5 1734 so->so_tail = mb1;
2d21ac55 1735 if (flags & MSG_HOLD) {
3a60a9f5
A
1736 top = NULL;
1737 goto release;
1738 }
1739 top = so->so_temp;
2d21ac55
A
1740 }
1741 if (dontroute)
1742 so->so_options |= SO_DONTROUTE;
1743
1744 /* Compute flags here, for pru_send and NKEs */
1745 sendflags = (flags & MSG_OOB) ? PRUS_OOB :
1746 /*
1747 * If the user set MSG_EOF, the protocol
1748 * understands this flag and nothing left to
1749 * send then use PRU_SEND_EOF instead of PRU_SEND.
1750 */
1751 ((flags & MSG_EOF) &&
1752 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1753 (resid <= 0)) ?
1c79356b 1754 PRUS_EOF :
2d21ac55
A
1755 /* If there is more to send set PRUS_MORETOCOME */
1756 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
1757
91447636
A
1758 /*
1759 * Socket filter processing
1760 */
2d21ac55
A
1761 recursive = (so->so_send_filt_thread != NULL);
1762 filtered = 0;
1763 error = 0;
1764 for (filter = so->so_filt; filter && (error == 0);
1765 filter = filter->sfe_next_onsocket) {
1766 if (filter->sfe_filter->sf_filter.sf_data_out) {
1767 int so_flags = 0;
1768 if (filtered == 0) {
1769 filtered = 1;
1770 so->so_send_filt_thread =
1771 current_thread();
1772 sflt_use(so);
1773 socket_unlock(so, 0);
1774 so_flags =
1775 (sendflags & MSG_OOB) ?
1776 sock_data_filt_flag_oob : 0;
91447636 1777 }
2d21ac55
A
1778 error = filter->sfe_filter->sf_filter.
1779 sf_data_out(filter->sfe_cookie, so,
1780 addr, &top, &control, so_flags);
91447636 1781 }
2d21ac55
A
1782 }
1783
1784 if (filtered) {
1785 /*
1786 * At this point, we've run at least one
1787 * filter. The socket is unlocked as is
1788 * the socket buffer. Clear the recorded
1789 * filter thread only when we are outside
1790 * of a filter's context. This allows for
1791 * a filter to issue multiple inject calls
1792 * from its sf_data_out callback routine.
1793 */
1794 socket_lock(so, 0);
1795 sflt_unuse(so);
1796 if (!recursive)
3a60a9f5 1797 so->so_send_filt_thread = 0;
2d21ac55
A
1798 if (error) {
1799 if (error == EJUSTRETURN) {
1800 error = 0;
1801 clen = 0;
1802 control = 0;
1803 top = 0;
1c79356b 1804 }
2d21ac55
A
1805
1806 goto release;
1c79356b
A
1807 }
1808 }
91447636
A
1809 /*
1810 * End Socket filter processing
1811 */
2d21ac55 1812
91447636
A
1813 if (error == EJUSTRETURN) {
1814 /* A socket filter handled this data */
1815 error = 0;
2d21ac55
A
1816 } else {
1817 error = (*so->so_proto->pr_usrreqs->pru_send)
1818 (so, sendflags, top, addr, control, p);
91447636 1819 }
9bccf70c 1820#ifdef __APPLE__
2d21ac55
A
1821 if (flags & MSG_SEND)
1822 so->so_temp = NULL;
9bccf70c 1823#endif
2d21ac55
A
1824 if (dontroute)
1825 so->so_options &= ~SO_DONTROUTE;
1826
1827 clen = 0;
1828 control = 0;
1829 top = 0;
1830 mp = &top;
1831 if (error)
1832 goto release;
1c79356b
A
1833 } while (resid && space > 0);
1834 } while (resid);
1835
1836release:
3a60a9f5
A
1837 if (sblocked)
1838 sbunlock(&so->so_snd, 0); /* will unlock socket */
1839 else
1840 socket_unlock(so, 1);
1c79356b
A
1841out:
1842 if (top)
1843 m_freem(top);
1844 if (control)
1845 m_freem(control);
fa4905b1 1846 if (freelist)
2d21ac55 1847 m_freem_list(freelist);
1c79356b 1848
2d21ac55
A
1849 KERNEL_DEBUG(DBG_FNC_SOSEND | DBG_FUNC_END, so, resid, so->so_snd.sb_cc,
1850 space, error);
1c79356b
A
1851
1852 return (error);
1853}
1854
1855/*
1856 * Implement receive operations on a socket.
1857 * We depend on the way that records are added to the sockbuf
1858 * by sbappend*. In particular, each record (mbufs linked through m_next)
1859 * must begin with an address if the protocol so specifies,
1860 * followed by an optional mbuf or mbufs containing ancillary data,
1861 * and then zero or more mbufs of data.
1862 * In order to avoid blocking network interrupts for the entire time here,
1863 * we splx() while doing the actual copy to user space.
1864 * Although the sockbuf is locked, new data may still be appended,
1865 * and thus we must maintain consistency of the sockbuf during that time.
1866 *
1867 * The caller may receive the data as a single mbuf chain by supplying
1868 * an mbuf **mp0 for use in returning the chain. The uio is then used
1869 * only for the count in uio_resid.
2d21ac55
A
1870 *
1871 * Returns: 0 Success
1872 * ENOBUFS
1873 * ENOTCONN
1874 * EWOULDBLOCK
1875 * uiomove:EFAULT
1876 * sblock:EWOULDBLOCK
1877 * sblock:EINTR
1878 * sbwait:EBADF
1879 * sbwait:EINTR
1880 * sodelayed_copy:EFAULT
1881 * <pru_rcvoob>:EINVAL[TCP]
1882 * <pru_rcvoob>:EWOULDBLOCK[TCP]
1883 * <pru_rcvoob>:???
1884 * <pr_domain->dom_externalize>:EMSGSIZE[AF_UNIX]
1885 * <pr_domain->dom_externalize>:ENOBUFS[AF_UNIX]
1886 * <pr_domain->dom_externalize>:???
1887 *
1888 * Notes: Additional return values from calls through <pru_rcvoob> and
1889 * <pr_domain->dom_externalize> depend on protocols other than
1890 * TCP or AF_UNIX, which are documented above.
1c79356b
A
1891 */
1892int
2d21ac55
A
1893soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
1894 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1c79356b 1895{
91447636
A
1896 register struct mbuf *m, **mp, *ml = NULL;
1897 register int flags, len, error, offset;
1c79356b
A
1898 struct protosw *pr = so->so_proto;
1899 struct mbuf *nextrecord;
1900 int moff, type = 0;
91447636 1901 int orig_resid = uio_resid(uio);
2d21ac55
A
1902 struct mbuf *free_list;
1903 int delayed_copy_len;
55e303ae
A
1904 int can_delay;
1905 int need_event;
1906 struct proc *p = current_proc();
1907
2d21ac55
A
1908 // LP64todo - fix this!
1909 KERNEL_DEBUG(DBG_FNC_SORECEIVE | DBG_FUNC_START, so, uio_resid(uio),
1910 so->so_rcv.sb_cc, so->so_rcv.sb_lowat, so->so_rcv.sb_hiwat);
1c79356b 1911
91447636 1912 socket_lock(so, 1);
1c79356b 1913
91447636
A
1914#ifdef MORE_LOCKING_DEBUG
1915 if (so->so_usecount == 1)
1916 panic("soreceive: so=%x no other reference on socket\n", so);
1917#endif
1c79356b
A
1918 mp = mp0;
1919 if (psa)
1920 *psa = 0;
1921 if (controlp)
1922 *controlp = 0;
1923 if (flagsp)
1924 flags = *flagsp &~ MSG_EOR;
1925 else
1926 flags = 0;
2d21ac55
A
1927
1928 /*
1929 * If a recv attempt is made on a previously-accepted socket
1930 * that has been marked as inactive (disconnected), reject
1931 * the request.
1932 */
1933 if (so->so_flags & SOF_DEFUNCT) {
1934 struct sockbuf *sb = &so->so_rcv;
1935
1936 /*
1937 * This socket should have been disconnected and flushed
1938 * prior to being returned from accept; there should be
1939 * no data on its receive list, so panic otherwise.
1940 */
1941 sb_empty_assert(sb, __func__);
1942 socket_unlock(so, 1);
1943 return (ENOTCONN);
1944 }
1945
1946 /*
1947 * When SO_WANTOOBFLAG is set we try to get out-of-band data
1948 * regardless of the flags argument. Here is the case were
1949 * out-of-band data is not inline.
1950 */
1951 if ((flags & MSG_OOB) ||
1952 ((so->so_options & SO_WANTOOBFLAG) != 0 &&
1953 (so->so_options & SO_OOBINLINE) == 0 &&
1954 (so->so_oobmark || (so->so_state & SS_RCVATMARK)))) {
1c79356b 1955 m = m_get(M_WAIT, MT_DATA);
55e303ae 1956 if (m == NULL) {
91447636 1957 socket_unlock(so, 1);
2d21ac55
A
1958 KERNEL_DEBUG(DBG_FNC_SORECEIVE | DBG_FUNC_END,
1959 ENOBUFS, 0, 0, 0, 0);
9bccf70c 1960 return (ENOBUFS);
55e303ae 1961 }
1c79356b
A
1962 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1963 if (error)
1964 goto bad;
91447636 1965 socket_unlock(so, 0);
1c79356b
A
1966 do {
1967 error = uiomove(mtod(m, caddr_t),
b0d623f7 1968 imin(uio_resid(uio), m->m_len), uio);
1c79356b 1969 m = m_free(m);
91447636
A
1970 } while (uio_resid(uio) && error == 0 && m);
1971 socket_lock(so, 0);
1c79356b
A
1972bad:
1973 if (m)
1974 m_freem(m);
9bccf70c
A
1975#ifdef __APPLE__
1976 if ((so->so_options & SO_WANTOOBFLAG) != 0) {
1977 if (error == EWOULDBLOCK || error == EINVAL) {
2d21ac55 1978 /*
9bccf70c 1979 * Let's try to get normal data:
2d21ac55
A
1980 * EWOULDBLOCK: out-of-band data not
1981 * receive yet. EINVAL: out-of-band data
1982 * already read.
9bccf70c
A
1983 */
1984 error = 0;
1985 goto nooob;
2d21ac55 1986 } else if (error == 0 && flagsp) {
9bccf70c 1987 *flagsp |= MSG_OOB;
2d21ac55
A
1988 }
1989 }
91447636 1990 socket_unlock(so, 1);
2d21ac55
A
1991 KERNEL_DEBUG(DBG_FNC_SORECEIVE | DBG_FUNC_END, error,
1992 0, 0, 0, 0);
9bccf70c 1993#endif
1c79356b
A
1994 return (error);
1995 }
1996nooob:
1997 if (mp)
1998 *mp = (struct mbuf *)0;
91447636 1999 if (so->so_state & SS_ISCONFIRMING && uio_resid(uio))
1c79356b
A
2000 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
2001
55e303ae
A
2002
2003 free_list = (struct mbuf *)0;
2004 delayed_copy_len = 0;
1c79356b 2005restart:
91447636
A
2006#ifdef MORE_LOCKING_DEBUG
2007 if (so->so_usecount <= 1)
2d21ac55
A
2008 printf("soreceive: sblock so=%p ref=%d on socket\n",
2009 so, so->so_usecount);
91447636 2010#endif
6601e61a
A
2011 /*
2012 * See if the socket has been closed (SS_NOFDREF|SS_CANTRCVMORE)
2013 * and if so just return to the caller. This could happen when
2014 * soreceive() is called by a socket upcall function during the
2015 * time the socket is freed. The socket buffer would have been
2016 * locked across the upcall, therefore we cannot put this thread
2017 * to sleep (else we will deadlock) or return EWOULDBLOCK (else
2018 * we may livelock), because the lock on the socket buffer will
2019 * only be released when the upcall routine returns to its caller.
2020 * Because the socket has been officially closed, there can be
2021 * no further read on it.
2022 */
2023 if ((so->so_state & (SS_NOFDREF | SS_CANTRCVMORE)) ==
2024 (SS_NOFDREF | SS_CANTRCVMORE)) {
2025 socket_unlock(so, 1);
2026 return (0);
2027 }
2028
9bccf70c
A
2029 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
2030 if (error) {
91447636 2031 socket_unlock(so, 1);
2d21ac55
A
2032 KERNEL_DEBUG(DBG_FNC_SORECEIVE | DBG_FUNC_END, error,
2033 0, 0, 0, 0);
1c79356b
A
2034 return (error);
2035 }
1c79356b
A
2036
2037 m = so->so_rcv.sb_mb;
2038 /*
2039 * If we have less data than requested, block awaiting more
2040 * (subject to any timeout) if:
2041 * 1. the current count is less than the low water mark, or
2042 * 2. MSG_WAITALL is set, and it is possible to do the entire
2043 * receive operation at once if we block (resid <= hiwat).
2044 * 3. MSG_DONTWAIT is not set
2045 * If MSG_WAITALL is set but resid is larger than the receive buffer,
2046 * we have to do the receive in sections, and thus risk returning
2047 * a short count if a timeout or signal occurs after we start.
2048 */
2049 if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
91447636 2050 so->so_rcv.sb_cc < uio_resid(uio)) &&
2d21ac55 2051 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
91447636 2052 ((flags & MSG_WAITALL) && uio_resid(uio) <= so->so_rcv.sb_hiwat)) &&
1c79356b 2053 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
2d21ac55
A
2054 /*
2055 * Panic if we notice inconsistencies in the socket's
2056 * receive list; both sb_mb and sb_cc should correctly
2057 * reflect the contents of the list, otherwise we may
2058 * end up with false positives during select() or poll()
2059 * which could put the application in a bad state.
2060 */
2061 if (m == NULL && so->so_rcv.sb_cc != 0)
b0d623f7 2062 panic("soreceive corrupted so_rcv: m %p cc %u",
2d21ac55 2063 m, so->so_rcv.sb_cc);
55e303ae 2064
1c79356b
A
2065 if (so->so_error) {
2066 if (m)
2067 goto dontblock;
2068 error = so->so_error;
2069 if ((flags & MSG_PEEK) == 0)
2070 so->so_error = 0;
2071 goto release;
2072 }
2073 if (so->so_state & SS_CANTRCVMORE) {
2074 if (m)
2075 goto dontblock;
2076 else
2077 goto release;
2078 }
2079 for (; m; m = m->m_next)
2d21ac55 2080 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1c79356b
A
2081 m = so->so_rcv.sb_mb;
2082 goto dontblock;
2083 }
2084 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
2085 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
2086 error = ENOTCONN;
2087 goto release;
2088 }
91447636 2089 if (uio_resid(uio) == 0)
1c79356b 2090 goto release;
2d21ac55
A
2091 if ((so->so_state & SS_NBIO) ||
2092 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1c79356b
A
2093 error = EWOULDBLOCK;
2094 goto release;
2095 }
2d21ac55
A
2096 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 1");
2097 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 1");
91447636 2098 sbunlock(&so->so_rcv, 1);
2d21ac55 2099#if EVEN_MORE_LOCKING_DEBUG
1c79356b 2100 if (socket_debug)
2d21ac55 2101 printf("Waiting for socket data\n");
91447636 2102#endif
55e303ae 2103
1c79356b 2104 error = sbwait(&so->so_rcv);
2d21ac55 2105#if EVEN_MORE_LOCKING_DEBUG
1c79356b 2106 if (socket_debug)
2d21ac55 2107 printf("SORECEIVE - sbwait returned %d\n", error);
91447636
A
2108#endif
2109 if (so->so_usecount < 1)
2d21ac55
A
2110 panic("soreceive: after 2nd sblock so=%p ref=%d on "
2111 "socket\n", so, so->so_usecount);
9bccf70c 2112 if (error) {
91447636 2113 socket_unlock(so, 1);
2d21ac55
A
2114 KERNEL_DEBUG(DBG_FNC_SORECEIVE | DBG_FUNC_END, error,
2115 0, 0, 0, 0);
2116 return (error);
1c79356b
A
2117 }
2118 goto restart;
2119 }
2120dontblock:
b0d623f7 2121 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_msgrcv);
2d21ac55
A
2122 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1");
2123 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1");
1c79356b
A
2124 nextrecord = m->m_nextpkt;
2125 if ((pr->pr_flags & PR_ADDR) && m->m_type == MT_SONAME) {
2126 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
2d21ac55
A
2127#if CONFIG_MACF_SOCKET_SUBSET
2128 /*
2129 * Call the MAC framework for policy checking if we're in
2130 * the user process context and the socket isn't connected.
2131 */
2132 if (p != kernproc && !(so->so_state & SS_ISCONNECTED)) {
2133 struct mbuf *m0 = m;
2134 /*
2135 * Dequeue this record (temporarily) from the receive
2136 * list since we're about to drop the socket's lock
2137 * where a new record may arrive and be appended to
2138 * the list. Upon MAC policy failure, the record
2139 * will be freed. Otherwise, we'll add it back to
2140 * the head of the list. We cannot rely on SB_LOCK
2141 * because append operation uses the socket's lock.
2142 */
2143 do {
2144 m->m_nextpkt = NULL;
2145 sbfree(&so->so_rcv, m);
2146 m = m->m_next;
2147 } while (m != NULL);
2148 m = m0;
2149 so->so_rcv.sb_mb = nextrecord;
2150 SB_EMPTY_FIXUP(&so->so_rcv);
2151 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1a");
2152 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1a");
2153 socket_unlock(so, 0);
2154 if (mac_socket_check_received(proc_ucred(p), so,
2155 mtod(m, struct sockaddr *)) != 0) {
2156 /*
2157 * MAC policy failure; free this record and
2158 * process the next record (or block until
2159 * one is available). We have adjusted sb_cc
2160 * and sb_mbcnt above so there is no need to
2161 * call sbfree() again.
2162 */
2163 do {
2164 m = m_free(m);
2165 } while (m != NULL);
2166 /*
2167 * Clear SB_LOCK but don't unlock the socket.
2168 * Process the next record or wait for one.
2169 */
2170 socket_lock(so, 0);
2171 sbunlock(&so->so_rcv, 1);
2172 goto restart;
2173 }
2174 socket_lock(so, 0);
2175 /*
2176 * Re-adjust the socket receive list and re-enqueue
2177 * the record in front of any packets which may have
2178 * been appended while we dropped the lock.
2179 */
2180 for (m = m0; m->m_next != NULL; m = m->m_next)
2181 sballoc(&so->so_rcv, m);
2182 sballoc(&so->so_rcv, m);
2183 if (so->so_rcv.sb_mb == NULL) {
2184 so->so_rcv.sb_lastrecord = m0;
2185 so->so_rcv.sb_mbtail = m;
2186 }
2187 m = m0;
2188 nextrecord = m->m_nextpkt = so->so_rcv.sb_mb;
2189 so->so_rcv.sb_mb = m;
2190 SBLASTRECORDCHK(&so->so_rcv, "soreceive 1b");
2191 SBLASTMBUFCHK(&so->so_rcv, "soreceive 1b");
2192 }
2193#endif /* CONFIG_MACF_SOCKET_SUBSET */
1c79356b 2194 orig_resid = 0;
4a249263 2195 if (psa) {
1c79356b 2196 *psa = dup_sockaddr(mtod(m, struct sockaddr *),
2d21ac55 2197 mp0 == 0);
4a249263
A
2198 if ((*psa == 0) && (flags & MSG_NEEDSA)) {
2199 error = EWOULDBLOCK;
2200 goto release;
2201 }
2202 }
1c79356b
A
2203 if (flags & MSG_PEEK) {
2204 m = m->m_next;
2205 } else {
2206 sbfree(&so->so_rcv, m);
91447636 2207 if (m->m_next == 0 && so->so_rcv.sb_cc != 0)
2d21ac55
A
2208 panic("soreceive: about to create invalid "
2209 "socketbuf");
1c79356b
A
2210 MFREE(m, so->so_rcv.sb_mb);
2211 m = so->so_rcv.sb_mb;
2d21ac55
A
2212 if (m != NULL) {
2213 m->m_nextpkt = nextrecord;
2214 } else {
2215 so->so_rcv.sb_mb = nextrecord;
2216 SB_EMPTY_FIXUP(&so->so_rcv);
2217 }
1c79356b
A
2218 }
2219 }
2d21ac55
A
2220
2221 /*
2222 * Process one or more MT_CONTROL mbufs present before any data mbufs
2223 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
2224 * just copy the data; if !MSG_PEEK, we call into the protocol to
2225 * perform externalization.
2226 */
2227 if (m != NULL && m->m_type == MT_CONTROL) {
2228 struct mbuf *cm = NULL, *cmn;
2229 struct mbuf **cme = &cm;
2230 struct sockbuf *sb_rcv = &so->so_rcv;
2231
2232 /*
2233 * Externalizing the control messages would require us to
2234 * drop the socket's lock below. Once we re-acquire the
2235 * lock, the mbuf chain might change. In order to preserve
2236 * consistency, we unlink all control messages from the
2237 * first mbuf chain in one shot and link them separately
2238 * onto a different chain.
2239 */
2240 do {
2241 if (flags & MSG_PEEK) {
2242 if (controlp != NULL) {
2243 *controlp = m_copy(m, 0, m->m_len);
2244 controlp = &(*controlp)->m_next;
91447636 2245 }
2d21ac55 2246 m = m->m_next;
1c79356b 2247 } else {
2d21ac55
A
2248 m->m_nextpkt = NULL;
2249 sbfree(sb_rcv, m);
2250 sb_rcv->sb_mb = m->m_next;
2251 m->m_next = NULL;
2252 *cme = m;
2253 cme = &(*cme)->m_next;
2254 m = sb_rcv->sb_mb;
2255 }
2256 } while (m != NULL && m->m_type == MT_CONTROL);
2257
2258 if (!(flags & MSG_PEEK)) {
2259 if (sb_rcv->sb_mb != NULL) {
2260 sb_rcv->sb_mb->m_nextpkt = nextrecord;
2261 } else {
2262 sb_rcv->sb_mb = nextrecord;
2263 SB_EMPTY_FIXUP(sb_rcv);
1c79356b 2264 }
2d21ac55
A
2265 if (nextrecord == NULL)
2266 sb_rcv->sb_lastrecord = m;
1c79356b 2267 }
2d21ac55
A
2268
2269 SBLASTRECORDCHK(&so->so_rcv, "soreceive ctl");
2270 SBLASTMBUFCHK(&so->so_rcv, "soreceive ctl");
2271
2272 while (cm != NULL) {
2273 int cmsg_type;
2274
2275 cmn = cm->m_next;
2276 cm->m_next = NULL;
2277 cmsg_type = mtod(cm, struct cmsghdr *)->cmsg_type;
2278
2279 /*
2280 * Call the protocol to externalize SCM_RIGHTS message
2281 * and return the modified message to the caller upon
2282 * success. Otherwise, all other control messages are
2283 * returned unmodified to the caller. Note that we
2284 * only get into this loop if MSG_PEEK is not set.
2285 */
2286 if (pr->pr_domain->dom_externalize != NULL &&
2287 cmsg_type == SCM_RIGHTS) {
2288 /*
2289 * Release socket lock: see 3903171. This
2290 * would also allow more records to be appended
2291 * to the socket buffer. We still have SB_LOCK
2292 * set on it, so we can be sure that the head
2293 * of the mbuf chain won't change.
2294 */
2295 socket_unlock(so, 0);
2296 error = (*pr->pr_domain->dom_externalize)(cm);
2297 socket_lock(so, 0);
2298 } else {
2299 error = 0;
2300 }
2301
2302 if (controlp != NULL && error == 0) {
2303 *controlp = cm;
2304 controlp = &(*controlp)->m_next;
2305 orig_resid = 0;
2306 } else {
2307 (void) m_free(cm);
2308 }
2309 cm = cmn;
1c79356b 2310 }
2d21ac55
A
2311 orig_resid = 0;
2312 if (sb_rcv->sb_mb != NULL)
2313 nextrecord = sb_rcv->sb_mb->m_nextpkt;
2314 else
2315 nextrecord = NULL;
1c79356b 2316 }
2d21ac55
A
2317
2318 if (m != NULL) {
2319 if (!(flags & MSG_PEEK)) {
2320 /*
2321 * We get here because m points to an mbuf following
2322 * any MT_SONAME or MT_CONTROL mbufs which have been
2323 * processed above. In any case, m should be pointing
2324 * to the head of the mbuf chain, and the nextrecord
2325 * should be either NULL or equal to m->m_nextpkt.
2326 * See comments above about SB_LOCK.
2327 */
2328 if (m != so->so_rcv.sb_mb || m->m_nextpkt != nextrecord)
2329 panic("soreceive: post-control !sync so=%p "
2330 "m=%p nextrecord=%p\n", so, m, nextrecord);
2331
2332 if (nextrecord == NULL)
2333 so->so_rcv.sb_lastrecord = m;
2334 }
1c79356b
A
2335 type = m->m_type;
2336 if (type == MT_OOBDATA)
2337 flags |= MSG_OOB;
2d21ac55
A
2338 } else {
2339 if (!(flags & MSG_PEEK)) {
2340 so->so_rcv.sb_mb = nextrecord;
2341 SB_EMPTY_FIXUP(&so->so_rcv);
2342 }
1c79356b 2343 }
2d21ac55
A
2344 SBLASTRECORDCHK(&so->so_rcv, "soreceive 2");
2345 SBLASTMBUFCHK(&so->so_rcv, "soreceive 2");
2346
1c79356b
A
2347 moff = 0;
2348 offset = 0;
fa4905b1 2349
91447636 2350 if (!(flags & MSG_PEEK) && uio_resid(uio) > sorecvmincopy)
2d21ac55 2351 can_delay = 1;
55e303ae 2352 else
2d21ac55 2353 can_delay = 0;
55e303ae
A
2354
2355 need_event = 0;
fa4905b1 2356
91447636 2357 while (m && (uio_resid(uio) - delayed_copy_len) > 0 && error == 0) {
1c79356b
A
2358 if (m->m_type == MT_OOBDATA) {
2359 if (type != MT_OOBDATA)
2360 break;
2d21ac55 2361 } else if (type == MT_OOBDATA) {
1c79356b 2362 break;
2d21ac55 2363 }
9bccf70c 2364 /*
2d21ac55 2365 * Make sure to allways set MSG_OOB event when getting
9bccf70c
A
2366 * out of band data inline.
2367 */
1c79356b 2368 if ((so->so_options & SO_WANTOOBFLAG) != 0 &&
2d21ac55
A
2369 (so->so_options & SO_OOBINLINE) != 0 &&
2370 (so->so_state & SS_RCVATMARK) != 0) {
9bccf70c
A
2371 flags |= MSG_OOB;
2372 }
1c79356b 2373 so->so_state &= ~SS_RCVATMARK;
91447636 2374 len = uio_resid(uio) - delayed_copy_len;
1c79356b
A
2375 if (so->so_oobmark && len > so->so_oobmark - offset)
2376 len = so->so_oobmark - offset;
2377 if (len > m->m_len - moff)
2378 len = m->m_len - moff;
2379 /*
2380 * If mp is set, just pass back the mbufs.
2381 * Otherwise copy them out via the uio, then free.
2382 * Sockbuf must be consistent here (points to current mbuf,
2383 * it points to next record) when we drop priority;
2384 * we must note any additions to the sockbuf when we
2385 * block interrupts again.
2386 */
2387 if (mp == 0) {
2d21ac55
A
2388 SBLASTRECORDCHK(&so->so_rcv, "soreceive uiomove");
2389 SBLASTMBUFCHK(&so->so_rcv, "soreceive uiomove");
55e303ae 2390 if (can_delay && len == m->m_len) {
2d21ac55 2391 /*
55e303ae
A
2392 * only delay the copy if we're consuming the
2393 * mbuf and we're NOT in MSG_PEEK mode
2394 * and we have enough data to make it worthwile
2d21ac55
A
2395 * to drop and retake the lock... can_delay
2396 * reflects the state of the 2 latter
2397 * constraints moff should always be zero
2398 * in these cases
55e303ae 2399 */
2d21ac55 2400 delayed_copy_len += len;
55e303ae 2401 } else {
2d21ac55
A
2402 if (delayed_copy_len) {
2403 error = sodelayed_copy(so, uio,
2404 &free_list, &delayed_copy_len);
55e303ae
A
2405
2406 if (error) {
55e303ae
A
2407 goto release;
2408 }
2d21ac55
A
2409 /*
2410 * can only get here if MSG_PEEK is not
2411 * set therefore, m should point at the
2412 * head of the rcv queue; if it doesn't,
2413 * it means something drastically
2414 * changed while we were out from behind
2415 * the lock in sodelayed_copy. perhaps
2416 * a RST on the stream. in any event,
2417 * the stream has been interrupted. it's
2418 * probably best just to return whatever
2419 * data we've moved and let the caller
2420 * sort it out...
2421 */
55e303ae 2422 if (m != so->so_rcv.sb_mb) {
2d21ac55 2423 break;
55e303ae
A
2424 }
2425 }
91447636 2426 socket_unlock(so, 0);
2d21ac55
A
2427 error = uiomove(mtod(m, caddr_t) + moff,
2428 (int)len, uio);
91447636 2429 socket_lock(so, 0);
55e303ae 2430
55e303ae 2431 if (error)
2d21ac55 2432 goto release;
55e303ae 2433 }
2d21ac55 2434 } else {
91447636 2435 uio_setresid(uio, (uio_resid(uio) - len));
2d21ac55 2436 }
1c79356b
A
2437 if (len == m->m_len - moff) {
2438 if (m->m_flags & M_EOR)
2439 flags |= MSG_EOR;
2440 if (flags & MSG_PEEK) {
2441 m = m->m_next;
2442 moff = 0;
2443 } else {
2444 nextrecord = m->m_nextpkt;
2445 sbfree(&so->so_rcv, m);
91447636 2446 m->m_nextpkt = NULL;
55e303ae 2447
1c79356b
A
2448 if (mp) {
2449 *mp = m;
2450 mp = &m->m_next;
2451 so->so_rcv.sb_mb = m = m->m_next;
2452 *mp = (struct mbuf *)0;
2453 } else {
55e303ae 2454 if (free_list == NULL)
2d21ac55
A
2455 free_list = m;
2456 else
2457 ml->m_next = m;
2458 ml = m;
14353aa8 2459 so->so_rcv.sb_mb = m = m->m_next;
2d21ac55 2460 ml->m_next = 0;
1c79356b 2461 }
2d21ac55 2462 if (m != NULL) {
1c79356b 2463 m->m_nextpkt = nextrecord;
2d21ac55
A
2464 if (nextrecord == NULL)
2465 so->so_rcv.sb_lastrecord = m;
2466 } else {
2467 so->so_rcv.sb_mb = nextrecord;
2468 SB_EMPTY_FIXUP(&so->so_rcv);
2469 }
2470 SBLASTRECORDCHK(&so->so_rcv, "soreceive 3");
2471 SBLASTMBUFCHK(&so->so_rcv, "soreceive 3");
1c79356b
A
2472 }
2473 } else {
2d21ac55 2474 if (flags & MSG_PEEK) {
1c79356b 2475 moff += len;
2d21ac55 2476 } else {
1c79356b
A
2477 if (mp)
2478 *mp = m_copym(m, 0, len, M_WAIT);
2479 m->m_data += len;
2480 m->m_len -= len;
2481 so->so_rcv.sb_cc -= len;
2482 }
2483 }
2484 if (so->so_oobmark) {
2485 if ((flags & MSG_PEEK) == 0) {
2486 so->so_oobmark -= len;
2487 if (so->so_oobmark == 0) {
2d21ac55
A
2488 so->so_state |= SS_RCVATMARK;
2489 /*
2490 * delay posting the actual event until
2491 * after any delayed copy processing
2492 * has finished
2493 */
2494 need_event = 1;
2495 break;
1c79356b
A
2496 }
2497 } else {
2498 offset += len;
2499 if (offset == so->so_oobmark)
2500 break;
2501 }
2502 }
2d21ac55 2503 if (flags & MSG_EOR)
1c79356b
A
2504 break;
2505 /*
2d21ac55
A
2506 * If the MSG_WAITALL or MSG_WAITSTREAM flag is set
2507 * (for non-atomic socket), we must not quit until
2508 * "uio->uio_resid == 0" or an error termination.
2509 * If a signal/timeout occurs, return with a short
2510 * count but without error. Keep sockbuf locked
2511 * against other readers.
1c79356b 2512 */
2d21ac55
A
2513 while (flags & (MSG_WAITALL|MSG_WAITSTREAM) && m == 0 &&
2514 (uio_resid(uio) - delayed_copy_len) > 0 &&
1c79356b
A
2515 !sosendallatonce(so) && !nextrecord) {
2516 if (so->so_error || so->so_state & SS_CANTRCVMORE)
2d21ac55 2517 goto release;
fa4905b1 2518
2d21ac55
A
2519 /*
2520 * Depending on the protocol (e.g. TCP), the following
2521 * might cause the socket lock to be dropped and later
2522 * be reacquired, and more data could have arrived and
2523 * have been appended to the receive socket buffer by
2524 * the time it returns. Therefore, we only sleep in
2525 * sbwait() below if and only if the socket buffer is
2526 * empty, in order to avoid a false sleep.
2527 */
2528 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb &&
2529 (((struct inpcb *)so->so_pcb)->inp_state !=
2530 INPCB_STATE_DEAD))
2531 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2532
2533 SBLASTRECORDCHK(&so->so_rcv, "soreceive sbwait 2");
2534 SBLASTMBUFCHK(&so->so_rcv, "soreceive sbwait 2");
2535
2536 if (so->so_rcv.sb_mb == NULL && sbwait(&so->so_rcv)) {
2537 error = 0;
55e303ae 2538 goto release;
fa4905b1 2539 }
55e303ae 2540 /*
2d21ac55
A
2541 * have to wait until after we get back from the sbwait
2542 * to do the copy because we will drop the lock if we
2543 * have enough data that has been delayed... by dropping
2544 * the lock we open up a window allowing the netisr
2545 * thread to process the incoming packets and to change
2546 * the state of this socket... we're issuing the sbwait
2547 * because the socket is empty and we're expecting the
2548 * netisr thread to wake us up when more packets arrive;
2549 * if we allow that processing to happen and then sbwait
2550 * we could stall forever with packets sitting in the
2551 * socket if no further packets arrive from the remote
2552 * side.
55e303ae 2553 *
2d21ac55
A
2554 * we want to copy before we've collected all the data
2555 * to satisfy this request to allow the copy to overlap
2556 * the incoming packet processing on an MP system
55e303ae 2557 */
2d21ac55
A
2558 if (delayed_copy_len > sorecvmincopy &&
2559 (delayed_copy_len > (so->so_rcv.sb_hiwat / 2))) {
2560 error = sodelayed_copy(so, uio,
2561 &free_list, &delayed_copy_len);
55e303ae
A
2562
2563 if (error)
2d21ac55 2564 goto release;
1c79356b
A
2565 }
2566 m = so->so_rcv.sb_mb;
fa4905b1 2567 if (m) {
1c79356b 2568 nextrecord = m->m_nextpkt;
fa4905b1 2569 }
1c79356b
A
2570 }
2571 }
91447636
A
2572#ifdef MORE_LOCKING_DEBUG
2573 if (so->so_usecount <= 1)
2d21ac55
A
2574 panic("soreceive: after big while so=%p ref=%d on socket\n",
2575 so, so->so_usecount);
91447636 2576#endif
1c79356b
A
2577
2578 if (m && pr->pr_flags & PR_ATOMIC) {
9bccf70c 2579#ifdef __APPLE__
2d21ac55 2580 if (so->so_options & SO_DONTTRUNC) {
1c79356b 2581 flags |= MSG_RCVMORE;
2d21ac55 2582 } else {
9bccf70c
A
2583#endif
2584 flags |= MSG_TRUNC;
1c79356b
A
2585 if ((flags & MSG_PEEK) == 0)
2586 (void) sbdroprecord(&so->so_rcv);
9bccf70c 2587#ifdef __APPLE__
1c79356b 2588 }
9bccf70c 2589#endif
1c79356b 2590 }
2d21ac55
A
2591
2592 /*
2593 * pru_rcvd below (for TCP) may cause more data to be received
2594 * if the socket lock is dropped prior to sending the ACK; some
2595 * legacy OpenTransport applications don't handle this well
2596 * (if it receives less data than requested while MSG_HAVEMORE
2597 * is set), and so we set the flag now based on what we know
2598 * prior to calling pru_rcvd.
2599 */
2600 if ((so->so_options & SO_WANTMORE) && so->so_rcv.sb_cc > 0)
2601 flags |= MSG_HAVEMORE;
2602
1c79356b 2603 if ((flags & MSG_PEEK) == 0) {
2d21ac55 2604 if (m == 0) {
1c79356b 2605 so->so_rcv.sb_mb = nextrecord;
2d21ac55
A
2606 /*
2607 * First part is an inline SB_EMPTY_FIXUP(). Second
2608 * part makes sure sb_lastrecord is up-to-date if
2609 * there is still data in the socket buffer.
2610 */
2611 if (so->so_rcv.sb_mb == NULL) {
2612 so->so_rcv.sb_mbtail = NULL;
2613 so->so_rcv.sb_lastrecord = NULL;
2614 } else if (nextrecord->m_nextpkt == NULL) {
2615 so->so_rcv.sb_lastrecord = nextrecord;
2616 }
2617 }
2618 SBLASTRECORDCHK(&so->so_rcv, "soreceive 4");
2619 SBLASTMBUFCHK(&so->so_rcv, "soreceive 4");
1c79356b
A
2620 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
2621 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2622 }
9bccf70c 2623#ifdef __APPLE__
55e303ae 2624 if (delayed_copy_len) {
91447636 2625 error = sodelayed_copy(so, uio, &free_list, &delayed_copy_len);
55e303ae
A
2626
2627 if (error)
2d21ac55 2628 goto release;
55e303ae
A
2629 }
2630 if (free_list) {
2d21ac55 2631 m_freem_list((struct mbuf *)free_list);
55e303ae
A
2632 free_list = (struct mbuf *)0;
2633 }
2634 if (need_event)
2d21ac55 2635 postevent(so, 0, EV_OOB);
9bccf70c 2636#endif
91447636 2637 if (orig_resid == uio_resid(uio) && orig_resid &&
1c79356b 2638 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
91447636 2639 sbunlock(&so->so_rcv, 1);
1c79356b
A
2640 goto restart;
2641 }
2642
2643 if (flagsp)
2644 *flagsp |= flags;
2645release:
91447636
A
2646#ifdef MORE_LOCKING_DEBUG
2647 if (so->so_usecount <= 1)
2d21ac55
A
2648 panic("soreceive: release so=%p ref=%d on socket\n",
2649 so, so->so_usecount);
91447636 2650#endif
55e303ae 2651 if (delayed_copy_len) {
2d21ac55 2652 error = sodelayed_copy(so, uio, &free_list, &delayed_copy_len);
55e303ae
A
2653 }
2654 if (free_list) {
2d21ac55 2655 m_freem_list((struct mbuf *)free_list);
55e303ae 2656 }
91447636 2657 sbunlock(&so->so_rcv, 0); /* will unlock socket */
1c79356b 2658
2d21ac55
A
2659 // LP64todo - fix this!
2660 KERNEL_DEBUG(DBG_FNC_SORECEIVE | DBG_FUNC_END, so, uio_resid(uio),
2661 so->so_rcv.sb_cc, 0, error);
1c79356b
A
2662
2663 return (error);
2664}
2665
2d21ac55
A
2666/*
2667 * Returns: 0 Success
2668 * uiomove:EFAULT
2669 */
2670static int
2671sodelayed_copy(struct socket *so, struct uio *uio, struct mbuf **free_list,
2672 int *resid)
55e303ae 2673{
2d21ac55 2674 int error = 0;
55e303ae
A
2675 struct mbuf *m;
2676
2677 m = *free_list;
2678
91447636 2679 socket_unlock(so, 0);
55e303ae 2680
2d21ac55
A
2681 while (m && error == 0) {
2682
2683 error = uiomove(mtod(m, caddr_t), (int)m->m_len, uio);
2684
2685 m = m->m_next;
2686 }
2687 m_freem_list(*free_list);
2688
2689 *free_list = (struct mbuf *)NULL;
2690 *resid = 0;
2691
2692 socket_lock(so, 0);
55e303ae 2693
2d21ac55
A
2694 return (error);
2695}
2696
2697
2698/*
2699 * Returns: 0 Success
2700 * EINVAL
2701 * ENOTCONN
2702 * <pru_shutdown>:EINVAL
2703 * <pru_shutdown>:EADDRNOTAVAIL[TCP]
2704 * <pru_shutdown>:ENOBUFS[TCP]
2705 * <pru_shutdown>:EMSGSIZE[TCP]
2706 * <pru_shutdown>:EHOSTUNREACH[TCP]
2707 * <pru_shutdown>:ENETUNREACH[TCP]
2708 * <pru_shutdown>:ENETDOWN[TCP]
2709 * <pru_shutdown>:ENOMEM[TCP]
2710 * <pru_shutdown>:EACCES[TCP]
2711 * <pru_shutdown>:EMSGSIZE[TCP]
2712 * <pru_shutdown>:ENOBUFS[TCP]
2713 * <pru_shutdown>:???[TCP] [ignorable: mostly IPSEC/firewall/DLIL]
2714 * <pru_shutdown>:??? [other protocol families]
2715 */
2716int
2717soshutdown(struct socket *so, int how)
2718{
2719 int error;
55e303ae 2720
2d21ac55
A
2721 switch (how) {
2722 case SHUT_RD:
2723 case SHUT_WR:
2724 case SHUT_RDWR:
2725 socket_lock(so, 1);
2726 if ((so->so_state &
2727 (SS_ISCONNECTED|SS_ISCONNECTING|SS_ISDISCONNECTING)) == 0) {
2728 error = ENOTCONN;
2729 } else {
2730 error = soshutdownlock(so, how);
2731 }
2732 socket_unlock(so, 1);
2733 break;
2734 default:
2735 error = EINVAL;
2736 break;
55e303ae 2737 }
55e303ae
A
2738
2739 return (error);
2740}
2741
1c79356b 2742int
2d21ac55 2743soshutdownlock(struct socket *so, int how)
1c79356b 2744{
2d21ac55
A
2745 struct protosw *pr = so->so_proto;
2746 int error = 0;
1c79356b 2747
91447636 2748 sflt_notify(so, sock_evt_shutdown, &how);
1c79356b 2749
9bccf70c 2750 if (how != SHUT_WR) {
2d21ac55
A
2751 if ((so->so_state & SS_CANTRCVMORE) != 0) {
2752 /* read already shut down */
2753 error = ENOTCONN;
2754 goto done;
2755 }
1c79356b
A
2756 sorflush(so);
2757 postevent(so, 0, EV_RCLOSED);
2758 }
9bccf70c 2759 if (how != SHUT_RD) {
2d21ac55
A
2760 if ((so->so_state & SS_CANTSENDMORE) != 0) {
2761 /* write already shut down */
2762 error = ENOTCONN;
2763 goto done;
2764 }
2765 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2766 postevent(so, 0, EV_WCLOSED);
1c79356b 2767 }
2d21ac55
A
2768done:
2769 KERNEL_DEBUG(DBG_FNC_SOSHUTDOWN | DBG_FUNC_END, 0, 0, 0, 0, 0);
2770 return (error);
1c79356b
A
2771}
2772
2773void
2d21ac55 2774sorflush(struct socket *so)
1c79356b
A
2775{
2776 register struct sockbuf *sb = &so->so_rcv;
2777 register struct protosw *pr = so->so_proto;
1c79356b 2778 struct sockbuf asb;
1c79356b 2779
91447636 2780#ifdef MORE_LOCKING_DEBUG
2d21ac55 2781 lck_mtx_t *mutex_held;
91447636 2782
2d21ac55 2783 if (so->so_proto->pr_getlock != NULL)
91447636 2784 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
2d21ac55 2785 else
91447636
A
2786 mutex_held = so->so_proto->pr_domain->dom_mtx;
2787 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
2788#endif
2789
2790 sflt_notify(so, sock_evt_flush_read, NULL);
1c79356b
A
2791
2792 sb->sb_flags |= SB_NOINTR;
2793 (void) sblock(sb, M_WAIT);
1c79356b 2794 socantrcvmore(so);
91447636 2795 sbunlock(sb, 1);
9bccf70c 2796#ifdef __APPLE__
0b4e3aa0 2797 selthreadclear(&sb->sb_sel);
9bccf70c 2798#endif
1c79356b
A
2799 asb = *sb;
2800 bzero((caddr_t)sb, sizeof (*sb));
91447636 2801 sb->sb_so = so; /* reestablish link to socket */
9bccf70c
A
2802 if (asb.sb_flags & SB_KNOTE) {
2803 sb->sb_sel.si_note = asb.sb_sel.si_note;
2804 sb->sb_flags = SB_KNOTE;
2805 }
2d21ac55
A
2806 if (asb.sb_flags & SB_DROP)
2807 sb->sb_flags |= SB_DROP;
2808 if (asb.sb_flags & SB_UNIX)
2809 sb->sb_flags |= SB_UNIX;
2810 if ((pr->pr_flags & PR_RIGHTS) && pr->pr_domain->dom_dispose) {
1c79356b 2811 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2d21ac55 2812 }
1c79356b
A
2813 sbrelease(&asb);
2814}
2815
2816/*
2817 * Perhaps this routine, and sooptcopyout(), below, ought to come in
2818 * an additional variant to handle the case where the option value needs
2819 * to be some kind of integer, but not a specific size.
2820 * In addition to their use here, these functions are also called by the
2821 * protocol-level pr_ctloutput() routines.
2d21ac55
A
2822 *
2823 * Returns: 0 Success
2824 * EINVAL
2825 * copyin:EFAULT
1c79356b
A
2826 */
2827int
2d21ac55 2828sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1c79356b
A
2829{
2830 size_t valsize;
2831
2832 /*
2833 * If the user gives us more than we wanted, we ignore it,
2834 * but if we don't get the minimum length the caller
2835 * wants, we return EINVAL. On success, sopt->sopt_valsize
2836 * is set to however much we actually retrieved.
2837 */
2838 if ((valsize = sopt->sopt_valsize) < minlen)
2d21ac55 2839 return (EINVAL);
1c79356b
A
2840 if (valsize > len)
2841 sopt->sopt_valsize = valsize = len;
2842
b0d623f7 2843 if (sopt->sopt_p != kernproc)
1c79356b
A
2844 return (copyin(sopt->sopt_val, buf, valsize));
2845
91447636 2846 bcopy(CAST_DOWN(caddr_t, sopt->sopt_val), buf, valsize);
2d21ac55
A
2847 return (0);
2848}
2849
2850/*
2851 * sooptcopyin_timeval
2852 * Copy in a timeval value into tv_p, and take into account whether the
2853 * the calling process is 64-bit or 32-bit. Moved the sanity checking
2854 * code here so that we can verify the 64-bit tv_sec value before we lose
2855 * the top 32-bits assigning tv64.tv_sec to tv_p->tv_sec.
2856 */
2857static int
2858sooptcopyin_timeval(struct sockopt *sopt, struct timeval * tv_p)
2859{
2860 int error;
b0d623f7 2861
2d21ac55 2862 if (proc_is64bit(sopt->sopt_p)) {
b0d623f7 2863 struct user64_timeval tv64;
2d21ac55
A
2864
2865 if (sopt->sopt_valsize < sizeof(tv64)) {
2866 return (EINVAL);
2867 }
2868 sopt->sopt_valsize = sizeof(tv64);
b0d623f7
A
2869 if (sopt->sopt_p != kernproc) {
2870 error = copyin(sopt->sopt_val, &tv64, sizeof(tv64));
2871 if (error != 0)
2872 return (error);
2873 } else {
2874 bcopy(CAST_DOWN(caddr_t, sopt->sopt_val), &tv64,
2875 sizeof(tv64));
2d21ac55
A
2876 }
2877 if (tv64.tv_sec < 0 || tv64.tv_sec > LONG_MAX
2878 || tv64.tv_usec < 0 || tv64.tv_usec >= 1000000) {
2879 return (EDOM);
2880 }
2881 tv_p->tv_sec = tv64.tv_sec;
2882 tv_p->tv_usec = tv64.tv_usec;
2883 } else {
b0d623f7
A
2884 struct user32_timeval tv32;
2885
2886 if (sopt->sopt_valsize < sizeof(tv32)) {
2d21ac55
A
2887 return (EINVAL);
2888 }
b0d623f7
A
2889 sopt->sopt_valsize = sizeof(tv32);
2890 if (sopt->sopt_p != kernproc) {
2891 error = copyin(sopt->sopt_val, &tv32, sizeof(tv32));
2d21ac55
A
2892 if (error != 0) {
2893 return (error);
2894 }
2895 } else {
b0d623f7
A
2896 bcopy(CAST_DOWN(caddr_t, sopt->sopt_val), &tv32,
2897 sizeof(tv32));
2d21ac55 2898 }
b0d623f7
A
2899#ifndef __LP64__ // K64todo "comparison is always false due to limited range of data type"
2900 if (tv32.tv_sec < 0 || tv32.tv_sec > LONG_MAX
2901 || tv32.tv_usec < 0 || tv32.tv_usec >= 1000000) {
2d21ac55
A
2902 return (EDOM);
2903 }
b0d623f7
A
2904#endif
2905 tv_p->tv_sec = tv32.tv_sec;
2906 tv_p->tv_usec = tv32.tv_usec;
2d21ac55
A
2907 }
2908 return (0);
1c79356b
A
2909}
2910
2d21ac55
A
2911/*
2912 * Returns: 0 Success
2913 * EINVAL
2914 * ENOPROTOOPT
2915 * ENOBUFS
2916 * EDOM
2917 * sooptcopyin:EINVAL
2918 * sooptcopyin:EFAULT
2919 * sooptcopyin_timeval:EINVAL
2920 * sooptcopyin_timeval:EFAULT
2921 * sooptcopyin_timeval:EDOM
2922 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
2923 * <pr_ctloutput>:???w
2924 * sflt_attach_private:??? [whatever a filter author chooses]
2925 * <sf_setoption>:??? [whatever a filter author chooses]
2926 *
2927 * Notes: Other <pru_listen> returns depend on the protocol family; all
2928 * <sf_listen> returns depend on what the filter author causes
2929 * their filter to return.
2930 */
1c79356b 2931int
2d21ac55 2932sosetopt(struct socket *so, struct sockopt *sopt)
1c79356b
A
2933{
2934 int error, optval;
2935 struct linger l;
2936 struct timeval tv;
2d21ac55
A
2937 struct socket_filter_entry *filter;
2938 int filtered = 0;
2939#if CONFIG_MACF_SOCKET
2940 struct mac extmac;
2941#endif /* MAC_SOCKET */
91447636
A
2942
2943 socket_lock(so, 1);
2d21ac55 2944 if ((so->so_state & (SS_CANTRCVMORE | SS_CANTSENDMORE))
b0d623f7
A
2945 == (SS_CANTRCVMORE | SS_CANTSENDMORE) &&
2946 (so->so_flags & SOF_NPX_SETOPTSHUT) == 0) {
2d21ac55
A
2947 /* the socket has been shutdown, no more sockopt's */
2948 error = EINVAL;
2949 goto bad;
2950 }
1c79356b 2951
9bccf70c
A
2952 if (sopt->sopt_dir != SOPT_SET) {
2953 sopt->sopt_dir = SOPT_SET;
2954 }
2955
2d21ac55
A
2956 error = 0;
2957 for (filter = so->so_filt; filter && (error == 0);
2958 filter = filter->sfe_next_onsocket) {
2959 if (filter->sfe_filter->sf_filter.sf_setoption) {
2960 if (filtered == 0) {
2961 filtered = 1;
2962 sflt_use(so);
2963 socket_unlock(so, 0);
91447636 2964 }
2d21ac55
A
2965 error = filter->sfe_filter->sf_filter.
2966 sf_setoption(filter->sfe_cookie, so, sopt);
91447636 2967 }
2d21ac55
A
2968 }
2969
2970 if (filtered != 0) {
2971 socket_lock(so, 0);
2972 sflt_unuse(so);
2973
2974 if (error) {
2975 if (error == EJUSTRETURN)
2976 error = 0;
2977 goto bad;
1c79356b 2978 }
1c79356b
A
2979 }
2980
2981 error = 0;
2982 if (sopt->sopt_level != SOL_SOCKET) {
91447636 2983 if (so->so_proto && so->so_proto->pr_ctloutput) {
2d21ac55 2984 error = (*so->so_proto->pr_ctloutput)(so, sopt);
91447636
A
2985 socket_unlock(so, 1);
2986 return (error);
2987 }
1c79356b
A
2988 error = ENOPROTOOPT;
2989 } else {
2990 switch (sopt->sopt_name) {
2991 case SO_LINGER:
91447636 2992 case SO_LINGER_SEC:
2d21ac55 2993 error = sooptcopyin(sopt, &l, sizeof (l), sizeof (l));
1c79356b
A
2994 if (error)
2995 goto bad;
2996
2d21ac55
A
2997 so->so_linger = (sopt->sopt_name == SO_LINGER) ?
2998 l.l_linger : l.l_linger * hz;
1c79356b
A
2999 if (l.l_onoff)
3000 so->so_options |= SO_LINGER;
3001 else
3002 so->so_options &= ~SO_LINGER;
3003 break;
3004
3005 case SO_DEBUG:
3006 case SO_KEEPALIVE:
3007 case SO_DONTROUTE:
3008 case SO_USELOOPBACK:
3009 case SO_BROADCAST:
3010 case SO_REUSEADDR:
3011 case SO_REUSEPORT:
3012 case SO_OOBINLINE:
3013 case SO_TIMESTAMP:
9bccf70c 3014#ifdef __APPLE__
1c79356b
A
3015 case SO_DONTTRUNC:
3016 case SO_WANTMORE:
9bccf70c
A
3017 case SO_WANTOOBFLAG:
3018#endif
2d21ac55
A
3019 error = sooptcopyin(sopt, &optval, sizeof (optval),
3020 sizeof (optval));
1c79356b
A
3021 if (error)
3022 goto bad;
3023 if (optval)
3024 so->so_options |= sopt->sopt_name;
3025 else
3026 so->so_options &= ~sopt->sopt_name;
3027 break;
3028
3029 case SO_SNDBUF:
3030 case SO_RCVBUF:
3031 case SO_SNDLOWAT:
3032 case SO_RCVLOWAT:
2d21ac55
A
3033 error = sooptcopyin(sopt, &optval, sizeof (optval),
3034 sizeof (optval));
1c79356b
A
3035 if (error)
3036 goto bad;
3037
3038 /*
3039 * Values < 1 make no sense for any of these
3040 * options, so disallow them.
3041 */
3042 if (optval < 1) {
3043 error = EINVAL;
3044 goto bad;
3045 }
3046
3047 switch (sopt->sopt_name) {
3048 case SO_SNDBUF:
3049 case SO_RCVBUF:
3050 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2d21ac55 3051 &so->so_snd : &so->so_rcv,
b0d623f7 3052 (u_int32_t) optval) == 0) {
1c79356b
A
3053 error = ENOBUFS;
3054 goto bad;
3055 }
2d21ac55
A
3056 if (sopt->sopt_name == SO_SNDBUF)
3057 so->so_snd.sb_flags |= SB_USRSIZE;
3058 else
3059 so->so_rcv.sb_flags |= SB_USRSIZE;
1c79356b
A
3060 break;
3061
3062 /*
3063 * Make sure the low-water is never greater than
3064 * the high-water.
3065 */
3066 case SO_SNDLOWAT:
3067 so->so_snd.sb_lowat =
3068 (optval > so->so_snd.sb_hiwat) ?
3069 so->so_snd.sb_hiwat : optval;
3070 break;
3071 case SO_RCVLOWAT:
3072 so->so_rcv.sb_lowat =
3073 (optval > so->so_rcv.sb_hiwat) ?
3074 so->so_rcv.sb_hiwat : optval;
3075 break;
3076 }
3077 break;
3078
3079 case SO_SNDTIMEO:
3080 case SO_RCVTIMEO:
2d21ac55 3081 error = sooptcopyin_timeval(sopt, &tv);
1c79356b
A
3082 if (error)
3083 goto bad;
3084
1c79356b
A
3085 switch (sopt->sopt_name) {
3086 case SO_SNDTIMEO:
91447636 3087 so->so_snd.sb_timeo = tv;
1c79356b
A
3088 break;
3089 case SO_RCVTIMEO:
91447636 3090 so->so_rcv.sb_timeo = tv;
1c79356b
A
3091 break;
3092 }
3093 break;
3094
3095 case SO_NKE:
9bccf70c
A
3096 {
3097 struct so_nke nke;
1c79356b 3098
2d21ac55
A
3099 error = sooptcopyin(sopt, &nke, sizeof (nke),
3100 sizeof (nke));
1c79356b 3101 if (error)
2d21ac55 3102 goto bad;
1c79356b 3103
2d21ac55
A
3104 error = sflt_attach_private(so, NULL,
3105 nke.nke_handle, 1);
1c79356b
A
3106 break;
3107 }
3108
9bccf70c 3109 case SO_NOSIGPIPE:
2d21ac55
A
3110 error = sooptcopyin(sopt, &optval, sizeof (optval),
3111 sizeof (optval));
3112 if (error)
3113 goto bad;
3114 if (optval)
3115 so->so_flags |= SOF_NOSIGPIPE;
3116 else
3117 so->so_flags &= ~SOF_NOSIGPIPE;
3118
9bccf70c
A
3119 break;
3120
55e303ae 3121 case SO_NOADDRERR:
2d21ac55
A
3122 error = sooptcopyin(sopt, &optval, sizeof (optval),
3123 sizeof (optval));
3124 if (error)
3125 goto bad;
3126 if (optval)
3127 so->so_flags |= SOF_NOADDRAVAIL;
3128 else
3129 so->so_flags &= ~SOF_NOADDRAVAIL;
3130
3131 break;
3132
3133 case SO_REUSESHAREUID:
3134 error = sooptcopyin(sopt, &optval, sizeof (optval),
3135 sizeof (optval));
3136 if (error)
3137 goto bad;
3138 if (optval)
3139 so->so_flags |= SOF_REUSESHAREUID;
3140 else
3141 so->so_flags &= ~SOF_REUSESHAREUID;
3142 break;
3143#ifdef __APPLE_API_PRIVATE
3144 case SO_NOTIFYCONFLICT:
3145 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
3146 error = EPERM;
3147 goto bad;
3148 }
3149 error = sooptcopyin(sopt, &optval, sizeof (optval),
3150 sizeof (optval));
3151 if (error)
3152 goto bad;
3153 if (optval)
3154 so->so_flags |= SOF_NOTIFYCONFLICT;
3155 else
3156 so->so_flags &= ~SOF_NOTIFYCONFLICT;
3157 break;
3158#endif
3159 case SO_RESTRICTIONS:
3160 if (kauth_cred_issuser(kauth_cred_get()) == 0) {
3161 error = EPERM;
3162 goto bad;
3163 }
3164 error = sooptcopyin(sopt, &optval, sizeof (optval),
3165 sizeof (optval));
3166 if (error)
3167 goto bad;
3168 so->so_restrictions = (optval & (SO_RESTRICT_DENYIN |
3169 SO_RESTRICT_DENYOUT | SO_RESTRICT_DENYSET));
3170 break;
3171
3172 case SO_LABEL:
3173#if CONFIG_MACF_SOCKET
3174 if ((error = sooptcopyin(sopt, &extmac, sizeof (extmac),
3175 sizeof (extmac))) != 0)
3176 goto bad;
3177
3178 error = mac_setsockopt_label(proc_ucred(sopt->sopt_p),
3179 so, &extmac);
3180#else
3181 error = EOPNOTSUPP;
3182#endif /* MAC_SOCKET */
55e303ae
A
3183 break;
3184
4a3eedf9
A
3185#ifdef __APPLE_API_PRIVATE
3186 case SO_UPCALLCLOSEWAIT:
3187 error = sooptcopyin(sopt, &optval, sizeof (optval),
3188 sizeof (optval));
3189 if (error)
3190 goto bad;
3191 if (optval)
3192 so->so_flags |= SOF_UPCALLCLOSEWAIT;
3193 else
3194 so->so_flags &= ~SOF_UPCALLCLOSEWAIT;
3195 break;
3196#endif
3197
b0d623f7
A
3198 case SO_RANDOMPORT:
3199 error = sooptcopyin(sopt, &optval, sizeof (optval),
3200 sizeof (optval));
3201 if (error)
3202 goto bad;
3203 if (optval)
3204 so->so_flags |= SOF_BINDRANDOMPORT;
3205 else
3206 so->so_flags &= ~SOF_BINDRANDOMPORT;
3207 break;
3208
3209 case SO_NP_EXTENSIONS: {
3210 struct so_np_extensions sonpx;
3211
3212 error = sooptcopyin(sopt, &sonpx, sizeof(sonpx), sizeof(sonpx));
3213 if (error)
3214 goto bad;
3215 if (sonpx.npx_mask & ~SONPX_MASK_VALID) {
3216 error = EINVAL;
3217 goto bad;
3218 }
3219 /*
3220 * Only one bit defined for now
3221 */
3222 if ((sonpx.npx_mask & SONPX_SETOPTSHUT)) {
3223 if ((sonpx.npx_flags & SONPX_SETOPTSHUT))
3224 so->so_flags |= SOF_NPX_SETOPTSHUT;
3225 else
3226 so->so_flags &= ~SOF_NPX_SETOPTSHUT;
3227 }
3228 break;
3229 }
3230
1c79356b
A
3231 default:
3232 error = ENOPROTOOPT;
3233 break;
3234 }
3235 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
2d21ac55 3236 (void) ((*so->so_proto->pr_ctloutput)(so, sopt));
1c79356b
A
3237 }
3238 }
3239bad:
91447636 3240 socket_unlock(so, 1);
1c79356b
A
3241 return (error);
3242}
3243
2d21ac55 3244/* Helper routines for getsockopt */
1c79356b 3245int
2d21ac55 3246sooptcopyout(struct sockopt *sopt, void *buf, size_t len)
1c79356b
A
3247{
3248 int error;
3249 size_t valsize;
3250
3251 error = 0;
3252
3253 /*
3254 * Documented get behavior is that we always return a value,
3255 * possibly truncated to fit in the user's buffer.
3256 * Traditional behavior is that we always tell the user
3257 * precisely how much we copied, rather than something useful
3258 * like the total amount we had available for her.
3259 * Note that this interface is not idempotent; the entire answer must
3260 * generated ahead of time.
3261 */
3262 valsize = min(len, sopt->sopt_valsize);
3263 sopt->sopt_valsize = valsize;
91447636 3264 if (sopt->sopt_val != USER_ADDR_NULL) {
b0d623f7 3265 if (sopt->sopt_p != kernproc)
1c79356b
A
3266 error = copyout(buf, sopt->sopt_val, valsize);
3267 else
91447636 3268 bcopy(buf, CAST_DOWN(caddr_t, sopt->sopt_val), valsize);
1c79356b 3269 }
2d21ac55
A
3270 return (error);
3271}
3272
3273static int
3274sooptcopyout_timeval(struct sockopt *sopt, const struct timeval * tv_p)
3275{
3276 int error;
3277 size_t len;
b0d623f7
A
3278 struct user64_timeval tv64;
3279 struct user32_timeval tv32;
2d21ac55
A
3280 const void * val;
3281 size_t valsize;
b0d623f7 3282
2d21ac55
A
3283 error = 0;
3284 if (proc_is64bit(sopt->sopt_p)) {
b0d623f7 3285 len = sizeof(tv64);
2d21ac55
A
3286 tv64.tv_sec = tv_p->tv_sec;
3287 tv64.tv_usec = tv_p->tv_usec;
3288 val = &tv64;
3289 } else {
b0d623f7
A
3290 len = sizeof(tv32);
3291 tv32.tv_sec = tv_p->tv_sec;
3292 tv32.tv_usec = tv_p->tv_usec;
3293 val = &tv32;
2d21ac55
A
3294 }
3295 valsize = min(len, sopt->sopt_valsize);
3296 sopt->sopt_valsize = valsize;
3297 if (sopt->sopt_val != USER_ADDR_NULL) {
b0d623f7 3298 if (sopt->sopt_p != kernproc)
2d21ac55
A
3299 error = copyout(val, sopt->sopt_val, valsize);
3300 else
3301 bcopy(val, CAST_DOWN(caddr_t, sopt->sopt_val), valsize);
3302 }
3303 return (error);
1c79356b
A
3304}
3305
2d21ac55
A
3306/*
3307 * Return: 0 Success
3308 * ENOPROTOOPT
3309 * <pr_ctloutput>:EOPNOTSUPP[AF_UNIX]
3310 * <pr_ctloutput>:???
3311 * <sf_getoption>:???
3312 */
1c79356b 3313int
2d21ac55 3314sogetopt(struct socket *so, struct sockopt *sopt)
1c79356b
A
3315{
3316 int error, optval;
3317 struct linger l;
3318 struct timeval tv;
2d21ac55
A
3319 struct socket_filter_entry *filter;
3320 int filtered = 0;
3321#if CONFIG_MACF_SOCKET
3322 struct mac extmac;
3323#endif /* MAC_SOCKET */
1c79356b 3324
2d21ac55
A
3325 if (sopt->sopt_dir != SOPT_GET) {
3326 sopt->sopt_dir = SOPT_GET;
3327 }
9bccf70c 3328
91447636 3329 socket_lock(so, 1);
2d21ac55
A
3330
3331 error = 0;
3332 for (filter = so->so_filt; filter && (error == 0);
3333 filter = filter->sfe_next_onsocket) {
3334 if (filter->sfe_filter->sf_filter.sf_getoption) {
3335 if (filtered == 0) {
3336 filtered = 1;
3337 sflt_use(so);
3338 socket_unlock(so, 0);
91447636 3339 }
2d21ac55
A
3340 error = filter->sfe_filter->sf_filter.
3341 sf_getoption(filter->sfe_cookie, so, sopt);
91447636 3342 }
2d21ac55
A
3343 }
3344 if (filtered != 0) {
3345 socket_lock(so, 0);
3346 sflt_unuse(so);
3347
3348 if (error) {
3349 if (error == EJUSTRETURN)
3350 error = 0;
3351 socket_unlock(so, 1);
3352 return (error);
1c79356b 3353 }
1c79356b
A
3354 }
3355
3356 error = 0;
3357 if (sopt->sopt_level != SOL_SOCKET) {
3358 if (so->so_proto && so->so_proto->pr_ctloutput) {
2d21ac55 3359 error = (*so->so_proto->pr_ctloutput)(so, sopt);
91447636
A
3360 socket_unlock(so, 1);
3361 return (error);
3362 } else {
3363 socket_unlock(so, 1);
1c79356b 3364 return (ENOPROTOOPT);
91447636 3365 }
1c79356b
A
3366 } else {
3367 switch (sopt->sopt_name) {
3368 case SO_LINGER:
91447636 3369 case SO_LINGER_SEC:
1c79356b 3370 l.l_onoff = so->so_options & SO_LINGER;
2d21ac55
A
3371 l.l_linger = (sopt->sopt_name == SO_LINGER) ?
3372 so->so_linger : so->so_linger / hz;
3373 error = sooptcopyout(sopt, &l, sizeof (l));
1c79356b
A
3374 break;
3375
3376 case SO_USELOOPBACK:
3377 case SO_DONTROUTE:
3378 case SO_DEBUG:
3379 case SO_KEEPALIVE:
3380 case SO_REUSEADDR:
3381 case SO_REUSEPORT:
3382 case SO_BROADCAST:
3383 case SO_OOBINLINE:
3384 case SO_TIMESTAMP:
9bccf70c 3385#ifdef __APPLE__
1c79356b
A
3386 case SO_DONTTRUNC:
3387 case SO_WANTMORE:
9bccf70c
A
3388 case SO_WANTOOBFLAG:
3389#endif
1c79356b
A
3390 optval = so->so_options & sopt->sopt_name;
3391integer:
2d21ac55 3392 error = sooptcopyout(sopt, &optval, sizeof (optval));
1c79356b
A
3393 break;
3394
3395 case SO_TYPE:
3396 optval = so->so_type;
3397 goto integer;
3398
9bccf70c 3399#ifdef __APPLE__
1c79356b 3400 case SO_NREAD:
2d21ac55
A
3401 if (so->so_proto->pr_flags & PR_ATOMIC) {
3402 int pkt_total;
3403 struct mbuf *m1;
1c79356b 3404
2d21ac55
A
3405 pkt_total = 0;
3406 m1 = so->so_rcv.sb_mb;
9bccf70c 3407 while (m1) {
2d21ac55
A
3408 if (m1->m_type == MT_DATA || m1->m_type == MT_HEADER ||
3409 m1->m_type == MT_OOBDATA)
1c79356b 3410 pkt_total += m1->m_len;
1c79356b
A
3411 m1 = m1->m_next;
3412 }
3413 optval = pkt_total;
2d21ac55
A
3414 } else {
3415 optval = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
3416 }
1c79356b 3417 goto integer;
2d21ac55 3418
91447636
A
3419 case SO_NWRITE:
3420 optval = so->so_snd.sb_cc;
2d21ac55 3421 goto integer;
9bccf70c 3422#endif
1c79356b
A
3423 case SO_ERROR:
3424 optval = so->so_error;
3425 so->so_error = 0;
3426 goto integer;
3427
3428 case SO_SNDBUF:
3429 optval = so->so_snd.sb_hiwat;
3430 goto integer;
3431
3432 case SO_RCVBUF:
3433 optval = so->so_rcv.sb_hiwat;
3434 goto integer;
3435
3436 case SO_SNDLOWAT:
3437 optval = so->so_snd.sb_lowat;
3438 goto integer;
3439
3440 case SO_RCVLOWAT:
3441 optval = so->so_rcv.sb_lowat;
3442 goto integer;
3443
3444 case SO_SNDTIMEO:
3445 case SO_RCVTIMEO:
91447636 3446 tv = (sopt->sopt_name == SO_SNDTIMEO ?
2d21ac55 3447 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1c79356b 3448
2d21ac55
A
3449 error = sooptcopyout_timeval(sopt, &tv);
3450 break;
1c79356b 3451
91447636
A
3452 case SO_NOSIGPIPE:
3453 optval = (so->so_flags & SOF_NOSIGPIPE);
3454 goto integer;
9bccf70c 3455
55e303ae 3456 case SO_NOADDRERR:
91447636
A
3457 optval = (so->so_flags & SOF_NOADDRAVAIL);
3458 goto integer;
55e303ae 3459
2d21ac55
A
3460 case SO_REUSESHAREUID:
3461 optval = (so->so_flags & SOF_REUSESHAREUID);
3462 goto integer;
3463
3464#ifdef __APPLE_API_PRIVATE
3465 case SO_NOTIFYCONFLICT:
3466 optval = (so->so_flags & SOF_NOTIFYCONFLICT);
3467 goto integer;
3468#endif
3469 case SO_RESTRICTIONS:
3470 optval = so->so_restrictions & (SO_RESTRICT_DENYIN |
3471 SO_RESTRICT_DENYOUT | SO_RESTRICT_DENYSET);
3472 goto integer;
3473
3474 case SO_LABEL:
3475#if CONFIG_MACF_SOCKET
3476 if ((error = sooptcopyin(sopt, &extmac, sizeof (extmac),
3477 sizeof (extmac))) != 0 ||
3478 (error = mac_socket_label_get(proc_ucred(
3479 sopt->sopt_p), so, &extmac)) != 0)
3480 break;
3481
3482 error = sooptcopyout(sopt, &extmac, sizeof (extmac));
3483#else
3484 error = EOPNOTSUPP;
3485#endif /* MAC_SOCKET */
3486 break;
3487
3488 case SO_PEERLABEL:
3489#if CONFIG_MACF_SOCKET
3490 if ((error = sooptcopyin(sopt, &extmac, sizeof (extmac),
3491 sizeof (extmac))) != 0 ||
3492 (error = mac_socketpeer_label_get(proc_ucred(
3493 sopt->sopt_p), so, &extmac)) != 0)
3494 break;
3495
3496 error = sooptcopyout(sopt, &extmac, sizeof (extmac));
3497#else
3498 error = EOPNOTSUPP;
3499#endif /* MAC_SOCKET */
3500 break;
3501
4a3eedf9
A
3502#ifdef __APPLE_API_PRIVATE
3503 case SO_UPCALLCLOSEWAIT:
3504 optval = (so->so_flags & SOF_UPCALLCLOSEWAIT);
3505 goto integer;
3506#endif
b0d623f7
A
3507 case SO_RANDOMPORT:
3508 optval = (so->so_flags & SOF_BINDRANDOMPORT);
3509 goto integer;
3510
3511 case SO_NP_EXTENSIONS: {
3512 struct so_np_extensions sonpx;
3513
3514 sonpx.npx_flags = (so->so_flags & SOF_NPX_SETOPTSHUT) ? SONPX_SETOPTSHUT : 0;
3515 sonpx.npx_mask = SONPX_MASK_VALID;
4a3eedf9 3516
b0d623f7
A
3517 error = sooptcopyout(sopt, &sonpx, sizeof(struct so_np_extensions));
3518 break;
3519 }
1c79356b
A
3520 default:
3521 error = ENOPROTOOPT;
3522 break;
3523 }
91447636 3524 socket_unlock(so, 1);
1c79356b
A
3525 return (error);
3526 }
3527}
3528
9bccf70c 3529/* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1c79356b 3530int
9bccf70c 3531soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1c79356b
A
3532{
3533 struct mbuf *m, *m_prev;
3534 int sopt_size = sopt->sopt_valsize;
b0d623f7 3535 int how;
1c79356b 3536
a3d08fcd 3537 if (sopt_size > MAX_SOOPTGETM_SIZE)
2d21ac55 3538 return (EMSGSIZE);
a3d08fcd 3539
b0d623f7
A
3540 how = sopt->sopt_p != kernproc ? M_WAIT : M_DONTWAIT;
3541 MGET(m, how, MT_DATA);
1c79356b 3542 if (m == 0)
2d21ac55 3543 return (ENOBUFS);
1c79356b 3544 if (sopt_size > MLEN) {
b0d623f7 3545 MCLGET(m, how);
1c79356b
A
3546 if ((m->m_flags & M_EXT) == 0) {
3547 m_free(m);
2d21ac55 3548 return (ENOBUFS);
1c79356b
A
3549 }
3550 m->m_len = min(MCLBYTES, sopt_size);
3551 } else {
3552 m->m_len = min(MLEN, sopt_size);
3553 }
3554 sopt_size -= m->m_len;
3555 *mp = m;
3556 m_prev = m;
3557
3558 while (sopt_size) {
b0d623f7 3559 MGET(m, how, MT_DATA);
1c79356b
A
3560 if (m == 0) {
3561 m_freem(*mp);
2d21ac55 3562 return (ENOBUFS);
1c79356b
A
3563 }
3564 if (sopt_size > MLEN) {
b0d623f7 3565 MCLGET(m, how);
1c79356b
A
3566 if ((m->m_flags & M_EXT) == 0) {
3567 m_freem(*mp);
2d21ac55 3568 return (ENOBUFS);
1c79356b
A
3569 }
3570 m->m_len = min(MCLBYTES, sopt_size);
3571 } else {
3572 m->m_len = min(MLEN, sopt_size);
3573 }
3574 sopt_size -= m->m_len;
3575 m_prev->m_next = m;
3576 m_prev = m;
3577 }
2d21ac55 3578 return (0);
1c79356b
A
3579}
3580
3581/* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
3582int
9bccf70c 3583soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1c79356b
A
3584{
3585 struct mbuf *m0 = m;
3586
91447636 3587 if (sopt->sopt_val == USER_ADDR_NULL)
2d21ac55 3588 return (0);
1c79356b 3589 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
b0d623f7 3590 if (sopt->sopt_p != kernproc) {
1c79356b
A
3591 int error;
3592
2d21ac55
A
3593 error = copyin(sopt->sopt_val, mtod(m, char *),
3594 m->m_len);
1c79356b
A
3595 if (error != 0) {
3596 m_freem(m0);
2d21ac55 3597 return (error);
1c79356b 3598 }
2d21ac55
A
3599 } else {
3600 bcopy(CAST_DOWN(caddr_t, sopt->sopt_val),
3601 mtod(m, char *), m->m_len);
3602 }
1c79356b 3603 sopt->sopt_valsize -= m->m_len;
2d21ac55 3604 sopt->sopt_val += m->m_len;
1c79356b
A
3605 m = m->m_next;
3606 }
3607 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
9bccf70c 3608 panic("soopt_mcopyin");
2d21ac55 3609 return (0);
1c79356b
A
3610}
3611
3612/* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
3613int
9bccf70c 3614soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1c79356b
A
3615{
3616 struct mbuf *m0 = m;
3617 size_t valsize = 0;
3618
91447636 3619 if (sopt->sopt_val == USER_ADDR_NULL)
2d21ac55 3620 return (0);
1c79356b 3621 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
b0d623f7 3622 if (sopt->sopt_p != kernproc) {
1c79356b
A
3623 int error;
3624
2d21ac55
A
3625 error = copyout(mtod(m, char *), sopt->sopt_val,
3626 m->m_len);
1c79356b
A
3627 if (error != 0) {
3628 m_freem(m0);
2d21ac55 3629 return (error);
1c79356b 3630 }
2d21ac55
A
3631 } else {
3632 bcopy(mtod(m, char *),
3633 CAST_DOWN(caddr_t, sopt->sopt_val), m->m_len);
3634 }
3635 sopt->sopt_valsize -= m->m_len;
3636 sopt->sopt_val += m->m_len;
3637 valsize += m->m_len;
3638 m = m->m_next;
1c79356b
A
3639 }
3640 if (m != NULL) {
3641 /* enough soopt buffer should be given from user-land */
3642 m_freem(m0);
2d21ac55 3643 return (EINVAL);
1c79356b
A
3644 }
3645 sopt->sopt_valsize = valsize;
2d21ac55 3646 return (0);
1c79356b
A
3647}
3648
9bccf70c 3649void
2d21ac55 3650sohasoutofband(struct socket *so)
9bccf70c 3651{
9bccf70c 3652
9bccf70c
A
3653 if (so->so_pgid < 0)
3654 gsignal(-so->so_pgid, SIGURG);
2d21ac55
A
3655 else if (so->so_pgid > 0)
3656 proc_signal(so->so_pgid, SIGURG);
9bccf70c
A
3657 selwakeup(&so->so_rcv.sb_sel);
3658}
3659
3660int
91447636 3661sopoll(struct socket *so, int events, __unused kauth_cred_t cred, void * wql)
9bccf70c
A
3662{
3663 struct proc *p = current_proc();
3664 int revents = 0;
91447636
A
3665
3666 socket_lock(so, 1);
9bccf70c
A
3667
3668 if (events & (POLLIN | POLLRDNORM))
3669 if (soreadable(so))
3670 revents |= events & (POLLIN | POLLRDNORM);
3671
3672 if (events & (POLLOUT | POLLWRNORM))
3673 if (sowriteable(so))
3674 revents |= events & (POLLOUT | POLLWRNORM);
3675
3676 if (events & (POLLPRI | POLLRDBAND))
3677 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
3678 revents |= events & (POLLPRI | POLLRDBAND);
3679
3680 if (revents == 0) {
3681 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
2d21ac55
A
3682 /*
3683 * Darwin sets the flag first,
3684 * BSD calls selrecord first
3685 */
9bccf70c
A
3686 so->so_rcv.sb_flags |= SB_SEL;
3687 selrecord(p, &so->so_rcv.sb_sel, wql);
3688 }
3689
3690 if (events & (POLLOUT | POLLWRNORM)) {
2d21ac55
A
3691 /*
3692 * Darwin sets the flag first,
3693 * BSD calls selrecord first
3694 */
9bccf70c
A
3695 so->so_snd.sb_flags |= SB_SEL;
3696 selrecord(p, &so->so_snd.sb_sel, wql);
3697 }
3698 }
3699
91447636 3700 socket_unlock(so, 1);
9bccf70c
A
3701 return (revents);
3702}
55e303ae 3703
55e303ae 3704int
2d21ac55
A
3705soo_kqfilter(__unused struct fileproc *fp, struct knote *kn,
3706 __unused struct proc *p)
55e303ae 3707{
91447636 3708 struct socket *so = (struct socket *)kn->kn_fp->f_fglob->fg_data;
55e303ae 3709 struct sockbuf *sb;
2d21ac55 3710
91447636 3711 socket_lock(so, 1);
55e303ae 3712
2d21ac55
A
3713#if CONFIG_MACF_SOCKET
3714 if (mac_socket_check_kqfilter(proc_ucred(p), kn, so) != 0) {
3715 socket_unlock(so, 1);
3716 return (1);
3717 }
3718#endif /* MAC_SOCKET */
3719
55e303ae
A
3720 switch (kn->kn_filter) {
3721 case EVFILT_READ:
b0d623f7 3722 kn->kn_fop = &soread_filtops;
55e303ae
A
3723 sb = &so->so_rcv;
3724 break;
3725 case EVFILT_WRITE:
3726 kn->kn_fop = &sowrite_filtops;
3727 sb = &so->so_snd;
3728 break;
3729 default:
91447636 3730 socket_unlock(so, 1);
55e303ae
A
3731 return (1);
3732 }
3733
55e303ae
A
3734 if (KNOTE_ATTACH(&sb->sb_sel.si_note, kn))
3735 sb->sb_flags |= SB_KNOTE;
91447636 3736 socket_unlock(so, 1);
55e303ae
A
3737 return (0);
3738}
3739
3740static void
3741filt_sordetach(struct knote *kn)
3742{
91447636 3743 struct socket *so = (struct socket *)kn->kn_fp->f_fglob->fg_data;
55e303ae 3744
91447636
A
3745 socket_lock(so, 1);
3746 if (so->so_rcv.sb_flags & SB_KNOTE)
55e303ae
A
3747 if (KNOTE_DETACH(&so->so_rcv.sb_sel.si_note, kn))
3748 so->so_rcv.sb_flags &= ~SB_KNOTE;
91447636 3749 socket_unlock(so, 1);
55e303ae
A
3750}
3751
3752/*ARGSUSED*/
3753static int
3754filt_soread(struct knote *kn, long hint)
3755{
91447636 3756 struct socket *so = (struct socket *)kn->kn_fp->f_fglob->fg_data;
55e303ae 3757
91447636
A
3758 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3759 socket_lock(so, 1);
3760
b0d623f7
A
3761 if (so->so_options & SO_ACCEPTCONN) {
3762 int isempty;
3763
3764 /* Radar 6615193 handle the listen case dynamically
3765 * for kqueue read filter. This allows to call listen() after registering
3766 * the kqueue EVFILT_READ.
3767 */
3768
3769 kn->kn_data = so->so_qlen;
3770 isempty = ! TAILQ_EMPTY(&so->so_comp);
3771
3772 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3773 socket_unlock(so, 1);
3774
3775 return (isempty);
3776 }
3777
3778 /* socket isn't a listener */
3779
2d21ac55
A
3780 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
3781
91447636
A
3782 if (so->so_oobmark) {
3783 if (kn->kn_flags & EV_OOBAND) {
2d21ac55 3784 kn->kn_data -= so->so_oobmark;
91447636
A
3785 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3786 socket_unlock(so, 1);
3787 return (1);
3788 }
3789 kn->kn_data = so->so_oobmark;
3790 kn->kn_flags |= EV_OOBAND;
3791 } else {
91447636
A
3792 if (so->so_state & SS_CANTRCVMORE) {
3793 kn->kn_flags |= EV_EOF;
3794 kn->kn_fflags = so->so_error;
3795 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3796 socket_unlock(so, 1);
3797 return (1);
3798 }
55e303ae 3799 }
91447636
A
3800
3801 if (so->so_state & SS_RCVATMARK) {
3802 if (kn->kn_flags & EV_OOBAND) {
3803 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3804 socket_unlock(so, 1);
3805 return (1);
3806 }
3807 kn->kn_flags |= EV_OOBAND;
3808 } else if (kn->kn_flags & EV_OOBAND) {
3809 kn->kn_data = 0;
3810 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3811 socket_unlock(so, 1);
3812 return (0);
3813 }
3814
3815 if (so->so_error) { /* temporary udp error */
3816 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3817 socket_unlock(so, 1);
55e303ae 3818 return (1);
91447636
A
3819 }
3820
3821 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3822 socket_unlock(so, 1);
3823
2d21ac55
A
3824 return ((kn->kn_flags & EV_OOBAND) ||
3825 kn->kn_data >= ((kn->kn_sfflags & NOTE_LOWAT) ?
3826 kn->kn_sdata : so->so_rcv.sb_lowat));
55e303ae
A
3827}
3828
3829static void
3830filt_sowdetach(struct knote *kn)
3831{
91447636
A
3832 struct socket *so = (struct socket *)kn->kn_fp->f_fglob->fg_data;
3833 socket_lock(so, 1);
55e303ae 3834
2d21ac55 3835 if (so->so_snd.sb_flags & SB_KNOTE)
55e303ae
A
3836 if (KNOTE_DETACH(&so->so_snd.sb_sel.si_note, kn))
3837 so->so_snd.sb_flags &= ~SB_KNOTE;
91447636 3838 socket_unlock(so, 1);
55e303ae
A
3839}
3840
3841/*ARGSUSED*/
3842static int
3843filt_sowrite(struct knote *kn, long hint)
3844{
91447636
A
3845 struct socket *so = (struct socket *)kn->kn_fp->f_fglob->fg_data;
3846
3847 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3848 socket_lock(so, 1);
55e303ae
A
3849
3850 kn->kn_data = sbspace(&so->so_snd);
3851 if (so->so_state & SS_CANTSENDMORE) {
2d21ac55 3852 kn->kn_flags |= EV_EOF;
55e303ae 3853 kn->kn_fflags = so->so_error;
91447636
A
3854 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3855 socket_unlock(so, 1);
55e303ae
A
3856 return (1);
3857 }
91447636
A
3858 if (so->so_error) { /* temporary udp error */
3859 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3860 socket_unlock(so, 1);
55e303ae 3861 return (1);
91447636 3862 }
55e303ae 3863 if (((so->so_state & SS_ISCONNECTED) == 0) &&
91447636
A
3864 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
3865 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3866 socket_unlock(so, 1);
55e303ae 3867 return (0);
91447636
A
3868 }
3869 if ((hint & SO_FILT_HINT_LOCKED) == 0)
3870 socket_unlock(so, 1);
55e303ae
A
3871 if (kn->kn_sfflags & NOTE_LOWAT)
3872 return (kn->kn_data >= kn->kn_sdata);
3873 return (kn->kn_data >= so->so_snd.sb_lowat);
3874}
3875
b0d623f7
A
3876#define SO_LOCK_HISTORY_STR_LEN (2 * SO_LCKDBG_MAX * (2 + sizeof(void *) + 1) + 1)
3877
3878__private_extern__ const char * solockhistory_nr(struct socket *so)
55e303ae 3879{
b0d623f7
A
3880 size_t n = 0;
3881 int i;
3882 static char lock_history_str[SO_LOCK_HISTORY_STR_LEN];
55e303ae 3883
b0d623f7
A
3884 for (i = SO_LCKDBG_MAX - 1; i >= 0; i--) {
3885 n += snprintf(lock_history_str + n, SO_LOCK_HISTORY_STR_LEN - n, "%lx:%lx ",
3886 (uintptr_t) so->lock_lr[(so->next_lock_lr + i) % SO_LCKDBG_MAX],
3887 (uintptr_t) so->unlock_lr[(so->next_unlock_lr + i) % SO_LCKDBG_MAX]);
3888 }
3889 return lock_history_str;
55e303ae
A
3890}
3891
91447636 3892int
2d21ac55 3893socket_lock(struct socket *so, int refcount)
91447636 3894{
b0d623f7
A
3895 int error = 0;
3896 void *lr_saved;
0c530ab8 3897
b0d623f7 3898 lr_saved = __builtin_return_address(0);
91447636
A
3899
3900 if (so->so_proto->pr_lock) {
3901 error = (*so->so_proto->pr_lock)(so, refcount, lr_saved);
2d21ac55 3902 } else {
91447636 3903#ifdef MORE_LOCKING_DEBUG
2d21ac55
A
3904 lck_mtx_assert(so->so_proto->pr_domain->dom_mtx,
3905 LCK_MTX_ASSERT_NOTOWNED);
91447636
A
3906#endif
3907 lck_mtx_lock(so->so_proto->pr_domain->dom_mtx);
3908 if (refcount)
3909 so->so_usecount++;
b0d623f7 3910 so->lock_lr[so->next_lock_lr] = lr_saved;
0c530ab8 3911 so->next_lock_lr = (so->next_lock_lr+1) % SO_LCKDBG_MAX;
91447636
A
3912 }
3913
2d21ac55 3914 return (error);
91447636
A
3915}
3916
3917int
2d21ac55 3918socket_unlock(struct socket *so, int refcount)
91447636 3919{
b0d623f7
A
3920 int error = 0;
3921 void *lr_saved;
2d21ac55 3922 lck_mtx_t *mutex_held;
91447636 3923
b0d623f7 3924 lr_saved = __builtin_return_address(0);
91447636
A
3925
3926 if (so->so_proto == NULL)
2d21ac55 3927 panic("socket_unlock null so_proto so=%p\n", so);
91447636 3928
2d21ac55 3929 if (so && so->so_proto->pr_unlock) {
91447636 3930 error = (*so->so_proto->pr_unlock)(so, refcount, lr_saved);
2d21ac55 3931 } else {
91447636
A
3932 mutex_held = so->so_proto->pr_domain->dom_mtx;
3933#ifdef MORE_LOCKING_DEBUG
3934 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
3935#endif
b0d623f7 3936 so->unlock_lr[so->next_unlock_lr] = lr_saved;
0c530ab8
A
3937 so->next_unlock_lr = (so->next_unlock_lr+1) % SO_LCKDBG_MAX;
3938
91447636
A
3939 if (refcount) {
3940 if (so->so_usecount <= 0)
b0d623f7
A
3941 panic("socket_unlock: bad refcount=%d so=%p (%d, %d, %d) lrh=%s",
3942 so->so_usecount, so, so->so_proto->pr_domain->dom_family,
3943 so->so_type, so->so_proto->pr_protocol,
3944 solockhistory_nr(so));
3945
91447636
A
3946 so->so_usecount--;
3947 if (so->so_usecount == 0) {
3948 sofreelastref(so, 1);
3949 }
91447636
A
3950 }
3951 lck_mtx_unlock(mutex_held);
3952 }
3953
2d21ac55 3954 return (error);
91447636 3955}
2d21ac55
A
3956
3957/* Called with socket locked, will unlock socket */
91447636 3958void
2d21ac55 3959sofree(struct socket *so)
91447636
A
3960{
3961
2d21ac55
A
3962 lck_mtx_t *mutex_held;
3963 if (so->so_proto->pr_getlock != NULL)
91447636 3964 mutex_held = (*so->so_proto->pr_getlock)(so, 0);
2d21ac55 3965 else
91447636
A
3966 mutex_held = so->so_proto->pr_domain->dom_mtx;
3967 lck_mtx_assert(mutex_held, LCK_MTX_ASSERT_OWNED);
2d21ac55 3968
91447636
A
3969 sofreelastref(so, 0);
3970}
3971
3972void
2d21ac55 3973soreference(struct socket *so)
91447636
A
3974{
3975 socket_lock(so, 1); /* locks & take one reference on socket */
3976 socket_unlock(so, 0); /* unlock only */
3977}
3978
3979void
2d21ac55 3980sodereference(struct socket *so)
91447636
A
3981{
3982 socket_lock(so, 0);
3983 socket_unlock(so, 1);
3984}
2d21ac55
A
3985
3986/*
3987 * Set or clear SOF_MULTIPAGES on the socket to enable or disable the
3988 * possibility of using jumbo clusters. Caller must ensure to hold
3989 * the socket lock.
3990 */
3991void
3992somultipages(struct socket *so, boolean_t set)
3993{
3994 if (set)
3995 so->so_flags |= SOF_MULTIPAGES;
3996 else
3997 so->so_flags &= ~SOF_MULTIPAGES;
3998}
b0d623f7
A
3999
4000int
4001so_isdstlocal(struct socket *so) {
4002
4003 struct inpcb *inp = (struct inpcb *)so->so_pcb;
4004
4005 if (so->so_proto->pr_domain->dom_family == AF_INET) {
4006 return inaddr_local(inp->inp_faddr);
4007 } else if (so->so_proto->pr_domain->dom_family == AF_INET6) {
4008 return in6addr_local(&inp->in6p_faddr);
4009 }
4010 return 0;
4011}