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