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