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