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