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