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