1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1988, 1990, 1993 5 * The Regents of the University of California. 6 * Copyright (c) 2004 The FreeBSD Foundation 7 * Copyright (c) 2004-2008 Robert N. M. Watson 8 * All rights reserved. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 /* 36 * Comments on the socket life cycle: 37 * 38 * soalloc() sets of socket layer state for a socket, called only by 39 * socreate() and sonewconn(). Socket layer private. 40 * 41 * sodealloc() tears down socket layer state for a socket, called only by 42 * sofree() and sonewconn(). Socket layer private. 43 * 44 * pr_attach() associates protocol layer state with an allocated socket; 45 * called only once, may fail, aborting socket allocation. This is called 46 * from socreate() and sonewconn(). Socket layer private. 47 * 48 * pr_detach() disassociates protocol layer state from an attached socket, 49 * and will be called exactly once for sockets in which pr_attach() has 50 * been successfully called. If pr_attach() returned an error, 51 * pr_detach() will not be called. Socket layer private. 52 * 53 * pr_abort() and pr_close() notify the protocol layer that the last 54 * consumer of a socket is starting to tear down the socket, and that the 55 * protocol should terminate the connection. Historically, pr_abort() also 56 * detached protocol state from the socket state, but this is no longer the 57 * case. pr_fdclose() is called when userspace invokes close(2) on a socket 58 * file descriptor. 59 * 60 * socreate() creates a socket and attaches protocol state. This is a public 61 * interface that may be used by socket layer consumers to create new 62 * sockets. 63 * 64 * sonewconn() creates a socket and attaches protocol state. This is a 65 * public interface that may be used by protocols to create new sockets when 66 * a new connection is received and will be available for accept() on a 67 * listen socket. 68 * 69 * soclose() destroys a socket after possibly waiting for it to disconnect. 70 * This is a public interface that socket consumers should use to close and 71 * release a socket when done with it. 72 * 73 * soabort() destroys a socket without waiting for it to disconnect (used 74 * only for incoming connections that are already partially or fully 75 * connected). This is used internally by the socket layer when clearing 76 * listen socket queues (due to overflow or close on the listen socket), but 77 * is also a public interface protocols may use to abort connections in 78 * their incomplete listen queues should they no longer be required. Sockets 79 * placed in completed connection listen queues should not be aborted for 80 * reasons described in the comment above the soclose() implementation. This 81 * is not a general purpose close routine, and except in the specific 82 * circumstances described here, should not be used. 83 * 84 * sofree() will free a socket and its protocol state if all references on 85 * the socket have been released, and is the public interface to attempt to 86 * free a socket when a reference is removed. This is a socket layer private 87 * interface. 88 * 89 * NOTE: In addition to socreate() and soclose(), which provide a single 90 * socket reference to the consumer to be managed as required, there are two 91 * calls to explicitly manage socket references, soref(), and sorele(). 92 * Currently, these are generally required only when transitioning a socket 93 * from a listen queue to a file descriptor, in order to prevent garbage 94 * collection of the socket at an untimely moment. For a number of reasons, 95 * these interfaces are not preferred, and should be avoided. 96 * 97 * NOTE: With regard to VNETs the general rule is that callers do not set 98 * curvnet. Exceptions to this rule include soabort(), sodisconnect(), 99 * sofree(), sorele(), sonewconn() and sorflush(), which are usually called 100 * from a pre-set VNET context. sopoll_generic() currently does not need a 101 * VNET context to be set. 102 */ 103 104 #include <sys/cdefs.h> 105 #include "opt_inet.h" 106 #include "opt_inet6.h" 107 #include "opt_kern_tls.h" 108 #include "opt_ktrace.h" 109 #include "opt_sctp.h" 110 111 #include <sys/param.h> 112 #include <sys/systm.h> 113 #include <sys/capsicum.h> 114 #include <sys/fcntl.h> 115 #include <sys/limits.h> 116 #include <sys/lock.h> 117 #include <sys/mac.h> 118 #include <sys/malloc.h> 119 #include <sys/mbuf.h> 120 #include <sys/mutex.h> 121 #include <sys/domain.h> 122 #include <sys/file.h> /* for struct knote */ 123 #include <sys/hhook.h> 124 #include <sys/kernel.h> 125 #include <sys/khelp.h> 126 #include <sys/kthread.h> 127 #include <sys/ktls.h> 128 #include <sys/event.h> 129 #include <sys/eventhandler.h> 130 #include <sys/poll.h> 131 #include <sys/proc.h> 132 #include <sys/protosw.h> 133 #include <sys/sbuf.h> 134 #include <sys/socket.h> 135 #include <sys/socketvar.h> 136 #include <sys/resourcevar.h> 137 #include <net/route.h> 138 #include <sys/sched.h> 139 #include <sys/signalvar.h> 140 #include <sys/smp.h> 141 #include <sys/stat.h> 142 #include <sys/sx.h> 143 #include <sys/sysctl.h> 144 #include <sys/taskqueue.h> 145 #include <sys/uio.h> 146 #include <sys/un.h> 147 #include <sys/unpcb.h> 148 #include <sys/jail.h> 149 #include <sys/syslog.h> 150 #include <netinet/in.h> 151 #include <netinet/in_pcb.h> 152 #include <netinet/tcp.h> 153 154 #include <net/vnet.h> 155 156 #include <security/mac/mac_framework.h> 157 #include <security/mac/mac_internal.h> 158 159 #include <vm/uma.h> 160 161 #ifdef COMPAT_FREEBSD32 162 #include <sys/mount.h> 163 #include <sys/sysent.h> 164 #include <compat/freebsd32/freebsd32.h> 165 #endif 166 167 static int soreceive_generic_locked(struct socket *so, 168 struct sockaddr **psa, struct uio *uio, struct mbuf **mp, 169 struct mbuf **controlp, int *flagsp); 170 static int soreceive_rcvoob(struct socket *so, struct uio *uio, 171 int flags); 172 static int soreceive_stream_locked(struct socket *so, struct sockbuf *sb, 173 struct sockaddr **psa, struct uio *uio, struct mbuf **mp, 174 struct mbuf **controlp, int flags); 175 static int sosend_generic_locked(struct socket *so, struct sockaddr *addr, 176 struct uio *uio, struct mbuf *top, struct mbuf *control, 177 int flags, struct thread *td); 178 static void so_rdknl_lock(void *); 179 static void so_rdknl_unlock(void *); 180 static void so_rdknl_assert_lock(void *, int); 181 static void so_wrknl_lock(void *); 182 static void so_wrknl_unlock(void *); 183 static void so_wrknl_assert_lock(void *, int); 184 185 static void filt_sordetach(struct knote *kn); 186 static int filt_soread(struct knote *kn, long hint); 187 static void filt_sowdetach(struct knote *kn); 188 static int filt_sowrite(struct knote *kn, long hint); 189 static int filt_soempty(struct knote *kn, long hint); 190 191 static const struct filterops soread_filtops = { 192 .f_isfd = 1, 193 .f_detach = filt_sordetach, 194 .f_event = filt_soread, 195 .f_copy = knote_triv_copy, 196 }; 197 static const struct filterops sowrite_filtops = { 198 .f_isfd = 1, 199 .f_detach = filt_sowdetach, 200 .f_event = filt_sowrite, 201 .f_copy = knote_triv_copy, 202 }; 203 static const struct filterops soempty_filtops = { 204 .f_isfd = 1, 205 .f_detach = filt_sowdetach, 206 .f_event = filt_soempty, 207 .f_copy = knote_triv_copy, 208 }; 209 210 so_gen_t so_gencnt; /* generation count for sockets */ 211 212 MALLOC_DEFINE(M_SONAME, "soname", "socket name"); 213 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block"); 214 215 #define VNET_SO_ASSERT(so) \ 216 VNET_ASSERT(curvnet != NULL, \ 217 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so))); 218 219 #ifdef SOCKET_HHOOK 220 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]); 221 #define V_socket_hhh VNET(socket_hhh) 222 static inline int hhook_run_socket(struct socket *, void *, int32_t); 223 #endif 224 225 #ifdef COMPAT_FREEBSD32 226 #ifdef __amd64__ 227 /* off_t has 4-byte alignment on i386 but not on other 32-bit platforms. */ 228 #define __splice32_packed __packed 229 #else 230 #define __splice32_packed 231 #endif 232 struct splice32 { 233 int32_t sp_fd; 234 int64_t sp_max; 235 struct timeval32 sp_idle; 236 } __splice32_packed; 237 #undef __splice32_packed 238 #endif 239 240 /* 241 * Limit on the number of connections in the listen queue waiting 242 * for accept(2). 243 * NB: The original sysctl somaxconn is still available but hidden 244 * to prevent confusion about the actual purpose of this number. 245 */ 246 VNET_DEFINE_STATIC(u_int, somaxconn) = SOMAXCONN; 247 #define V_somaxconn VNET(somaxconn) 248 249 static int 250 sysctl_somaxconn(SYSCTL_HANDLER_ARGS) 251 { 252 int error; 253 u_int val; 254 255 val = V_somaxconn; 256 error = sysctl_handle_int(oidp, &val, 0, req); 257 if (error || !req->newptr ) 258 return (error); 259 260 /* 261 * The purpose of the UINT_MAX / 3 limit, is so that the formula 262 * 3 * sol_qlimit / 2 263 * below, will not overflow. 264 */ 265 266 if (val < 1 || val > UINT_MAX / 3) 267 return (EINVAL); 268 269 V_somaxconn = val; 270 return (0); 271 } 272 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, 273 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, sizeof(u_int), 274 sysctl_somaxconn, "IU", 275 "Maximum listen socket pending connection accept queue size"); 276 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, 277 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, 278 sizeof(u_int), sysctl_somaxconn, "IU", 279 "Maximum listen socket pending connection accept queue size (compat)"); 280 281 static u_int numopensockets; 282 static int 283 sysctl_numopensockets(SYSCTL_HANDLER_ARGS) 284 { 285 u_int val; 286 287 #ifdef VIMAGE 288 if(!IS_DEFAULT_VNET(curvnet)) 289 val = curvnet->vnet_sockcnt; 290 else 291 #endif 292 val = numopensockets; 293 return (sysctl_handle_int(oidp, &val, 0, req)); 294 } 295 SYSCTL_PROC(_kern_ipc, OID_AUTO, numopensockets, 296 CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_VNET, 0, sizeof(u_int), 297 sysctl_numopensockets, "IU", "Number of open sockets"); 298 299 /* 300 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket 301 * so_gencnt field. 302 */ 303 static struct mtx so_global_mtx; 304 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF); 305 306 /* 307 * General IPC sysctl name space, used by sockets and a variety of other IPC 308 * types. 309 */ 310 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 311 "IPC"); 312 313 /* 314 * Initialize the socket subsystem and set up the socket 315 * memory allocator. 316 */ 317 static uma_zone_t socket_zone; 318 int maxsockets; 319 320 static void 321 socket_zone_change(void *tag) 322 { 323 324 maxsockets = uma_zone_set_max(socket_zone, maxsockets); 325 } 326 327 static int splice_init_state; 328 static struct sx splice_init_lock; 329 SX_SYSINIT(splice_init_lock, &splice_init_lock, "splice_init"); 330 331 static SYSCTL_NODE(_kern_ipc, OID_AUTO, splice, CTLFLAG_RW, 0, 332 "Settings relating to the SO_SPLICE socket option"); 333 334 static bool splice_receive_stream = true; 335 SYSCTL_BOOL(_kern_ipc_splice, OID_AUTO, receive_stream, CTLFLAG_RWTUN, 336 &splice_receive_stream, 0, 337 "Use soreceive_stream() for stream splices"); 338 339 static uma_zone_t splice_zone; 340 static struct proc *splice_proc; 341 struct splice_wq { 342 struct mtx mtx; 343 STAILQ_HEAD(, so_splice) head; 344 bool running; 345 } __aligned(CACHE_LINE_SIZE); 346 static struct splice_wq *splice_wq; 347 static uint32_t splice_index = 0; 348 349 static void so_splice_timeout(void *arg, int pending); 350 static void so_splice_xfer(struct so_splice *s); 351 static int so_unsplice(struct socket *so, bool timeout); 352 353 static void 354 splice_work_thread(void *ctx) 355 { 356 struct splice_wq *wq = ctx; 357 struct so_splice *s, *s_temp; 358 STAILQ_HEAD(, so_splice) local_head; 359 int cpu; 360 361 cpu = wq - splice_wq; 362 if (bootverbose) 363 printf("starting so_splice worker thread for CPU %d\n", cpu); 364 365 for (;;) { 366 mtx_lock(&wq->mtx); 367 while (STAILQ_EMPTY(&wq->head)) { 368 wq->running = false; 369 mtx_sleep(wq, &wq->mtx, 0, "-", 0); 370 wq->running = true; 371 } 372 STAILQ_INIT(&local_head); 373 STAILQ_CONCAT(&local_head, &wq->head); 374 STAILQ_INIT(&wq->head); 375 mtx_unlock(&wq->mtx); 376 STAILQ_FOREACH_SAFE(s, &local_head, next, s_temp) { 377 mtx_lock(&s->mtx); 378 CURVNET_SET(s->src->so_vnet); 379 so_splice_xfer(s); 380 CURVNET_RESTORE(); 381 } 382 } 383 } 384 385 static void 386 so_splice_dispatch_async(struct so_splice *sp) 387 { 388 struct splice_wq *wq; 389 bool running; 390 391 wq = &splice_wq[sp->wq_index]; 392 mtx_lock(&wq->mtx); 393 STAILQ_INSERT_TAIL(&wq->head, sp, next); 394 running = wq->running; 395 mtx_unlock(&wq->mtx); 396 if (!running) 397 wakeup(wq); 398 } 399 400 void 401 so_splice_dispatch(struct so_splice *sp) 402 { 403 mtx_assert(&sp->mtx, MA_OWNED); 404 405 if (sp->state != SPLICE_IDLE) { 406 mtx_unlock(&sp->mtx); 407 } else { 408 sp->state = SPLICE_QUEUED; 409 mtx_unlock(&sp->mtx); 410 so_splice_dispatch_async(sp); 411 } 412 } 413 414 static int 415 splice_zinit(void *mem, int size __unused, int flags __unused) 416 { 417 struct so_splice *s; 418 419 s = (struct so_splice *)mem; 420 mtx_init(&s->mtx, "so_splice", NULL, MTX_DEF); 421 return (0); 422 } 423 424 static void 425 splice_zfini(void *mem, int size) 426 { 427 struct so_splice *s; 428 429 s = (struct so_splice *)mem; 430 mtx_destroy(&s->mtx); 431 } 432 433 static int 434 splice_init(void) 435 { 436 struct thread *td; 437 int error, i, state; 438 439 state = atomic_load_acq_int(&splice_init_state); 440 if (__predict_true(state > 0)) 441 return (0); 442 if (state < 0) 443 return (ENXIO); 444 sx_xlock(&splice_init_lock); 445 if (splice_init_state != 0) { 446 sx_xunlock(&splice_init_lock); 447 return (0); 448 } 449 450 splice_zone = uma_zcreate("splice", sizeof(struct so_splice), NULL, 451 NULL, splice_zinit, splice_zfini, UMA_ALIGN_CACHE, 0); 452 453 splice_wq = mallocarray(mp_maxid + 1, sizeof(*splice_wq), M_TEMP, 454 M_WAITOK | M_ZERO); 455 456 /* 457 * Initialize the workqueues to run the splice work. We create a 458 * work queue for each CPU. 459 */ 460 CPU_FOREACH(i) { 461 STAILQ_INIT(&splice_wq[i].head); 462 mtx_init(&splice_wq[i].mtx, "splice work queue", NULL, MTX_DEF); 463 } 464 465 /* Start kthreads for each workqueue. */ 466 error = 0; 467 CPU_FOREACH(i) { 468 error = kproc_kthread_add(splice_work_thread, &splice_wq[i], 469 &splice_proc, &td, 0, 0, "so_splice", "thr_%d", i); 470 if (error) { 471 printf("Can't add so_splice thread %d error %d\n", 472 i, error); 473 break; 474 } 475 476 /* 477 * It's possible to create loops with SO_SPLICE; ensure that 478 * worker threads aren't able to starve the system too easily. 479 */ 480 thread_lock(td); 481 sched_prio(td, PUSER); 482 thread_unlock(td); 483 } 484 485 splice_init_state = error != 0 ? -1 : 1; 486 sx_xunlock(&splice_init_lock); 487 488 return (error); 489 } 490 491 /* 492 * Lock a pair of socket's I/O locks for splicing. Avoid blocking while holding 493 * one lock in order to avoid potential deadlocks in case there is some other 494 * code path which acquires more than one I/O lock at a time. 495 */ 496 static void 497 splice_lock_pair(struct socket *so_src, struct socket *so_dst) 498 { 499 int error; 500 501 for (;;) { 502 error = SOCK_IO_SEND_LOCK(so_dst, SBL_WAIT | SBL_NOINTR); 503 KASSERT(error == 0, 504 ("%s: failed to lock send I/O lock: %d", __func__, error)); 505 error = SOCK_IO_RECV_LOCK(so_src, 0); 506 KASSERT(error == 0 || error == EWOULDBLOCK, 507 ("%s: failed to lock recv I/O lock: %d", __func__, error)); 508 if (error == 0) 509 break; 510 SOCK_IO_SEND_UNLOCK(so_dst); 511 512 error = SOCK_IO_RECV_LOCK(so_src, SBL_WAIT | SBL_NOINTR); 513 KASSERT(error == 0, 514 ("%s: failed to lock recv I/O lock: %d", __func__, error)); 515 error = SOCK_IO_SEND_LOCK(so_dst, 0); 516 KASSERT(error == 0 || error == EWOULDBLOCK, 517 ("%s: failed to lock send I/O lock: %d", __func__, error)); 518 if (error == 0) 519 break; 520 SOCK_IO_RECV_UNLOCK(so_src); 521 } 522 } 523 524 static void 525 splice_unlock_pair(struct socket *so_src, struct socket *so_dst) 526 { 527 SOCK_IO_RECV_UNLOCK(so_src); 528 SOCK_IO_SEND_UNLOCK(so_dst); 529 } 530 531 /* 532 * Move data from the source to the sink. Assumes that both of the relevant 533 * socket I/O locks are held. 534 */ 535 static int 536 so_splice_xfer_data(struct socket *so_src, struct socket *so_dst, off_t max, 537 ssize_t *lenp) 538 { 539 struct uio uio; 540 struct mbuf *m; 541 struct sockbuf *sb_src, *sb_dst; 542 ssize_t len; 543 long space; 544 int error, flags; 545 546 SOCK_IO_RECV_ASSERT_LOCKED(so_src); 547 SOCK_IO_SEND_ASSERT_LOCKED(so_dst); 548 549 error = 0; 550 m = NULL; 551 memset(&uio, 0, sizeof(uio)); 552 553 sb_src = &so_src->so_rcv; 554 sb_dst = &so_dst->so_snd; 555 556 space = sbspace(sb_dst); 557 if (space < 0) 558 space = 0; 559 len = MIN(max, MIN(space, sbavail(sb_src))); 560 if (len == 0) { 561 SOCK_RECVBUF_LOCK(so_src); 562 if ((sb_src->sb_state & SBS_CANTRCVMORE) != 0) 563 error = EPIPE; 564 SOCK_RECVBUF_UNLOCK(so_src); 565 } else { 566 flags = MSG_DONTWAIT; 567 uio.uio_resid = len; 568 if (splice_receive_stream && sb_src->sb_tls_info == NULL) { 569 error = soreceive_stream_locked(so_src, sb_src, NULL, 570 &uio, &m, NULL, flags); 571 } else { 572 error = soreceive_generic_locked(so_src, NULL, 573 &uio, &m, NULL, &flags); 574 } 575 if (error != 0 && m != NULL) { 576 m_freem(m); 577 m = NULL; 578 } 579 } 580 if (m != NULL) { 581 len -= uio.uio_resid; 582 error = sosend_generic_locked(so_dst, NULL, NULL, m, NULL, 583 MSG_DONTWAIT, curthread); 584 } else if (error == 0) { 585 len = 0; 586 SOCK_SENDBUF_LOCK(so_dst); 587 if ((sb_dst->sb_state & SBS_CANTSENDMORE) != 0) 588 error = EPIPE; 589 SOCK_SENDBUF_UNLOCK(so_dst); 590 } 591 if (error == 0) 592 *lenp = len; 593 return (error); 594 } 595 596 /* 597 * Transfer data from the source to the sink. 598 */ 599 static void 600 so_splice_xfer(struct so_splice *sp) 601 { 602 struct socket *so_src, *so_dst; 603 off_t max; 604 ssize_t len; 605 int error; 606 607 mtx_assert(&sp->mtx, MA_OWNED); 608 KASSERT(sp->state == SPLICE_QUEUED || sp->state == SPLICE_CLOSING, 609 ("so_splice_xfer: invalid state %d", sp->state)); 610 KASSERT(sp->max != 0, ("so_splice_xfer: max == 0")); 611 612 if (sp->state == SPLICE_CLOSING) { 613 /* Userspace asked us to close the splice. */ 614 goto closing; 615 } 616 617 sp->state = SPLICE_RUNNING; 618 so_src = sp->src; 619 so_dst = sp->dst; 620 max = sp->max > 0 ? sp->max - so_src->so_splice_sent : OFF_MAX; 621 if (max < 0) 622 max = 0; 623 624 /* 625 * Lock the sockets in order to block userspace from doing anything 626 * sneaky. If an error occurs or one of the sockets can no longer 627 * transfer data, we will automatically unsplice. 628 */ 629 mtx_unlock(&sp->mtx); 630 splice_lock_pair(so_src, so_dst); 631 632 error = so_splice_xfer_data(so_src, so_dst, max, &len); 633 634 mtx_lock(&sp->mtx); 635 636 /* 637 * Update our stats while still holding the socket locks. This 638 * synchronizes with getsockopt(SO_SPLICE), see the comment there. 639 */ 640 if (error == 0) { 641 KASSERT(len >= 0, ("%s: len %zd < 0", __func__, len)); 642 so_src->so_splice_sent += len; 643 } 644 splice_unlock_pair(so_src, so_dst); 645 646 switch (sp->state) { 647 case SPLICE_CLOSING: 648 closing: 649 sp->state = SPLICE_CLOSED; 650 wakeup(sp); 651 mtx_unlock(&sp->mtx); 652 break; 653 case SPLICE_RUNNING: 654 if (error != 0 || 655 (sp->max > 0 && so_src->so_splice_sent >= sp->max)) { 656 sp->state = SPLICE_EXCEPTION; 657 soref(so_src); 658 mtx_unlock(&sp->mtx); 659 (void)so_unsplice(so_src, false); 660 sorele(so_src); 661 } else { 662 /* 663 * Locklessly check for additional bytes in the source's 664 * receive buffer and queue more work if possible. We 665 * may end up queuing needless work, but that's ok, and 666 * if we race with a thread inserting more data into the 667 * buffer and observe sbavail() == 0, the splice mutex 668 * ensures that splice_push() will queue more work for 669 * us. 670 */ 671 if (sbavail(&so_src->so_rcv) > 0 && 672 sbspace(&so_dst->so_snd) > 0) { 673 sp->state = SPLICE_QUEUED; 674 mtx_unlock(&sp->mtx); 675 so_splice_dispatch_async(sp); 676 } else { 677 sp->state = SPLICE_IDLE; 678 mtx_unlock(&sp->mtx); 679 } 680 } 681 break; 682 default: 683 __assert_unreachable(); 684 } 685 } 686 687 static void 688 socket_init(void *tag) 689 { 690 691 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL, 692 NULL, NULL, UMA_ALIGN_PTR, 0); 693 maxsockets = uma_zone_set_max(socket_zone, maxsockets); 694 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached"); 695 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL, 696 EVENTHANDLER_PRI_FIRST); 697 } 698 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL); 699 700 #ifdef SOCKET_HHOOK 701 static void 702 socket_hhook_register(int subtype) 703 { 704 705 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype, 706 &V_socket_hhh[subtype], 707 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0) 708 printf("%s: WARNING: unable to register hook\n", __func__); 709 } 710 711 static void 712 socket_hhook_deregister(int subtype) 713 { 714 715 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0) 716 printf("%s: WARNING: unable to deregister hook\n", __func__); 717 } 718 719 static void 720 socket_vnet_init(const void *unused __unused) 721 { 722 int i; 723 724 /* We expect a contiguous range */ 725 for (i = 0; i <= HHOOK_SOCKET_LAST; i++) 726 socket_hhook_register(i); 727 } 728 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, 729 socket_vnet_init, NULL); 730 731 static void 732 socket_vnet_uninit(const void *unused __unused) 733 { 734 int i; 735 736 for (i = 0; i <= HHOOK_SOCKET_LAST; i++) 737 socket_hhook_deregister(i); 738 } 739 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, 740 socket_vnet_uninit, NULL); 741 #endif /* SOCKET_HHOOK */ 742 743 /* 744 * Initialise maxsockets. This SYSINIT must be run after 745 * tunable_mbinit(). 746 */ 747 static void 748 init_maxsockets(void *ignored) 749 { 750 751 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets); 752 maxsockets = imax(maxsockets, maxfiles); 753 } 754 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL); 755 756 /* 757 * Sysctl to get and set the maximum global sockets limit. Notify protocols 758 * of the change so that they can update their dependent limits as required. 759 */ 760 static int 761 sysctl_maxsockets(SYSCTL_HANDLER_ARGS) 762 { 763 int error, newmaxsockets; 764 765 newmaxsockets = maxsockets; 766 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req); 767 if (error == 0 && req->newptr && newmaxsockets != maxsockets) { 768 if (newmaxsockets > maxsockets && 769 newmaxsockets <= maxfiles) { 770 maxsockets = newmaxsockets; 771 EVENTHANDLER_INVOKE(maxsockets_change); 772 } else 773 error = EINVAL; 774 } 775 return (error); 776 } 777 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, 778 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NOFETCH | CTLFLAG_MPSAFE, 779 &maxsockets, 0, sysctl_maxsockets, "IU", 780 "Maximum number of sockets available"); 781 782 /* 783 * Socket operation routines. These routines are called by the routines in 784 * sys_socket.c or from a system process, and implement the semantics of 785 * socket operations by switching out to the protocol specific routines. 786 */ 787 788 /* 789 * Get a socket structure from our zone, and initialize it. Note that it 790 * would probably be better to allocate socket and PCB at the same time, but 791 * I'm not convinced that all the protocols can be easily modified to do 792 * this. 793 * 794 * soalloc() returns a socket with a ref count of 0. 795 */ 796 static struct socket * 797 soalloc(struct vnet *vnet) 798 { 799 struct socket *so; 800 801 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO); 802 if (so == NULL) 803 return (NULL); 804 #ifdef MAC 805 if (mac_socket_init(so, M_NOWAIT) != 0) { 806 uma_zfree(socket_zone, so); 807 return (NULL); 808 } 809 #endif 810 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) { 811 uma_zfree(socket_zone, so); 812 return (NULL); 813 } 814 815 /* 816 * The socket locking protocol allows to lock 2 sockets at a time, 817 * however, the first one must be a listening socket. WITNESS lacks 818 * a feature to change class of an existing lock, so we use DUPOK. 819 */ 820 mtx_init(&so->so_lock, "socket", NULL, MTX_DEF | MTX_DUPOK); 821 mtx_init(&so->so_snd_mtx, "so_snd", NULL, MTX_DEF); 822 mtx_init(&so->so_rcv_mtx, "so_rcv", NULL, MTX_DEF); 823 so->so_rcv.sb_sel = &so->so_rdsel; 824 so->so_snd.sb_sel = &so->so_wrsel; 825 sx_init(&so->so_snd_sx, "so_snd_sx"); 826 sx_init(&so->so_rcv_sx, "so_rcv_sx"); 827 TAILQ_INIT(&so->so_snd.sb_aiojobq); 828 TAILQ_INIT(&so->so_rcv.sb_aiojobq); 829 TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so); 830 TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so); 831 #ifdef VIMAGE 832 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p", 833 __func__, __LINE__, so)); 834 so->so_vnet = vnet; 835 #endif 836 #ifdef SOCKET_HHOOK 837 /* We shouldn't need the so_global_mtx */ 838 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) { 839 /* Do we need more comprehensive error returns? */ 840 uma_zfree(socket_zone, so); 841 return (NULL); 842 } 843 #endif 844 mtx_lock(&so_global_mtx); 845 so->so_gencnt = ++so_gencnt; 846 ++numopensockets; 847 #ifdef VIMAGE 848 vnet->vnet_sockcnt++; 849 #endif 850 mtx_unlock(&so_global_mtx); 851 852 return (so); 853 } 854 855 /* 856 * Free the storage associated with a socket at the socket layer, tear down 857 * locks, labels, etc. All protocol state is assumed already to have been 858 * torn down (and possibly never set up) by the caller. 859 */ 860 void 861 sodealloc(struct socket *so) 862 { 863 864 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count)); 865 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL")); 866 867 mtx_lock(&so_global_mtx); 868 so->so_gencnt = ++so_gencnt; 869 --numopensockets; /* Could be below, but faster here. */ 870 #ifdef VIMAGE 871 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p", 872 __func__, __LINE__, so)); 873 so->so_vnet->vnet_sockcnt--; 874 #endif 875 mtx_unlock(&so_global_mtx); 876 #ifdef MAC 877 mac_socket_destroy(so); 878 #endif 879 #ifdef SOCKET_HHOOK 880 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE); 881 #endif 882 883 khelp_destroy_osd(&so->osd); 884 if (SOLISTENING(so)) { 885 if (so->sol_accept_filter != NULL) 886 accept_filt_setopt(so, NULL); 887 } else { 888 if (so->so_rcv.sb_hiwat) 889 (void)chgsbsize(so->so_cred->cr_uidinfo, 890 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY); 891 if (so->so_snd.sb_hiwat) 892 (void)chgsbsize(so->so_cred->cr_uidinfo, 893 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY); 894 sx_destroy(&so->so_snd_sx); 895 sx_destroy(&so->so_rcv_sx); 896 mtx_destroy(&so->so_snd_mtx); 897 mtx_destroy(&so->so_rcv_mtx); 898 } 899 crfree(so->so_cred); 900 mtx_destroy(&so->so_lock); 901 uma_zfree(socket_zone, so); 902 } 903 904 /* 905 * socreate returns a socket with a ref count of 1 and a file descriptor 906 * reference. The socket should be closed with soclose(). 907 */ 908 int 909 socreate(int dom, struct socket **aso, int type, int proto, 910 struct ucred *cred, struct thread *td) 911 { 912 struct protosw *prp; 913 struct socket *so; 914 int error; 915 916 /* 917 * XXX: divert(4) historically abused PF_INET. Keep this compatibility 918 * shim until all applications have been updated. 919 */ 920 if (__predict_false(dom == PF_INET && type == SOCK_RAW && 921 proto == IPPROTO_DIVERT)) { 922 dom = PF_DIVERT; 923 printf("%s uses obsolete way to create divert(4) socket\n", 924 td->td_proc->p_comm); 925 } 926 927 prp = pffindproto(dom, type, proto); 928 if (prp == NULL) { 929 /* No support for domain. */ 930 if (pffinddomain(dom) == NULL) 931 return (EAFNOSUPPORT); 932 /* No support for socket type. */ 933 if (proto == 0 && type != 0) 934 return (EPROTOTYPE); 935 return (EPROTONOSUPPORT); 936 } 937 938 MPASS(prp->pr_attach); 939 940 if ((prp->pr_flags & PR_CAPATTACH) == 0) { 941 if (CAP_TRACING(td)) 942 ktrcapfail(CAPFAIL_PROTO, &proto); 943 if (IN_CAPABILITY_MODE(td)) 944 return (ECAPMODE); 945 } 946 947 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0) 948 return (EPROTONOSUPPORT); 949 950 so = soalloc(CRED_TO_VNET(cred)); 951 if (so == NULL) 952 return (ENOBUFS); 953 954 so->so_type = type; 955 so->so_cred = crhold(cred); 956 if ((prp->pr_domain->dom_family == PF_INET) || 957 (prp->pr_domain->dom_family == PF_INET6) || 958 (prp->pr_domain->dom_family == PF_ROUTE)) 959 so->so_fibnum = td->td_proc->p_fibnum; 960 else 961 so->so_fibnum = 0; 962 so->so_proto = prp; 963 #ifdef MAC 964 mac_socket_create(cred, so); 965 #endif 966 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock, 967 so_rdknl_assert_lock); 968 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock, 969 so_wrknl_assert_lock); 970 if ((prp->pr_flags & PR_SOCKBUF) == 0) { 971 so->so_snd.sb_mtx = &so->so_snd_mtx; 972 so->so_rcv.sb_mtx = &so->so_rcv_mtx; 973 } 974 /* 975 * Auto-sizing of socket buffers is managed by the protocols and 976 * the appropriate flags must be set in the pr_attach() method. 977 */ 978 CURVNET_SET(so->so_vnet); 979 error = prp->pr_attach(so, proto, td); 980 CURVNET_RESTORE(); 981 if (error) { 982 sodealloc(so); 983 return (error); 984 } 985 soref(so); 986 *aso = so; 987 return (0); 988 } 989 990 #ifdef REGRESSION 991 static int regression_sonewconn_earlytest = 1; 992 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW, 993 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test"); 994 #endif 995 996 static int sooverprio = LOG_DEBUG; 997 SYSCTL_INT(_kern_ipc, OID_AUTO, sooverprio, CTLFLAG_RW, 998 &sooverprio, 0, "Log priority for listen socket overflows: 0..7 or -1 to disable"); 999 1000 static struct timeval overinterval = { 60, 0 }; 1001 SYSCTL_TIMEVAL_SEC(_kern_ipc, OID_AUTO, sooverinterval, CTLFLAG_RW, 1002 &overinterval, 1003 "Delay in seconds between warnings for listen socket overflows"); 1004 1005 /* 1006 * When an attempt at a new connection is noted on a socket which supports 1007 * accept(2), the protocol has two options: 1008 * 1) Call legacy sonewconn() function, which would call protocol attach 1009 * method, same as used for socket(2). 1010 * 2) Call solisten_clone(), do attach that is specific to a cloned connection, 1011 * and then call solisten_enqueue(). 1012 * 1013 * Note: the ref count on the socket is 0 on return. 1014 */ 1015 struct socket * 1016 solisten_clone(struct socket *head) 1017 { 1018 struct sbuf descrsb; 1019 struct socket *so; 1020 int len, overcount; 1021 u_int qlen; 1022 const char localprefix[] = "local:"; 1023 char descrbuf[SUNPATHLEN + sizeof(localprefix)]; 1024 #if defined(INET6) 1025 char addrbuf[INET6_ADDRSTRLEN]; 1026 #elif defined(INET) 1027 char addrbuf[INET_ADDRSTRLEN]; 1028 #endif 1029 bool dolog, over; 1030 1031 SOLISTEN_LOCK(head); 1032 over = (head->sol_qlen > 3 * head->sol_qlimit / 2); 1033 #ifdef REGRESSION 1034 if (regression_sonewconn_earlytest && over) { 1035 #else 1036 if (over) { 1037 #endif 1038 head->sol_overcount++; 1039 dolog = (sooverprio >= 0) && 1040 !!ratecheck(&head->sol_lastover, &overinterval); 1041 1042 /* 1043 * If we're going to log, copy the overflow count and queue 1044 * length from the listen socket before dropping the lock. 1045 * Also, reset the overflow count. 1046 */ 1047 if (dolog) { 1048 overcount = head->sol_overcount; 1049 head->sol_overcount = 0; 1050 qlen = head->sol_qlen; 1051 } 1052 SOLISTEN_UNLOCK(head); 1053 1054 if (dolog) { 1055 /* 1056 * Try to print something descriptive about the 1057 * socket for the error message. 1058 */ 1059 sbuf_new(&descrsb, descrbuf, sizeof(descrbuf), 1060 SBUF_FIXEDLEN); 1061 switch (head->so_proto->pr_domain->dom_family) { 1062 #if defined(INET) || defined(INET6) 1063 #ifdef INET 1064 case AF_INET: 1065 #endif 1066 #ifdef INET6 1067 case AF_INET6: 1068 if (head->so_proto->pr_domain->dom_family == 1069 AF_INET6 || 1070 (sotoinpcb(head)->inp_inc.inc_flags & 1071 INC_ISIPV6)) { 1072 ip6_sprintf(addrbuf, 1073 &sotoinpcb(head)->inp_inc.inc6_laddr); 1074 sbuf_printf(&descrsb, "[%s]", addrbuf); 1075 } else 1076 #endif 1077 { 1078 #ifdef INET 1079 inet_ntoa_r( 1080 sotoinpcb(head)->inp_inc.inc_laddr, 1081 addrbuf); 1082 sbuf_cat(&descrsb, addrbuf); 1083 #endif 1084 } 1085 sbuf_printf(&descrsb, ":%hu (proto %u)", 1086 ntohs(sotoinpcb(head)->inp_inc.inc_lport), 1087 head->so_proto->pr_protocol); 1088 break; 1089 #endif /* INET || INET6 */ 1090 case AF_UNIX: 1091 sbuf_cat(&descrsb, localprefix); 1092 if (sotounpcb(head)->unp_addr != NULL) 1093 len = 1094 sotounpcb(head)->unp_addr->sun_len - 1095 offsetof(struct sockaddr_un, 1096 sun_path); 1097 else 1098 len = 0; 1099 if (len > 0) 1100 sbuf_bcat(&descrsb, 1101 sotounpcb(head)->unp_addr->sun_path, 1102 len); 1103 else 1104 sbuf_cat(&descrsb, "(unknown)"); 1105 break; 1106 } 1107 1108 /* 1109 * If we can't print something more specific, at least 1110 * print the domain name. 1111 */ 1112 if (sbuf_finish(&descrsb) != 0 || 1113 sbuf_len(&descrsb) <= 0) { 1114 sbuf_clear(&descrsb); 1115 sbuf_cat(&descrsb, 1116 head->so_proto->pr_domain->dom_name ?: 1117 "unknown"); 1118 sbuf_finish(&descrsb); 1119 } 1120 KASSERT(sbuf_len(&descrsb) > 0, 1121 ("%s: sbuf creation failed", __func__)); 1122 /* 1123 * Preserve the historic listen queue overflow log 1124 * message, that starts with "sonewconn:". It has 1125 * been known to sysadmins for years and also test 1126 * sys/kern/sonewconn_overflow checks for it. 1127 */ 1128 if (head->so_cred == 0) { 1129 log(LOG_PRI(sooverprio), 1130 "sonewconn: pcb %p (%s): " 1131 "Listen queue overflow: %i already in " 1132 "queue awaiting acceptance (%d " 1133 "occurrences)\n", head->so_pcb, 1134 sbuf_data(&descrsb), 1135 qlen, overcount); 1136 } else { 1137 log(LOG_PRI(sooverprio), 1138 "sonewconn: pcb %p (%s): " 1139 "Listen queue overflow: " 1140 "%i already in queue awaiting acceptance " 1141 "(%d occurrences), euid %d, rgid %d, jail %s\n", 1142 head->so_pcb, sbuf_data(&descrsb), qlen, 1143 overcount, head->so_cred->cr_uid, 1144 head->so_cred->cr_rgid, 1145 head->so_cred->cr_prison ? 1146 head->so_cred->cr_prison->pr_name : 1147 "not_jailed"); 1148 } 1149 sbuf_delete(&descrsb); 1150 1151 overcount = 0; 1152 } 1153 1154 return (NULL); 1155 } 1156 SOLISTEN_UNLOCK(head); 1157 VNET_ASSERT(head->so_vnet != NULL, ("%s: so %p vnet is NULL", 1158 __func__, head)); 1159 so = soalloc(head->so_vnet); 1160 if (so == NULL) { 1161 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: " 1162 "limit reached or out of memory\n", 1163 __func__, head->so_pcb); 1164 return (NULL); 1165 } 1166 so->so_listen = head; 1167 so->so_type = head->so_type; 1168 /* 1169 * POSIX is ambiguous on what options an accept(2)ed socket should 1170 * inherit from the listener. Words "create a new socket" may be 1171 * interpreted as not inheriting anything. Best programming practice 1172 * for application developers is to not rely on such inheritance. 1173 * FreeBSD had historically inherited all so_options excluding 1174 * SO_ACCEPTCONN, which virtually means all SOL_SOCKET level options, 1175 * including those completely irrelevant to a new born socket. For 1176 * compatibility with older versions we will inherit a list of 1177 * meaningful options. 1178 * The crucial bit to inherit is SO_ACCEPTFILTER. We need it present 1179 * in the child socket for soisconnected() promoting socket from the 1180 * incomplete queue to complete. It will be cleared before the child 1181 * gets available to accept(2). 1182 */ 1183 so->so_options = head->so_options & (SO_ACCEPTFILTER | SO_KEEPALIVE | 1184 SO_DONTROUTE | SO_LINGER | SO_OOBINLINE | SO_NOSIGPIPE); 1185 so->so_linger = head->so_linger; 1186 so->so_state = head->so_state; 1187 so->so_fibnum = head->so_fibnum; 1188 so->so_proto = head->so_proto; 1189 so->so_cred = crhold(head->so_cred); 1190 #ifdef SOCKET_HHOOK 1191 if (V_socket_hhh[HHOOK_SOCKET_NEWCONN]->hhh_nhooks > 0) { 1192 if (hhook_run_socket(so, head, HHOOK_SOCKET_NEWCONN)) { 1193 sodealloc(so); 1194 log(LOG_DEBUG, "%s: hhook run failed\n", __func__); 1195 return (NULL); 1196 } 1197 } 1198 #endif 1199 #ifdef MAC 1200 mac_socket_newconn(head, so); 1201 #endif 1202 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock, 1203 so_rdknl_assert_lock); 1204 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock, 1205 so_wrknl_assert_lock); 1206 VNET_SO_ASSERT(head); 1207 if (soreserve(so, head->sol_sbsnd_hiwat, head->sol_sbrcv_hiwat)) { 1208 sodealloc(so); 1209 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n", 1210 __func__, head->so_pcb); 1211 return (NULL); 1212 } 1213 so->so_rcv.sb_lowat = head->sol_sbrcv_lowat; 1214 so->so_snd.sb_lowat = head->sol_sbsnd_lowat; 1215 so->so_rcv.sb_timeo = head->sol_sbrcv_timeo; 1216 so->so_snd.sb_timeo = head->sol_sbsnd_timeo; 1217 so->so_rcv.sb_flags = head->sol_sbrcv_flags & SB_AUTOSIZE; 1218 so->so_snd.sb_flags = head->sol_sbsnd_flags & 1219 (SB_AUTOSIZE | SB_AUTOLOWAT); 1220 if ((so->so_proto->pr_flags & PR_SOCKBUF) == 0) { 1221 so->so_snd.sb_mtx = &so->so_snd_mtx; 1222 so->so_rcv.sb_mtx = &so->so_rcv_mtx; 1223 } 1224 1225 return (so); 1226 } 1227 1228 /* Connstatus may be 0 or SS_ISCONNECTED. */ 1229 struct socket * 1230 sonewconn(struct socket *head, int connstatus) 1231 { 1232 struct socket *so; 1233 1234 if ((so = solisten_clone(head)) == NULL) 1235 return (NULL); 1236 1237 if (so->so_proto->pr_attach(so, 0, NULL) != 0) { 1238 sodealloc(so); 1239 log(LOG_DEBUG, "%s: pcb %p: pr_attach() failed\n", 1240 __func__, head->so_pcb); 1241 return (NULL); 1242 } 1243 1244 (void)solisten_enqueue(so, connstatus); 1245 1246 return (so); 1247 } 1248 1249 /* 1250 * Enqueue socket cloned by solisten_clone() to the listen queue of the 1251 * listener it has been cloned from. 1252 * 1253 * Return 'true' if socket landed on complete queue, otherwise 'false'. 1254 */ 1255 bool 1256 solisten_enqueue(struct socket *so, int connstatus) 1257 { 1258 struct socket *head = so->so_listen; 1259 1260 MPASS(refcount_load(&so->so_count) == 0); 1261 refcount_init(&so->so_count, 1); 1262 1263 SOLISTEN_LOCK(head); 1264 if (head->sol_accept_filter != NULL) 1265 connstatus = 0; 1266 so->so_state |= connstatus; 1267 soref(head); /* A socket on (in)complete queue refs head. */ 1268 if (connstatus) { 1269 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list); 1270 so->so_qstate = SQ_COMP; 1271 head->sol_qlen++; 1272 solisten_wakeup(head); /* unlocks */ 1273 return (true); 1274 } else { 1275 /* 1276 * Keep removing sockets from the head until there's room for 1277 * us to insert on the tail. In pre-locking revisions, this 1278 * was a simple if(), but as we could be racing with other 1279 * threads and soabort() requires dropping locks, we must 1280 * loop waiting for the condition to be true. 1281 */ 1282 while (head->sol_incqlen > head->sol_qlimit) { 1283 struct socket *sp; 1284 1285 sp = TAILQ_FIRST(&head->sol_incomp); 1286 TAILQ_REMOVE(&head->sol_incomp, sp, so_list); 1287 head->sol_incqlen--; 1288 SOCK_LOCK(sp); 1289 sp->so_qstate = SQ_NONE; 1290 sp->so_listen = NULL; 1291 SOCK_UNLOCK(sp); 1292 sorele_locked(head); /* does SOLISTEN_UNLOCK, head stays */ 1293 soabort(sp); 1294 SOLISTEN_LOCK(head); 1295 } 1296 TAILQ_INSERT_TAIL(&head->sol_incomp, so, so_list); 1297 so->so_qstate = SQ_INCOMP; 1298 head->sol_incqlen++; 1299 SOLISTEN_UNLOCK(head); 1300 return (false); 1301 } 1302 } 1303 1304 #if defined(SCTP) || defined(SCTP_SUPPORT) 1305 /* 1306 * Socket part of sctp_peeloff(). Detach a new socket from an 1307 * association. The new socket is returned with a reference. 1308 * 1309 * XXXGL: reduce copy-paste with solisten_clone(). 1310 */ 1311 struct socket * 1312 sopeeloff(struct socket *head) 1313 { 1314 struct socket *so; 1315 1316 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p", 1317 __func__, __LINE__, head)); 1318 so = soalloc(head->so_vnet); 1319 if (so == NULL) { 1320 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: " 1321 "limit reached or out of memory\n", 1322 __func__, head->so_pcb); 1323 return (NULL); 1324 } 1325 so->so_type = head->so_type; 1326 so->so_options = head->so_options; 1327 so->so_linger = head->so_linger; 1328 so->so_state = (head->so_state & SS_NBIO) | SS_ISCONNECTED; 1329 so->so_fibnum = head->so_fibnum; 1330 so->so_proto = head->so_proto; 1331 so->so_cred = crhold(head->so_cred); 1332 #ifdef MAC 1333 mac_socket_newconn(head, so); 1334 #endif 1335 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock, 1336 so_rdknl_assert_lock); 1337 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock, 1338 so_wrknl_assert_lock); 1339 VNET_SO_ASSERT(head); 1340 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) { 1341 sodealloc(so); 1342 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n", 1343 __func__, head->so_pcb); 1344 return (NULL); 1345 } 1346 if (so->so_proto->pr_attach(so, 0, NULL)) { 1347 sodealloc(so); 1348 log(LOG_DEBUG, "%s: pcb %p: pr_attach() failed\n", 1349 __func__, head->so_pcb); 1350 return (NULL); 1351 } 1352 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat; 1353 so->so_snd.sb_lowat = head->so_snd.sb_lowat; 1354 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo; 1355 so->so_snd.sb_timeo = head->so_snd.sb_timeo; 1356 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE; 1357 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE; 1358 if ((so->so_proto->pr_flags & PR_SOCKBUF) == 0) { 1359 so->so_snd.sb_mtx = &so->so_snd_mtx; 1360 so->so_rcv.sb_mtx = &so->so_rcv_mtx; 1361 } 1362 1363 soref(so); 1364 1365 return (so); 1366 } 1367 #endif /* SCTP */ 1368 1369 int 1370 sobind(struct socket *so, struct sockaddr *nam, struct thread *td) 1371 { 1372 int error; 1373 1374 CURVNET_SET(so->so_vnet); 1375 error = so->so_proto->pr_bind(so, nam, td); 1376 CURVNET_RESTORE(); 1377 return (error); 1378 } 1379 1380 int 1381 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td) 1382 { 1383 int error; 1384 1385 CURVNET_SET(so->so_vnet); 1386 error = so->so_proto->pr_bindat(fd, so, nam, td); 1387 CURVNET_RESTORE(); 1388 return (error); 1389 } 1390 1391 /* 1392 * solisten() transitions a socket from a non-listening state to a listening 1393 * state, but can also be used to update the listen queue depth on an 1394 * existing listen socket. The protocol will call back into the sockets 1395 * layer using solisten_proto_check() and solisten_proto() to check and set 1396 * socket-layer listen state. Call backs are used so that the protocol can 1397 * acquire both protocol and socket layer locks in whatever order is required 1398 * by the protocol. 1399 * 1400 * Protocol implementors are advised to hold the socket lock across the 1401 * socket-layer test and set to avoid races at the socket layer. 1402 */ 1403 int 1404 solisten(struct socket *so, int backlog, struct thread *td) 1405 { 1406 int error; 1407 1408 CURVNET_SET(so->so_vnet); 1409 error = so->so_proto->pr_listen(so, backlog, td); 1410 CURVNET_RESTORE(); 1411 return (error); 1412 } 1413 1414 /* 1415 * Prepare for a call to solisten_proto(). Acquire all socket buffer locks in 1416 * order to interlock with socket I/O. 1417 */ 1418 int 1419 solisten_proto_check(struct socket *so) 1420 { 1421 SOCK_LOCK_ASSERT(so); 1422 1423 if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING | 1424 SS_ISDISCONNECTING)) != 0) 1425 return (EINVAL); 1426 1427 /* 1428 * Sleeping is not permitted here, so simply fail if userspace is 1429 * attempting to transmit or receive on the socket. This kind of 1430 * transient failure is not ideal, but it should occur only if userspace 1431 * is misusing the socket interfaces. 1432 */ 1433 if (!sx_try_xlock(&so->so_snd_sx)) 1434 return (EAGAIN); 1435 if (!sx_try_xlock(&so->so_rcv_sx)) { 1436 sx_xunlock(&so->so_snd_sx); 1437 return (EAGAIN); 1438 } 1439 mtx_lock(&so->so_snd_mtx); 1440 mtx_lock(&so->so_rcv_mtx); 1441 1442 /* Interlock with soo_aio_queue() and KTLS. */ 1443 if (!SOLISTENING(so)) { 1444 bool ktls; 1445 1446 #ifdef KERN_TLS 1447 ktls = so->so_snd.sb_tls_info != NULL || 1448 so->so_rcv.sb_tls_info != NULL; 1449 #else 1450 ktls = false; 1451 #endif 1452 if (ktls || 1453 (so->so_snd.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0 || 1454 (so->so_rcv.sb_flags & (SB_AIO | SB_AIO_RUNNING)) != 0) { 1455 solisten_proto_abort(so); 1456 return (EINVAL); 1457 } 1458 } 1459 1460 return (0); 1461 } 1462 1463 /* 1464 * Undo the setup done by solisten_proto_check(). 1465 */ 1466 void 1467 solisten_proto_abort(struct socket *so) 1468 { 1469 mtx_unlock(&so->so_snd_mtx); 1470 mtx_unlock(&so->so_rcv_mtx); 1471 sx_xunlock(&so->so_snd_sx); 1472 sx_xunlock(&so->so_rcv_sx); 1473 } 1474 1475 void 1476 solisten_proto(struct socket *so, int backlog) 1477 { 1478 int sbrcv_lowat, sbsnd_lowat; 1479 u_int sbrcv_hiwat, sbsnd_hiwat; 1480 short sbrcv_flags, sbsnd_flags; 1481 sbintime_t sbrcv_timeo, sbsnd_timeo; 1482 1483 SOCK_LOCK_ASSERT(so); 1484 KASSERT((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING | 1485 SS_ISDISCONNECTING)) == 0, 1486 ("%s: bad socket state %p", __func__, so)); 1487 1488 if (SOLISTENING(so)) 1489 goto listening; 1490 1491 /* 1492 * Change this socket to listening state. 1493 */ 1494 sbrcv_lowat = so->so_rcv.sb_lowat; 1495 sbsnd_lowat = so->so_snd.sb_lowat; 1496 sbrcv_hiwat = so->so_rcv.sb_hiwat; 1497 sbsnd_hiwat = so->so_snd.sb_hiwat; 1498 sbrcv_flags = so->so_rcv.sb_flags; 1499 sbsnd_flags = so->so_snd.sb_flags; 1500 sbrcv_timeo = so->so_rcv.sb_timeo; 1501 sbsnd_timeo = so->so_snd.sb_timeo; 1502 1503 #ifdef MAC 1504 mac_socketpeer_label_free(so->so_peerlabel); 1505 #endif 1506 1507 if (!(so->so_proto->pr_flags & PR_SOCKBUF)) { 1508 sbdestroy(so, SO_SND); 1509 sbdestroy(so, SO_RCV); 1510 } 1511 1512 #ifdef INVARIANTS 1513 bzero(&so->so_rcv, 1514 sizeof(struct socket) - offsetof(struct socket, so_rcv)); 1515 #endif 1516 1517 so->sol_sbrcv_lowat = sbrcv_lowat; 1518 so->sol_sbsnd_lowat = sbsnd_lowat; 1519 so->sol_sbrcv_hiwat = sbrcv_hiwat; 1520 so->sol_sbsnd_hiwat = sbsnd_hiwat; 1521 so->sol_sbrcv_flags = sbrcv_flags; 1522 so->sol_sbsnd_flags = sbsnd_flags; 1523 so->sol_sbrcv_timeo = sbrcv_timeo; 1524 so->sol_sbsnd_timeo = sbsnd_timeo; 1525 1526 so->sol_qlen = so->sol_incqlen = 0; 1527 TAILQ_INIT(&so->sol_incomp); 1528 TAILQ_INIT(&so->sol_comp); 1529 1530 so->sol_accept_filter = NULL; 1531 so->sol_accept_filter_arg = NULL; 1532 so->sol_accept_filter_str = NULL; 1533 1534 so->sol_upcall = NULL; 1535 so->sol_upcallarg = NULL; 1536 1537 so->so_options |= SO_ACCEPTCONN; 1538 1539 listening: 1540 if (backlog < 0 || backlog > V_somaxconn) 1541 backlog = V_somaxconn; 1542 so->sol_qlimit = backlog; 1543 1544 mtx_unlock(&so->so_snd_mtx); 1545 mtx_unlock(&so->so_rcv_mtx); 1546 sx_xunlock(&so->so_snd_sx); 1547 sx_xunlock(&so->so_rcv_sx); 1548 } 1549 1550 /* 1551 * Wakeup listeners/subsystems once we have a complete connection. 1552 * Enters with lock, returns unlocked. 1553 */ 1554 void 1555 solisten_wakeup(struct socket *sol) 1556 { 1557 1558 if (sol->sol_upcall != NULL) 1559 (void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT); 1560 else { 1561 selwakeuppri(&sol->so_rdsel, PSOCK); 1562 KNOTE_LOCKED(&sol->so_rdsel.si_note, 0); 1563 } 1564 SOLISTEN_UNLOCK(sol); 1565 wakeup_one(&sol->sol_comp); 1566 if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL) 1567 pgsigio(&sol->so_sigio, SIGIO, 0); 1568 } 1569 1570 /* 1571 * Return single connection off a listening socket queue. Main consumer of 1572 * the function is kern_accept4(). Some modules, that do their own accept 1573 * management also use the function. The socket reference held by the 1574 * listen queue is handed to the caller. 1575 * 1576 * Listening socket must be locked on entry and is returned unlocked on 1577 * return. 1578 * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT. 1579 */ 1580 int 1581 solisten_dequeue(struct socket *head, struct socket **ret, int flags) 1582 { 1583 struct socket *so; 1584 int error; 1585 1586 SOLISTEN_LOCK_ASSERT(head); 1587 1588 while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) && 1589 head->so_error == 0) { 1590 error = msleep(&head->sol_comp, SOCK_MTX(head), PSOCK | PCATCH, 1591 "accept", 0); 1592 if (error != 0) { 1593 SOLISTEN_UNLOCK(head); 1594 return (error); 1595 } 1596 } 1597 if (head->so_error) { 1598 error = head->so_error; 1599 head->so_error = 0; 1600 } else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp)) 1601 error = EWOULDBLOCK; 1602 else 1603 error = 0; 1604 if (error) { 1605 SOLISTEN_UNLOCK(head); 1606 return (error); 1607 } 1608 so = TAILQ_FIRST(&head->sol_comp); 1609 SOCK_LOCK(so); 1610 KASSERT(so->so_qstate == SQ_COMP, 1611 ("%s: so %p not SQ_COMP", __func__, so)); 1612 head->sol_qlen--; 1613 so->so_qstate = SQ_NONE; 1614 so->so_listen = NULL; 1615 TAILQ_REMOVE(&head->sol_comp, so, so_list); 1616 if (flags & ACCEPT4_INHERIT) 1617 so->so_state |= (head->so_state & SS_NBIO); 1618 else 1619 so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0; 1620 SOCK_UNLOCK(so); 1621 sorele_locked(head); 1622 1623 *ret = so; 1624 return (0); 1625 } 1626 1627 static struct so_splice * 1628 so_splice_alloc(off_t max) 1629 { 1630 struct so_splice *sp; 1631 1632 sp = uma_zalloc(splice_zone, M_WAITOK); 1633 sp->src = NULL; 1634 sp->dst = NULL; 1635 sp->max = max > 0 ? max : -1; 1636 do { 1637 sp->wq_index = atomic_fetchadd_32(&splice_index, 1) % 1638 (mp_maxid + 1); 1639 } while (CPU_ABSENT(sp->wq_index)); 1640 sp->state = SPLICE_INIT; 1641 TIMEOUT_TASK_INIT(taskqueue_thread, &sp->timeout, 0, so_splice_timeout, 1642 sp); 1643 return (sp); 1644 } 1645 1646 static void 1647 so_splice_free(struct so_splice *sp) 1648 { 1649 KASSERT(sp->state == SPLICE_CLOSED, 1650 ("so_splice_free: sp %p not closed", sp)); 1651 uma_zfree(splice_zone, sp); 1652 } 1653 1654 static void 1655 so_splice_timeout(void *arg, int pending __unused) 1656 { 1657 struct so_splice *sp; 1658 1659 sp = arg; 1660 (void)so_unsplice(sp->src, true); 1661 } 1662 1663 /* 1664 * Splice the output from so to the input of so2. 1665 */ 1666 static int 1667 so_splice(struct socket *so, struct socket *so2, struct splice *splice) 1668 { 1669 struct so_splice *sp; 1670 int error; 1671 1672 if (splice->sp_max < 0) 1673 return (EINVAL); 1674 /* Handle only TCP for now; TODO: other streaming protos */ 1675 if (so->so_proto->pr_protocol != IPPROTO_TCP || 1676 so2->so_proto->pr_protocol != IPPROTO_TCP) 1677 return (EPROTONOSUPPORT); 1678 if (so->so_vnet != so2->so_vnet) 1679 return (EINVAL); 1680 1681 /* so_splice_xfer() assumes that we're using these implementations. */ 1682 KASSERT(so->so_proto->pr_sosend == sosend_generic, 1683 ("so_splice: sosend not sosend_generic")); 1684 KASSERT(so2->so_proto->pr_soreceive == soreceive_generic || 1685 so2->so_proto->pr_soreceive == soreceive_stream, 1686 ("so_splice: soreceive not soreceive_generic/stream")); 1687 1688 sp = so_splice_alloc(splice->sp_max); 1689 so->so_splice_sent = 0; 1690 sp->src = so; 1691 sp->dst = so2; 1692 1693 error = 0; 1694 SOCK_LOCK(so); 1695 if (SOLISTENING(so)) 1696 error = EINVAL; 1697 else if ((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) == 0) 1698 error = ENOTCONN; 1699 else if (so->so_splice != NULL) 1700 error = EBUSY; 1701 if (error != 0) { 1702 SOCK_UNLOCK(so); 1703 uma_zfree(splice_zone, sp); 1704 return (error); 1705 } 1706 SOCK_RECVBUF_LOCK(so); 1707 if (so->so_rcv.sb_tls_info != NULL) { 1708 SOCK_RECVBUF_UNLOCK(so); 1709 SOCK_UNLOCK(so); 1710 uma_zfree(splice_zone, sp); 1711 return (EINVAL); 1712 } 1713 so->so_rcv.sb_flags |= SB_SPLICED; 1714 so->so_splice = sp; 1715 soref(so); 1716 SOCK_RECVBUF_UNLOCK(so); 1717 SOCK_UNLOCK(so); 1718 1719 error = 0; 1720 SOCK_LOCK(so2); 1721 if (SOLISTENING(so2)) 1722 error = EINVAL; 1723 else if ((so2->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) == 0) 1724 error = ENOTCONN; 1725 else if (so2->so_splice_back != NULL) 1726 error = EBUSY; 1727 if (error != 0) { 1728 SOCK_UNLOCK(so2); 1729 so_unsplice(so, false); 1730 return (error); 1731 } 1732 SOCK_SENDBUF_LOCK(so2); 1733 if (so->so_snd.sb_tls_info != NULL) { 1734 SOCK_SENDBUF_UNLOCK(so2); 1735 SOCK_UNLOCK(so2); 1736 so_unsplice(so, false); 1737 return (EINVAL); 1738 } 1739 so2->so_snd.sb_flags |= SB_SPLICED; 1740 so2->so_splice_back = sp; 1741 soref(so2); 1742 mtx_lock(&sp->mtx); 1743 SOCK_SENDBUF_UNLOCK(so2); 1744 SOCK_UNLOCK(so2); 1745 1746 if (splice->sp_idle.tv_sec != 0 || splice->sp_idle.tv_usec != 0) { 1747 taskqueue_enqueue_timeout_sbt(taskqueue_thread, &sp->timeout, 1748 tvtosbt(splice->sp_idle), 0, C_PREL(4)); 1749 } 1750 1751 /* 1752 * Transfer any data already present in the socket buffer. 1753 */ 1754 KASSERT(sp->state == SPLICE_INIT, 1755 ("so_splice: splice %p state %d", sp, sp->state)); 1756 sp->state = SPLICE_QUEUED; 1757 so_splice_xfer(sp); 1758 return (0); 1759 } 1760 1761 static int 1762 so_unsplice(struct socket *so, bool timeout) 1763 { 1764 struct socket *so2; 1765 struct so_splice *sp; 1766 bool drain, so2rele; 1767 1768 /* 1769 * First unset SB_SPLICED and hide the splice structure so that 1770 * wakeup routines will stop enqueuing work. This also ensures that 1771 * a only a single thread will proceed with the unsplice. 1772 */ 1773 SOCK_LOCK(so); 1774 if (SOLISTENING(so)) { 1775 SOCK_UNLOCK(so); 1776 return (EINVAL); 1777 } 1778 SOCK_RECVBUF_LOCK(so); 1779 if ((so->so_rcv.sb_flags & SB_SPLICED) == 0) { 1780 SOCK_RECVBUF_UNLOCK(so); 1781 SOCK_UNLOCK(so); 1782 return (ENOTCONN); 1783 } 1784 sp = so->so_splice; 1785 mtx_lock(&sp->mtx); 1786 if (sp->state == SPLICE_INIT) { 1787 /* 1788 * A splice is in the middle of being set up. 1789 */ 1790 mtx_unlock(&sp->mtx); 1791 SOCK_RECVBUF_UNLOCK(so); 1792 SOCK_UNLOCK(so); 1793 return (ENOTCONN); 1794 } 1795 mtx_unlock(&sp->mtx); 1796 so->so_rcv.sb_flags &= ~SB_SPLICED; 1797 so->so_splice = NULL; 1798 SOCK_RECVBUF_UNLOCK(so); 1799 SOCK_UNLOCK(so); 1800 1801 so2 = sp->dst; 1802 SOCK_LOCK(so2); 1803 KASSERT(!SOLISTENING(so2), ("%s: so2 is listening", __func__)); 1804 SOCK_SENDBUF_LOCK(so2); 1805 KASSERT(sp->state == SPLICE_INIT || 1806 (so2->so_snd.sb_flags & SB_SPLICED) != 0, 1807 ("%s: so2 is not spliced", __func__)); 1808 KASSERT(sp->state == SPLICE_INIT || 1809 so2->so_splice_back == sp, 1810 ("%s: so_splice_back != sp", __func__)); 1811 so2->so_snd.sb_flags &= ~SB_SPLICED; 1812 so2rele = so2->so_splice_back != NULL; 1813 so2->so_splice_back = NULL; 1814 SOCK_SENDBUF_UNLOCK(so2); 1815 SOCK_UNLOCK(so2); 1816 1817 /* 1818 * No new work is being enqueued. The worker thread might be 1819 * splicing data right now, in which case we want to wait for it to 1820 * finish before proceeding. 1821 */ 1822 mtx_lock(&sp->mtx); 1823 switch (sp->state) { 1824 case SPLICE_QUEUED: 1825 case SPLICE_RUNNING: 1826 sp->state = SPLICE_CLOSING; 1827 while (sp->state == SPLICE_CLOSING) 1828 msleep(sp, &sp->mtx, PSOCK, "unsplice", 0); 1829 break; 1830 case SPLICE_INIT: 1831 case SPLICE_IDLE: 1832 case SPLICE_EXCEPTION: 1833 sp->state = SPLICE_CLOSED; 1834 break; 1835 default: 1836 __assert_unreachable(); 1837 } 1838 if (!timeout) { 1839 drain = taskqueue_cancel_timeout(taskqueue_thread, &sp->timeout, 1840 NULL) != 0; 1841 } else { 1842 drain = false; 1843 } 1844 mtx_unlock(&sp->mtx); 1845 if (drain) 1846 taskqueue_drain_timeout(taskqueue_thread, &sp->timeout); 1847 1848 /* 1849 * Now we hold the sole reference to the splice structure. 1850 * Clean up: signal userspace and release socket references. 1851 */ 1852 sorwakeup(so); 1853 CURVNET_SET(so->so_vnet); 1854 sorele(so); 1855 sowwakeup(so2); 1856 if (so2rele) 1857 sorele(so2); 1858 CURVNET_RESTORE(); 1859 so_splice_free(sp); 1860 return (0); 1861 } 1862 1863 /* 1864 * Free socket upon release of the very last reference. 1865 */ 1866 static void 1867 sofree(struct socket *so) 1868 { 1869 struct protosw *pr = so->so_proto; 1870 1871 SOCK_LOCK_ASSERT(so); 1872 KASSERT(refcount_load(&so->so_count) == 0, 1873 ("%s: so %p has references", __func__, so)); 1874 KASSERT(SOLISTENING(so) || so->so_qstate == SQ_NONE, 1875 ("%s: so %p is on listen queue", __func__, so)); 1876 KASSERT(SOLISTENING(so) || (so->so_rcv.sb_flags & SB_SPLICED) == 0, 1877 ("%s: so %p rcvbuf is spliced", __func__, so)); 1878 KASSERT(SOLISTENING(so) || (so->so_snd.sb_flags & SB_SPLICED) == 0, 1879 ("%s: so %p sndbuf is spliced", __func__, so)); 1880 KASSERT(so->so_splice == NULL && so->so_splice_back == NULL, 1881 ("%s: so %p has spliced data", __func__, so)); 1882 1883 SOCK_UNLOCK(so); 1884 1885 if (so->so_dtor != NULL) 1886 so->so_dtor(so); 1887 1888 VNET_SO_ASSERT(so); 1889 if (pr->pr_detach != NULL) 1890 pr->pr_detach(so); 1891 1892 if (!(pr->pr_flags & PR_SOCKBUF) && !SOLISTENING(so)) { 1893 /* 1894 * From this point on, we assume that no other references to 1895 * this socket exist anywhere else in the stack. Therefore, 1896 * no locks need to be acquired or held. 1897 */ 1898 #ifdef INVARIANTS 1899 SOCK_SENDBUF_LOCK(so); 1900 SOCK_RECVBUF_LOCK(so); 1901 #endif 1902 sbdestroy(so, SO_SND); 1903 sbdestroy(so, SO_RCV); 1904 #ifdef INVARIANTS 1905 SOCK_SENDBUF_UNLOCK(so); 1906 SOCK_RECVBUF_UNLOCK(so); 1907 #endif 1908 } 1909 seldrain(&so->so_rdsel); 1910 seldrain(&so->so_wrsel); 1911 knlist_destroy(&so->so_rdsel.si_note); 1912 knlist_destroy(&so->so_wrsel.si_note); 1913 sodealloc(so); 1914 } 1915 1916 /* 1917 * Release a reference on a socket while holding the socket lock. 1918 * Unlocks the socket lock before returning. 1919 */ 1920 void 1921 sorele_locked(struct socket *so) 1922 { 1923 SOCK_LOCK_ASSERT(so); 1924 if (refcount_release(&so->so_count)) 1925 sofree(so); 1926 else 1927 SOCK_UNLOCK(so); 1928 } 1929 1930 /* 1931 * Close a socket on last file table reference removal. Initiate disconnect 1932 * if connected. Free socket when disconnect complete. 1933 * 1934 * This function will sorele() the socket. Note that soclose() may be called 1935 * prior to the ref count reaching zero. The actual socket structure will 1936 * not be freed until the ref count reaches zero. 1937 */ 1938 int 1939 soclose(struct socket *so) 1940 { 1941 struct accept_queue lqueue; 1942 int error = 0; 1943 bool listening, last __diagused; 1944 1945 CURVNET_SET(so->so_vnet); 1946 funsetown(&so->so_sigio); 1947 if (so->so_state & SS_ISCONNECTED) { 1948 if ((so->so_state & SS_ISDISCONNECTING) == 0) { 1949 error = sodisconnect(so); 1950 if (error) { 1951 if (error == ENOTCONN) 1952 error = 0; 1953 goto drop; 1954 } 1955 } 1956 1957 if ((so->so_options & SO_LINGER) != 0 && so->so_linger != 0) { 1958 if ((so->so_state & SS_ISDISCONNECTING) && 1959 (so->so_state & SS_NBIO)) 1960 goto drop; 1961 while (so->so_state & SS_ISCONNECTED) { 1962 error = tsleep(&so->so_timeo, 1963 PSOCK | PCATCH, "soclos", 1964 so->so_linger * hz); 1965 if (error) 1966 break; 1967 } 1968 } 1969 } 1970 1971 drop: 1972 if (so->so_proto->pr_close != NULL) 1973 so->so_proto->pr_close(so); 1974 1975 SOCK_LOCK(so); 1976 if ((listening = SOLISTENING(so))) { 1977 struct socket *sp; 1978 1979 TAILQ_INIT(&lqueue); 1980 TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list); 1981 TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list); 1982 1983 so->sol_qlen = so->sol_incqlen = 0; 1984 1985 TAILQ_FOREACH(sp, &lqueue, so_list) { 1986 SOCK_LOCK(sp); 1987 sp->so_qstate = SQ_NONE; 1988 sp->so_listen = NULL; 1989 SOCK_UNLOCK(sp); 1990 last = refcount_release(&so->so_count); 1991 KASSERT(!last, ("%s: released last reference for %p", 1992 __func__, so)); 1993 } 1994 } 1995 sorele_locked(so); 1996 if (listening) { 1997 struct socket *sp, *tsp; 1998 1999 TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp) 2000 soabort(sp); 2001 } 2002 CURVNET_RESTORE(); 2003 return (error); 2004 } 2005 2006 /* 2007 * soabort() is used to abruptly tear down a connection, such as when a 2008 * resource limit is reached (listen queue depth exceeded), or if a listen 2009 * socket is closed while there are sockets waiting to be accepted. 2010 * 2011 * This interface is tricky, because it is called on an unreferenced socket, 2012 * and must be called only by a thread that has actually removed the socket 2013 * from the listen queue it was on. Likely this thread holds the last 2014 * reference on the socket and soabort() will proceed with sofree(). But 2015 * it might be not the last, as the sockets on the listen queues are seen 2016 * from the protocol side. 2017 * 2018 * This interface will call into the protocol code, so must not be called 2019 * with any socket locks held. Protocols do call it while holding their own 2020 * recursible protocol mutexes, but this is something that should be subject 2021 * to review in the future. 2022 * 2023 * Usually socket should have a single reference left, but this is not a 2024 * requirement. In the past, when we have had named references for file 2025 * descriptor and protocol, we asserted that none of them are being held. 2026 */ 2027 void 2028 soabort(struct socket *so) 2029 { 2030 2031 VNET_SO_ASSERT(so); 2032 2033 if (so->so_proto->pr_abort != NULL) 2034 so->so_proto->pr_abort(so); 2035 SOCK_LOCK(so); 2036 sorele_locked(so); 2037 } 2038 2039 int 2040 soaccept(struct socket *so, struct sockaddr *sa) 2041 { 2042 #ifdef INVARIANTS 2043 u_char len = sa->sa_len; 2044 #endif 2045 int error; 2046 2047 CURVNET_SET(so->so_vnet); 2048 error = so->so_proto->pr_accept(so, sa); 2049 KASSERT(sa->sa_len <= len, 2050 ("%s: protocol %p sockaddr overflow", __func__, so->so_proto)); 2051 CURVNET_RESTORE(); 2052 return (error); 2053 } 2054 2055 int 2056 sopeeraddr(struct socket *so, struct sockaddr *sa) 2057 { 2058 #ifdef INVARIANTS 2059 u_char len = sa->sa_len; 2060 #endif 2061 int error; 2062 2063 CURVNET_ASSERT_SET(); 2064 2065 error = so->so_proto->pr_peeraddr(so, sa); 2066 KASSERT(sa->sa_len <= len, 2067 ("%s: protocol %p sockaddr overflow", __func__, so->so_proto)); 2068 2069 return (error); 2070 } 2071 2072 int 2073 sosockaddr(struct socket *so, struct sockaddr *sa) 2074 { 2075 #ifdef INVARIANTS 2076 u_char len = sa->sa_len; 2077 #endif 2078 int error; 2079 2080 CURVNET_SET(so->so_vnet); 2081 error = so->so_proto->pr_sockaddr(so, sa); 2082 KASSERT(sa->sa_len <= len, 2083 ("%s: protocol %p sockaddr overflow", __func__, so->so_proto)); 2084 CURVNET_RESTORE(); 2085 2086 return (error); 2087 } 2088 2089 int 2090 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td) 2091 { 2092 2093 return (soconnectat(AT_FDCWD, so, nam, td)); 2094 } 2095 2096 int 2097 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td) 2098 { 2099 int error; 2100 2101 CURVNET_SET(so->so_vnet); 2102 2103 /* 2104 * If protocol is connection-based, can only connect once. 2105 * Otherwise, if connected, try to disconnect first. This allows 2106 * user to disconnect by connecting to, e.g., a null address. 2107 * 2108 * Note, this check is racy and may need to be re-evaluated at the 2109 * protocol layer. 2110 */ 2111 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) && 2112 ((so->so_proto->pr_flags & PR_CONNREQUIRED) || 2113 (error = sodisconnect(so)))) { 2114 error = EISCONN; 2115 } else { 2116 /* 2117 * Prevent accumulated error from previous connection from 2118 * biting us. 2119 */ 2120 so->so_error = 0; 2121 if (fd == AT_FDCWD) { 2122 error = so->so_proto->pr_connect(so, nam, td); 2123 } else { 2124 error = so->so_proto->pr_connectat(fd, so, nam, td); 2125 } 2126 } 2127 CURVNET_RESTORE(); 2128 2129 return (error); 2130 } 2131 2132 int 2133 soconnect2(struct socket *so1, struct socket *so2) 2134 { 2135 int error; 2136 2137 CURVNET_SET(so1->so_vnet); 2138 error = so1->so_proto->pr_connect2(so1, so2); 2139 CURVNET_RESTORE(); 2140 return (error); 2141 } 2142 2143 int 2144 sodisconnect(struct socket *so) 2145 { 2146 int error; 2147 2148 if ((so->so_state & SS_ISCONNECTED) == 0) 2149 return (ENOTCONN); 2150 if (so->so_state & SS_ISDISCONNECTING) 2151 return (EALREADY); 2152 VNET_SO_ASSERT(so); 2153 error = so->so_proto->pr_disconnect(so); 2154 return (error); 2155 } 2156 2157 int 2158 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio, 2159 struct mbuf *top, struct mbuf *control, int flags, struct thread *td) 2160 { 2161 long space; 2162 ssize_t resid; 2163 int clen = 0, error, dontroute; 2164 2165 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM")); 2166 KASSERT(so->so_proto->pr_flags & PR_ATOMIC, 2167 ("sosend_dgram: !PR_ATOMIC")); 2168 2169 if (uio != NULL) 2170 resid = uio->uio_resid; 2171 else 2172 resid = top->m_pkthdr.len; 2173 /* 2174 * In theory resid should be unsigned. However, space must be 2175 * signed, as it might be less than 0 if we over-committed, and we 2176 * must use a signed comparison of space and resid. On the other 2177 * hand, a negative resid causes us to loop sending 0-length 2178 * segments to the protocol. 2179 */ 2180 if (resid < 0) { 2181 error = EINVAL; 2182 goto out; 2183 } 2184 2185 dontroute = 2186 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0; 2187 if (td != NULL) 2188 td->td_ru.ru_msgsnd++; 2189 if (control != NULL) 2190 clen = control->m_len; 2191 2192 SOCKBUF_LOCK(&so->so_snd); 2193 if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 2194 SOCKBUF_UNLOCK(&so->so_snd); 2195 error = EPIPE; 2196 goto out; 2197 } 2198 if (so->so_error) { 2199 error = so->so_error; 2200 so->so_error = 0; 2201 SOCKBUF_UNLOCK(&so->so_snd); 2202 goto out; 2203 } 2204 if ((so->so_state & SS_ISCONNECTED) == 0) { 2205 /* 2206 * `sendto' and `sendmsg' is allowed on a connection-based 2207 * socket if it supports implied connect. Return ENOTCONN if 2208 * not connected and no address is supplied. 2209 */ 2210 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) && 2211 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) { 2212 if (!(resid == 0 && clen != 0)) { 2213 SOCKBUF_UNLOCK(&so->so_snd); 2214 error = ENOTCONN; 2215 goto out; 2216 } 2217 } else if (addr == NULL) { 2218 if (so->so_proto->pr_flags & PR_CONNREQUIRED) 2219 error = ENOTCONN; 2220 else 2221 error = EDESTADDRREQ; 2222 SOCKBUF_UNLOCK(&so->so_snd); 2223 goto out; 2224 } 2225 } 2226 2227 /* 2228 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a 2229 * problem and need fixing. 2230 */ 2231 space = sbspace(&so->so_snd); 2232 if (flags & MSG_OOB) 2233 space += 1024; 2234 space -= clen; 2235 SOCKBUF_UNLOCK(&so->so_snd); 2236 if (resid > space) { 2237 error = EMSGSIZE; 2238 goto out; 2239 } 2240 if (uio == NULL) { 2241 resid = 0; 2242 if (flags & MSG_EOR) 2243 top->m_flags |= M_EOR; 2244 } else { 2245 /* 2246 * Copy the data from userland into a mbuf chain. 2247 * If no data is to be copied in, a single empty mbuf 2248 * is returned. 2249 */ 2250 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr, 2251 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0))); 2252 if (top == NULL) { 2253 error = EFAULT; /* only possible error */ 2254 goto out; 2255 } 2256 space -= resid - uio->uio_resid; 2257 resid = uio->uio_resid; 2258 } 2259 KASSERT(resid == 0, ("sosend_dgram: resid != 0")); 2260 /* 2261 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock 2262 * than with. 2263 */ 2264 if (dontroute) { 2265 SOCK_LOCK(so); 2266 so->so_options |= SO_DONTROUTE; 2267 SOCK_UNLOCK(so); 2268 } 2269 /* 2270 * XXX all the SBS_CANTSENDMORE checks previously done could be out 2271 * of date. We could have received a reset packet in an interrupt or 2272 * maybe we slept while doing page faults in uiomove() etc. We could 2273 * probably recheck again inside the locking protection here, but 2274 * there are probably other places that this also happens. We must 2275 * rethink this. 2276 */ 2277 VNET_SO_ASSERT(so); 2278 error = so->so_proto->pr_send(so, (flags & MSG_OOB) ? PRUS_OOB : 2279 /* 2280 * If the user set MSG_EOF, the protocol understands this flag and 2281 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND. 2282 */ 2283 ((flags & MSG_EOF) && 2284 (so->so_proto->pr_flags & PR_IMPLOPCL) && 2285 (resid <= 0)) ? 2286 PRUS_EOF : 2287 /* If there is more to send set PRUS_MORETOCOME */ 2288 (flags & MSG_MORETOCOME) || 2289 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0, 2290 top, addr, control, td); 2291 if (dontroute) { 2292 SOCK_LOCK(so); 2293 so->so_options &= ~SO_DONTROUTE; 2294 SOCK_UNLOCK(so); 2295 } 2296 clen = 0; 2297 control = NULL; 2298 top = NULL; 2299 out: 2300 if (top != NULL) 2301 m_freem(top); 2302 if (control != NULL) 2303 m_freem(control); 2304 return (error); 2305 } 2306 2307 /* 2308 * Send on a socket. If send must go all at once and message is larger than 2309 * send buffering, then hard error. Lock against other senders. If must go 2310 * all at once and not enough room now, then inform user that this would 2311 * block and do nothing. Otherwise, if nonblocking, send as much as 2312 * possible. The data to be sent is described by "uio" if nonzero, otherwise 2313 * by the mbuf chain "top" (which must be null if uio is not). Data provided 2314 * in mbuf chain must be small enough to send all at once. 2315 * 2316 * Returns nonzero on error, timeout or signal; callers must check for short 2317 * counts if EINTR/ERESTART are returned. Data and control buffers are freed 2318 * on return. 2319 */ 2320 static int 2321 sosend_generic_locked(struct socket *so, struct sockaddr *addr, struct uio *uio, 2322 struct mbuf *top, struct mbuf *control, int flags, struct thread *td) 2323 { 2324 long space; 2325 ssize_t resid; 2326 int clen = 0, error, dontroute; 2327 int atomic = sosendallatonce(so) || top; 2328 int pr_send_flag; 2329 #ifdef KERN_TLS 2330 struct ktls_session *tls; 2331 int tls_enq_cnt, tls_send_flag; 2332 uint8_t tls_rtype; 2333 2334 tls = NULL; 2335 tls_rtype = TLS_RLTYPE_APP; 2336 #endif 2337 2338 SOCK_IO_SEND_ASSERT_LOCKED(so); 2339 2340 if (uio != NULL) 2341 resid = uio->uio_resid; 2342 else if ((top->m_flags & M_PKTHDR) != 0) 2343 resid = top->m_pkthdr.len; 2344 else 2345 resid = m_length(top, NULL); 2346 /* 2347 * In theory resid should be unsigned. However, space must be 2348 * signed, as it might be less than 0 if we over-committed, and we 2349 * must use a signed comparison of space and resid. On the other 2350 * hand, a negative resid causes us to loop sending 0-length 2351 * segments to the protocol. 2352 * 2353 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM 2354 * type sockets since that's an error. 2355 */ 2356 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) { 2357 error = EINVAL; 2358 goto out; 2359 } 2360 2361 dontroute = 2362 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 && 2363 (so->so_proto->pr_flags & PR_ATOMIC); 2364 if (td != NULL) 2365 td->td_ru.ru_msgsnd++; 2366 if (control != NULL) 2367 clen = control->m_len; 2368 2369 #ifdef KERN_TLS 2370 tls_send_flag = 0; 2371 tls = ktls_hold(so->so_snd.sb_tls_info); 2372 if (tls != NULL) { 2373 if (tls->mode == TCP_TLS_MODE_SW) 2374 tls_send_flag = PRUS_NOTREADY; 2375 2376 if (control != NULL) { 2377 struct cmsghdr *cm = mtod(control, struct cmsghdr *); 2378 2379 if (clen >= sizeof(*cm) && 2380 cm->cmsg_type == TLS_SET_RECORD_TYPE) { 2381 tls_rtype = *((uint8_t *)CMSG_DATA(cm)); 2382 clen = 0; 2383 m_freem(control); 2384 control = NULL; 2385 atomic = 1; 2386 } 2387 } 2388 2389 if (resid == 0 && !ktls_permit_empty_frames(tls)) { 2390 error = EINVAL; 2391 goto out; 2392 } 2393 } 2394 #endif 2395 2396 restart: 2397 do { 2398 SOCKBUF_LOCK(&so->so_snd); 2399 if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 2400 SOCKBUF_UNLOCK(&so->so_snd); 2401 error = EPIPE; 2402 goto out; 2403 } 2404 if (so->so_error) { 2405 error = so->so_error; 2406 so->so_error = 0; 2407 SOCKBUF_UNLOCK(&so->so_snd); 2408 goto out; 2409 } 2410 if ((so->so_state & SS_ISCONNECTED) == 0) { 2411 /* 2412 * `sendto' and `sendmsg' is allowed on a connection- 2413 * based socket if it supports implied connect. 2414 * Return ENOTCONN if not connected and no address is 2415 * supplied. 2416 */ 2417 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) && 2418 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) { 2419 if (!(resid == 0 && clen != 0)) { 2420 SOCKBUF_UNLOCK(&so->so_snd); 2421 error = ENOTCONN; 2422 goto out; 2423 } 2424 } else if (addr == NULL) { 2425 SOCKBUF_UNLOCK(&so->so_snd); 2426 if (so->so_proto->pr_flags & PR_CONNREQUIRED) 2427 error = ENOTCONN; 2428 else 2429 error = EDESTADDRREQ; 2430 goto out; 2431 } 2432 } 2433 space = sbspace(&so->so_snd); 2434 if (flags & MSG_OOB) 2435 space += 1024; 2436 if ((atomic && resid > so->so_snd.sb_hiwat) || 2437 clen > so->so_snd.sb_hiwat) { 2438 SOCKBUF_UNLOCK(&so->so_snd); 2439 error = EMSGSIZE; 2440 goto out; 2441 } 2442 if (space < resid + clen && 2443 (atomic || space < so->so_snd.sb_lowat || space < clen)) { 2444 if ((so->so_state & SS_NBIO) || 2445 (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) { 2446 SOCKBUF_UNLOCK(&so->so_snd); 2447 error = EWOULDBLOCK; 2448 goto out; 2449 } 2450 error = sbwait(so, SO_SND); 2451 SOCKBUF_UNLOCK(&so->so_snd); 2452 if (error) 2453 goto out; 2454 goto restart; 2455 } 2456 SOCKBUF_UNLOCK(&so->so_snd); 2457 space -= clen; 2458 do { 2459 if (uio == NULL) { 2460 resid = 0; 2461 if (flags & MSG_EOR) 2462 top->m_flags |= M_EOR; 2463 #ifdef KERN_TLS 2464 if (tls != NULL) { 2465 ktls_frame(top, tls, &tls_enq_cnt, 2466 tls_rtype); 2467 tls_rtype = TLS_RLTYPE_APP; 2468 } 2469 #endif 2470 } else { 2471 /* 2472 * Copy the data from userland into a mbuf 2473 * chain. If resid is 0, which can happen 2474 * only if we have control to send, then 2475 * a single empty mbuf is returned. This 2476 * is a workaround to prevent protocol send 2477 * methods to panic. 2478 */ 2479 #ifdef KERN_TLS 2480 if (tls != NULL) { 2481 top = m_uiotombuf(uio, M_WAITOK, space, 2482 tls->params.max_frame_len, 2483 M_EXTPG | 2484 ((flags & MSG_EOR) ? M_EOR : 0)); 2485 if (top != NULL) { 2486 ktls_frame(top, tls, 2487 &tls_enq_cnt, tls_rtype); 2488 } 2489 tls_rtype = TLS_RLTYPE_APP; 2490 } else 2491 #endif 2492 top = m_uiotombuf(uio, M_WAITOK, space, 2493 (atomic ? max_hdr : 0), 2494 (atomic ? M_PKTHDR : 0) | 2495 ((flags & MSG_EOR) ? M_EOR : 0)); 2496 if (top == NULL) { 2497 error = EFAULT; /* only possible error */ 2498 goto out; 2499 } 2500 space -= resid - uio->uio_resid; 2501 resid = uio->uio_resid; 2502 } 2503 if (dontroute) { 2504 SOCK_LOCK(so); 2505 so->so_options |= SO_DONTROUTE; 2506 SOCK_UNLOCK(so); 2507 } 2508 /* 2509 * XXX all the SBS_CANTSENDMORE checks previously 2510 * done could be out of date. We could have received 2511 * a reset packet in an interrupt or maybe we slept 2512 * while doing page faults in uiomove() etc. We 2513 * could probably recheck again inside the locking 2514 * protection here, but there are probably other 2515 * places that this also happens. We must rethink 2516 * this. 2517 */ 2518 VNET_SO_ASSERT(so); 2519 2520 pr_send_flag = (flags & MSG_OOB) ? PRUS_OOB : 2521 /* 2522 * If the user set MSG_EOF, the protocol understands 2523 * this flag and nothing left to send then use 2524 * PRU_SEND_EOF instead of PRU_SEND. 2525 */ 2526 ((flags & MSG_EOF) && 2527 (so->so_proto->pr_flags & PR_IMPLOPCL) && 2528 (resid <= 0)) ? 2529 PRUS_EOF : 2530 /* If there is more to send set PRUS_MORETOCOME. */ 2531 (flags & MSG_MORETOCOME) || 2532 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0; 2533 2534 #ifdef KERN_TLS 2535 pr_send_flag |= tls_send_flag; 2536 #endif 2537 2538 error = so->so_proto->pr_send(so, pr_send_flag, top, 2539 addr, control, td); 2540 2541 if (dontroute) { 2542 SOCK_LOCK(so); 2543 so->so_options &= ~SO_DONTROUTE; 2544 SOCK_UNLOCK(so); 2545 } 2546 2547 #ifdef KERN_TLS 2548 if (tls != NULL && tls->mode == TCP_TLS_MODE_SW) { 2549 if (error != 0) { 2550 m_freem(top); 2551 top = NULL; 2552 } else { 2553 soref(so); 2554 ktls_enqueue(top, so, tls_enq_cnt); 2555 } 2556 } 2557 #endif 2558 clen = 0; 2559 control = NULL; 2560 top = NULL; 2561 if (error) 2562 goto out; 2563 } while (resid && space > 0); 2564 } while (resid); 2565 2566 out: 2567 #ifdef KERN_TLS 2568 if (tls != NULL) 2569 ktls_free(tls); 2570 #endif 2571 if (top != NULL) 2572 m_freem(top); 2573 if (control != NULL) 2574 m_freem(control); 2575 return (error); 2576 } 2577 2578 int 2579 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio, 2580 struct mbuf *top, struct mbuf *control, int flags, struct thread *td) 2581 { 2582 int error; 2583 2584 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags)); 2585 if (error) 2586 return (error); 2587 error = sosend_generic_locked(so, addr, uio, top, control, flags, td); 2588 SOCK_IO_SEND_UNLOCK(so); 2589 return (error); 2590 } 2591 2592 /* 2593 * Send to a socket from a kernel thread. 2594 * 2595 * XXXGL: in almost all cases uio is NULL and the mbuf is supplied. 2596 * Exception is nfs/bootp_subr.c. It is arguable that the VNET context needs 2597 * to be set at all. This function should just boil down to a static inline 2598 * calling the protocol method. 2599 */ 2600 int 2601 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio, 2602 struct mbuf *top, struct mbuf *control, int flags, struct thread *td) 2603 { 2604 int error; 2605 2606 CURVNET_SET(so->so_vnet); 2607 error = so->so_proto->pr_sosend(so, addr, uio, 2608 top, control, flags, td); 2609 CURVNET_RESTORE(); 2610 return (error); 2611 } 2612 2613 /* 2614 * send(2), write(2) or aio_write(2) on a socket. 2615 */ 2616 int 2617 sousrsend(struct socket *so, struct sockaddr *addr, struct uio *uio, 2618 struct mbuf *control, int flags, struct proc *userproc) 2619 { 2620 struct thread *td; 2621 ssize_t len; 2622 int error; 2623 2624 td = uio->uio_td; 2625 len = uio->uio_resid; 2626 CURVNET_SET(so->so_vnet); 2627 error = so->so_proto->pr_sosend(so, addr, uio, NULL, control, flags, 2628 td); 2629 CURVNET_RESTORE(); 2630 if (error != 0) { 2631 /* 2632 * Clear transient errors for stream protocols if they made 2633 * some progress. Make exclusion for aio(4) that would 2634 * schedule a new write in case of EWOULDBLOCK and clear 2635 * error itself. See soaio_process_job(). 2636 */ 2637 if (uio->uio_resid != len && 2638 (so->so_proto->pr_flags & PR_ATOMIC) == 0 && 2639 userproc == NULL && 2640 (error == ERESTART || error == EINTR || 2641 error == EWOULDBLOCK)) 2642 error = 0; 2643 /* Generation of SIGPIPE can be controlled per socket. */ 2644 if (error == EPIPE && (so->so_options & SO_NOSIGPIPE) == 0 && 2645 (flags & MSG_NOSIGNAL) == 0) { 2646 if (userproc != NULL) { 2647 /* aio(4) job */ 2648 PROC_LOCK(userproc); 2649 kern_psignal(userproc, SIGPIPE); 2650 PROC_UNLOCK(userproc); 2651 } else { 2652 PROC_LOCK(td->td_proc); 2653 tdsignal(td, SIGPIPE); 2654 PROC_UNLOCK(td->td_proc); 2655 } 2656 } 2657 } 2658 return (error); 2659 } 2660 2661 /* 2662 * The part of soreceive() that implements reading non-inline out-of-band 2663 * data from a socket. For more complete comments, see soreceive(), from 2664 * which this code originated. 2665 * 2666 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is 2667 * unable to return an mbuf chain to the caller. 2668 */ 2669 static int 2670 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags) 2671 { 2672 struct protosw *pr = so->so_proto; 2673 struct mbuf *m; 2674 int error; 2675 2676 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0")); 2677 VNET_SO_ASSERT(so); 2678 2679 m = m_get(M_WAITOK, MT_DATA); 2680 error = pr->pr_rcvoob(so, m, flags & MSG_PEEK); 2681 if (error) 2682 goto bad; 2683 do { 2684 error = uiomove(mtod(m, void *), 2685 (int) min(uio->uio_resid, m->m_len), uio); 2686 m = m_free(m); 2687 } while (uio->uio_resid && error == 0 && m); 2688 bad: 2689 if (m != NULL) 2690 m_freem(m); 2691 return (error); 2692 } 2693 2694 /* 2695 * Following replacement or removal of the first mbuf on the first mbuf chain 2696 * of a socket buffer, push necessary state changes back into the socket 2697 * buffer so that other consumers see the values consistently. 'nextrecord' 2698 * is the callers locally stored value of the original value of 2699 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes. 2700 * NOTE: 'nextrecord' may be NULL. 2701 */ 2702 static __inline void 2703 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord) 2704 { 2705 2706 SOCKBUF_LOCK_ASSERT(sb); 2707 /* 2708 * First, update for the new value of nextrecord. If necessary, make 2709 * it the first record. 2710 */ 2711 if (sb->sb_mb != NULL) 2712 sb->sb_mb->m_nextpkt = nextrecord; 2713 else 2714 sb->sb_mb = nextrecord; 2715 2716 /* 2717 * Now update any dependent socket buffer fields to reflect the new 2718 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the 2719 * addition of a second clause that takes care of the case where 2720 * sb_mb has been updated, but remains the last record. 2721 */ 2722 if (sb->sb_mb == NULL) { 2723 sb->sb_mbtail = NULL; 2724 sb->sb_lastrecord = NULL; 2725 } else if (sb->sb_mb->m_nextpkt == NULL) 2726 sb->sb_lastrecord = sb->sb_mb; 2727 } 2728 2729 /* 2730 * Implement receive operations on a socket. We depend on the way that 2731 * records are added to the sockbuf by sbappend. In particular, each record 2732 * (mbufs linked through m_next) must begin with an address if the protocol 2733 * so specifies, followed by an optional mbuf or mbufs containing ancillary 2734 * data, and then zero or more mbufs of data. In order to allow parallelism 2735 * between network receive and copying to user space, as well as avoid 2736 * sleeping with a mutex held, we release the socket buffer mutex during the 2737 * user space copy. Although the sockbuf is locked, new data may still be 2738 * appended, and thus we must maintain consistency of the sockbuf during that 2739 * time. 2740 * 2741 * The caller may receive the data as a single mbuf chain by supplying an 2742 * mbuf **mp0 for use in returning the chain. The uio is then used only for 2743 * the count in uio_resid. 2744 */ 2745 static int 2746 soreceive_generic_locked(struct socket *so, struct sockaddr **psa, 2747 struct uio *uio, struct mbuf **mp, struct mbuf **controlp, int *flagsp) 2748 { 2749 struct mbuf *m; 2750 int flags, error, offset; 2751 ssize_t len; 2752 struct protosw *pr = so->so_proto; 2753 struct mbuf *nextrecord; 2754 int moff, type = 0; 2755 ssize_t orig_resid = uio->uio_resid; 2756 bool report_real_len = false; 2757 2758 SOCK_IO_RECV_ASSERT_LOCKED(so); 2759 2760 error = 0; 2761 if (flagsp != NULL) { 2762 report_real_len = *flagsp & MSG_TRUNC; 2763 *flagsp &= ~MSG_TRUNC; 2764 flags = *flagsp &~ MSG_EOR; 2765 } else 2766 flags = 0; 2767 2768 restart: 2769 SOCKBUF_LOCK(&so->so_rcv); 2770 m = so->so_rcv.sb_mb; 2771 /* 2772 * If we have less data than requested, block awaiting more (subject 2773 * to any timeout) if: 2774 * 1. the current count is less than the low water mark, or 2775 * 2. MSG_DONTWAIT is not set 2776 */ 2777 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 && 2778 sbavail(&so->so_rcv) < uio->uio_resid) && 2779 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat && 2780 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) { 2781 KASSERT(m != NULL || !sbavail(&so->so_rcv), 2782 ("receive: m == %p sbavail == %u", 2783 m, sbavail(&so->so_rcv))); 2784 if (so->so_error || so->so_rerror) { 2785 if (m != NULL) 2786 goto dontblock; 2787 if (so->so_error) 2788 error = so->so_error; 2789 else 2790 error = so->so_rerror; 2791 if ((flags & MSG_PEEK) == 0) { 2792 if (so->so_error) 2793 so->so_error = 0; 2794 else 2795 so->so_rerror = 0; 2796 } 2797 SOCKBUF_UNLOCK(&so->so_rcv); 2798 goto release; 2799 } 2800 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2801 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 2802 if (m != NULL) 2803 goto dontblock; 2804 #ifdef KERN_TLS 2805 else if (so->so_rcv.sb_tlsdcc == 0 && 2806 so->so_rcv.sb_tlscc == 0) { 2807 #else 2808 else { 2809 #endif 2810 SOCKBUF_UNLOCK(&so->so_rcv); 2811 goto release; 2812 } 2813 } 2814 for (; m != NULL; m = m->m_next) 2815 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) { 2816 m = so->so_rcv.sb_mb; 2817 goto dontblock; 2818 } 2819 if ((so->so_state & (SS_ISCONNECTING | SS_ISCONNECTED | 2820 SS_ISDISCONNECTING | SS_ISDISCONNECTED)) == 0 && 2821 (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) { 2822 SOCKBUF_UNLOCK(&so->so_rcv); 2823 error = ENOTCONN; 2824 goto release; 2825 } 2826 if (uio->uio_resid == 0 && !report_real_len) { 2827 SOCKBUF_UNLOCK(&so->so_rcv); 2828 goto release; 2829 } 2830 if ((so->so_state & SS_NBIO) || 2831 (flags & (MSG_DONTWAIT|MSG_NBIO))) { 2832 SOCKBUF_UNLOCK(&so->so_rcv); 2833 error = EWOULDBLOCK; 2834 goto release; 2835 } 2836 SBLASTRECORDCHK(&so->so_rcv); 2837 SBLASTMBUFCHK(&so->so_rcv); 2838 error = sbwait(so, SO_RCV); 2839 SOCKBUF_UNLOCK(&so->so_rcv); 2840 if (error) 2841 goto release; 2842 goto restart; 2843 } 2844 dontblock: 2845 /* 2846 * From this point onward, we maintain 'nextrecord' as a cache of the 2847 * pointer to the next record in the socket buffer. We must keep the 2848 * various socket buffer pointers and local stack versions of the 2849 * pointers in sync, pushing out modifications before dropping the 2850 * socket buffer mutex, and re-reading them when picking it up. 2851 * 2852 * Otherwise, we will race with the network stack appending new data 2853 * or records onto the socket buffer by using inconsistent/stale 2854 * versions of the field, possibly resulting in socket buffer 2855 * corruption. 2856 * 2857 * By holding the high-level sblock(), we prevent simultaneous 2858 * readers from pulling off the front of the socket buffer. 2859 */ 2860 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2861 if (uio->uio_td) 2862 uio->uio_td->td_ru.ru_msgrcv++; 2863 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb")); 2864 SBLASTRECORDCHK(&so->so_rcv); 2865 SBLASTMBUFCHK(&so->so_rcv); 2866 nextrecord = m->m_nextpkt; 2867 if (pr->pr_flags & PR_ADDR) { 2868 KASSERT(m->m_type == MT_SONAME, 2869 ("m->m_type == %d", m->m_type)); 2870 orig_resid = 0; 2871 if (psa != NULL) 2872 *psa = sodupsockaddr(mtod(m, struct sockaddr *), 2873 M_NOWAIT); 2874 if (flags & MSG_PEEK) { 2875 m = m->m_next; 2876 } else { 2877 sbfree(&so->so_rcv, m); 2878 so->so_rcv.sb_mb = m_free(m); 2879 m = so->so_rcv.sb_mb; 2880 sockbuf_pushsync(&so->so_rcv, nextrecord); 2881 } 2882 } 2883 2884 /* 2885 * Process one or more MT_CONTROL mbufs present before any data mbufs 2886 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we 2887 * just copy the data; if !MSG_PEEK, we call into the protocol to 2888 * perform externalization (or freeing if controlp == NULL). 2889 */ 2890 if (m != NULL && m->m_type == MT_CONTROL) { 2891 struct mbuf *cm = NULL, *cmn; 2892 struct mbuf **cme = &cm; 2893 #ifdef KERN_TLS 2894 struct cmsghdr *cmsg; 2895 struct tls_get_record tgr; 2896 2897 /* 2898 * For MSG_TLSAPPDATA, check for an alert record. 2899 * If found, return ENXIO without removing 2900 * it from the receive queue. This allows a subsequent 2901 * call without MSG_TLSAPPDATA to receive it. 2902 * Note that, for TLS, there should only be a single 2903 * control mbuf with the TLS_GET_RECORD message in it. 2904 */ 2905 if (flags & MSG_TLSAPPDATA) { 2906 cmsg = mtod(m, struct cmsghdr *); 2907 if (cmsg->cmsg_type == TLS_GET_RECORD && 2908 cmsg->cmsg_len == CMSG_LEN(sizeof(tgr))) { 2909 memcpy(&tgr, CMSG_DATA(cmsg), sizeof(tgr)); 2910 if (__predict_false(tgr.tls_type == 2911 TLS_RLTYPE_ALERT)) { 2912 SOCKBUF_UNLOCK(&so->so_rcv); 2913 error = ENXIO; 2914 goto release; 2915 } 2916 } 2917 } 2918 #endif 2919 2920 do { 2921 if (flags & MSG_PEEK) { 2922 if (controlp != NULL) { 2923 *controlp = m_copym(m, 0, m->m_len, 2924 M_NOWAIT); 2925 controlp = &(*controlp)->m_next; 2926 } 2927 m = m->m_next; 2928 } else { 2929 sbfree(&so->so_rcv, m); 2930 so->so_rcv.sb_mb = m->m_next; 2931 m->m_next = NULL; 2932 *cme = m; 2933 cme = &(*cme)->m_next; 2934 m = so->so_rcv.sb_mb; 2935 } 2936 } while (m != NULL && m->m_type == MT_CONTROL); 2937 if ((flags & MSG_PEEK) == 0) 2938 sockbuf_pushsync(&so->so_rcv, nextrecord); 2939 while (cm != NULL) { 2940 cmn = cm->m_next; 2941 cm->m_next = NULL; 2942 if (controlp != NULL) 2943 *controlp = cm; 2944 else 2945 m_freem(cm); 2946 if (controlp != NULL) { 2947 while (*controlp != NULL) 2948 controlp = &(*controlp)->m_next; 2949 } 2950 cm = cmn; 2951 } 2952 if (m != NULL) 2953 nextrecord = so->so_rcv.sb_mb->m_nextpkt; 2954 else 2955 nextrecord = so->so_rcv.sb_mb; 2956 orig_resid = 0; 2957 } 2958 if (m != NULL) { 2959 if ((flags & MSG_PEEK) == 0) { 2960 KASSERT(m->m_nextpkt == nextrecord, 2961 ("soreceive: post-control, nextrecord !sync")); 2962 if (nextrecord == NULL) { 2963 KASSERT(so->so_rcv.sb_mb == m, 2964 ("soreceive: post-control, sb_mb!=m")); 2965 KASSERT(so->so_rcv.sb_lastrecord == m, 2966 ("soreceive: post-control, lastrecord!=m")); 2967 } 2968 } 2969 type = m->m_type; 2970 if (type == MT_OOBDATA) 2971 flags |= MSG_OOB; 2972 } else { 2973 if ((flags & MSG_PEEK) == 0) { 2974 KASSERT(so->so_rcv.sb_mb == nextrecord, 2975 ("soreceive: sb_mb != nextrecord")); 2976 if (so->so_rcv.sb_mb == NULL) { 2977 KASSERT(so->so_rcv.sb_lastrecord == NULL, 2978 ("soreceive: sb_lastercord != NULL")); 2979 } 2980 } 2981 } 2982 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2983 SBLASTRECORDCHK(&so->so_rcv); 2984 SBLASTMBUFCHK(&so->so_rcv); 2985 2986 /* 2987 * Now continue to read any data mbufs off of the head of the socket 2988 * buffer until the read request is satisfied. Note that 'type' is 2989 * used to store the type of any mbuf reads that have happened so far 2990 * such that soreceive() can stop reading if the type changes, which 2991 * causes soreceive() to return only one of regular data and inline 2992 * out-of-band data in a single socket receive operation. 2993 */ 2994 moff = 0; 2995 offset = 0; 2996 while (m != NULL && !(m->m_flags & M_NOTREADY) && uio->uio_resid > 0 && 2997 error == 0) { 2998 /* 2999 * If the type of mbuf has changed since the last mbuf 3000 * examined ('type'), end the receive operation. 3001 */ 3002 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3003 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) { 3004 if (type != m->m_type) 3005 break; 3006 } else if (type == MT_OOBDATA) 3007 break; 3008 else 3009 KASSERT(m->m_type == MT_DATA, 3010 ("m->m_type == %d", m->m_type)); 3011 so->so_rcv.sb_state &= ~SBS_RCVATMARK; 3012 len = uio->uio_resid; 3013 if (so->so_oobmark && len > so->so_oobmark - offset) 3014 len = so->so_oobmark - offset; 3015 if (len > m->m_len - moff) 3016 len = m->m_len - moff; 3017 /* 3018 * If mp is set, just pass back the mbufs. Otherwise copy 3019 * them out via the uio, then free. Sockbuf must be 3020 * consistent here (points to current mbuf, it points to next 3021 * record) when we drop priority; we must note any additions 3022 * to the sockbuf when we block interrupts again. 3023 */ 3024 if (mp == NULL) { 3025 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3026 SBLASTRECORDCHK(&so->so_rcv); 3027 SBLASTMBUFCHK(&so->so_rcv); 3028 SOCKBUF_UNLOCK(&so->so_rcv); 3029 if ((m->m_flags & M_EXTPG) != 0) 3030 error = m_unmapped_uiomove(m, moff, uio, 3031 (int)len); 3032 else 3033 error = uiomove(mtod(m, char *) + moff, 3034 (int)len, uio); 3035 SOCKBUF_LOCK(&so->so_rcv); 3036 if (error) { 3037 /* 3038 * The MT_SONAME mbuf has already been removed 3039 * from the record, so it is necessary to 3040 * remove the data mbufs, if any, to preserve 3041 * the invariant in the case of PR_ADDR that 3042 * requires MT_SONAME mbufs at the head of 3043 * each record. 3044 */ 3045 if (pr->pr_flags & PR_ATOMIC && 3046 ((flags & MSG_PEEK) == 0)) 3047 (void)sbdroprecord_locked(&so->so_rcv); 3048 SOCKBUF_UNLOCK(&so->so_rcv); 3049 goto release; 3050 } 3051 } else 3052 uio->uio_resid -= len; 3053 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3054 if (len == m->m_len - moff) { 3055 if (m->m_flags & M_EOR) 3056 flags |= MSG_EOR; 3057 if (flags & MSG_PEEK) { 3058 m = m->m_next; 3059 moff = 0; 3060 } else { 3061 nextrecord = m->m_nextpkt; 3062 sbfree(&so->so_rcv, m); 3063 if (mp != NULL) { 3064 m->m_nextpkt = NULL; 3065 *mp = m; 3066 mp = &m->m_next; 3067 so->so_rcv.sb_mb = m = m->m_next; 3068 *mp = NULL; 3069 } else { 3070 so->so_rcv.sb_mb = m_free(m); 3071 m = so->so_rcv.sb_mb; 3072 } 3073 sockbuf_pushsync(&so->so_rcv, nextrecord); 3074 SBLASTRECORDCHK(&so->so_rcv); 3075 SBLASTMBUFCHK(&so->so_rcv); 3076 } 3077 } else { 3078 if (flags & MSG_PEEK) 3079 moff += len; 3080 else { 3081 if (mp != NULL) { 3082 if (flags & MSG_DONTWAIT) { 3083 *mp = m_copym(m, 0, len, 3084 M_NOWAIT); 3085 if (*mp == NULL) { 3086 /* 3087 * m_copym() couldn't 3088 * allocate an mbuf. 3089 * Adjust uio_resid back 3090 * (it was adjusted 3091 * down by len bytes, 3092 * which we didn't end 3093 * up "copying" over). 3094 */ 3095 uio->uio_resid += len; 3096 break; 3097 } 3098 } else { 3099 SOCKBUF_UNLOCK(&so->so_rcv); 3100 *mp = m_copym(m, 0, len, 3101 M_WAITOK); 3102 SOCKBUF_LOCK(&so->so_rcv); 3103 } 3104 } 3105 sbcut_locked(&so->so_rcv, len); 3106 } 3107 } 3108 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3109 if (so->so_oobmark) { 3110 if ((flags & MSG_PEEK) == 0) { 3111 so->so_oobmark -= len; 3112 if (so->so_oobmark == 0) { 3113 so->so_rcv.sb_state |= SBS_RCVATMARK; 3114 break; 3115 } 3116 } else { 3117 offset += len; 3118 if (offset == so->so_oobmark) 3119 break; 3120 } 3121 } 3122 if (flags & MSG_EOR) 3123 break; 3124 /* 3125 * If the MSG_WAITALL flag is set (for non-atomic socket), we 3126 * must not quit until "uio->uio_resid == 0" or an error 3127 * termination. If a signal/timeout occurs, return with a 3128 * short count but without error. Keep sockbuf locked 3129 * against other readers. 3130 */ 3131 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 && 3132 !sosendallatonce(so) && nextrecord == NULL) { 3133 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3134 if (so->so_error || so->so_rerror || 3135 so->so_rcv.sb_state & SBS_CANTRCVMORE) 3136 break; 3137 /* 3138 * Notify the protocol that some data has been 3139 * drained before blocking. 3140 */ 3141 if (pr->pr_flags & PR_WANTRCVD) { 3142 SOCKBUF_UNLOCK(&so->so_rcv); 3143 VNET_SO_ASSERT(so); 3144 pr->pr_rcvd(so, flags); 3145 SOCKBUF_LOCK(&so->so_rcv); 3146 if (__predict_false(so->so_rcv.sb_mb == NULL && 3147 (so->so_error || so->so_rerror || 3148 so->so_rcv.sb_state & SBS_CANTRCVMORE))) 3149 break; 3150 } 3151 SBLASTRECORDCHK(&so->so_rcv); 3152 SBLASTMBUFCHK(&so->so_rcv); 3153 /* 3154 * We could receive some data while was notifying 3155 * the protocol. Skip blocking in this case. 3156 */ 3157 if (so->so_rcv.sb_mb == NULL) { 3158 error = sbwait(so, SO_RCV); 3159 if (error) { 3160 SOCKBUF_UNLOCK(&so->so_rcv); 3161 goto release; 3162 } 3163 } 3164 m = so->so_rcv.sb_mb; 3165 if (m != NULL) 3166 nextrecord = m->m_nextpkt; 3167 } 3168 } 3169 3170 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3171 if (m != NULL && pr->pr_flags & PR_ATOMIC) { 3172 if (report_real_len) 3173 uio->uio_resid -= m_length(m, NULL) - moff; 3174 flags |= MSG_TRUNC; 3175 if ((flags & MSG_PEEK) == 0) 3176 (void) sbdroprecord_locked(&so->so_rcv); 3177 } 3178 if ((flags & MSG_PEEK) == 0) { 3179 if (m == NULL) { 3180 /* 3181 * First part is an inline SB_EMPTY_FIXUP(). Second 3182 * part makes sure sb_lastrecord is up-to-date if 3183 * there is still data in the socket buffer. 3184 */ 3185 so->so_rcv.sb_mb = nextrecord; 3186 if (so->so_rcv.sb_mb == NULL) { 3187 so->so_rcv.sb_mbtail = NULL; 3188 so->so_rcv.sb_lastrecord = NULL; 3189 } else if (nextrecord->m_nextpkt == NULL) 3190 so->so_rcv.sb_lastrecord = nextrecord; 3191 } 3192 SBLASTRECORDCHK(&so->so_rcv); 3193 SBLASTMBUFCHK(&so->so_rcv); 3194 /* 3195 * If soreceive() is being done from the socket callback, 3196 * then don't need to generate ACK to peer to update window, 3197 * since ACK will be generated on return to TCP. 3198 */ 3199 if (!(flags & MSG_SOCALLBCK) && 3200 (pr->pr_flags & PR_WANTRCVD)) { 3201 SOCKBUF_UNLOCK(&so->so_rcv); 3202 VNET_SO_ASSERT(so); 3203 pr->pr_rcvd(so, flags); 3204 SOCKBUF_LOCK(&so->so_rcv); 3205 } 3206 } 3207 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3208 if (orig_resid == uio->uio_resid && orig_resid && 3209 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) { 3210 SOCKBUF_UNLOCK(&so->so_rcv); 3211 goto restart; 3212 } 3213 SOCKBUF_UNLOCK(&so->so_rcv); 3214 3215 if (flagsp != NULL) 3216 *flagsp |= flags; 3217 release: 3218 return (error); 3219 } 3220 3221 int 3222 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio, 3223 struct mbuf **mp, struct mbuf **controlp, int *flagsp) 3224 { 3225 int error, flags; 3226 3227 if (psa != NULL) 3228 *psa = NULL; 3229 if (controlp != NULL) 3230 *controlp = NULL; 3231 if (flagsp != NULL) { 3232 flags = *flagsp; 3233 if ((flags & MSG_OOB) != 0) 3234 return (soreceive_rcvoob(so, uio, flags)); 3235 } else { 3236 flags = 0; 3237 } 3238 if (mp != NULL) 3239 *mp = NULL; 3240 3241 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags)); 3242 if (error) 3243 return (error); 3244 error = soreceive_generic_locked(so, psa, uio, mp, controlp, flagsp); 3245 SOCK_IO_RECV_UNLOCK(so); 3246 return (error); 3247 } 3248 3249 /* 3250 * Optimized version of soreceive() for stream (TCP) sockets. 3251 */ 3252 static int 3253 soreceive_stream_locked(struct socket *so, struct sockbuf *sb, 3254 struct sockaddr **psa, struct uio *uio, struct mbuf **mp0, 3255 struct mbuf **controlp, int flags) 3256 { 3257 int len = 0, error = 0, oresid; 3258 struct mbuf *m, *n = NULL; 3259 3260 SOCK_IO_RECV_ASSERT_LOCKED(so); 3261 3262 /* Easy one, no space to copyout anything. */ 3263 if (uio->uio_resid == 0) 3264 return (EINVAL); 3265 oresid = uio->uio_resid; 3266 3267 SOCKBUF_LOCK(sb); 3268 /* We will never ever get anything unless we are or were connected. */ 3269 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) { 3270 error = ENOTCONN; 3271 goto out; 3272 } 3273 3274 restart: 3275 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3276 3277 /* Abort if socket has reported problems. */ 3278 if (so->so_error) { 3279 if (sbavail(sb) > 0) 3280 goto deliver; 3281 if (oresid > uio->uio_resid) 3282 goto out; 3283 error = so->so_error; 3284 if (!(flags & MSG_PEEK)) 3285 so->so_error = 0; 3286 goto out; 3287 } 3288 3289 /* Door is closed. Deliver what is left, if any. */ 3290 if (sb->sb_state & SBS_CANTRCVMORE) { 3291 if (sbavail(sb) > 0) 3292 goto deliver; 3293 else 3294 goto out; 3295 } 3296 3297 /* Socket buffer is empty and we shall not block. */ 3298 if (sbavail(sb) == 0 && 3299 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) { 3300 error = EAGAIN; 3301 goto out; 3302 } 3303 3304 /* Socket buffer got some data that we shall deliver now. */ 3305 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) && 3306 ((so->so_state & SS_NBIO) || 3307 (flags & (MSG_DONTWAIT|MSG_NBIO)) || 3308 sbavail(sb) >= sb->sb_lowat || 3309 sbavail(sb) >= uio->uio_resid || 3310 sbavail(sb) >= sb->sb_hiwat) ) { 3311 goto deliver; 3312 } 3313 3314 /* On MSG_WAITALL we must wait until all data or error arrives. */ 3315 if ((flags & MSG_WAITALL) && 3316 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat)) 3317 goto deliver; 3318 3319 /* 3320 * Wait and block until (more) data comes in. 3321 * NB: Drops the sockbuf lock during wait. 3322 */ 3323 error = sbwait(so, SO_RCV); 3324 if (error) 3325 goto out; 3326 goto restart; 3327 3328 deliver: 3329 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3330 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__)); 3331 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__)); 3332 3333 /* Statistics. */ 3334 if (uio->uio_td) 3335 uio->uio_td->td_ru.ru_msgrcv++; 3336 3337 /* Fill uio until full or current end of socket buffer is reached. */ 3338 len = min(uio->uio_resid, sbavail(sb)); 3339 if (mp0 != NULL) { 3340 /* Dequeue as many mbufs as possible. */ 3341 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) { 3342 if (*mp0 == NULL) 3343 *mp0 = sb->sb_mb; 3344 else 3345 m_cat(*mp0, sb->sb_mb); 3346 for (m = sb->sb_mb; 3347 m != NULL && m->m_len <= len; 3348 m = m->m_next) { 3349 KASSERT(!(m->m_flags & M_NOTREADY), 3350 ("%s: m %p not available", __func__, m)); 3351 len -= m->m_len; 3352 uio->uio_resid -= m->m_len; 3353 sbfree(sb, m); 3354 n = m; 3355 } 3356 n->m_next = NULL; 3357 sb->sb_mb = m; 3358 sb->sb_lastrecord = sb->sb_mb; 3359 if (sb->sb_mb == NULL) 3360 SB_EMPTY_FIXUP(sb); 3361 } 3362 /* Copy the remainder. */ 3363 if (len > 0) { 3364 KASSERT(sb->sb_mb != NULL, 3365 ("%s: len > 0 && sb->sb_mb empty", __func__)); 3366 3367 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT); 3368 if (m == NULL) 3369 len = 0; /* Don't flush data from sockbuf. */ 3370 else 3371 uio->uio_resid -= len; 3372 if (*mp0 != NULL) 3373 m_cat(*mp0, m); 3374 else 3375 *mp0 = m; 3376 if (*mp0 == NULL) { 3377 error = ENOBUFS; 3378 goto out; 3379 } 3380 } 3381 } else { 3382 /* NB: Must unlock socket buffer as uiomove may sleep. */ 3383 SOCKBUF_UNLOCK(sb); 3384 error = m_mbuftouio(uio, sb->sb_mb, len); 3385 SOCKBUF_LOCK(sb); 3386 if (error) 3387 goto out; 3388 } 3389 SBLASTRECORDCHK(sb); 3390 SBLASTMBUFCHK(sb); 3391 3392 /* 3393 * Remove the delivered data from the socket buffer unless we 3394 * were only peeking. 3395 */ 3396 if (!(flags & MSG_PEEK)) { 3397 if (len > 0) 3398 sbdrop_locked(sb, len); 3399 3400 /* Notify protocol that we drained some data. */ 3401 if ((so->so_proto->pr_flags & PR_WANTRCVD) && 3402 (((flags & MSG_WAITALL) && uio->uio_resid > 0) || 3403 !(flags & MSG_SOCALLBCK))) { 3404 SOCKBUF_UNLOCK(sb); 3405 VNET_SO_ASSERT(so); 3406 so->so_proto->pr_rcvd(so, flags); 3407 SOCKBUF_LOCK(sb); 3408 } 3409 } 3410 3411 /* 3412 * For MSG_WAITALL we may have to loop again and wait for 3413 * more data to come in. 3414 */ 3415 if ((flags & MSG_WAITALL) && uio->uio_resid > 0) 3416 goto restart; 3417 out: 3418 SBLASTRECORDCHK(sb); 3419 SBLASTMBUFCHK(sb); 3420 SOCKBUF_UNLOCK(sb); 3421 return (error); 3422 } 3423 3424 int 3425 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio, 3426 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 3427 { 3428 struct sockbuf *sb; 3429 int error, flags; 3430 3431 sb = &so->so_rcv; 3432 3433 /* We only do stream sockets. */ 3434 if (so->so_type != SOCK_STREAM) 3435 return (EINVAL); 3436 if (psa != NULL) 3437 *psa = NULL; 3438 if (flagsp != NULL) 3439 flags = *flagsp & ~MSG_EOR; 3440 else 3441 flags = 0; 3442 if (controlp != NULL) 3443 *controlp = NULL; 3444 if (flags & MSG_OOB) 3445 return (soreceive_rcvoob(so, uio, flags)); 3446 if (mp0 != NULL) 3447 *mp0 = NULL; 3448 3449 #ifdef KERN_TLS 3450 /* 3451 * KTLS store TLS records as records with a control message to 3452 * describe the framing. 3453 * 3454 * We check once here before acquiring locks to optimize the 3455 * common case. 3456 */ 3457 if (sb->sb_tls_info != NULL) 3458 return (soreceive_generic(so, psa, uio, mp0, controlp, 3459 flagsp)); 3460 #endif 3461 3462 /* 3463 * Prevent other threads from reading from the socket. This lock may be 3464 * dropped in order to sleep waiting for data to arrive. 3465 */ 3466 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags)); 3467 if (error) 3468 return (error); 3469 #ifdef KERN_TLS 3470 if (__predict_false(sb->sb_tls_info != NULL)) { 3471 SOCK_IO_RECV_UNLOCK(so); 3472 return (soreceive_generic(so, psa, uio, mp0, controlp, 3473 flagsp)); 3474 } 3475 #endif 3476 error = soreceive_stream_locked(so, sb, psa, uio, mp0, controlp, flags); 3477 SOCK_IO_RECV_UNLOCK(so); 3478 return (error); 3479 } 3480 3481 /* 3482 * Optimized version of soreceive() for simple datagram cases from userspace. 3483 * Unlike in the stream case, we're able to drop a datagram if copyout() 3484 * fails, and because we handle datagrams atomically, we don't need to use a 3485 * sleep lock to prevent I/O interlacing. 3486 */ 3487 int 3488 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio, 3489 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 3490 { 3491 struct mbuf *m, *m2; 3492 int flags, error; 3493 ssize_t len; 3494 struct protosw *pr = so->so_proto; 3495 struct mbuf *nextrecord; 3496 3497 if (psa != NULL) 3498 *psa = NULL; 3499 if (controlp != NULL) 3500 *controlp = NULL; 3501 if (flagsp != NULL) 3502 flags = *flagsp &~ MSG_EOR; 3503 else 3504 flags = 0; 3505 3506 /* 3507 * For any complicated cases, fall back to the full 3508 * soreceive_generic(). 3509 */ 3510 if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC))) 3511 return (soreceive_generic(so, psa, uio, mp0, controlp, 3512 flagsp)); 3513 3514 /* 3515 * Enforce restrictions on use. 3516 */ 3517 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0, 3518 ("soreceive_dgram: wantrcvd")); 3519 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic")); 3520 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0, 3521 ("soreceive_dgram: SBS_RCVATMARK")); 3522 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0, 3523 ("soreceive_dgram: P_CONNREQUIRED")); 3524 3525 /* 3526 * Loop blocking while waiting for a datagram. 3527 */ 3528 SOCKBUF_LOCK(&so->so_rcv); 3529 while ((m = so->so_rcv.sb_mb) == NULL) { 3530 KASSERT(sbavail(&so->so_rcv) == 0, 3531 ("soreceive_dgram: sb_mb NULL but sbavail %u", 3532 sbavail(&so->so_rcv))); 3533 if (so->so_error) { 3534 error = so->so_error; 3535 so->so_error = 0; 3536 SOCKBUF_UNLOCK(&so->so_rcv); 3537 return (error); 3538 } 3539 if (so->so_rcv.sb_state & SBS_CANTRCVMORE || 3540 uio->uio_resid == 0) { 3541 SOCKBUF_UNLOCK(&so->so_rcv); 3542 return (0); 3543 } 3544 if ((so->so_state & SS_NBIO) || 3545 (flags & (MSG_DONTWAIT|MSG_NBIO))) { 3546 SOCKBUF_UNLOCK(&so->so_rcv); 3547 return (EWOULDBLOCK); 3548 } 3549 SBLASTRECORDCHK(&so->so_rcv); 3550 SBLASTMBUFCHK(&so->so_rcv); 3551 error = sbwait(so, SO_RCV); 3552 if (error) { 3553 SOCKBUF_UNLOCK(&so->so_rcv); 3554 return (error); 3555 } 3556 } 3557 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 3558 3559 if (uio->uio_td) 3560 uio->uio_td->td_ru.ru_msgrcv++; 3561 SBLASTRECORDCHK(&so->so_rcv); 3562 SBLASTMBUFCHK(&so->so_rcv); 3563 nextrecord = m->m_nextpkt; 3564 if (nextrecord == NULL) { 3565 KASSERT(so->so_rcv.sb_lastrecord == m, 3566 ("soreceive_dgram: lastrecord != m")); 3567 } 3568 3569 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord, 3570 ("soreceive_dgram: m_nextpkt != nextrecord")); 3571 3572 /* 3573 * Pull 'm' and its chain off the front of the packet queue. 3574 */ 3575 so->so_rcv.sb_mb = NULL; 3576 sockbuf_pushsync(&so->so_rcv, nextrecord); 3577 3578 /* 3579 * Walk 'm's chain and free that many bytes from the socket buffer. 3580 */ 3581 for (m2 = m; m2 != NULL; m2 = m2->m_next) 3582 sbfree(&so->so_rcv, m2); 3583 3584 /* 3585 * Do a few last checks before we let go of the lock. 3586 */ 3587 SBLASTRECORDCHK(&so->so_rcv); 3588 SBLASTMBUFCHK(&so->so_rcv); 3589 SOCKBUF_UNLOCK(&so->so_rcv); 3590 3591 if (pr->pr_flags & PR_ADDR) { 3592 KASSERT(m->m_type == MT_SONAME, 3593 ("m->m_type == %d", m->m_type)); 3594 if (psa != NULL) 3595 *psa = sodupsockaddr(mtod(m, struct sockaddr *), 3596 M_WAITOK); 3597 m = m_free(m); 3598 } 3599 KASSERT(m, ("%s: no data or control after soname", __func__)); 3600 3601 /* 3602 * Packet to copyout() is now in 'm' and it is disconnected from the 3603 * queue. 3604 * 3605 * Process one or more MT_CONTROL mbufs present before any data mbufs 3606 * in the first mbuf chain on the socket buffer. We call into the 3607 * protocol to perform externalization (or freeing if controlp == 3608 * NULL). In some cases there can be only MT_CONTROL mbufs without 3609 * MT_DATA mbufs. 3610 */ 3611 if (m->m_type == MT_CONTROL) { 3612 struct mbuf *cm = NULL, *cmn; 3613 struct mbuf **cme = &cm; 3614 3615 do { 3616 m2 = m->m_next; 3617 m->m_next = NULL; 3618 *cme = m; 3619 cme = &(*cme)->m_next; 3620 m = m2; 3621 } while (m != NULL && m->m_type == MT_CONTROL); 3622 while (cm != NULL) { 3623 cmn = cm->m_next; 3624 cm->m_next = NULL; 3625 if (controlp != NULL) 3626 *controlp = cm; 3627 else 3628 m_freem(cm); 3629 if (controlp != NULL) { 3630 while (*controlp != NULL) 3631 controlp = &(*controlp)->m_next; 3632 } 3633 cm = cmn; 3634 } 3635 } 3636 KASSERT(m == NULL || m->m_type == MT_DATA, 3637 ("soreceive_dgram: !data")); 3638 while (m != NULL && uio->uio_resid > 0) { 3639 len = uio->uio_resid; 3640 if (len > m->m_len) 3641 len = m->m_len; 3642 error = uiomove(mtod(m, char *), (int)len, uio); 3643 if (error) { 3644 m_freem(m); 3645 return (error); 3646 } 3647 if (len == m->m_len) 3648 m = m_free(m); 3649 else { 3650 m->m_data += len; 3651 m->m_len -= len; 3652 } 3653 } 3654 if (m != NULL) { 3655 flags |= MSG_TRUNC; 3656 m_freem(m); 3657 } 3658 if (flagsp != NULL) 3659 *flagsp |= flags; 3660 return (0); 3661 } 3662 3663 int 3664 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio, 3665 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 3666 { 3667 int error; 3668 3669 CURVNET_SET(so->so_vnet); 3670 error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp); 3671 CURVNET_RESTORE(); 3672 return (error); 3673 } 3674 3675 int 3676 soshutdown(struct socket *so, enum shutdown_how how) 3677 { 3678 int error; 3679 3680 CURVNET_SET(so->so_vnet); 3681 error = so->so_proto->pr_shutdown(so, how); 3682 CURVNET_RESTORE(); 3683 3684 return (error); 3685 } 3686 3687 /* 3688 * Used by several pr_shutdown implementations that use generic socket buffers. 3689 */ 3690 void 3691 sorflush(struct socket *so) 3692 { 3693 int error; 3694 3695 VNET_SO_ASSERT(so); 3696 3697 /* 3698 * Dislodge threads currently blocked in receive and wait to acquire 3699 * a lock against other simultaneous readers before clearing the 3700 * socket buffer. Don't let our acquire be interrupted by a signal 3701 * despite any existing socket disposition on interruptable waiting. 3702 * 3703 * The SOCK_IO_RECV_LOCK() is important here as there some pr_soreceive 3704 * methods that read the top of the socket buffer without acquisition 3705 * of the socket buffer mutex, assuming that top of the buffer 3706 * exclusively belongs to the read(2) syscall. This is handy when 3707 * performing MSG_PEEK. 3708 */ 3709 socantrcvmore(so); 3710 3711 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR); 3712 if (error != 0) { 3713 KASSERT(SOLISTENING(so), 3714 ("%s: soiolock(%p) failed", __func__, so)); 3715 return; 3716 } 3717 3718 sbrelease(so, SO_RCV); 3719 SOCK_IO_RECV_UNLOCK(so); 3720 3721 } 3722 3723 int 3724 sosetfib(struct socket *so, int fibnum) 3725 { 3726 if (fibnum < 0 || fibnum >= rt_numfibs) 3727 return (EINVAL); 3728 3729 SOCK_LOCK(so); 3730 so->so_fibnum = fibnum; 3731 SOCK_UNLOCK(so); 3732 3733 return (0); 3734 } 3735 3736 #ifdef SOCKET_HHOOK 3737 /* 3738 * Wrapper for Socket established helper hook. 3739 * Parameters: socket, context of the hook point, hook id. 3740 */ 3741 static inline int 3742 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id) 3743 { 3744 struct socket_hhook_data hhook_data = { 3745 .so = so, 3746 .hctx = hctx, 3747 .m = NULL, 3748 .status = 0 3749 }; 3750 3751 CURVNET_SET(so->so_vnet); 3752 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd); 3753 CURVNET_RESTORE(); 3754 3755 /* Ugly but needed, since hhooks return void for now */ 3756 return (hhook_data.status); 3757 } 3758 #endif 3759 3760 /* 3761 * Perhaps this routine, and sooptcopyout(), below, ought to come in an 3762 * additional variant to handle the case where the option value needs to be 3763 * some kind of integer, but not a specific size. In addition to their use 3764 * here, these functions are also called by the protocol-level pr_ctloutput() 3765 * routines. 3766 */ 3767 int 3768 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen) 3769 { 3770 size_t valsize; 3771 3772 /* 3773 * If the user gives us more than we wanted, we ignore it, but if we 3774 * don't get the minimum length the caller wants, we return EINVAL. 3775 * On success, sopt->sopt_valsize is set to however much we actually 3776 * retrieved. 3777 */ 3778 if ((valsize = sopt->sopt_valsize) < minlen) 3779 return EINVAL; 3780 if (valsize > len) 3781 sopt->sopt_valsize = valsize = len; 3782 3783 if (sopt->sopt_td != NULL) 3784 return (copyin(sopt->sopt_val, buf, valsize)); 3785 3786 bcopy(sopt->sopt_val, buf, valsize); 3787 return (0); 3788 } 3789 3790 /* 3791 * Kernel version of setsockopt(2). 3792 * 3793 * XXX: optlen is size_t, not socklen_t 3794 */ 3795 int 3796 so_setsockopt(struct socket *so, int level, int optname, void *optval, 3797 size_t optlen) 3798 { 3799 struct sockopt sopt; 3800 3801 sopt.sopt_level = level; 3802 sopt.sopt_name = optname; 3803 sopt.sopt_dir = SOPT_SET; 3804 sopt.sopt_val = optval; 3805 sopt.sopt_valsize = optlen; 3806 sopt.sopt_td = NULL; 3807 return (sosetopt(so, &sopt)); 3808 } 3809 3810 int 3811 sosetopt(struct socket *so, struct sockopt *sopt) 3812 { 3813 int error, optval; 3814 struct linger l; 3815 struct timeval tv; 3816 sbintime_t val, *valp; 3817 uint32_t val32; 3818 #ifdef MAC 3819 struct mac extmac; 3820 #endif 3821 3822 CURVNET_SET(so->so_vnet); 3823 error = 0; 3824 if (sopt->sopt_level != SOL_SOCKET) { 3825 error = so->so_proto->pr_ctloutput(so, sopt); 3826 } else { 3827 switch (sopt->sopt_name) { 3828 case SO_ACCEPTFILTER: 3829 error = accept_filt_setopt(so, sopt); 3830 if (error) 3831 goto bad; 3832 break; 3833 3834 case SO_LINGER: 3835 error = sooptcopyin(sopt, &l, sizeof l, sizeof l); 3836 if (error) 3837 goto bad; 3838 if (l.l_linger < 0 || 3839 l.l_linger > USHRT_MAX || 3840 l.l_linger > (INT_MAX / hz)) { 3841 error = EDOM; 3842 goto bad; 3843 } 3844 SOCK_LOCK(so); 3845 so->so_linger = l.l_linger; 3846 if (l.l_onoff) 3847 so->so_options |= SO_LINGER; 3848 else 3849 so->so_options &= ~SO_LINGER; 3850 SOCK_UNLOCK(so); 3851 break; 3852 3853 case SO_DEBUG: 3854 case SO_KEEPALIVE: 3855 case SO_DONTROUTE: 3856 case SO_USELOOPBACK: 3857 case SO_BROADCAST: 3858 case SO_REUSEADDR: 3859 case SO_REUSEPORT: 3860 case SO_REUSEPORT_LB: 3861 case SO_OOBINLINE: 3862 case SO_TIMESTAMP: 3863 case SO_BINTIME: 3864 case SO_NOSIGPIPE: 3865 case SO_NO_DDP: 3866 case SO_NO_OFFLOAD: 3867 case SO_RERROR: 3868 error = sooptcopyin(sopt, &optval, sizeof optval, 3869 sizeof optval); 3870 if (error) 3871 goto bad; 3872 SOCK_LOCK(so); 3873 if (optval) 3874 so->so_options |= sopt->sopt_name; 3875 else 3876 so->so_options &= ~sopt->sopt_name; 3877 SOCK_UNLOCK(so); 3878 break; 3879 3880 case SO_SETFIB: 3881 error = so->so_proto->pr_ctloutput(so, sopt); 3882 break; 3883 3884 case SO_USER_COOKIE: 3885 error = sooptcopyin(sopt, &val32, sizeof val32, 3886 sizeof val32); 3887 if (error) 3888 goto bad; 3889 so->so_user_cookie = val32; 3890 break; 3891 3892 case SO_SNDBUF: 3893 case SO_RCVBUF: 3894 case SO_SNDLOWAT: 3895 case SO_RCVLOWAT: 3896 error = so->so_proto->pr_setsbopt(so, sopt); 3897 if (error) 3898 goto bad; 3899 break; 3900 3901 case SO_SNDTIMEO: 3902 case SO_RCVTIMEO: 3903 #ifdef COMPAT_FREEBSD32 3904 if (SV_CURPROC_FLAG(SV_ILP32)) { 3905 struct timeval32 tv32; 3906 3907 error = sooptcopyin(sopt, &tv32, sizeof tv32, 3908 sizeof tv32); 3909 CP(tv32, tv, tv_sec); 3910 CP(tv32, tv, tv_usec); 3911 } else 3912 #endif 3913 error = sooptcopyin(sopt, &tv, sizeof tv, 3914 sizeof tv); 3915 if (error) 3916 goto bad; 3917 if (tv.tv_sec < 0 || tv.tv_usec < 0 || 3918 tv.tv_usec >= 1000000) { 3919 error = EDOM; 3920 goto bad; 3921 } 3922 if (tv.tv_sec > INT32_MAX) 3923 val = SBT_MAX; 3924 else 3925 val = tvtosbt(tv); 3926 SOCK_LOCK(so); 3927 valp = sopt->sopt_name == SO_SNDTIMEO ? 3928 (SOLISTENING(so) ? &so->sol_sbsnd_timeo : 3929 &so->so_snd.sb_timeo) : 3930 (SOLISTENING(so) ? &so->sol_sbrcv_timeo : 3931 &so->so_rcv.sb_timeo); 3932 *valp = val; 3933 SOCK_UNLOCK(so); 3934 break; 3935 3936 case SO_LABEL: 3937 #ifdef MAC 3938 error = sooptcopyin(sopt, &extmac, sizeof extmac, 3939 sizeof extmac); 3940 if (error) 3941 goto bad; 3942 error = mac_setsockopt_label(sopt->sopt_td->td_ucred, 3943 so, &extmac); 3944 #else 3945 error = EOPNOTSUPP; 3946 #endif 3947 break; 3948 3949 case SO_TS_CLOCK: 3950 error = sooptcopyin(sopt, &optval, sizeof optval, 3951 sizeof optval); 3952 if (error) 3953 goto bad; 3954 if (optval < 0 || optval > SO_TS_CLOCK_MAX) { 3955 error = EINVAL; 3956 goto bad; 3957 } 3958 so->so_ts_clock = optval; 3959 break; 3960 3961 case SO_MAX_PACING_RATE: 3962 error = sooptcopyin(sopt, &val32, sizeof(val32), 3963 sizeof(val32)); 3964 if (error) 3965 goto bad; 3966 so->so_max_pacing_rate = val32; 3967 break; 3968 3969 case SO_SPLICE: { 3970 struct splice splice; 3971 3972 #ifdef COMPAT_FREEBSD32 3973 if (SV_CURPROC_FLAG(SV_ILP32)) { 3974 struct splice32 splice32; 3975 3976 error = sooptcopyin(sopt, &splice32, 3977 sizeof(splice32), sizeof(splice32)); 3978 if (error == 0) { 3979 splice.sp_fd = splice32.sp_fd; 3980 splice.sp_max = splice32.sp_max; 3981 CP(splice32.sp_idle, splice.sp_idle, 3982 tv_sec); 3983 CP(splice32.sp_idle, splice.sp_idle, 3984 tv_usec); 3985 } 3986 } else 3987 #endif 3988 { 3989 error = sooptcopyin(sopt, &splice, 3990 sizeof(splice), sizeof(splice)); 3991 } 3992 if (error) 3993 goto bad; 3994 #ifdef KTRACE 3995 if (KTRPOINT(curthread, KTR_STRUCT)) 3996 ktrsplice(&splice); 3997 #endif 3998 3999 error = splice_init(); 4000 if (error != 0) 4001 goto bad; 4002 4003 if (splice.sp_fd >= 0) { 4004 struct file *fp; 4005 struct socket *so2; 4006 4007 if (!cap_rights_contains(sopt->sopt_rights, 4008 &cap_recv_rights)) { 4009 error = ENOTCAPABLE; 4010 goto bad; 4011 } 4012 error = getsock(sopt->sopt_td, splice.sp_fd, 4013 &cap_send_rights, &fp); 4014 if (error != 0) 4015 goto bad; 4016 so2 = fp->f_data; 4017 4018 error = so_splice(so, so2, &splice); 4019 fdrop(fp, sopt->sopt_td); 4020 } else { 4021 error = so_unsplice(so, false); 4022 } 4023 break; 4024 } 4025 default: 4026 #ifdef SOCKET_HHOOK 4027 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0) 4028 error = hhook_run_socket(so, sopt, 4029 HHOOK_SOCKET_OPT); 4030 else 4031 #endif 4032 error = ENOPROTOOPT; 4033 break; 4034 } 4035 if (error == 0) 4036 (void)so->so_proto->pr_ctloutput(so, sopt); 4037 } 4038 bad: 4039 CURVNET_RESTORE(); 4040 return (error); 4041 } 4042 4043 /* 4044 * Helper routine for getsockopt. 4045 */ 4046 int 4047 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len) 4048 { 4049 int error; 4050 size_t valsize; 4051 4052 error = 0; 4053 4054 /* 4055 * Documented get behavior is that we always return a value, possibly 4056 * truncated to fit in the user's buffer. Traditional behavior is 4057 * that we always tell the user precisely how much we copied, rather 4058 * than something useful like the total amount we had available for 4059 * her. Note that this interface is not idempotent; the entire 4060 * answer must be generated ahead of time. 4061 */ 4062 valsize = min(len, sopt->sopt_valsize); 4063 sopt->sopt_valsize = valsize; 4064 if (sopt->sopt_val != NULL) { 4065 if (sopt->sopt_td != NULL) 4066 error = copyout(buf, sopt->sopt_val, valsize); 4067 else 4068 bcopy(buf, sopt->sopt_val, valsize); 4069 } 4070 return (error); 4071 } 4072 4073 int 4074 sogetopt(struct socket *so, struct sockopt *sopt) 4075 { 4076 int error, optval; 4077 struct linger l; 4078 struct timeval tv; 4079 #ifdef MAC 4080 struct mac extmac; 4081 #endif 4082 4083 CURVNET_SET(so->so_vnet); 4084 error = 0; 4085 if (sopt->sopt_level != SOL_SOCKET) { 4086 error = so->so_proto->pr_ctloutput(so, sopt); 4087 CURVNET_RESTORE(); 4088 return (error); 4089 } else { 4090 switch (sopt->sopt_name) { 4091 case SO_ACCEPTFILTER: 4092 error = accept_filt_getopt(so, sopt); 4093 break; 4094 4095 case SO_LINGER: 4096 SOCK_LOCK(so); 4097 l.l_onoff = so->so_options & SO_LINGER; 4098 l.l_linger = so->so_linger; 4099 SOCK_UNLOCK(so); 4100 error = sooptcopyout(sopt, &l, sizeof l); 4101 break; 4102 4103 case SO_USELOOPBACK: 4104 case SO_DONTROUTE: 4105 case SO_DEBUG: 4106 case SO_KEEPALIVE: 4107 case SO_REUSEADDR: 4108 case SO_REUSEPORT: 4109 case SO_REUSEPORT_LB: 4110 case SO_BROADCAST: 4111 case SO_OOBINLINE: 4112 case SO_ACCEPTCONN: 4113 case SO_TIMESTAMP: 4114 case SO_BINTIME: 4115 case SO_NOSIGPIPE: 4116 case SO_NO_DDP: 4117 case SO_NO_OFFLOAD: 4118 case SO_RERROR: 4119 optval = so->so_options & sopt->sopt_name; 4120 integer: 4121 error = sooptcopyout(sopt, &optval, sizeof optval); 4122 break; 4123 4124 case SO_FIB: 4125 SOCK_LOCK(so); 4126 optval = so->so_fibnum; 4127 SOCK_UNLOCK(so); 4128 goto integer; 4129 4130 case SO_DOMAIN: 4131 optval = so->so_proto->pr_domain->dom_family; 4132 goto integer; 4133 4134 case SO_TYPE: 4135 optval = so->so_type; 4136 goto integer; 4137 4138 case SO_PROTOCOL: 4139 optval = so->so_proto->pr_protocol; 4140 goto integer; 4141 4142 case SO_ERROR: 4143 SOCK_LOCK(so); 4144 if (so->so_error) { 4145 optval = so->so_error; 4146 so->so_error = 0; 4147 } else { 4148 optval = so->so_rerror; 4149 so->so_rerror = 0; 4150 } 4151 SOCK_UNLOCK(so); 4152 goto integer; 4153 4154 case SO_SNDBUF: 4155 SOCK_LOCK(so); 4156 optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat : 4157 so->so_snd.sb_hiwat; 4158 SOCK_UNLOCK(so); 4159 goto integer; 4160 4161 case SO_RCVBUF: 4162 SOCK_LOCK(so); 4163 optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat : 4164 so->so_rcv.sb_hiwat; 4165 SOCK_UNLOCK(so); 4166 goto integer; 4167 4168 case SO_SNDLOWAT: 4169 SOCK_LOCK(so); 4170 optval = SOLISTENING(so) ? so->sol_sbsnd_lowat : 4171 so->so_snd.sb_lowat; 4172 SOCK_UNLOCK(so); 4173 goto integer; 4174 4175 case SO_RCVLOWAT: 4176 SOCK_LOCK(so); 4177 optval = SOLISTENING(so) ? so->sol_sbrcv_lowat : 4178 so->so_rcv.sb_lowat; 4179 SOCK_UNLOCK(so); 4180 goto integer; 4181 4182 case SO_SNDTIMEO: 4183 case SO_RCVTIMEO: 4184 SOCK_LOCK(so); 4185 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ? 4186 (SOLISTENING(so) ? so->sol_sbsnd_timeo : 4187 so->so_snd.sb_timeo) : 4188 (SOLISTENING(so) ? so->sol_sbrcv_timeo : 4189 so->so_rcv.sb_timeo)); 4190 SOCK_UNLOCK(so); 4191 #ifdef COMPAT_FREEBSD32 4192 if (SV_CURPROC_FLAG(SV_ILP32)) { 4193 struct timeval32 tv32; 4194 4195 CP(tv, tv32, tv_sec); 4196 CP(tv, tv32, tv_usec); 4197 error = sooptcopyout(sopt, &tv32, sizeof tv32); 4198 } else 4199 #endif 4200 error = sooptcopyout(sopt, &tv, sizeof tv); 4201 break; 4202 4203 case SO_LABEL: 4204 #ifdef MAC 4205 error = sooptcopyin(sopt, &extmac, sizeof(extmac), 4206 sizeof(extmac)); 4207 if (error) 4208 goto bad; 4209 error = mac_getsockopt_label(sopt->sopt_td->td_ucred, 4210 so, &extmac); 4211 if (error) 4212 goto bad; 4213 /* Don't copy out extmac, it is unchanged. */ 4214 #else 4215 error = EOPNOTSUPP; 4216 #endif 4217 break; 4218 4219 case SO_PEERLABEL: 4220 #ifdef MAC 4221 error = sooptcopyin(sopt, &extmac, sizeof(extmac), 4222 sizeof(extmac)); 4223 if (error) 4224 goto bad; 4225 error = mac_getsockopt_peerlabel( 4226 sopt->sopt_td->td_ucred, so, &extmac); 4227 if (error) 4228 goto bad; 4229 /* Don't copy out extmac, it is unchanged. */ 4230 #else 4231 error = EOPNOTSUPP; 4232 #endif 4233 break; 4234 4235 case SO_LISTENQLIMIT: 4236 SOCK_LOCK(so); 4237 optval = SOLISTENING(so) ? so->sol_qlimit : 0; 4238 SOCK_UNLOCK(so); 4239 goto integer; 4240 4241 case SO_LISTENQLEN: 4242 SOCK_LOCK(so); 4243 optval = SOLISTENING(so) ? so->sol_qlen : 0; 4244 SOCK_UNLOCK(so); 4245 goto integer; 4246 4247 case SO_LISTENINCQLEN: 4248 SOCK_LOCK(so); 4249 optval = SOLISTENING(so) ? so->sol_incqlen : 0; 4250 SOCK_UNLOCK(so); 4251 goto integer; 4252 4253 case SO_TS_CLOCK: 4254 optval = so->so_ts_clock; 4255 goto integer; 4256 4257 case SO_MAX_PACING_RATE: 4258 optval = so->so_max_pacing_rate; 4259 goto integer; 4260 4261 case SO_SPLICE: { 4262 off_t n; 4263 4264 /* 4265 * Acquire the I/O lock to serialize with 4266 * so_splice_xfer(). This is not required for 4267 * correctness, but makes testing simpler: once a byte 4268 * has been transmitted to the sink and observed (e.g., 4269 * by reading from the socket to which the sink is 4270 * connected), a subsequent getsockopt(SO_SPLICE) will 4271 * return an up-to-date value. 4272 */ 4273 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT); 4274 if (error != 0) 4275 goto bad; 4276 SOCK_LOCK(so); 4277 if (SOLISTENING(so)) { 4278 n = 0; 4279 } else { 4280 n = so->so_splice_sent; 4281 } 4282 SOCK_UNLOCK(so); 4283 SOCK_IO_RECV_UNLOCK(so); 4284 error = sooptcopyout(sopt, &n, sizeof(n)); 4285 break; 4286 } 4287 4288 default: 4289 #ifdef SOCKET_HHOOK 4290 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0) 4291 error = hhook_run_socket(so, sopt, 4292 HHOOK_SOCKET_OPT); 4293 else 4294 #endif 4295 error = ENOPROTOOPT; 4296 break; 4297 } 4298 } 4299 bad: 4300 CURVNET_RESTORE(); 4301 return (error); 4302 } 4303 4304 int 4305 soopt_getm(struct sockopt *sopt, struct mbuf **mp) 4306 { 4307 struct mbuf *m, *m_prev; 4308 int sopt_size = sopt->sopt_valsize; 4309 4310 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA); 4311 if (m == NULL) 4312 return ENOBUFS; 4313 if (sopt_size > MLEN) { 4314 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT); 4315 if ((m->m_flags & M_EXT) == 0) { 4316 m_free(m); 4317 return ENOBUFS; 4318 } 4319 m->m_len = min(MCLBYTES, sopt_size); 4320 } else { 4321 m->m_len = min(MLEN, sopt_size); 4322 } 4323 sopt_size -= m->m_len; 4324 *mp = m; 4325 m_prev = m; 4326 4327 while (sopt_size) { 4328 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA); 4329 if (m == NULL) { 4330 m_freem(*mp); 4331 return ENOBUFS; 4332 } 4333 if (sopt_size > MLEN) { 4334 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK : 4335 M_NOWAIT); 4336 if ((m->m_flags & M_EXT) == 0) { 4337 m_freem(m); 4338 m_freem(*mp); 4339 return ENOBUFS; 4340 } 4341 m->m_len = min(MCLBYTES, sopt_size); 4342 } else { 4343 m->m_len = min(MLEN, sopt_size); 4344 } 4345 sopt_size -= m->m_len; 4346 m_prev->m_next = m; 4347 m_prev = m; 4348 } 4349 return (0); 4350 } 4351 4352 int 4353 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m) 4354 { 4355 struct mbuf *m0 = m; 4356 4357 if (sopt->sopt_val == NULL) 4358 return (0); 4359 while (m != NULL && sopt->sopt_valsize >= m->m_len) { 4360 if (sopt->sopt_td != NULL) { 4361 int error; 4362 4363 error = copyin(sopt->sopt_val, mtod(m, char *), 4364 m->m_len); 4365 if (error != 0) { 4366 m_freem(m0); 4367 return(error); 4368 } 4369 } else 4370 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len); 4371 sopt->sopt_valsize -= m->m_len; 4372 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len; 4373 m = m->m_next; 4374 } 4375 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */ 4376 panic("ip6_sooptmcopyin"); 4377 return (0); 4378 } 4379 4380 int 4381 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m) 4382 { 4383 struct mbuf *m0 = m; 4384 size_t valsize = 0; 4385 4386 if (sopt->sopt_val == NULL) 4387 return (0); 4388 while (m != NULL && sopt->sopt_valsize >= m->m_len) { 4389 if (sopt->sopt_td != NULL) { 4390 int error; 4391 4392 error = copyout(mtod(m, char *), sopt->sopt_val, 4393 m->m_len); 4394 if (error != 0) { 4395 m_freem(m0); 4396 return(error); 4397 } 4398 } else 4399 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len); 4400 sopt->sopt_valsize -= m->m_len; 4401 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len; 4402 valsize += m->m_len; 4403 m = m->m_next; 4404 } 4405 if (m != NULL) { 4406 /* enough soopt buffer should be given from user-land */ 4407 m_freem(m0); 4408 return(EINVAL); 4409 } 4410 sopt->sopt_valsize = valsize; 4411 return (0); 4412 } 4413 4414 /* 4415 * sohasoutofband(): protocol notifies socket layer of the arrival of new 4416 * out-of-band data, which will then notify socket consumers. 4417 */ 4418 void 4419 sohasoutofband(struct socket *so) 4420 { 4421 4422 if (so->so_sigio != NULL) 4423 pgsigio(&so->so_sigio, SIGURG, 0); 4424 selwakeuppri(&so->so_rdsel, PSOCK); 4425 } 4426 4427 int 4428 sopoll_generic(struct socket *so, int events, struct thread *td) 4429 { 4430 int revents; 4431 4432 SOCK_LOCK(so); 4433 if (SOLISTENING(so)) { 4434 if (!(events & (POLLIN | POLLRDNORM))) 4435 revents = 0; 4436 else if (!TAILQ_EMPTY(&so->sol_comp)) 4437 revents = events & (POLLIN | POLLRDNORM); 4438 else if ((events & POLLINIGNEOF) == 0 && so->so_error) 4439 revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP; 4440 else { 4441 selrecord(td, &so->so_rdsel); 4442 revents = 0; 4443 } 4444 } else { 4445 revents = 0; 4446 SOCK_SENDBUF_LOCK(so); 4447 SOCK_RECVBUF_LOCK(so); 4448 if (events & (POLLIN | POLLRDNORM)) 4449 if (soreadabledata(so) && !isspliced(so)) 4450 revents |= events & (POLLIN | POLLRDNORM); 4451 if (events & (POLLOUT | POLLWRNORM)) 4452 if (sowriteable(so) && !issplicedback(so)) 4453 revents |= events & (POLLOUT | POLLWRNORM); 4454 if (events & (POLLPRI | POLLRDBAND)) 4455 if (so->so_oobmark || 4456 (so->so_rcv.sb_state & SBS_RCVATMARK)) 4457 revents |= events & (POLLPRI | POLLRDBAND); 4458 if ((events & POLLINIGNEOF) == 0) { 4459 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 4460 revents |= events & (POLLIN | POLLRDNORM); 4461 if (so->so_snd.sb_state & SBS_CANTSENDMORE) 4462 revents |= POLLHUP; 4463 } 4464 } 4465 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) 4466 revents |= events & POLLRDHUP; 4467 if (revents == 0) { 4468 if (events & 4469 (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) { 4470 selrecord(td, &so->so_rdsel); 4471 so->so_rcv.sb_flags |= SB_SEL; 4472 } 4473 if (events & (POLLOUT | POLLWRNORM)) { 4474 selrecord(td, &so->so_wrsel); 4475 so->so_snd.sb_flags |= SB_SEL; 4476 } 4477 } 4478 SOCK_RECVBUF_UNLOCK(so); 4479 SOCK_SENDBUF_UNLOCK(so); 4480 } 4481 SOCK_UNLOCK(so); 4482 return (revents); 4483 } 4484 4485 int 4486 sokqfilter_generic(struct socket *so, struct knote *kn) 4487 { 4488 struct sockbuf *sb; 4489 sb_which which; 4490 struct knlist *knl; 4491 4492 switch (kn->kn_filter) { 4493 case EVFILT_READ: 4494 kn->kn_fop = &soread_filtops; 4495 knl = &so->so_rdsel.si_note; 4496 sb = &so->so_rcv; 4497 which = SO_RCV; 4498 break; 4499 case EVFILT_WRITE: 4500 kn->kn_fop = &sowrite_filtops; 4501 knl = &so->so_wrsel.si_note; 4502 sb = &so->so_snd; 4503 which = SO_SND; 4504 break; 4505 case EVFILT_EMPTY: 4506 kn->kn_fop = &soempty_filtops; 4507 knl = &so->so_wrsel.si_note; 4508 sb = &so->so_snd; 4509 which = SO_SND; 4510 break; 4511 default: 4512 return (EINVAL); 4513 } 4514 4515 SOCK_LOCK(so); 4516 if (SOLISTENING(so)) { 4517 knlist_add(knl, kn, 1); 4518 } else { 4519 SOCK_BUF_LOCK(so, which); 4520 knlist_add(knl, kn, 1); 4521 sb->sb_flags |= SB_KNOTE; 4522 if ((kn->kn_sfflags & NOTE_LOWAT) && 4523 (sb->sb_flags & SB_AUTOLOWAT)) 4524 sb->sb_flags &= ~SB_AUTOLOWAT; 4525 SOCK_BUF_UNLOCK(so, which); 4526 } 4527 SOCK_UNLOCK(so); 4528 return (0); 4529 } 4530 4531 static void 4532 filt_sordetach(struct knote *kn) 4533 { 4534 struct socket *so = kn->kn_fp->f_data; 4535 4536 so_rdknl_lock(so); 4537 knlist_remove(&so->so_rdsel.si_note, kn, 1); 4538 if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note)) 4539 so->so_rcv.sb_flags &= ~SB_KNOTE; 4540 so_rdknl_unlock(so); 4541 } 4542 4543 /*ARGSUSED*/ 4544 static int 4545 filt_soread(struct knote *kn, long hint) 4546 { 4547 struct socket *so; 4548 4549 so = kn->kn_fp->f_data; 4550 4551 if (SOLISTENING(so)) { 4552 SOCK_LOCK_ASSERT(so); 4553 kn->kn_data = so->sol_qlen; 4554 if (so->so_error) { 4555 kn->kn_flags |= EV_EOF; 4556 kn->kn_fflags = so->so_error; 4557 return (1); 4558 } 4559 return (!TAILQ_EMPTY(&so->sol_comp)); 4560 } 4561 4562 if ((so->so_rcv.sb_flags & SB_SPLICED) != 0) 4563 return (0); 4564 4565 SOCK_RECVBUF_LOCK_ASSERT(so); 4566 4567 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl; 4568 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 4569 kn->kn_flags |= EV_EOF; 4570 kn->kn_fflags = so->so_error; 4571 return (1); 4572 } else if (so->so_error || so->so_rerror) 4573 return (1); 4574 4575 if (kn->kn_sfflags & NOTE_LOWAT) { 4576 if (kn->kn_data >= kn->kn_sdata) 4577 return (1); 4578 } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat) 4579 return (1); 4580 4581 #ifdef SOCKET_HHOOK 4582 /* This hook returning non-zero indicates an event, not error */ 4583 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD)); 4584 #else 4585 return (0); 4586 #endif 4587 } 4588 4589 static void 4590 filt_sowdetach(struct knote *kn) 4591 { 4592 struct socket *so = kn->kn_fp->f_data; 4593 4594 so_wrknl_lock(so); 4595 knlist_remove(&so->so_wrsel.si_note, kn, 1); 4596 if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note)) 4597 so->so_snd.sb_flags &= ~SB_KNOTE; 4598 so_wrknl_unlock(so); 4599 } 4600 4601 /*ARGSUSED*/ 4602 static int 4603 filt_sowrite(struct knote *kn, long hint) 4604 { 4605 struct socket *so; 4606 4607 so = kn->kn_fp->f_data; 4608 4609 if (SOLISTENING(so)) 4610 return (0); 4611 4612 SOCK_SENDBUF_LOCK_ASSERT(so); 4613 kn->kn_data = sbspace(&so->so_snd); 4614 4615 #ifdef SOCKET_HHOOK 4616 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE); 4617 #endif 4618 4619 if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 4620 kn->kn_flags |= EV_EOF; 4621 kn->kn_fflags = so->so_error; 4622 return (1); 4623 } else if (so->so_error) /* temporary udp error */ 4624 return (1); 4625 else if (((so->so_state & SS_ISCONNECTED) == 0) && 4626 (so->so_proto->pr_flags & PR_CONNREQUIRED)) 4627 return (0); 4628 else if (kn->kn_sfflags & NOTE_LOWAT) 4629 return (kn->kn_data >= kn->kn_sdata); 4630 else 4631 return (kn->kn_data >= so->so_snd.sb_lowat); 4632 } 4633 4634 static int 4635 filt_soempty(struct knote *kn, long hint) 4636 { 4637 struct socket *so; 4638 4639 so = kn->kn_fp->f_data; 4640 4641 if (SOLISTENING(so)) 4642 return (1); 4643 4644 SOCK_SENDBUF_LOCK_ASSERT(so); 4645 kn->kn_data = sbused(&so->so_snd); 4646 4647 if (kn->kn_data == 0) 4648 return (1); 4649 else 4650 return (0); 4651 } 4652 4653 int 4654 socheckuid(struct socket *so, uid_t uid) 4655 { 4656 4657 if (so == NULL) 4658 return (EPERM); 4659 if (so->so_cred->cr_uid != uid) 4660 return (EPERM); 4661 return (0); 4662 } 4663 4664 /* 4665 * These functions are used by protocols to notify the socket layer (and its 4666 * consumers) of state changes in the sockets driven by protocol-side events. 4667 */ 4668 4669 /* 4670 * Procedures to manipulate state flags of socket and do appropriate wakeups. 4671 * 4672 * Normal sequence from the active (originating) side is that 4673 * soisconnecting() is called during processing of connect() call, resulting 4674 * in an eventual call to soisconnected() if/when the connection is 4675 * established. When the connection is torn down soisdisconnecting() is 4676 * called during processing of disconnect() call, and soisdisconnected() is 4677 * called when the connection to the peer is totally severed. The semantics 4678 * of these routines are such that connectionless protocols can call 4679 * soisconnected() and soisdisconnected() only, bypassing the in-progress 4680 * calls when setting up a ``connection'' takes no time. 4681 * 4682 * From the passive side, a socket is created with two queues of sockets: 4683 * so_incomp for connections in progress and so_comp for connections already 4684 * made and awaiting user acceptance. As a protocol is preparing incoming 4685 * connections, it creates a socket structure queued on so_incomp by calling 4686 * sonewconn(). When the connection is established, soisconnected() is 4687 * called, and transfers the socket structure to so_comp, making it available 4688 * to accept(). 4689 * 4690 * If a socket is closed with sockets on either so_incomp or so_comp, these 4691 * sockets are dropped. 4692 * 4693 * If higher-level protocols are implemented in the kernel, the wakeups done 4694 * here will sometimes cause software-interrupt process scheduling. 4695 */ 4696 void 4697 soisconnecting(struct socket *so) 4698 { 4699 4700 SOCK_LOCK(so); 4701 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING); 4702 so->so_state |= SS_ISCONNECTING; 4703 SOCK_UNLOCK(so); 4704 } 4705 4706 void 4707 soisconnected(struct socket *so) 4708 { 4709 bool last __diagused; 4710 4711 SOCK_LOCK(so); 4712 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING); 4713 so->so_state |= SS_ISCONNECTED; 4714 4715 if (so->so_qstate == SQ_INCOMP) { 4716 struct socket *head = so->so_listen; 4717 int ret; 4718 4719 KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so)); 4720 /* 4721 * Promoting a socket from incomplete queue to complete, we 4722 * need to go through reverse order of locking. We first do 4723 * trylock, and if that doesn't succeed, we go the hard way 4724 * leaving a reference and rechecking consistency after proper 4725 * locking. 4726 */ 4727 if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) { 4728 soref(head); 4729 SOCK_UNLOCK(so); 4730 SOLISTEN_LOCK(head); 4731 SOCK_LOCK(so); 4732 if (__predict_false(head != so->so_listen)) { 4733 /* 4734 * The socket went off the listen queue, 4735 * should be lost race to close(2) of sol. 4736 * The socket is about to soabort(). 4737 */ 4738 SOCK_UNLOCK(so); 4739 sorele_locked(head); 4740 return; 4741 } 4742 last = refcount_release(&head->so_count); 4743 KASSERT(!last, ("%s: released last reference for %p", 4744 __func__, head)); 4745 } 4746 again: 4747 if ((so->so_options & SO_ACCEPTFILTER) == 0) { 4748 TAILQ_REMOVE(&head->sol_incomp, so, so_list); 4749 head->sol_incqlen--; 4750 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list); 4751 head->sol_qlen++; 4752 so->so_qstate = SQ_COMP; 4753 SOCK_UNLOCK(so); 4754 solisten_wakeup(head); /* unlocks */ 4755 } else { 4756 SOCK_RECVBUF_LOCK(so); 4757 soupcall_set(so, SO_RCV, 4758 head->sol_accept_filter->accf_callback, 4759 head->sol_accept_filter_arg); 4760 so->so_options &= ~SO_ACCEPTFILTER; 4761 ret = head->sol_accept_filter->accf_callback(so, 4762 head->sol_accept_filter_arg, M_NOWAIT); 4763 if (ret == SU_ISCONNECTED) { 4764 soupcall_clear(so, SO_RCV); 4765 SOCK_RECVBUF_UNLOCK(so); 4766 goto again; 4767 } 4768 SOCK_RECVBUF_UNLOCK(so); 4769 SOCK_UNLOCK(so); 4770 SOLISTEN_UNLOCK(head); 4771 } 4772 return; 4773 } 4774 SOCK_UNLOCK(so); 4775 wakeup(&so->so_timeo); 4776 sorwakeup(so); 4777 sowwakeup(so); 4778 } 4779 4780 void 4781 soisdisconnecting(struct socket *so) 4782 { 4783 4784 SOCK_LOCK(so); 4785 so->so_state &= ~SS_ISCONNECTING; 4786 so->so_state |= SS_ISDISCONNECTING; 4787 4788 if (!SOLISTENING(so)) { 4789 SOCK_RECVBUF_LOCK(so); 4790 socantrcvmore_locked(so); 4791 SOCK_SENDBUF_LOCK(so); 4792 socantsendmore_locked(so); 4793 } 4794 SOCK_UNLOCK(so); 4795 wakeup(&so->so_timeo); 4796 } 4797 4798 void 4799 soisdisconnected(struct socket *so) 4800 { 4801 4802 SOCK_LOCK(so); 4803 4804 /* 4805 * There is at least one reader of so_state that does not 4806 * acquire socket lock, namely soreceive_generic(). Ensure 4807 * that it never sees all flags that track connection status 4808 * cleared, by ordering the update with a barrier semantic of 4809 * our release thread fence. 4810 */ 4811 so->so_state |= SS_ISDISCONNECTED; 4812 atomic_thread_fence_rel(); 4813 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING); 4814 4815 if (!SOLISTENING(so)) { 4816 SOCK_UNLOCK(so); 4817 SOCK_RECVBUF_LOCK(so); 4818 socantrcvmore_locked(so); 4819 SOCK_SENDBUF_LOCK(so); 4820 sbdrop_locked(&so->so_snd, sbused(&so->so_snd)); 4821 socantsendmore_locked(so); 4822 } else 4823 SOCK_UNLOCK(so); 4824 wakeup(&so->so_timeo); 4825 } 4826 4827 int 4828 soiolock(struct socket *so, struct sx *sx, int flags) 4829 { 4830 int error; 4831 4832 KASSERT((flags & SBL_VALID) == flags, 4833 ("soiolock: invalid flags %#x", flags)); 4834 4835 if ((flags & SBL_WAIT) != 0) { 4836 if ((flags & SBL_NOINTR) != 0) { 4837 sx_xlock(sx); 4838 } else { 4839 error = sx_xlock_sig(sx); 4840 if (error != 0) 4841 return (error); 4842 } 4843 } else if (!sx_try_xlock(sx)) { 4844 return (EWOULDBLOCK); 4845 } 4846 4847 if (__predict_false(SOLISTENING(so))) { 4848 sx_xunlock(sx); 4849 return (ENOTCONN); 4850 } 4851 return (0); 4852 } 4853 4854 void 4855 soiounlock(struct sx *sx) 4856 { 4857 sx_xunlock(sx); 4858 } 4859 4860 /* 4861 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME. 4862 */ 4863 struct sockaddr * 4864 sodupsockaddr(const struct sockaddr *sa, int mflags) 4865 { 4866 struct sockaddr *sa2; 4867 4868 sa2 = malloc(sa->sa_len, M_SONAME, mflags); 4869 if (sa2) 4870 bcopy(sa, sa2, sa->sa_len); 4871 return sa2; 4872 } 4873 4874 /* 4875 * Register per-socket destructor. 4876 */ 4877 void 4878 sodtor_set(struct socket *so, so_dtor_t *func) 4879 { 4880 4881 SOCK_LOCK_ASSERT(so); 4882 so->so_dtor = func; 4883 } 4884 4885 /* 4886 * Register per-socket buffer upcalls. 4887 */ 4888 void 4889 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg) 4890 { 4891 struct sockbuf *sb; 4892 4893 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so)); 4894 4895 switch (which) { 4896 case SO_RCV: 4897 sb = &so->so_rcv; 4898 break; 4899 case SO_SND: 4900 sb = &so->so_snd; 4901 break; 4902 } 4903 SOCK_BUF_LOCK_ASSERT(so, which); 4904 sb->sb_upcall = func; 4905 sb->sb_upcallarg = arg; 4906 sb->sb_flags |= SB_UPCALL; 4907 } 4908 4909 void 4910 soupcall_clear(struct socket *so, sb_which which) 4911 { 4912 struct sockbuf *sb; 4913 4914 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so)); 4915 4916 switch (which) { 4917 case SO_RCV: 4918 sb = &so->so_rcv; 4919 break; 4920 case SO_SND: 4921 sb = &so->so_snd; 4922 break; 4923 } 4924 SOCK_BUF_LOCK_ASSERT(so, which); 4925 KASSERT(sb->sb_upcall != NULL, 4926 ("%s: so %p no upcall to clear", __func__, so)); 4927 sb->sb_upcall = NULL; 4928 sb->sb_upcallarg = NULL; 4929 sb->sb_flags &= ~SB_UPCALL; 4930 } 4931 4932 void 4933 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg) 4934 { 4935 4936 SOLISTEN_LOCK_ASSERT(so); 4937 so->sol_upcall = func; 4938 so->sol_upcallarg = arg; 4939 } 4940 4941 static void 4942 so_rdknl_lock(void *arg) 4943 { 4944 struct socket *so = arg; 4945 4946 retry: 4947 if (SOLISTENING(so)) { 4948 SOLISTEN_LOCK(so); 4949 } else { 4950 SOCK_RECVBUF_LOCK(so); 4951 if (__predict_false(SOLISTENING(so))) { 4952 SOCK_RECVBUF_UNLOCK(so); 4953 goto retry; 4954 } 4955 } 4956 } 4957 4958 static void 4959 so_rdknl_unlock(void *arg) 4960 { 4961 struct socket *so = arg; 4962 4963 if (SOLISTENING(so)) 4964 SOLISTEN_UNLOCK(so); 4965 else 4966 SOCK_RECVBUF_UNLOCK(so); 4967 } 4968 4969 static void 4970 so_rdknl_assert_lock(void *arg, int what) 4971 { 4972 struct socket *so = arg; 4973 4974 if (what == LA_LOCKED) { 4975 if (SOLISTENING(so)) 4976 SOLISTEN_LOCK_ASSERT(so); 4977 else 4978 SOCK_RECVBUF_LOCK_ASSERT(so); 4979 } else { 4980 if (SOLISTENING(so)) 4981 SOLISTEN_UNLOCK_ASSERT(so); 4982 else 4983 SOCK_RECVBUF_UNLOCK_ASSERT(so); 4984 } 4985 } 4986 4987 static void 4988 so_wrknl_lock(void *arg) 4989 { 4990 struct socket *so = arg; 4991 4992 retry: 4993 if (SOLISTENING(so)) { 4994 SOLISTEN_LOCK(so); 4995 } else { 4996 SOCK_SENDBUF_LOCK(so); 4997 if (__predict_false(SOLISTENING(so))) { 4998 SOCK_SENDBUF_UNLOCK(so); 4999 goto retry; 5000 } 5001 } 5002 } 5003 5004 static void 5005 so_wrknl_unlock(void *arg) 5006 { 5007 struct socket *so = arg; 5008 5009 if (SOLISTENING(so)) 5010 SOLISTEN_UNLOCK(so); 5011 else 5012 SOCK_SENDBUF_UNLOCK(so); 5013 } 5014 5015 static void 5016 so_wrknl_assert_lock(void *arg, int what) 5017 { 5018 struct socket *so = arg; 5019 5020 if (what == LA_LOCKED) { 5021 if (SOLISTENING(so)) 5022 SOLISTEN_LOCK_ASSERT(so); 5023 else 5024 SOCK_SENDBUF_LOCK_ASSERT(so); 5025 } else { 5026 if (SOLISTENING(so)) 5027 SOLISTEN_UNLOCK_ASSERT(so); 5028 else 5029 SOCK_SENDBUF_UNLOCK_ASSERT(so); 5030 } 5031 } 5032 5033 /* 5034 * Create an external-format (``xsocket'') structure using the information in 5035 * the kernel-format socket structure pointed to by so. This is done to 5036 * reduce the spew of irrelevant information over this interface, to isolate 5037 * user code from changes in the kernel structure, and potentially to provide 5038 * information-hiding if we decide that some of this information should be 5039 * hidden from users. 5040 */ 5041 void 5042 sotoxsocket(struct socket *so, struct xsocket *xso) 5043 { 5044 5045 bzero(xso, sizeof(*xso)); 5046 xso->xso_len = sizeof *xso; 5047 xso->xso_so = (uintptr_t)so; 5048 xso->so_type = so->so_type; 5049 xso->so_options = so->so_options; 5050 xso->so_linger = so->so_linger; 5051 xso->so_state = so->so_state; 5052 xso->so_pcb = (uintptr_t)so->so_pcb; 5053 xso->xso_protocol = so->so_proto->pr_protocol; 5054 xso->xso_family = so->so_proto->pr_domain->dom_family; 5055 xso->so_timeo = so->so_timeo; 5056 xso->so_error = so->so_error; 5057 xso->so_uid = so->so_cred->cr_uid; 5058 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0; 5059 SOCK_LOCK(so); 5060 xso->so_fibnum = so->so_fibnum; 5061 if (SOLISTENING(so)) { 5062 xso->so_qlen = so->sol_qlen; 5063 xso->so_incqlen = so->sol_incqlen; 5064 xso->so_qlimit = so->sol_qlimit; 5065 xso->so_oobmark = 0; 5066 } else { 5067 xso->so_state |= so->so_qstate; 5068 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0; 5069 xso->so_oobmark = so->so_oobmark; 5070 sbtoxsockbuf(&so->so_snd, &xso->so_snd); 5071 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv); 5072 if ((so->so_rcv.sb_flags & SB_SPLICED) != 0) 5073 xso->so_splice_so = (uintptr_t)so->so_splice->dst; 5074 } 5075 SOCK_UNLOCK(so); 5076 } 5077 5078 int 5079 so_options_get(const struct socket *so) 5080 { 5081 5082 return (so->so_options); 5083 } 5084 5085 void 5086 so_options_set(struct socket *so, int val) 5087 { 5088 5089 so->so_options = val; 5090 } 5091 5092 int 5093 so_error_get(const struct socket *so) 5094 { 5095 5096 return (so->so_error); 5097 } 5098 5099 void 5100 so_error_set(struct socket *so, int val) 5101 { 5102 5103 so->so_error = val; 5104 } 5105