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