]> git.saurik.com Git - apple/xnu.git/blob - bsd/kern/kpi_socket.c
xnu-6153.81.5.tar.gz
[apple/xnu.git] / bsd / kern / kpi_socket.c
1 /*
2 * Copyright (c) 2003-2017 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
29 #define __KPI__
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <sys/socketvar.h>
35 #include <sys/param.h>
36 #include <sys/proc.h>
37 #include <sys/errno.h>
38 #include <sys/malloc.h>
39 #include <sys/protosw.h>
40 #include <sys/domain.h>
41 #include <sys/mbuf.h>
42 #include <sys/mcache.h>
43 #include <sys/fcntl.h>
44 #include <sys/filio.h>
45 #include <sys/uio_internal.h>
46 #include <kern/locks.h>
47 #include <net/net_api_stats.h>
48 #include <netinet/in.h>
49 #include <libkern/OSAtomic.h>
50 #include <stdbool.h>
51
52 static errno_t sock_send_internal(socket_t, const struct msghdr *,
53 mbuf_t, int, size_t *);
54
55 #undef sock_accept
56 #undef sock_socket
57 errno_t sock_accept(socket_t so, struct sockaddr *from, int fromlen,
58 int flags, sock_upcall callback, void *cookie, socket_t *new_so);
59 errno_t sock_socket(int domain, int type, int protocol, sock_upcall callback,
60 void *context, socket_t *new_so);
61
62 static errno_t sock_accept_common(socket_t sock, struct sockaddr *from,
63 int fromlen, int flags, sock_upcall callback, void *cookie,
64 socket_t *new_sock, bool is_internal);
65 static errno_t sock_socket_common(int domain, int type, int protocol,
66 sock_upcall callback, void *context, socket_t *new_so, bool is_internal);
67
68 errno_t
69 sock_accept_common(socket_t sock, struct sockaddr *from, int fromlen, int flags,
70 sock_upcall callback, void *cookie, socket_t *new_sock, bool is_internal)
71 {
72 struct sockaddr *sa;
73 struct socket *new_so;
74 lck_mtx_t *mutex_held;
75 int dosocklock;
76 errno_t error = 0;
77
78 if (sock == NULL || new_sock == NULL) {
79 return EINVAL;
80 }
81
82 socket_lock(sock, 1);
83 if ((sock->so_options & SO_ACCEPTCONN) == 0) {
84 socket_unlock(sock, 1);
85 return EINVAL;
86 }
87 if ((flags & ~(MSG_DONTWAIT)) != 0) {
88 socket_unlock(sock, 1);
89 return ENOTSUP;
90 }
91 check_again:
92 if (((flags & MSG_DONTWAIT) != 0 || (sock->so_state & SS_NBIO) != 0) &&
93 sock->so_comp.tqh_first == NULL) {
94 socket_unlock(sock, 1);
95 return EWOULDBLOCK;
96 }
97
98 if (sock->so_proto->pr_getlock != NULL) {
99 mutex_held = (*sock->so_proto->pr_getlock)(sock, PR_F_WILLUNLOCK);
100 dosocklock = 1;
101 } else {
102 mutex_held = sock->so_proto->pr_domain->dom_mtx;
103 dosocklock = 0;
104 }
105
106 while (TAILQ_EMPTY(&sock->so_comp) && sock->so_error == 0) {
107 if (sock->so_state & SS_CANTRCVMORE) {
108 sock->so_error = ECONNABORTED;
109 break;
110 }
111 error = msleep((caddr_t)&sock->so_timeo, mutex_held,
112 PSOCK | PCATCH, "sock_accept", NULL);
113 if (error != 0) {
114 socket_unlock(sock, 1);
115 return error;
116 }
117 }
118 if (sock->so_error != 0) {
119 error = sock->so_error;
120 sock->so_error = 0;
121 socket_unlock(sock, 1);
122 return error;
123 }
124
125 so_acquire_accept_list(sock, NULL);
126 if (TAILQ_EMPTY(&sock->so_comp)) {
127 so_release_accept_list(sock);
128 goto check_again;
129 }
130 new_so = TAILQ_FIRST(&sock->so_comp);
131 TAILQ_REMOVE(&sock->so_comp, new_so, so_list);
132 new_so->so_state &= ~SS_COMP;
133 new_so->so_head = NULL;
134 sock->so_qlen--;
135
136 so_release_accept_list(sock);
137
138 /*
139 * Count the accepted socket as an in-kernel socket
140 */
141 new_so->so_flags1 |= SOF1_IN_KERNEL_SOCKET;
142 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_in_kernel_total);
143 if (is_internal) {
144 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_in_kernel_os_total);
145 }
146
147 /*
148 * Pass the pre-accepted socket to any interested socket filter(s).
149 * Upon failure, the socket would have been closed by the callee.
150 */
151 if (new_so->so_filt != NULL) {
152 /*
153 * Temporarily drop the listening socket's lock before we
154 * hand off control over to the socket filter(s), but keep
155 * a reference so that it won't go away. We'll grab it
156 * again once we're done with the filter(s).
157 */
158 socket_unlock(sock, 0);
159 if ((error = soacceptfilter(new_so, sock)) != 0) {
160 /* Drop reference on listening socket */
161 sodereference(sock);
162 return error;
163 }
164 socket_lock(sock, 0);
165 }
166
167 if (dosocklock) {
168 LCK_MTX_ASSERT(new_so->so_proto->pr_getlock(new_so, 0),
169 LCK_MTX_ASSERT_NOTOWNED);
170 socket_lock(new_so, 1);
171 }
172
173 (void) soacceptlock(new_so, &sa, 0);
174
175 socket_unlock(sock, 1); /* release the head */
176
177 /* see comments in sock_setupcall() */
178 if (callback != NULL) {
179 #if CONFIG_EMBEDDED
180 sock_setupcalls_locked(new_so, callback, cookie, callback, cookie, 0);
181 #else
182 sock_setupcalls_locked(new_so, callback, cookie, NULL, NULL, 0);
183 #endif /* !CONFIG_EMBEDDED */
184 }
185
186 if (sa != NULL && from != NULL) {
187 if (fromlen > sa->sa_len) {
188 fromlen = sa->sa_len;
189 }
190 memcpy(from, sa, fromlen);
191 }
192 if (sa != NULL) {
193 FREE(sa, M_SONAME);
194 }
195
196 /*
197 * If the socket has been marked as inactive by sosetdefunct(),
198 * disallow further operations on it.
199 */
200 if (new_so->so_flags & SOF_DEFUNCT) {
201 (void) sodefunct(current_proc(), new_so,
202 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_INTERNAL);
203 }
204 *new_sock = new_so;
205 if (dosocklock) {
206 socket_unlock(new_so, 1);
207 }
208 return error;
209 }
210
211 errno_t
212 sock_accept(socket_t sock, struct sockaddr *from, int fromlen, int flags,
213 sock_upcall callback, void *cookie, socket_t *new_sock)
214 {
215 return sock_accept_common(sock, from, fromlen, flags,
216 callback, cookie, new_sock, false);
217 }
218
219 errno_t
220 sock_accept_internal(socket_t sock, struct sockaddr *from, int fromlen, int flags,
221 sock_upcall callback, void *cookie, socket_t *new_sock)
222 {
223 return sock_accept_common(sock, from, fromlen, flags,
224 callback, cookie, new_sock, true);
225 }
226
227 errno_t
228 sock_bind(socket_t sock, const struct sockaddr *to)
229 {
230 int error = 0;
231 struct sockaddr *sa = NULL;
232 struct sockaddr_storage ss;
233 boolean_t want_free = TRUE;
234
235 if (sock == NULL || to == NULL) {
236 return EINVAL;
237 }
238
239 if (to->sa_len > sizeof(ss)) {
240 MALLOC(sa, struct sockaddr *, to->sa_len, M_SONAME, M_WAITOK);
241 if (sa == NULL) {
242 return ENOBUFS;
243 }
244 } else {
245 sa = (struct sockaddr *)&ss;
246 want_free = FALSE;
247 }
248 memcpy(sa, to, to->sa_len);
249
250 error = sobindlock(sock, sa, 1); /* will lock socket */
251
252 if (sa != NULL && want_free == TRUE) {
253 FREE(sa, M_SONAME);
254 }
255
256 return error;
257 }
258
259 errno_t
260 sock_connect(socket_t sock, const struct sockaddr *to, int flags)
261 {
262 int error = 0;
263 lck_mtx_t *mutex_held;
264 struct sockaddr *sa = NULL;
265 struct sockaddr_storage ss;
266 boolean_t want_free = TRUE;
267
268 if (sock == NULL || to == NULL) {
269 return EINVAL;
270 }
271
272 if (to->sa_len > sizeof(ss)) {
273 MALLOC(sa, struct sockaddr *, to->sa_len, M_SONAME,
274 (flags & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK);
275 if (sa == NULL) {
276 return ENOBUFS;
277 }
278 } else {
279 sa = (struct sockaddr *)&ss;
280 want_free = FALSE;
281 }
282 memcpy(sa, to, to->sa_len);
283
284 socket_lock(sock, 1);
285
286 if ((sock->so_state & SS_ISCONNECTING) &&
287 ((sock->so_state & SS_NBIO) != 0 || (flags & MSG_DONTWAIT) != 0)) {
288 error = EALREADY;
289 goto out;
290 }
291 error = soconnectlock(sock, sa, 0);
292 if (!error) {
293 if ((sock->so_state & SS_ISCONNECTING) &&
294 ((sock->so_state & SS_NBIO) != 0 ||
295 (flags & MSG_DONTWAIT) != 0)) {
296 error = EINPROGRESS;
297 goto out;
298 }
299
300 if (sock->so_proto->pr_getlock != NULL) {
301 mutex_held = (*sock->so_proto->pr_getlock)(sock, PR_F_WILLUNLOCK);
302 } else {
303 mutex_held = sock->so_proto->pr_domain->dom_mtx;
304 }
305
306 while ((sock->so_state & SS_ISCONNECTING) &&
307 sock->so_error == 0) {
308 error = msleep((caddr_t)&sock->so_timeo,
309 mutex_held, PSOCK | PCATCH, "sock_connect", NULL);
310 if (error != 0) {
311 break;
312 }
313 }
314
315 if (error == 0) {
316 error = sock->so_error;
317 sock->so_error = 0;
318 }
319 } else {
320 sock->so_state &= ~SS_ISCONNECTING;
321 }
322 out:
323 socket_unlock(sock, 1);
324
325 if (sa != NULL && want_free == TRUE) {
326 FREE(sa, M_SONAME);
327 }
328
329 return error;
330 }
331
332 errno_t
333 sock_connectwait(socket_t sock, const struct timeval *tv)
334 {
335 lck_mtx_t *mutex_held;
336 errno_t retval = 0;
337 struct timespec ts;
338
339 socket_lock(sock, 1);
340
341 /* Check if we're already connected or if we've already errored out */
342 if ((sock->so_state & SS_ISCONNECTING) == 0 || sock->so_error != 0) {
343 if (sock->so_error != 0) {
344 retval = sock->so_error;
345 sock->so_error = 0;
346 } else {
347 if ((sock->so_state & SS_ISCONNECTED) != 0) {
348 retval = 0;
349 } else {
350 retval = EINVAL;
351 }
352 }
353 goto done;
354 }
355
356 /* copied translation from timeval to hertz from SO_RCVTIMEO handling */
357 if (tv->tv_sec < 0 || tv->tv_sec > SHRT_MAX / hz ||
358 tv->tv_usec < 0 || tv->tv_usec >= 1000000) {
359 retval = EDOM;
360 goto done;
361 }
362
363 ts.tv_sec = tv->tv_sec;
364 ts.tv_nsec = (tv->tv_usec * (integer_t)NSEC_PER_USEC);
365 if ((ts.tv_sec + (ts.tv_nsec / (long)NSEC_PER_SEC)) / 100 > SHRT_MAX) {
366 retval = EDOM;
367 goto done;
368 }
369
370 if (sock->so_proto->pr_getlock != NULL) {
371 mutex_held = (*sock->so_proto->pr_getlock)(sock, PR_F_WILLUNLOCK);
372 } else {
373 mutex_held = sock->so_proto->pr_domain->dom_mtx;
374 }
375
376 msleep((caddr_t)&sock->so_timeo, mutex_held,
377 PSOCK, "sock_connectwait", &ts);
378
379 /* Check if we're still waiting to connect */
380 if ((sock->so_state & SS_ISCONNECTING) && sock->so_error == 0) {
381 retval = EINPROGRESS;
382 goto done;
383 }
384
385 if (sock->so_error != 0) {
386 retval = sock->so_error;
387 sock->so_error = 0;
388 }
389
390 done:
391 socket_unlock(sock, 1);
392 return retval;
393 }
394
395 errno_t
396 sock_nointerrupt(socket_t sock, int on)
397 {
398 socket_lock(sock, 1);
399
400 if (on) {
401 sock->so_rcv.sb_flags |= SB_NOINTR; /* This isn't safe */
402 sock->so_snd.sb_flags |= SB_NOINTR; /* This isn't safe */
403 } else {
404 sock->so_rcv.sb_flags &= ~SB_NOINTR; /* This isn't safe */
405 sock->so_snd.sb_flags &= ~SB_NOINTR; /* This isn't safe */
406 }
407
408 socket_unlock(sock, 1);
409
410 return 0;
411 }
412
413 errno_t
414 sock_getpeername(socket_t sock, struct sockaddr *peername, int peernamelen)
415 {
416 int error;
417 struct sockaddr *sa = NULL;
418
419 if (sock == NULL || peername == NULL || peernamelen < 0) {
420 return EINVAL;
421 }
422
423 socket_lock(sock, 1);
424 if (!(sock->so_state & (SS_ISCONNECTED | SS_ISCONFIRMING))) {
425 socket_unlock(sock, 1);
426 return ENOTCONN;
427 }
428 error = sogetaddr_locked(sock, &sa, 1);
429 socket_unlock(sock, 1);
430 if (error == 0) {
431 if (peernamelen > sa->sa_len) {
432 peernamelen = sa->sa_len;
433 }
434 memcpy(peername, sa, peernamelen);
435 FREE(sa, M_SONAME);
436 }
437 return error;
438 }
439
440 errno_t
441 sock_getsockname(socket_t sock, struct sockaddr *sockname, int socknamelen)
442 {
443 int error;
444 struct sockaddr *sa = NULL;
445
446 if (sock == NULL || sockname == NULL || socknamelen < 0) {
447 return EINVAL;
448 }
449
450 socket_lock(sock, 1);
451 error = sogetaddr_locked(sock, &sa, 0);
452 socket_unlock(sock, 1);
453 if (error == 0) {
454 if (socknamelen > sa->sa_len) {
455 socknamelen = sa->sa_len;
456 }
457 memcpy(sockname, sa, socknamelen);
458 FREE(sa, M_SONAME);
459 }
460 return error;
461 }
462
463 __private_extern__ int
464 sogetaddr_locked(struct socket *so, struct sockaddr **psa, int peer)
465 {
466 int error;
467
468 if (so == NULL || psa == NULL) {
469 return EINVAL;
470 }
471
472 *psa = NULL;
473 error = peer ? so->so_proto->pr_usrreqs->pru_peeraddr(so, psa) :
474 so->so_proto->pr_usrreqs->pru_sockaddr(so, psa);
475
476 if (error == 0 && *psa == NULL) {
477 error = ENOMEM;
478 } else if (error != 0 && *psa != NULL) {
479 FREE(*psa, M_SONAME);
480 *psa = NULL;
481 }
482 return error;
483 }
484
485 errno_t
486 sock_getaddr(socket_t sock, struct sockaddr **psa, int peer)
487 {
488 int error;
489
490 if (sock == NULL || psa == NULL) {
491 return EINVAL;
492 }
493
494 socket_lock(sock, 1);
495 error = sogetaddr_locked(sock, psa, peer);
496 socket_unlock(sock, 1);
497
498 return error;
499 }
500
501 void
502 sock_freeaddr(struct sockaddr *sa)
503 {
504 if (sa != NULL) {
505 FREE(sa, M_SONAME);
506 }
507 }
508
509 errno_t
510 sock_getsockopt(socket_t sock, int level, int optname, void *optval,
511 int *optlen)
512 {
513 int error = 0;
514 struct sockopt sopt;
515
516 if (sock == NULL || optval == NULL || optlen == NULL) {
517 return EINVAL;
518 }
519
520 sopt.sopt_dir = SOPT_GET;
521 sopt.sopt_level = level;
522 sopt.sopt_name = optname;
523 sopt.sopt_val = CAST_USER_ADDR_T(optval);
524 sopt.sopt_valsize = *optlen;
525 sopt.sopt_p = kernproc;
526 error = sogetoptlock(sock, &sopt, 1); /* will lock socket */
527 if (error == 0) {
528 *optlen = sopt.sopt_valsize;
529 }
530 return error;
531 }
532
533 errno_t
534 sock_ioctl(socket_t sock, unsigned long request, void *argp)
535 {
536 return soioctl(sock, request, argp, kernproc); /* will lock socket */
537 }
538
539 errno_t
540 sock_setsockopt(socket_t sock, int level, int optname, const void *optval,
541 int optlen)
542 {
543 struct sockopt sopt;
544
545 if (sock == NULL || optval == NULL) {
546 return EINVAL;
547 }
548
549 sopt.sopt_dir = SOPT_SET;
550 sopt.sopt_level = level;
551 sopt.sopt_name = optname;
552 sopt.sopt_val = CAST_USER_ADDR_T(optval);
553 sopt.sopt_valsize = optlen;
554 sopt.sopt_p = kernproc;
555 return sosetoptlock(sock, &sopt, 1); /* will lock socket */
556 }
557
558 /*
559 * This follows the recommended mappings between DSCP code points
560 * and WMM access classes.
561 */
562 static u_int32_t so_tc_from_dscp(u_int8_t dscp);
563 static u_int32_t
564 so_tc_from_dscp(u_int8_t dscp)
565 {
566 u_int32_t tc;
567
568 if (dscp >= 0x30 && dscp <= 0x3f) {
569 tc = SO_TC_VO;
570 } else if (dscp >= 0x20 && dscp <= 0x2f) {
571 tc = SO_TC_VI;
572 } else if (dscp >= 0x08 && dscp <= 0x17) {
573 tc = SO_TC_BK_SYS;
574 } else {
575 tc = SO_TC_BE;
576 }
577
578 return tc;
579 }
580
581 errno_t
582 sock_settclassopt(socket_t sock, const void *optval, size_t optlen)
583 {
584 errno_t error = 0;
585 struct sockopt sopt;
586 int sotc;
587
588 if (sock == NULL || optval == NULL || optlen != sizeof(int)) {
589 return EINVAL;
590 }
591
592 socket_lock(sock, 1);
593 if (!(sock->so_state & SS_ISCONNECTED)) {
594 /*
595 * If the socket is not connected then we don't know
596 * if the destination is on LAN or not. Skip
597 * setting traffic class in this case
598 */
599 error = ENOTCONN;
600 goto out;
601 }
602
603 if (sock->so_proto == NULL || sock->so_proto->pr_domain == NULL ||
604 sock->so_pcb == NULL) {
605 error = EINVAL;
606 goto out;
607 }
608
609 /*
610 * Set the socket traffic class based on the passed DSCP code point
611 * regardless of the scope of the destination
612 */
613 sotc = so_tc_from_dscp((*(const int *)optval) >> 2);
614
615 sopt.sopt_dir = SOPT_SET;
616 sopt.sopt_val = CAST_USER_ADDR_T(&sotc);
617 sopt.sopt_valsize = sizeof(sotc);
618 sopt.sopt_p = kernproc;
619 sopt.sopt_level = SOL_SOCKET;
620 sopt.sopt_name = SO_TRAFFIC_CLASS;
621
622 error = sosetoptlock(sock, &sopt, 0); /* already locked */
623
624 if (error != 0) {
625 printf("%s: sosetopt SO_TRAFFIC_CLASS failed %d\n",
626 __func__, error);
627 goto out;
628 }
629
630 /*
631 * Check if the destination address is LAN or link local address.
632 * We do not want to set traffic class bits if the destination
633 * is not local.
634 */
635 if (!so_isdstlocal(sock)) {
636 goto out;
637 }
638
639 sopt.sopt_dir = SOPT_SET;
640 sopt.sopt_val = CAST_USER_ADDR_T(optval);
641 sopt.sopt_valsize = optlen;
642 sopt.sopt_p = kernproc;
643
644 switch (SOCK_DOM(sock)) {
645 case PF_INET:
646 sopt.sopt_level = IPPROTO_IP;
647 sopt.sopt_name = IP_TOS;
648 break;
649 case PF_INET6:
650 sopt.sopt_level = IPPROTO_IPV6;
651 sopt.sopt_name = IPV6_TCLASS;
652 break;
653 default:
654 error = EINVAL;
655 goto out;
656 }
657
658 error = sosetoptlock(sock, &sopt, 0); /* already locked */
659 socket_unlock(sock, 1);
660 return error;
661 out:
662 socket_unlock(sock, 1);
663 return error;
664 }
665
666 errno_t
667 sock_gettclassopt(socket_t sock, void *optval, size_t *optlen)
668 {
669 errno_t error = 0;
670 struct sockopt sopt;
671
672 if (sock == NULL || optval == NULL || optlen == NULL) {
673 return EINVAL;
674 }
675
676 sopt.sopt_dir = SOPT_GET;
677 sopt.sopt_val = CAST_USER_ADDR_T(optval);
678 sopt.sopt_valsize = *optlen;
679 sopt.sopt_p = kernproc;
680
681 socket_lock(sock, 1);
682 if (sock->so_proto == NULL || sock->so_proto->pr_domain == NULL) {
683 socket_unlock(sock, 1);
684 return EINVAL;
685 }
686
687 switch (SOCK_DOM(sock)) {
688 case PF_INET:
689 sopt.sopt_level = IPPROTO_IP;
690 sopt.sopt_name = IP_TOS;
691 break;
692 case PF_INET6:
693 sopt.sopt_level = IPPROTO_IPV6;
694 sopt.sopt_name = IPV6_TCLASS;
695 break;
696 default:
697 socket_unlock(sock, 1);
698 return EINVAL;
699 }
700 error = sogetoptlock(sock, &sopt, 0); /* already locked */
701 socket_unlock(sock, 1);
702 if (error == 0) {
703 *optlen = sopt.sopt_valsize;
704 }
705 return error;
706 }
707
708 errno_t
709 sock_listen(socket_t sock, int backlog)
710 {
711 if (sock == NULL) {
712 return EINVAL;
713 }
714
715 return solisten(sock, backlog); /* will lock socket */
716 }
717
718 errno_t
719 sock_receive_internal(socket_t sock, struct msghdr *msg, mbuf_t *data,
720 int flags, size_t *recvdlen)
721 {
722 uio_t auio;
723 struct mbuf *control = NULL;
724 int error = 0;
725 int length = 0;
726 struct sockaddr *fromsa = NULL;
727 char uio_buf[UIO_SIZEOF((msg != NULL) ? msg->msg_iovlen : 0)];
728
729 if (sock == NULL) {
730 return EINVAL;
731 }
732
733 auio = uio_createwithbuffer(((msg != NULL) ? msg->msg_iovlen : 0),
734 0, UIO_SYSSPACE, UIO_READ, &uio_buf[0], sizeof(uio_buf));
735 if (msg != NULL && data == NULL) {
736 int i;
737 struct iovec *tempp = msg->msg_iov;
738
739 for (i = 0; i < msg->msg_iovlen; i++) {
740 uio_addiov(auio,
741 CAST_USER_ADDR_T((tempp + i)->iov_base),
742 (tempp + i)->iov_len);
743 }
744 if (uio_resid(auio) < 0) {
745 return EINVAL;
746 }
747 } else if (recvdlen != NULL) {
748 uio_setresid(auio, (uio_resid(auio) + *recvdlen));
749 }
750 length = uio_resid(auio);
751
752 if (recvdlen != NULL) {
753 *recvdlen = 0;
754 }
755
756 /* let pru_soreceive handle the socket locking */
757 error = sock->so_proto->pr_usrreqs->pru_soreceive(sock, &fromsa, auio,
758 data, (msg && msg->msg_control) ? &control : NULL, &flags);
759 if (error != 0) {
760 goto cleanup;
761 }
762
763 if (recvdlen != NULL) {
764 *recvdlen = length - uio_resid(auio);
765 }
766 if (msg != NULL) {
767 msg->msg_flags = flags;
768
769 if (msg->msg_name != NULL) {
770 int salen;
771 salen = msg->msg_namelen;
772 if (msg->msg_namelen > 0 && fromsa != NULL) {
773 salen = MIN(salen, fromsa->sa_len);
774 memcpy(msg->msg_name, fromsa,
775 msg->msg_namelen > fromsa->sa_len ?
776 fromsa->sa_len : msg->msg_namelen);
777 }
778 }
779
780 if (msg->msg_control != NULL) {
781 struct mbuf *m = control;
782 u_char *ctlbuf = msg->msg_control;
783 int clen = msg->msg_controllen;
784
785 msg->msg_controllen = 0;
786
787 while (m != NULL && clen > 0) {
788 unsigned int tocopy;
789
790 if (clen >= m->m_len) {
791 tocopy = m->m_len;
792 } else {
793 msg->msg_flags |= MSG_CTRUNC;
794 tocopy = clen;
795 }
796 memcpy(ctlbuf, mtod(m, caddr_t), tocopy);
797 ctlbuf += tocopy;
798 clen -= tocopy;
799 m = m->m_next;
800 }
801 msg->msg_controllen =
802 (uintptr_t)ctlbuf - (uintptr_t)msg->msg_control;
803 }
804 }
805
806 cleanup:
807 if (control != NULL) {
808 m_freem(control);
809 }
810 if (fromsa != NULL) {
811 FREE(fromsa, M_SONAME);
812 }
813 return error;
814 }
815
816 errno_t
817 sock_receive(socket_t sock, struct msghdr *msg, int flags, size_t *recvdlen)
818 {
819 if ((msg == NULL) || (msg->msg_iovlen < 1) ||
820 (msg->msg_iov[0].iov_len == 0) ||
821 (msg->msg_iov[0].iov_base == NULL)) {
822 return EINVAL;
823 }
824
825 return sock_receive_internal(sock, msg, NULL, flags, recvdlen);
826 }
827
828 errno_t
829 sock_receivembuf(socket_t sock, struct msghdr *msg, mbuf_t *data, int flags,
830 size_t *recvlen)
831 {
832 if (data == NULL || recvlen == 0 || *recvlen <= 0 || (msg != NULL &&
833 (msg->msg_iov != NULL || msg->msg_iovlen != 0))) {
834 return EINVAL;
835 }
836
837 return sock_receive_internal(sock, msg, data, flags, recvlen);
838 }
839
840 errno_t
841 sock_send_internal(socket_t sock, const struct msghdr *msg, mbuf_t data,
842 int flags, size_t *sentlen)
843 {
844 uio_t auio = NULL;
845 struct mbuf *control = NULL;
846 int error = 0;
847 int datalen = 0;
848 char uio_buf[UIO_SIZEOF((msg != NULL ? msg->msg_iovlen : 1))];
849
850 if (sock == NULL) {
851 error = EINVAL;
852 goto errorout;
853 }
854
855 if (data == NULL && msg != NULL) {
856 struct iovec *tempp = msg->msg_iov;
857
858 auio = uio_createwithbuffer(msg->msg_iovlen, 0,
859 UIO_SYSSPACE, UIO_WRITE, &uio_buf[0], sizeof(uio_buf));
860 if (tempp != NULL) {
861 int i;
862
863 for (i = 0; i < msg->msg_iovlen; i++) {
864 uio_addiov(auio,
865 CAST_USER_ADDR_T((tempp + i)->iov_base),
866 (tempp + i)->iov_len);
867 }
868
869 if (uio_resid(auio) < 0) {
870 error = EINVAL;
871 goto errorout;
872 }
873 }
874 }
875
876 if (sentlen != NULL) {
877 *sentlen = 0;
878 }
879
880 if (auio != NULL) {
881 datalen = uio_resid(auio);
882 } else {
883 datalen = data->m_pkthdr.len;
884 }
885
886 if (msg != NULL && msg->msg_control) {
887 if ((size_t)msg->msg_controllen < sizeof(struct cmsghdr)) {
888 error = EINVAL;
889 goto errorout;
890 }
891
892 if ((size_t)msg->msg_controllen > MLEN) {
893 error = EINVAL;
894 goto errorout;
895 }
896
897 control = m_get(M_NOWAIT, MT_CONTROL);
898 if (control == NULL) {
899 error = ENOMEM;
900 goto errorout;
901 }
902 memcpy(mtod(control, caddr_t), msg->msg_control,
903 msg->msg_controllen);
904 control->m_len = msg->msg_controllen;
905 }
906
907 error = sock->so_proto->pr_usrreqs->pru_sosend(sock, msg != NULL ?
908 (struct sockaddr *)msg->msg_name : NULL, auio, data,
909 control, flags);
910
911 /*
912 * Residual data is possible in the case of IO vectors but not
913 * in the mbuf case since the latter is treated as atomic send.
914 * If pru_sosend() consumed a portion of the iovecs data and
915 * the error returned is transient, treat it as success; this
916 * is consistent with sendit() behavior.
917 */
918 if (auio != NULL && uio_resid(auio) != datalen &&
919 (error == ERESTART || error == EINTR || error == EWOULDBLOCK)) {
920 error = 0;
921 }
922
923 if (error == 0 && sentlen != NULL) {
924 if (auio != NULL) {
925 *sentlen = datalen - uio_resid(auio);
926 } else {
927 *sentlen = datalen;
928 }
929 }
930
931 return error;
932
933 /*
934 * In cases where we detect an error before returning, we need to
935 * free the mbuf chain if there is one. sosend (and pru_sosend) will
936 * free the mbuf chain if they encounter an error.
937 */
938 errorout:
939 if (control) {
940 m_freem(control);
941 }
942 if (data) {
943 m_freem(data);
944 }
945 if (sentlen) {
946 *sentlen = 0;
947 }
948 return error;
949 }
950
951 errno_t
952 sock_send(socket_t sock, const struct msghdr *msg, int flags, size_t *sentlen)
953 {
954 if (msg == NULL || msg->msg_iov == NULL || msg->msg_iovlen < 1) {
955 return EINVAL;
956 }
957
958 return sock_send_internal(sock, msg, NULL, flags, sentlen);
959 }
960
961 errno_t
962 sock_sendmbuf(socket_t sock, const struct msghdr *msg, mbuf_t data,
963 int flags, size_t *sentlen)
964 {
965 if (data == NULL || (msg != NULL && (msg->msg_iov != NULL ||
966 msg->msg_iovlen != 0))) {
967 if (data != NULL) {
968 m_freem(data);
969 }
970 return EINVAL;
971 }
972 return sock_send_internal(sock, msg, data, flags, sentlen);
973 }
974
975 errno_t
976 sock_shutdown(socket_t sock, int how)
977 {
978 if (sock == NULL) {
979 return EINVAL;
980 }
981
982 return soshutdown(sock, how);
983 }
984
985 errno_t
986 sock_socket_common(int domain, int type, int protocol, sock_upcall callback,
987 void *context, socket_t *new_so, bool is_internal)
988 {
989 int error = 0;
990
991 if (new_so == NULL) {
992 return EINVAL;
993 }
994
995 /* socreate will create an initial so_count */
996 error = socreate(domain, new_so, type, protocol);
997 if (error == 0) {
998 /*
999 * This is an in-kernel socket
1000 */
1001 (*new_so)->so_flags1 |= SOF1_IN_KERNEL_SOCKET;
1002 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_in_kernel_total);
1003 if (is_internal) {
1004 INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_in_kernel_os_total);
1005 }
1006
1007 /* see comments in sock_setupcall() */
1008 if (callback != NULL) {
1009 sock_setupcall(*new_so, callback, context);
1010 }
1011 /*
1012 * last_pid and last_upid should be zero for sockets
1013 * created using sock_socket
1014 */
1015 (*new_so)->last_pid = 0;
1016 (*new_so)->last_upid = 0;
1017 }
1018 return error;
1019 }
1020
1021 errno_t
1022 sock_socket_internal(int domain, int type, int protocol, sock_upcall callback,
1023 void *context, socket_t *new_so)
1024 {
1025 return sock_socket_common(domain, type, protocol, callback,
1026 context, new_so, true);
1027 }
1028
1029 errno_t
1030 sock_socket(int domain, int type, int protocol, sock_upcall callback,
1031 void *context, socket_t *new_so)
1032 {
1033 return sock_socket_common(domain, type, protocol, callback,
1034 context, new_so, false);
1035 }
1036
1037 void
1038 sock_close(socket_t sock)
1039 {
1040 if (sock == NULL) {
1041 return;
1042 }
1043
1044 soclose(sock);
1045 }
1046
1047 /* Do we want this to be APPLE_PRIVATE API?: YES (LD 12/23/04) */
1048 void
1049 sock_retain(socket_t sock)
1050 {
1051 if (sock == NULL) {
1052 return;
1053 }
1054
1055 socket_lock(sock, 1);
1056 sock->so_retaincnt++;
1057 sock->so_usecount++; /* add extra reference for holding the socket */
1058 socket_unlock(sock, 1);
1059 }
1060
1061 /* Do we want this to be APPLE_PRIVATE API? */
1062 void
1063 sock_release(socket_t sock)
1064 {
1065 if (sock == NULL) {
1066 return;
1067 }
1068
1069 socket_lock(sock, 1);
1070 if (sock->so_upcallusecount > 0) {
1071 soclose_wait_locked(sock);
1072 }
1073
1074 sock->so_retaincnt--;
1075 if (sock->so_retaincnt < 0) {
1076 panic("%s: negative retain count (%d) for sock=%p\n",
1077 __func__, sock->so_retaincnt, sock);
1078 /* NOTREACHED */
1079 }
1080 /*
1081 * Check SS_NOFDREF in case a close happened as sock_retain()
1082 * was grabbing the lock
1083 */
1084 if ((sock->so_retaincnt == 0) && (sock->so_usecount == 2) &&
1085 (!(sock->so_state & SS_NOFDREF) ||
1086 (sock->so_flags & SOF_MP_SUBFLOW))) {
1087 /* close socket only if the FD is not holding it */
1088 soclose_locked(sock);
1089 } else {
1090 /* remove extra reference holding the socket */
1091 VERIFY(sock->so_usecount > 1);
1092 sock->so_usecount--;
1093 }
1094 socket_unlock(sock, 1);
1095 }
1096
1097 errno_t
1098 sock_setpriv(socket_t sock, int on)
1099 {
1100 if (sock == NULL) {
1101 return EINVAL;
1102 }
1103
1104 socket_lock(sock, 1);
1105 if (on) {
1106 sock->so_state |= SS_PRIV;
1107 } else {
1108 sock->so_state &= ~SS_PRIV;
1109 }
1110 socket_unlock(sock, 1);
1111 return 0;
1112 }
1113
1114 int
1115 sock_isconnected(socket_t sock)
1116 {
1117 int retval;
1118
1119 socket_lock(sock, 1);
1120 retval = ((sock->so_state & SS_ISCONNECTED) ? 1 : 0);
1121 socket_unlock(sock, 1);
1122 return retval;
1123 }
1124
1125 int
1126 sock_isnonblocking(socket_t sock)
1127 {
1128 int retval;
1129
1130 socket_lock(sock, 1);
1131 retval = ((sock->so_state & SS_NBIO) ? 1 : 0);
1132 socket_unlock(sock, 1);
1133 return retval;
1134 }
1135
1136 errno_t
1137 sock_gettype(socket_t sock, int *outDomain, int *outType, int *outProtocol)
1138 {
1139 socket_lock(sock, 1);
1140 if (outDomain != NULL) {
1141 *outDomain = SOCK_DOM(sock);
1142 }
1143 if (outType != NULL) {
1144 *outType = sock->so_type;
1145 }
1146 if (outProtocol != NULL) {
1147 *outProtocol = SOCK_PROTO(sock);
1148 }
1149 socket_unlock(sock, 1);
1150 return 0;
1151 }
1152
1153 /*
1154 * Return the listening socket of a pre-accepted socket. It returns the
1155 * listener (so_head) value of a given socket. This is intended to be
1156 * called by a socket filter during a filter attach (sf_attach) callback.
1157 * The value returned by this routine is safe to be used only in the
1158 * context of that callback, because we hold the listener's lock across
1159 * the sflt_initsock() call.
1160 */
1161 socket_t
1162 sock_getlistener(socket_t sock)
1163 {
1164 return sock->so_head;
1165 }
1166
1167 static inline void
1168 sock_set_tcp_stream_priority(socket_t sock)
1169 {
1170 if ((SOCK_DOM(sock) == PF_INET || SOCK_DOM(sock) == PF_INET6) &&
1171 SOCK_TYPE(sock) == SOCK_STREAM) {
1172 set_tcp_stream_priority(sock);
1173 }
1174 }
1175
1176 /*
1177 * Caller must have ensured socket is valid and won't be going away.
1178 */
1179 void
1180 socket_set_traffic_mgt_flags_locked(socket_t sock, u_int8_t flags)
1181 {
1182 u_int32_t soflags1 = 0;
1183
1184 if ((flags & TRAFFIC_MGT_SO_BACKGROUND)) {
1185 soflags1 |= SOF1_TRAFFIC_MGT_SO_BACKGROUND;
1186 }
1187 if ((flags & TRAFFIC_MGT_TCP_RECVBG)) {
1188 soflags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
1189 }
1190
1191 (void) OSBitOrAtomic(soflags1, &sock->so_flags1);
1192
1193 sock_set_tcp_stream_priority(sock);
1194 }
1195
1196 void
1197 socket_set_traffic_mgt_flags(socket_t sock, u_int8_t flags)
1198 {
1199 socket_lock(sock, 1);
1200 socket_set_traffic_mgt_flags_locked(sock, flags);
1201 socket_unlock(sock, 1);
1202 }
1203
1204 /*
1205 * Caller must have ensured socket is valid and won't be going away.
1206 */
1207 void
1208 socket_clear_traffic_mgt_flags_locked(socket_t sock, u_int8_t flags)
1209 {
1210 u_int32_t soflags1 = 0;
1211
1212 if ((flags & TRAFFIC_MGT_SO_BACKGROUND)) {
1213 soflags1 |= SOF1_TRAFFIC_MGT_SO_BACKGROUND;
1214 }
1215 if ((flags & TRAFFIC_MGT_TCP_RECVBG)) {
1216 soflags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
1217 }
1218
1219 (void) OSBitAndAtomic(~soflags1, &sock->so_flags1);
1220
1221 sock_set_tcp_stream_priority(sock);
1222 }
1223
1224 void
1225 socket_clear_traffic_mgt_flags(socket_t sock, u_int8_t flags)
1226 {
1227 socket_lock(sock, 1);
1228 socket_clear_traffic_mgt_flags_locked(sock, flags);
1229 socket_unlock(sock, 1);
1230 }
1231
1232
1233 /*
1234 * Caller must have ensured socket is valid and won't be going away.
1235 */
1236 errno_t
1237 socket_defunct(struct proc *p, socket_t so, int level)
1238 {
1239 errno_t retval;
1240
1241 if (level != SHUTDOWN_SOCKET_LEVEL_DISCONNECT_SVC &&
1242 level != SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL) {
1243 return EINVAL;
1244 }
1245
1246 socket_lock(so, 1);
1247 /*
1248 * SHUTDOWN_SOCKET_LEVEL_DISCONNECT_SVC level is meant to tear down
1249 * all of mDNSResponder IPC sockets, currently those of AF_UNIX; note
1250 * that this is an implementation artifact of mDNSResponder. We do
1251 * a quick test against the socket buffers for SB_UNIX, since that
1252 * would have been set by unp_attach() at socket creation time.
1253 */
1254 if (level == SHUTDOWN_SOCKET_LEVEL_DISCONNECT_SVC &&
1255 (so->so_rcv.sb_flags & so->so_snd.sb_flags & SB_UNIX) != SB_UNIX) {
1256 socket_unlock(so, 1);
1257 return EOPNOTSUPP;
1258 }
1259 retval = sosetdefunct(p, so, level, TRUE);
1260 if (retval == 0) {
1261 retval = sodefunct(p, so, level);
1262 }
1263 socket_unlock(so, 1);
1264 return retval;
1265 }
1266
1267 void
1268 sock_setupcalls_locked(socket_t sock, sock_upcall rcallback, void *rcontext,
1269 sock_upcall wcallback, void *wcontext, int locked)
1270 {
1271 if (rcallback != NULL) {
1272 sock->so_rcv.sb_flags |= SB_UPCALL;
1273 if (locked) {
1274 sock->so_rcv.sb_flags |= SB_UPCALL_LOCK;
1275 }
1276 sock->so_rcv.sb_upcall = rcallback;
1277 sock->so_rcv.sb_upcallarg = rcontext;
1278 } else {
1279 sock->so_rcv.sb_flags &= ~(SB_UPCALL | SB_UPCALL_LOCK);
1280 sock->so_rcv.sb_upcall = NULL;
1281 sock->so_rcv.sb_upcallarg = NULL;
1282 }
1283
1284 if (wcallback != NULL) {
1285 sock->so_snd.sb_flags |= SB_UPCALL;
1286 if (locked) {
1287 sock->so_snd.sb_flags |= SB_UPCALL_LOCK;
1288 }
1289 sock->so_snd.sb_upcall = wcallback;
1290 sock->so_snd.sb_upcallarg = wcontext;
1291 } else {
1292 sock->so_snd.sb_flags &= ~(SB_UPCALL | SB_UPCALL_LOCK);
1293 sock->so_snd.sb_upcall = NULL;
1294 sock->so_snd.sb_upcallarg = NULL;
1295 }
1296 }
1297
1298 errno_t
1299 sock_setupcall(socket_t sock, sock_upcall callback, void *context)
1300 {
1301 if (sock == NULL) {
1302 return EINVAL;
1303 }
1304
1305 /*
1306 * Note that we don't wait for any in progress upcall to complete.
1307 * On embedded, sock_setupcall() causes both read and write
1308 * callbacks to be set; on desktop, only read callback is set
1309 * to maintain legacy KPI behavior.
1310 *
1311 * The newer sock_setupcalls() KPI should be used instead to set
1312 * the read and write callbacks and their respective parameters.
1313 */
1314 socket_lock(sock, 1);
1315 #if CONFIG_EMBEDDED
1316 sock_setupcalls_locked(sock, callback, context, callback, context, 0);
1317 #else
1318 sock_setupcalls_locked(sock, callback, context, NULL, NULL, 0);
1319 #endif /* !CONFIG_EMBEDDED */
1320 socket_unlock(sock, 1);
1321
1322 return 0;
1323 }
1324
1325 errno_t
1326 sock_setupcalls(socket_t sock, sock_upcall rcallback, void *rcontext,
1327 sock_upcall wcallback, void *wcontext)
1328 {
1329 if (sock == NULL) {
1330 return EINVAL;
1331 }
1332
1333 /*
1334 * Note that we don't wait for any in progress upcall to complete.
1335 */
1336 socket_lock(sock, 1);
1337 sock_setupcalls_locked(sock, rcallback, rcontext, wcallback, wcontext, 0);
1338 socket_unlock(sock, 1);
1339
1340 return 0;
1341 }
1342
1343 void
1344 sock_catchevents_locked(socket_t sock, sock_evupcall ecallback, void *econtext,
1345 u_int32_t emask)
1346 {
1347 socket_lock_assert_owned(sock);
1348
1349 /*
1350 * Note that we don't wait for any in progress upcall to complete.
1351 */
1352 if (ecallback != NULL) {
1353 sock->so_event = ecallback;
1354 sock->so_eventarg = econtext;
1355 sock->so_eventmask = emask;
1356 } else {
1357 sock->so_event = sonullevent;
1358 sock->so_eventarg = NULL;
1359 sock->so_eventmask = 0;
1360 }
1361 }
1362
1363 errno_t
1364 sock_catchevents(socket_t sock, sock_evupcall ecallback, void *econtext,
1365 u_int32_t emask)
1366 {
1367 if (sock == NULL) {
1368 return EINVAL;
1369 }
1370
1371 socket_lock(sock, 1);
1372 sock_catchevents_locked(sock, ecallback, econtext, emask);
1373 socket_unlock(sock, 1);
1374
1375 return 0;
1376 }
1377
1378 /*
1379 * Returns true whether or not a socket belongs to the kernel.
1380 */
1381 int
1382 sock_iskernel(socket_t so)
1383 {
1384 return so && so->last_pid == 0;
1385 }