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 if (__predict_false(so->so_rcv.sb_mb == NULL && 2433 (so->so_error || so->so_rerror || 2434 so->so_rcv.sb_state & SBS_CANTRCVMORE))) 2435 break; 2436 } 2437 SBLASTRECORDCHK(&so->so_rcv); 2438 SBLASTMBUFCHK(&so->so_rcv); 2439 /* 2440 * We could receive some data while was notifying 2441 * the protocol. Skip blocking in this case. 2442 */ 2443 if (so->so_rcv.sb_mb == NULL) { 2444 error = sbwait(so, SO_RCV); 2445 if (error) { 2446 SOCKBUF_UNLOCK(&so->so_rcv); 2447 goto release; 2448 } 2449 } 2450 m = so->so_rcv.sb_mb; 2451 if (m != NULL) 2452 nextrecord = m->m_nextpkt; 2453 } 2454 } 2455 2456 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2457 if (m != NULL && pr->pr_flags & PR_ATOMIC) { 2458 if (report_real_len) 2459 uio->uio_resid -= m_length(m, NULL) - moff; 2460 flags |= MSG_TRUNC; 2461 if ((flags & MSG_PEEK) == 0) 2462 (void) sbdroprecord_locked(&so->so_rcv); 2463 } 2464 if ((flags & MSG_PEEK) == 0) { 2465 if (m == NULL) { 2466 /* 2467 * First part is an inline SB_EMPTY_FIXUP(). Second 2468 * part makes sure sb_lastrecord is up-to-date if 2469 * there is still data in the socket buffer. 2470 */ 2471 so->so_rcv.sb_mb = nextrecord; 2472 if (so->so_rcv.sb_mb == NULL) { 2473 so->so_rcv.sb_mbtail = NULL; 2474 so->so_rcv.sb_lastrecord = NULL; 2475 } else if (nextrecord->m_nextpkt == NULL) 2476 so->so_rcv.sb_lastrecord = nextrecord; 2477 } 2478 SBLASTRECORDCHK(&so->so_rcv); 2479 SBLASTMBUFCHK(&so->so_rcv); 2480 /* 2481 * If soreceive() is being done from the socket callback, 2482 * then don't need to generate ACK to peer to update window, 2483 * since ACK will be generated on return to TCP. 2484 */ 2485 if (!(flags & MSG_SOCALLBCK) && 2486 (pr->pr_flags & PR_WANTRCVD)) { 2487 SOCKBUF_UNLOCK(&so->so_rcv); 2488 VNET_SO_ASSERT(so); 2489 pr->pr_rcvd(so, flags); 2490 SOCKBUF_LOCK(&so->so_rcv); 2491 } 2492 } 2493 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2494 if (orig_resid == uio->uio_resid && orig_resid && 2495 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) { 2496 SOCKBUF_UNLOCK(&so->so_rcv); 2497 goto restart; 2498 } 2499 SOCKBUF_UNLOCK(&so->so_rcv); 2500 2501 if (flagsp != NULL) 2502 *flagsp |= flags; 2503 release: 2504 SOCK_IO_RECV_UNLOCK(so); 2505 return (error); 2506 } 2507 2508 /* 2509 * Optimized version of soreceive() for stream (TCP) sockets. 2510 */ 2511 int 2512 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio, 2513 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 2514 { 2515 int len = 0, error = 0, flags, oresid; 2516 struct sockbuf *sb; 2517 struct mbuf *m, *n = NULL; 2518 2519 /* We only do stream sockets. */ 2520 if (so->so_type != SOCK_STREAM) 2521 return (EINVAL); 2522 if (psa != NULL) 2523 *psa = NULL; 2524 if (flagsp != NULL) 2525 flags = *flagsp &~ MSG_EOR; 2526 else 2527 flags = 0; 2528 if (controlp != NULL) 2529 *controlp = NULL; 2530 if (flags & MSG_OOB) 2531 return (soreceive_rcvoob(so, uio, flags)); 2532 if (mp0 != NULL) 2533 *mp0 = NULL; 2534 2535 sb = &so->so_rcv; 2536 2537 #ifdef KERN_TLS 2538 /* 2539 * KTLS store TLS records as records with a control message to 2540 * describe the framing. 2541 * 2542 * We check once here before acquiring locks to optimize the 2543 * common case. 2544 */ 2545 if (sb->sb_tls_info != NULL) 2546 return (soreceive_generic(so, psa, uio, mp0, controlp, 2547 flagsp)); 2548 #endif 2549 2550 /* Prevent other readers from entering the socket. */ 2551 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags)); 2552 if (error) 2553 return (error); 2554 SOCKBUF_LOCK(sb); 2555 2556 #ifdef KERN_TLS 2557 if (sb->sb_tls_info != NULL) { 2558 SOCKBUF_UNLOCK(sb); 2559 SOCK_IO_RECV_UNLOCK(so); 2560 return (soreceive_generic(so, psa, uio, mp0, controlp, 2561 flagsp)); 2562 } 2563 #endif 2564 2565 /* Easy one, no space to copyout anything. */ 2566 if (uio->uio_resid == 0) { 2567 error = EINVAL; 2568 goto out; 2569 } 2570 oresid = uio->uio_resid; 2571 2572 /* We will never ever get anything unless we are or were connected. */ 2573 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) { 2574 error = ENOTCONN; 2575 goto out; 2576 } 2577 2578 restart: 2579 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2580 2581 /* Abort if socket has reported problems. */ 2582 if (so->so_error) { 2583 if (sbavail(sb) > 0) 2584 goto deliver; 2585 if (oresid > uio->uio_resid) 2586 goto out; 2587 error = so->so_error; 2588 if (!(flags & MSG_PEEK)) 2589 so->so_error = 0; 2590 goto out; 2591 } 2592 2593 /* Door is closed. Deliver what is left, if any. */ 2594 if (sb->sb_state & SBS_CANTRCVMORE) { 2595 if (sbavail(sb) > 0) 2596 goto deliver; 2597 else 2598 goto out; 2599 } 2600 2601 /* Socket buffer is empty and we shall not block. */ 2602 if (sbavail(sb) == 0 && 2603 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) { 2604 error = EAGAIN; 2605 goto out; 2606 } 2607 2608 /* Socket buffer got some data that we shall deliver now. */ 2609 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) && 2610 ((so->so_state & SS_NBIO) || 2611 (flags & (MSG_DONTWAIT|MSG_NBIO)) || 2612 sbavail(sb) >= sb->sb_lowat || 2613 sbavail(sb) >= uio->uio_resid || 2614 sbavail(sb) >= sb->sb_hiwat) ) { 2615 goto deliver; 2616 } 2617 2618 /* On MSG_WAITALL we must wait until all data or error arrives. */ 2619 if ((flags & MSG_WAITALL) && 2620 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat)) 2621 goto deliver; 2622 2623 /* 2624 * Wait and block until (more) data comes in. 2625 * NB: Drops the sockbuf lock during wait. 2626 */ 2627 error = sbwait(so, SO_RCV); 2628 if (error) 2629 goto out; 2630 goto restart; 2631 2632 deliver: 2633 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2634 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__)); 2635 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__)); 2636 2637 /* Statistics. */ 2638 if (uio->uio_td) 2639 uio->uio_td->td_ru.ru_msgrcv++; 2640 2641 /* Fill uio until full or current end of socket buffer is reached. */ 2642 len = min(uio->uio_resid, sbavail(sb)); 2643 if (mp0 != NULL) { 2644 /* Dequeue as many mbufs as possible. */ 2645 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) { 2646 if (*mp0 == NULL) 2647 *mp0 = sb->sb_mb; 2648 else 2649 m_cat(*mp0, sb->sb_mb); 2650 for (m = sb->sb_mb; 2651 m != NULL && m->m_len <= len; 2652 m = m->m_next) { 2653 KASSERT(!(m->m_flags & M_NOTAVAIL), 2654 ("%s: m %p not available", __func__, m)); 2655 len -= m->m_len; 2656 uio->uio_resid -= m->m_len; 2657 sbfree(sb, m); 2658 n = m; 2659 } 2660 n->m_next = NULL; 2661 sb->sb_mb = m; 2662 sb->sb_lastrecord = sb->sb_mb; 2663 if (sb->sb_mb == NULL) 2664 SB_EMPTY_FIXUP(sb); 2665 } 2666 /* Copy the remainder. */ 2667 if (len > 0) { 2668 KASSERT(sb->sb_mb != NULL, 2669 ("%s: len > 0 && sb->sb_mb empty", __func__)); 2670 2671 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT); 2672 if (m == NULL) 2673 len = 0; /* Don't flush data from sockbuf. */ 2674 else 2675 uio->uio_resid -= len; 2676 if (*mp0 != NULL) 2677 m_cat(*mp0, m); 2678 else 2679 *mp0 = m; 2680 if (*mp0 == NULL) { 2681 error = ENOBUFS; 2682 goto out; 2683 } 2684 } 2685 } else { 2686 /* NB: Must unlock socket buffer as uiomove may sleep. */ 2687 SOCKBUF_UNLOCK(sb); 2688 error = m_mbuftouio(uio, sb->sb_mb, len); 2689 SOCKBUF_LOCK(sb); 2690 if (error) 2691 goto out; 2692 } 2693 SBLASTRECORDCHK(sb); 2694 SBLASTMBUFCHK(sb); 2695 2696 /* 2697 * Remove the delivered data from the socket buffer unless we 2698 * were only peeking. 2699 */ 2700 if (!(flags & MSG_PEEK)) { 2701 if (len > 0) 2702 sbdrop_locked(sb, len); 2703 2704 /* Notify protocol that we drained some data. */ 2705 if ((so->so_proto->pr_flags & PR_WANTRCVD) && 2706 (((flags & MSG_WAITALL) && uio->uio_resid > 0) || 2707 !(flags & MSG_SOCALLBCK))) { 2708 SOCKBUF_UNLOCK(sb); 2709 VNET_SO_ASSERT(so); 2710 so->so_proto->pr_rcvd(so, flags); 2711 SOCKBUF_LOCK(sb); 2712 } 2713 } 2714 2715 /* 2716 * For MSG_WAITALL we may have to loop again and wait for 2717 * more data to come in. 2718 */ 2719 if ((flags & MSG_WAITALL) && uio->uio_resid > 0) 2720 goto restart; 2721 out: 2722 SBLASTRECORDCHK(sb); 2723 SBLASTMBUFCHK(sb); 2724 SOCKBUF_UNLOCK(sb); 2725 SOCK_IO_RECV_UNLOCK(so); 2726 return (error); 2727 } 2728 2729 /* 2730 * Optimized version of soreceive() for simple datagram cases from userspace. 2731 * Unlike in the stream case, we're able to drop a datagram if copyout() 2732 * fails, and because we handle datagrams atomically, we don't need to use a 2733 * sleep lock to prevent I/O interlacing. 2734 */ 2735 int 2736 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio, 2737 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 2738 { 2739 struct mbuf *m, *m2; 2740 int flags, error; 2741 ssize_t len; 2742 struct protosw *pr = so->so_proto; 2743 struct mbuf *nextrecord; 2744 2745 if (psa != NULL) 2746 *psa = NULL; 2747 if (controlp != NULL) 2748 *controlp = NULL; 2749 if (flagsp != NULL) 2750 flags = *flagsp &~ MSG_EOR; 2751 else 2752 flags = 0; 2753 2754 /* 2755 * For any complicated cases, fall back to the full 2756 * soreceive_generic(). 2757 */ 2758 if (mp0 != NULL || (flags & (MSG_PEEK | MSG_OOB | MSG_TRUNC))) 2759 return (soreceive_generic(so, psa, uio, mp0, controlp, 2760 flagsp)); 2761 2762 /* 2763 * Enforce restrictions on use. 2764 */ 2765 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0, 2766 ("soreceive_dgram: wantrcvd")); 2767 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic")); 2768 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0, 2769 ("soreceive_dgram: SBS_RCVATMARK")); 2770 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0, 2771 ("soreceive_dgram: P_CONNREQUIRED")); 2772 2773 /* 2774 * Loop blocking while waiting for a datagram. 2775 */ 2776 SOCKBUF_LOCK(&so->so_rcv); 2777 while ((m = so->so_rcv.sb_mb) == NULL) { 2778 KASSERT(sbavail(&so->so_rcv) == 0, 2779 ("soreceive_dgram: sb_mb NULL but sbavail %u", 2780 sbavail(&so->so_rcv))); 2781 if (so->so_error) { 2782 error = so->so_error; 2783 so->so_error = 0; 2784 SOCKBUF_UNLOCK(&so->so_rcv); 2785 return (error); 2786 } 2787 if (so->so_rcv.sb_state & SBS_CANTRCVMORE || 2788 uio->uio_resid == 0) { 2789 SOCKBUF_UNLOCK(&so->so_rcv); 2790 return (0); 2791 } 2792 if ((so->so_state & SS_NBIO) || 2793 (flags & (MSG_DONTWAIT|MSG_NBIO))) { 2794 SOCKBUF_UNLOCK(&so->so_rcv); 2795 return (EWOULDBLOCK); 2796 } 2797 SBLASTRECORDCHK(&so->so_rcv); 2798 SBLASTMBUFCHK(&so->so_rcv); 2799 error = sbwait(so, SO_RCV); 2800 if (error) { 2801 SOCKBUF_UNLOCK(&so->so_rcv); 2802 return (error); 2803 } 2804 } 2805 SOCKBUF_LOCK_ASSERT(&so->so_rcv); 2806 2807 if (uio->uio_td) 2808 uio->uio_td->td_ru.ru_msgrcv++; 2809 SBLASTRECORDCHK(&so->so_rcv); 2810 SBLASTMBUFCHK(&so->so_rcv); 2811 nextrecord = m->m_nextpkt; 2812 if (nextrecord == NULL) { 2813 KASSERT(so->so_rcv.sb_lastrecord == m, 2814 ("soreceive_dgram: lastrecord != m")); 2815 } 2816 2817 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord, 2818 ("soreceive_dgram: m_nextpkt != nextrecord")); 2819 2820 /* 2821 * Pull 'm' and its chain off the front of the packet queue. 2822 */ 2823 so->so_rcv.sb_mb = NULL; 2824 sockbuf_pushsync(&so->so_rcv, nextrecord); 2825 2826 /* 2827 * Walk 'm's chain and free that many bytes from the socket buffer. 2828 */ 2829 for (m2 = m; m2 != NULL; m2 = m2->m_next) 2830 sbfree(&so->so_rcv, m2); 2831 2832 /* 2833 * Do a few last checks before we let go of the lock. 2834 */ 2835 SBLASTRECORDCHK(&so->so_rcv); 2836 SBLASTMBUFCHK(&so->so_rcv); 2837 SOCKBUF_UNLOCK(&so->so_rcv); 2838 2839 if (pr->pr_flags & PR_ADDR) { 2840 KASSERT(m->m_type == MT_SONAME, 2841 ("m->m_type == %d", m->m_type)); 2842 if (psa != NULL) 2843 *psa = sodupsockaddr(mtod(m, struct sockaddr *), 2844 M_NOWAIT); 2845 m = m_free(m); 2846 } 2847 if (m == NULL) { 2848 /* XXXRW: Can this happen? */ 2849 return (0); 2850 } 2851 2852 /* 2853 * Packet to copyout() is now in 'm' and it is disconnected from the 2854 * queue. 2855 * 2856 * Process one or more MT_CONTROL mbufs present before any data mbufs 2857 * in the first mbuf chain on the socket buffer. We call into the 2858 * protocol to perform externalization (or freeing if controlp == 2859 * NULL). In some cases there can be only MT_CONTROL mbufs without 2860 * MT_DATA mbufs. 2861 */ 2862 if (m->m_type == MT_CONTROL) { 2863 struct mbuf *cm = NULL, *cmn; 2864 struct mbuf **cme = &cm; 2865 2866 do { 2867 m2 = m->m_next; 2868 m->m_next = NULL; 2869 *cme = m; 2870 cme = &(*cme)->m_next; 2871 m = m2; 2872 } while (m != NULL && m->m_type == MT_CONTROL); 2873 while (cm != NULL) { 2874 cmn = cm->m_next; 2875 cm->m_next = NULL; 2876 if (pr->pr_domain->dom_externalize != NULL) { 2877 error = (*pr->pr_domain->dom_externalize) 2878 (cm, controlp, flags); 2879 } else if (controlp != NULL) 2880 *controlp = cm; 2881 else 2882 m_freem(cm); 2883 if (controlp != NULL) { 2884 while (*controlp != NULL) 2885 controlp = &(*controlp)->m_next; 2886 } 2887 cm = cmn; 2888 } 2889 } 2890 KASSERT(m == NULL || m->m_type == MT_DATA, 2891 ("soreceive_dgram: !data")); 2892 while (m != NULL && uio->uio_resid > 0) { 2893 len = uio->uio_resid; 2894 if (len > m->m_len) 2895 len = m->m_len; 2896 error = uiomove(mtod(m, char *), (int)len, uio); 2897 if (error) { 2898 m_freem(m); 2899 return (error); 2900 } 2901 if (len == m->m_len) 2902 m = m_free(m); 2903 else { 2904 m->m_data += len; 2905 m->m_len -= len; 2906 } 2907 } 2908 if (m != NULL) { 2909 flags |= MSG_TRUNC; 2910 m_freem(m); 2911 } 2912 if (flagsp != NULL) 2913 *flagsp |= flags; 2914 return (0); 2915 } 2916 2917 int 2918 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio, 2919 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 2920 { 2921 int error; 2922 2923 CURVNET_SET(so->so_vnet); 2924 error = so->so_proto->pr_soreceive(so, psa, uio, mp0, controlp, flagsp); 2925 CURVNET_RESTORE(); 2926 return (error); 2927 } 2928 2929 int 2930 soshutdown(struct socket *so, int how) 2931 { 2932 struct protosw *pr; 2933 int error, soerror_enotconn; 2934 2935 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR)) 2936 return (EINVAL); 2937 2938 soerror_enotconn = 0; 2939 SOCK_LOCK(so); 2940 if ((so->so_state & 2941 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) { 2942 /* 2943 * POSIX mandates us to return ENOTCONN when shutdown(2) is 2944 * invoked on a datagram sockets, however historically we would 2945 * actually tear socket down. This is known to be leveraged by 2946 * some applications to unblock process waiting in recvXXX(2) 2947 * by other process that it shares that socket with. Try to meet 2948 * both backward-compatibility and POSIX requirements by forcing 2949 * ENOTCONN but still asking protocol to perform pru_shutdown(). 2950 */ 2951 if (so->so_type != SOCK_DGRAM && !SOLISTENING(so)) { 2952 SOCK_UNLOCK(so); 2953 return (ENOTCONN); 2954 } 2955 soerror_enotconn = 1; 2956 } 2957 2958 if (SOLISTENING(so)) { 2959 if (how != SHUT_WR) { 2960 so->so_error = ECONNABORTED; 2961 solisten_wakeup(so); /* unlocks so */ 2962 } else { 2963 SOCK_UNLOCK(so); 2964 } 2965 goto done; 2966 } 2967 SOCK_UNLOCK(so); 2968 2969 CURVNET_SET(so->so_vnet); 2970 pr = so->so_proto; 2971 if (pr->pr_flush != NULL) 2972 pr->pr_flush(so, how); 2973 if (how != SHUT_WR) 2974 sorflush(so); 2975 if (how != SHUT_RD) { 2976 error = pr->pr_shutdown(so); 2977 wakeup(&so->so_timeo); 2978 CURVNET_RESTORE(); 2979 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error); 2980 } 2981 wakeup(&so->so_timeo); 2982 CURVNET_RESTORE(); 2983 2984 done: 2985 return (soerror_enotconn ? ENOTCONN : 0); 2986 } 2987 2988 void 2989 sorflush(struct socket *so) 2990 { 2991 struct protosw *pr; 2992 int error; 2993 2994 VNET_SO_ASSERT(so); 2995 2996 /* 2997 * Dislodge threads currently blocked in receive and wait to acquire 2998 * a lock against other simultaneous readers before clearing the 2999 * socket buffer. Don't let our acquire be interrupted by a signal 3000 * despite any existing socket disposition on interruptable waiting. 3001 */ 3002 socantrcvmore(so); 3003 3004 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR); 3005 if (error != 0) { 3006 KASSERT(SOLISTENING(so), 3007 ("%s: soiolock(%p) failed", __func__, so)); 3008 return; 3009 } 3010 3011 pr = so->so_proto; 3012 if (pr->pr_flags & PR_RIGHTS) { 3013 MPASS(pr->pr_domain->dom_dispose != NULL); 3014 (*pr->pr_domain->dom_dispose)(so); 3015 } else { 3016 sbrelease(so, SO_RCV); 3017 SOCK_IO_RECV_UNLOCK(so); 3018 } 3019 3020 } 3021 3022 /* 3023 * Wrapper for Socket established helper hook. 3024 * Parameters: socket, context of the hook point, hook id. 3025 */ 3026 static int inline 3027 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id) 3028 { 3029 struct socket_hhook_data hhook_data = { 3030 .so = so, 3031 .hctx = hctx, 3032 .m = NULL, 3033 .status = 0 3034 }; 3035 3036 CURVNET_SET(so->so_vnet); 3037 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd); 3038 CURVNET_RESTORE(); 3039 3040 /* Ugly but needed, since hhooks return void for now */ 3041 return (hhook_data.status); 3042 } 3043 3044 /* 3045 * Perhaps this routine, and sooptcopyout(), below, ought to come in an 3046 * additional variant to handle the case where the option value needs to be 3047 * some kind of integer, but not a specific size. In addition to their use 3048 * here, these functions are also called by the protocol-level pr_ctloutput() 3049 * routines. 3050 */ 3051 int 3052 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen) 3053 { 3054 size_t valsize; 3055 3056 /* 3057 * If the user gives us more than we wanted, we ignore it, but if we 3058 * don't get the minimum length the caller wants, we return EINVAL. 3059 * On success, sopt->sopt_valsize is set to however much we actually 3060 * retrieved. 3061 */ 3062 if ((valsize = sopt->sopt_valsize) < minlen) 3063 return EINVAL; 3064 if (valsize > len) 3065 sopt->sopt_valsize = valsize = len; 3066 3067 if (sopt->sopt_td != NULL) 3068 return (copyin(sopt->sopt_val, buf, valsize)); 3069 3070 bcopy(sopt->sopt_val, buf, valsize); 3071 return (0); 3072 } 3073 3074 /* 3075 * Kernel version of setsockopt(2). 3076 * 3077 * XXX: optlen is size_t, not socklen_t 3078 */ 3079 int 3080 so_setsockopt(struct socket *so, int level, int optname, void *optval, 3081 size_t optlen) 3082 { 3083 struct sockopt sopt; 3084 3085 sopt.sopt_level = level; 3086 sopt.sopt_name = optname; 3087 sopt.sopt_dir = SOPT_SET; 3088 sopt.sopt_val = optval; 3089 sopt.sopt_valsize = optlen; 3090 sopt.sopt_td = NULL; 3091 return (sosetopt(so, &sopt)); 3092 } 3093 3094 int 3095 sosetopt(struct socket *so, struct sockopt *sopt) 3096 { 3097 int error, optval; 3098 struct linger l; 3099 struct timeval tv; 3100 sbintime_t val, *valp; 3101 uint32_t val32; 3102 #ifdef MAC 3103 struct mac extmac; 3104 #endif 3105 3106 CURVNET_SET(so->so_vnet); 3107 error = 0; 3108 if (sopt->sopt_level != SOL_SOCKET) { 3109 if (so->so_proto->pr_ctloutput != NULL) 3110 error = (*so->so_proto->pr_ctloutput)(so, sopt); 3111 else 3112 error = ENOPROTOOPT; 3113 } else { 3114 switch (sopt->sopt_name) { 3115 case SO_ACCEPTFILTER: 3116 error = accept_filt_setopt(so, sopt); 3117 if (error) 3118 goto bad; 3119 break; 3120 3121 case SO_LINGER: 3122 error = sooptcopyin(sopt, &l, sizeof l, sizeof l); 3123 if (error) 3124 goto bad; 3125 if (l.l_linger < 0 || 3126 l.l_linger > USHRT_MAX || 3127 l.l_linger > (INT_MAX / hz)) { 3128 error = EDOM; 3129 goto bad; 3130 } 3131 SOCK_LOCK(so); 3132 so->so_linger = l.l_linger; 3133 if (l.l_onoff) 3134 so->so_options |= SO_LINGER; 3135 else 3136 so->so_options &= ~SO_LINGER; 3137 SOCK_UNLOCK(so); 3138 break; 3139 3140 case SO_DEBUG: 3141 case SO_KEEPALIVE: 3142 case SO_DONTROUTE: 3143 case SO_USELOOPBACK: 3144 case SO_BROADCAST: 3145 case SO_REUSEADDR: 3146 case SO_REUSEPORT: 3147 case SO_REUSEPORT_LB: 3148 case SO_OOBINLINE: 3149 case SO_TIMESTAMP: 3150 case SO_BINTIME: 3151 case SO_NOSIGPIPE: 3152 case SO_NO_DDP: 3153 case SO_NO_OFFLOAD: 3154 case SO_RERROR: 3155 error = sooptcopyin(sopt, &optval, sizeof optval, 3156 sizeof optval); 3157 if (error) 3158 goto bad; 3159 SOCK_LOCK(so); 3160 if (optval) 3161 so->so_options |= sopt->sopt_name; 3162 else 3163 so->so_options &= ~sopt->sopt_name; 3164 SOCK_UNLOCK(so); 3165 break; 3166 3167 case SO_SETFIB: 3168 error = sooptcopyin(sopt, &optval, sizeof optval, 3169 sizeof optval); 3170 if (error) 3171 goto bad; 3172 3173 if (optval < 0 || optval >= rt_numfibs) { 3174 error = EINVAL; 3175 goto bad; 3176 } 3177 if (((so->so_proto->pr_domain->dom_family == PF_INET) || 3178 (so->so_proto->pr_domain->dom_family == PF_INET6) || 3179 (so->so_proto->pr_domain->dom_family == PF_ROUTE))) 3180 so->so_fibnum = optval; 3181 else 3182 so->so_fibnum = 0; 3183 break; 3184 3185 case SO_USER_COOKIE: 3186 error = sooptcopyin(sopt, &val32, sizeof val32, 3187 sizeof val32); 3188 if (error) 3189 goto bad; 3190 so->so_user_cookie = val32; 3191 break; 3192 3193 case SO_SNDBUF: 3194 case SO_RCVBUF: 3195 case SO_SNDLOWAT: 3196 case SO_RCVLOWAT: 3197 error = so->so_proto->pr_setsbopt(so, sopt); 3198 if (error) 3199 goto bad; 3200 break; 3201 3202 case SO_SNDTIMEO: 3203 case SO_RCVTIMEO: 3204 #ifdef COMPAT_FREEBSD32 3205 if (SV_CURPROC_FLAG(SV_ILP32)) { 3206 struct timeval32 tv32; 3207 3208 error = sooptcopyin(sopt, &tv32, sizeof tv32, 3209 sizeof tv32); 3210 CP(tv32, tv, tv_sec); 3211 CP(tv32, tv, tv_usec); 3212 } else 3213 #endif 3214 error = sooptcopyin(sopt, &tv, sizeof tv, 3215 sizeof tv); 3216 if (error) 3217 goto bad; 3218 if (tv.tv_sec < 0 || tv.tv_usec < 0 || 3219 tv.tv_usec >= 1000000) { 3220 error = EDOM; 3221 goto bad; 3222 } 3223 if (tv.tv_sec > INT32_MAX) 3224 val = SBT_MAX; 3225 else 3226 val = tvtosbt(tv); 3227 SOCK_LOCK(so); 3228 valp = sopt->sopt_name == SO_SNDTIMEO ? 3229 (SOLISTENING(so) ? &so->sol_sbsnd_timeo : 3230 &so->so_snd.sb_timeo) : 3231 (SOLISTENING(so) ? &so->sol_sbrcv_timeo : 3232 &so->so_rcv.sb_timeo); 3233 *valp = val; 3234 SOCK_UNLOCK(so); 3235 break; 3236 3237 case SO_LABEL: 3238 #ifdef MAC 3239 error = sooptcopyin(sopt, &extmac, sizeof extmac, 3240 sizeof extmac); 3241 if (error) 3242 goto bad; 3243 error = mac_setsockopt_label(sopt->sopt_td->td_ucred, 3244 so, &extmac); 3245 #else 3246 error = EOPNOTSUPP; 3247 #endif 3248 break; 3249 3250 case SO_TS_CLOCK: 3251 error = sooptcopyin(sopt, &optval, sizeof optval, 3252 sizeof optval); 3253 if (error) 3254 goto bad; 3255 if (optval < 0 || optval > SO_TS_CLOCK_MAX) { 3256 error = EINVAL; 3257 goto bad; 3258 } 3259 so->so_ts_clock = optval; 3260 break; 3261 3262 case SO_MAX_PACING_RATE: 3263 error = sooptcopyin(sopt, &val32, sizeof(val32), 3264 sizeof(val32)); 3265 if (error) 3266 goto bad; 3267 so->so_max_pacing_rate = val32; 3268 break; 3269 3270 default: 3271 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0) 3272 error = hhook_run_socket(so, sopt, 3273 HHOOK_SOCKET_OPT); 3274 else 3275 error = ENOPROTOOPT; 3276 break; 3277 } 3278 if (error == 0 && so->so_proto->pr_ctloutput != NULL) 3279 (void)(*so->so_proto->pr_ctloutput)(so, sopt); 3280 } 3281 bad: 3282 CURVNET_RESTORE(); 3283 return (error); 3284 } 3285 3286 /* 3287 * Helper routine for getsockopt. 3288 */ 3289 int 3290 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len) 3291 { 3292 int error; 3293 size_t valsize; 3294 3295 error = 0; 3296 3297 /* 3298 * Documented get behavior is that we always return a value, possibly 3299 * truncated to fit in the user's buffer. Traditional behavior is 3300 * that we always tell the user precisely how much we copied, rather 3301 * than something useful like the total amount we had available for 3302 * her. Note that this interface is not idempotent; the entire 3303 * answer must be generated ahead of time. 3304 */ 3305 valsize = min(len, sopt->sopt_valsize); 3306 sopt->sopt_valsize = valsize; 3307 if (sopt->sopt_val != NULL) { 3308 if (sopt->sopt_td != NULL) 3309 error = copyout(buf, sopt->sopt_val, valsize); 3310 else 3311 bcopy(buf, sopt->sopt_val, valsize); 3312 } 3313 return (error); 3314 } 3315 3316 int 3317 sogetopt(struct socket *so, struct sockopt *sopt) 3318 { 3319 int error, optval; 3320 struct linger l; 3321 struct timeval tv; 3322 #ifdef MAC 3323 struct mac extmac; 3324 #endif 3325 3326 CURVNET_SET(so->so_vnet); 3327 error = 0; 3328 if (sopt->sopt_level != SOL_SOCKET) { 3329 if (so->so_proto->pr_ctloutput != NULL) 3330 error = (*so->so_proto->pr_ctloutput)(so, sopt); 3331 else 3332 error = ENOPROTOOPT; 3333 CURVNET_RESTORE(); 3334 return (error); 3335 } else { 3336 switch (sopt->sopt_name) { 3337 case SO_ACCEPTFILTER: 3338 error = accept_filt_getopt(so, sopt); 3339 break; 3340 3341 case SO_LINGER: 3342 SOCK_LOCK(so); 3343 l.l_onoff = so->so_options & SO_LINGER; 3344 l.l_linger = so->so_linger; 3345 SOCK_UNLOCK(so); 3346 error = sooptcopyout(sopt, &l, sizeof l); 3347 break; 3348 3349 case SO_USELOOPBACK: 3350 case SO_DONTROUTE: 3351 case SO_DEBUG: 3352 case SO_KEEPALIVE: 3353 case SO_REUSEADDR: 3354 case SO_REUSEPORT: 3355 case SO_REUSEPORT_LB: 3356 case SO_BROADCAST: 3357 case SO_OOBINLINE: 3358 case SO_ACCEPTCONN: 3359 case SO_TIMESTAMP: 3360 case SO_BINTIME: 3361 case SO_NOSIGPIPE: 3362 case SO_NO_DDP: 3363 case SO_NO_OFFLOAD: 3364 case SO_RERROR: 3365 optval = so->so_options & sopt->sopt_name; 3366 integer: 3367 error = sooptcopyout(sopt, &optval, sizeof optval); 3368 break; 3369 3370 case SO_DOMAIN: 3371 optval = so->so_proto->pr_domain->dom_family; 3372 goto integer; 3373 3374 case SO_TYPE: 3375 optval = so->so_type; 3376 goto integer; 3377 3378 case SO_PROTOCOL: 3379 optval = so->so_proto->pr_protocol; 3380 goto integer; 3381 3382 case SO_ERROR: 3383 SOCK_LOCK(so); 3384 if (so->so_error) { 3385 optval = so->so_error; 3386 so->so_error = 0; 3387 } else { 3388 optval = so->so_rerror; 3389 so->so_rerror = 0; 3390 } 3391 SOCK_UNLOCK(so); 3392 goto integer; 3393 3394 case SO_SNDBUF: 3395 optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat : 3396 so->so_snd.sb_hiwat; 3397 goto integer; 3398 3399 case SO_RCVBUF: 3400 optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat : 3401 so->so_rcv.sb_hiwat; 3402 goto integer; 3403 3404 case SO_SNDLOWAT: 3405 optval = SOLISTENING(so) ? so->sol_sbsnd_lowat : 3406 so->so_snd.sb_lowat; 3407 goto integer; 3408 3409 case SO_RCVLOWAT: 3410 optval = SOLISTENING(so) ? so->sol_sbrcv_lowat : 3411 so->so_rcv.sb_lowat; 3412 goto integer; 3413 3414 case SO_SNDTIMEO: 3415 case SO_RCVTIMEO: 3416 SOCK_LOCK(so); 3417 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ? 3418 (SOLISTENING(so) ? so->sol_sbsnd_timeo : 3419 so->so_snd.sb_timeo) : 3420 (SOLISTENING(so) ? so->sol_sbrcv_timeo : 3421 so->so_rcv.sb_timeo)); 3422 SOCK_UNLOCK(so); 3423 #ifdef COMPAT_FREEBSD32 3424 if (SV_CURPROC_FLAG(SV_ILP32)) { 3425 struct timeval32 tv32; 3426 3427 CP(tv, tv32, tv_sec); 3428 CP(tv, tv32, tv_usec); 3429 error = sooptcopyout(sopt, &tv32, sizeof tv32); 3430 } else 3431 #endif 3432 error = sooptcopyout(sopt, &tv, sizeof tv); 3433 break; 3434 3435 case SO_LABEL: 3436 #ifdef MAC 3437 error = sooptcopyin(sopt, &extmac, sizeof(extmac), 3438 sizeof(extmac)); 3439 if (error) 3440 goto bad; 3441 error = mac_getsockopt_label(sopt->sopt_td->td_ucred, 3442 so, &extmac); 3443 if (error) 3444 goto bad; 3445 error = sooptcopyout(sopt, &extmac, sizeof extmac); 3446 #else 3447 error = EOPNOTSUPP; 3448 #endif 3449 break; 3450 3451 case SO_PEERLABEL: 3452 #ifdef MAC 3453 error = sooptcopyin(sopt, &extmac, sizeof(extmac), 3454 sizeof(extmac)); 3455 if (error) 3456 goto bad; 3457 error = mac_getsockopt_peerlabel( 3458 sopt->sopt_td->td_ucred, so, &extmac); 3459 if (error) 3460 goto bad; 3461 error = sooptcopyout(sopt, &extmac, sizeof extmac); 3462 #else 3463 error = EOPNOTSUPP; 3464 #endif 3465 break; 3466 3467 case SO_LISTENQLIMIT: 3468 optval = SOLISTENING(so) ? so->sol_qlimit : 0; 3469 goto integer; 3470 3471 case SO_LISTENQLEN: 3472 optval = SOLISTENING(so) ? so->sol_qlen : 0; 3473 goto integer; 3474 3475 case SO_LISTENINCQLEN: 3476 optval = SOLISTENING(so) ? so->sol_incqlen : 0; 3477 goto integer; 3478 3479 case SO_TS_CLOCK: 3480 optval = so->so_ts_clock; 3481 goto integer; 3482 3483 case SO_MAX_PACING_RATE: 3484 optval = so->so_max_pacing_rate; 3485 goto integer; 3486 3487 default: 3488 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0) 3489 error = hhook_run_socket(so, sopt, 3490 HHOOK_SOCKET_OPT); 3491 else 3492 error = ENOPROTOOPT; 3493 break; 3494 } 3495 } 3496 #ifdef MAC 3497 bad: 3498 #endif 3499 CURVNET_RESTORE(); 3500 return (error); 3501 } 3502 3503 int 3504 soopt_getm(struct sockopt *sopt, struct mbuf **mp) 3505 { 3506 struct mbuf *m, *m_prev; 3507 int sopt_size = sopt->sopt_valsize; 3508 3509 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA); 3510 if (m == NULL) 3511 return ENOBUFS; 3512 if (sopt_size > MLEN) { 3513 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT); 3514 if ((m->m_flags & M_EXT) == 0) { 3515 m_free(m); 3516 return ENOBUFS; 3517 } 3518 m->m_len = min(MCLBYTES, sopt_size); 3519 } else { 3520 m->m_len = min(MLEN, sopt_size); 3521 } 3522 sopt_size -= m->m_len; 3523 *mp = m; 3524 m_prev = m; 3525 3526 while (sopt_size) { 3527 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA); 3528 if (m == NULL) { 3529 m_freem(*mp); 3530 return ENOBUFS; 3531 } 3532 if (sopt_size > MLEN) { 3533 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK : 3534 M_NOWAIT); 3535 if ((m->m_flags & M_EXT) == 0) { 3536 m_freem(m); 3537 m_freem(*mp); 3538 return ENOBUFS; 3539 } 3540 m->m_len = min(MCLBYTES, sopt_size); 3541 } else { 3542 m->m_len = min(MLEN, sopt_size); 3543 } 3544 sopt_size -= m->m_len; 3545 m_prev->m_next = m; 3546 m_prev = m; 3547 } 3548 return (0); 3549 } 3550 3551 int 3552 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m) 3553 { 3554 struct mbuf *m0 = m; 3555 3556 if (sopt->sopt_val == NULL) 3557 return (0); 3558 while (m != NULL && sopt->sopt_valsize >= m->m_len) { 3559 if (sopt->sopt_td != NULL) { 3560 int error; 3561 3562 error = copyin(sopt->sopt_val, mtod(m, char *), 3563 m->m_len); 3564 if (error != 0) { 3565 m_freem(m0); 3566 return(error); 3567 } 3568 } else 3569 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len); 3570 sopt->sopt_valsize -= m->m_len; 3571 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len; 3572 m = m->m_next; 3573 } 3574 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */ 3575 panic("ip6_sooptmcopyin"); 3576 return (0); 3577 } 3578 3579 int 3580 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m) 3581 { 3582 struct mbuf *m0 = m; 3583 size_t valsize = 0; 3584 3585 if (sopt->sopt_val == NULL) 3586 return (0); 3587 while (m != NULL && sopt->sopt_valsize >= m->m_len) { 3588 if (sopt->sopt_td != NULL) { 3589 int error; 3590 3591 error = copyout(mtod(m, char *), sopt->sopt_val, 3592 m->m_len); 3593 if (error != 0) { 3594 m_freem(m0); 3595 return(error); 3596 } 3597 } else 3598 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len); 3599 sopt->sopt_valsize -= m->m_len; 3600 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len; 3601 valsize += m->m_len; 3602 m = m->m_next; 3603 } 3604 if (m != NULL) { 3605 /* enough soopt buffer should be given from user-land */ 3606 m_freem(m0); 3607 return(EINVAL); 3608 } 3609 sopt->sopt_valsize = valsize; 3610 return (0); 3611 } 3612 3613 /* 3614 * sohasoutofband(): protocol notifies socket layer of the arrival of new 3615 * out-of-band data, which will then notify socket consumers. 3616 */ 3617 void 3618 sohasoutofband(struct socket *so) 3619 { 3620 3621 if (so->so_sigio != NULL) 3622 pgsigio(&so->so_sigio, SIGURG, 0); 3623 selwakeuppri(&so->so_rdsel, PSOCK); 3624 } 3625 3626 int 3627 sopoll(struct socket *so, int events, struct ucred *active_cred, 3628 struct thread *td) 3629 { 3630 3631 /* 3632 * We do not need to set or assert curvnet as long as everyone uses 3633 * sopoll_generic(). 3634 */ 3635 return (so->so_proto->pr_sopoll(so, events, active_cred, td)); 3636 } 3637 3638 int 3639 sopoll_generic(struct socket *so, int events, struct ucred *active_cred, 3640 struct thread *td) 3641 { 3642 int revents; 3643 3644 SOCK_LOCK(so); 3645 if (SOLISTENING(so)) { 3646 if (!(events & (POLLIN | POLLRDNORM))) 3647 revents = 0; 3648 else if (!TAILQ_EMPTY(&so->sol_comp)) 3649 revents = events & (POLLIN | POLLRDNORM); 3650 else if ((events & POLLINIGNEOF) == 0 && so->so_error) 3651 revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP; 3652 else { 3653 selrecord(td, &so->so_rdsel); 3654 revents = 0; 3655 } 3656 } else { 3657 revents = 0; 3658 SOCK_SENDBUF_LOCK(so); 3659 SOCK_RECVBUF_LOCK(so); 3660 if (events & (POLLIN | POLLRDNORM)) 3661 if (soreadabledata(so)) 3662 revents |= events & (POLLIN | POLLRDNORM); 3663 if (events & (POLLOUT | POLLWRNORM)) 3664 if (sowriteable(so)) 3665 revents |= events & (POLLOUT | POLLWRNORM); 3666 if (events & (POLLPRI | POLLRDBAND)) 3667 if (so->so_oobmark || 3668 (so->so_rcv.sb_state & SBS_RCVATMARK)) 3669 revents |= events & (POLLPRI | POLLRDBAND); 3670 if ((events & POLLINIGNEOF) == 0) { 3671 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 3672 revents |= events & (POLLIN | POLLRDNORM); 3673 if (so->so_snd.sb_state & SBS_CANTSENDMORE) 3674 revents |= POLLHUP; 3675 } 3676 } 3677 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) 3678 revents |= events & POLLRDHUP; 3679 if (revents == 0) { 3680 if (events & 3681 (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND | POLLRDHUP)) { 3682 selrecord(td, &so->so_rdsel); 3683 so->so_rcv.sb_flags |= SB_SEL; 3684 } 3685 if (events & (POLLOUT | POLLWRNORM)) { 3686 selrecord(td, &so->so_wrsel); 3687 so->so_snd.sb_flags |= SB_SEL; 3688 } 3689 } 3690 SOCK_RECVBUF_UNLOCK(so); 3691 SOCK_SENDBUF_UNLOCK(so); 3692 } 3693 SOCK_UNLOCK(so); 3694 return (revents); 3695 } 3696 3697 int 3698 soo_kqfilter(struct file *fp, struct knote *kn) 3699 { 3700 struct socket *so = kn->kn_fp->f_data; 3701 struct sockbuf *sb; 3702 sb_which which; 3703 struct knlist *knl; 3704 3705 switch (kn->kn_filter) { 3706 case EVFILT_READ: 3707 kn->kn_fop = &soread_filtops; 3708 knl = &so->so_rdsel.si_note; 3709 sb = &so->so_rcv; 3710 which = SO_RCV; 3711 break; 3712 case EVFILT_WRITE: 3713 kn->kn_fop = &sowrite_filtops; 3714 knl = &so->so_wrsel.si_note; 3715 sb = &so->so_snd; 3716 which = SO_SND; 3717 break; 3718 case EVFILT_EMPTY: 3719 kn->kn_fop = &soempty_filtops; 3720 knl = &so->so_wrsel.si_note; 3721 sb = &so->so_snd; 3722 which = SO_SND; 3723 break; 3724 default: 3725 return (EINVAL); 3726 } 3727 3728 SOCK_LOCK(so); 3729 if (SOLISTENING(so)) { 3730 knlist_add(knl, kn, 1); 3731 } else { 3732 SOCK_BUF_LOCK(so, which); 3733 knlist_add(knl, kn, 1); 3734 sb->sb_flags |= SB_KNOTE; 3735 SOCK_BUF_UNLOCK(so, which); 3736 } 3737 SOCK_UNLOCK(so); 3738 return (0); 3739 } 3740 3741 static void 3742 filt_sordetach(struct knote *kn) 3743 { 3744 struct socket *so = kn->kn_fp->f_data; 3745 3746 so_rdknl_lock(so); 3747 knlist_remove(&so->so_rdsel.si_note, kn, 1); 3748 if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note)) 3749 so->so_rcv.sb_flags &= ~SB_KNOTE; 3750 so_rdknl_unlock(so); 3751 } 3752 3753 /*ARGSUSED*/ 3754 static int 3755 filt_soread(struct knote *kn, long hint) 3756 { 3757 struct socket *so; 3758 3759 so = kn->kn_fp->f_data; 3760 3761 if (SOLISTENING(so)) { 3762 SOCK_LOCK_ASSERT(so); 3763 kn->kn_data = so->sol_qlen; 3764 if (so->so_error) { 3765 kn->kn_flags |= EV_EOF; 3766 kn->kn_fflags = so->so_error; 3767 return (1); 3768 } 3769 return (!TAILQ_EMPTY(&so->sol_comp)); 3770 } 3771 3772 SOCK_RECVBUF_LOCK_ASSERT(so); 3773 3774 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl; 3775 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) { 3776 kn->kn_flags |= EV_EOF; 3777 kn->kn_fflags = so->so_error; 3778 return (1); 3779 } else if (so->so_error || so->so_rerror) 3780 return (1); 3781 3782 if (kn->kn_sfflags & NOTE_LOWAT) { 3783 if (kn->kn_data >= kn->kn_sdata) 3784 return (1); 3785 } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat) 3786 return (1); 3787 3788 /* This hook returning non-zero indicates an event, not error */ 3789 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD)); 3790 } 3791 3792 static void 3793 filt_sowdetach(struct knote *kn) 3794 { 3795 struct socket *so = kn->kn_fp->f_data; 3796 3797 so_wrknl_lock(so); 3798 knlist_remove(&so->so_wrsel.si_note, kn, 1); 3799 if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note)) 3800 so->so_snd.sb_flags &= ~SB_KNOTE; 3801 so_wrknl_unlock(so); 3802 } 3803 3804 /*ARGSUSED*/ 3805 static int 3806 filt_sowrite(struct knote *kn, long hint) 3807 { 3808 struct socket *so; 3809 3810 so = kn->kn_fp->f_data; 3811 3812 if (SOLISTENING(so)) 3813 return (0); 3814 3815 SOCK_SENDBUF_LOCK_ASSERT(so); 3816 kn->kn_data = sbspace(&so->so_snd); 3817 3818 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE); 3819 3820 if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 3821 kn->kn_flags |= EV_EOF; 3822 kn->kn_fflags = so->so_error; 3823 return (1); 3824 } else if (so->so_error) /* temporary udp error */ 3825 return (1); 3826 else if (((so->so_state & SS_ISCONNECTED) == 0) && 3827 (so->so_proto->pr_flags & PR_CONNREQUIRED)) 3828 return (0); 3829 else if (kn->kn_sfflags & NOTE_LOWAT) 3830 return (kn->kn_data >= kn->kn_sdata); 3831 else 3832 return (kn->kn_data >= so->so_snd.sb_lowat); 3833 } 3834 3835 static int 3836 filt_soempty(struct knote *kn, long hint) 3837 { 3838 struct socket *so; 3839 3840 so = kn->kn_fp->f_data; 3841 3842 if (SOLISTENING(so)) 3843 return (1); 3844 3845 SOCK_SENDBUF_LOCK_ASSERT(so); 3846 kn->kn_data = sbused(&so->so_snd); 3847 3848 if (kn->kn_data == 0) 3849 return (1); 3850 else 3851 return (0); 3852 } 3853 3854 int 3855 socheckuid(struct socket *so, uid_t uid) 3856 { 3857 3858 if (so == NULL) 3859 return (EPERM); 3860 if (so->so_cred->cr_uid != uid) 3861 return (EPERM); 3862 return (0); 3863 } 3864 3865 /* 3866 * These functions are used by protocols to notify the socket layer (and its 3867 * consumers) of state changes in the sockets driven by protocol-side events. 3868 */ 3869 3870 /* 3871 * Procedures to manipulate state flags of socket and do appropriate wakeups. 3872 * 3873 * Normal sequence from the active (originating) side is that 3874 * soisconnecting() is called during processing of connect() call, resulting 3875 * in an eventual call to soisconnected() if/when the connection is 3876 * established. When the connection is torn down soisdisconnecting() is 3877 * called during processing of disconnect() call, and soisdisconnected() is 3878 * called when the connection to the peer is totally severed. The semantics 3879 * of these routines are such that connectionless protocols can call 3880 * soisconnected() and soisdisconnected() only, bypassing the in-progress 3881 * calls when setting up a ``connection'' takes no time. 3882 * 3883 * From the passive side, a socket is created with two queues of sockets: 3884 * so_incomp for connections in progress and so_comp for connections already 3885 * made and awaiting user acceptance. As a protocol is preparing incoming 3886 * connections, it creates a socket structure queued on so_incomp by calling 3887 * sonewconn(). When the connection is established, soisconnected() is 3888 * called, and transfers the socket structure to so_comp, making it available 3889 * to accept(). 3890 * 3891 * If a socket is closed with sockets on either so_incomp or so_comp, these 3892 * sockets are dropped. 3893 * 3894 * If higher-level protocols are implemented in the kernel, the wakeups done 3895 * here will sometimes cause software-interrupt process scheduling. 3896 */ 3897 void 3898 soisconnecting(struct socket *so) 3899 { 3900 3901 SOCK_LOCK(so); 3902 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING); 3903 so->so_state |= SS_ISCONNECTING; 3904 SOCK_UNLOCK(so); 3905 } 3906 3907 void 3908 soisconnected(struct socket *so) 3909 { 3910 bool last __diagused; 3911 3912 SOCK_LOCK(so); 3913 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING); 3914 so->so_state |= SS_ISCONNECTED; 3915 3916 if (so->so_qstate == SQ_INCOMP) { 3917 struct socket *head = so->so_listen; 3918 int ret; 3919 3920 KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so)); 3921 /* 3922 * Promoting a socket from incomplete queue to complete, we 3923 * need to go through reverse order of locking. We first do 3924 * trylock, and if that doesn't succeed, we go the hard way 3925 * leaving a reference and rechecking consistency after proper 3926 * locking. 3927 */ 3928 if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) { 3929 soref(head); 3930 SOCK_UNLOCK(so); 3931 SOLISTEN_LOCK(head); 3932 SOCK_LOCK(so); 3933 if (__predict_false(head != so->so_listen)) { 3934 /* 3935 * The socket went off the listen queue, 3936 * should be lost race to close(2) of sol. 3937 * The socket is about to soabort(). 3938 */ 3939 SOCK_UNLOCK(so); 3940 sorele_locked(head); 3941 return; 3942 } 3943 last = refcount_release(&head->so_count); 3944 KASSERT(!last, ("%s: released last reference for %p", 3945 __func__, head)); 3946 } 3947 again: 3948 if ((so->so_options & SO_ACCEPTFILTER) == 0) { 3949 TAILQ_REMOVE(&head->sol_incomp, so, so_list); 3950 head->sol_incqlen--; 3951 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list); 3952 head->sol_qlen++; 3953 so->so_qstate = SQ_COMP; 3954 SOCK_UNLOCK(so); 3955 solisten_wakeup(head); /* unlocks */ 3956 } else { 3957 SOCK_RECVBUF_LOCK(so); 3958 soupcall_set(so, SO_RCV, 3959 head->sol_accept_filter->accf_callback, 3960 head->sol_accept_filter_arg); 3961 so->so_options &= ~SO_ACCEPTFILTER; 3962 ret = head->sol_accept_filter->accf_callback(so, 3963 head->sol_accept_filter_arg, M_NOWAIT); 3964 if (ret == SU_ISCONNECTED) { 3965 soupcall_clear(so, SO_RCV); 3966 SOCK_RECVBUF_UNLOCK(so); 3967 goto again; 3968 } 3969 SOCK_RECVBUF_UNLOCK(so); 3970 SOCK_UNLOCK(so); 3971 SOLISTEN_UNLOCK(head); 3972 } 3973 return; 3974 } 3975 SOCK_UNLOCK(so); 3976 wakeup(&so->so_timeo); 3977 sorwakeup(so); 3978 sowwakeup(so); 3979 } 3980 3981 void 3982 soisdisconnecting(struct socket *so) 3983 { 3984 3985 SOCK_LOCK(so); 3986 so->so_state &= ~SS_ISCONNECTING; 3987 so->so_state |= SS_ISDISCONNECTING; 3988 3989 if (!SOLISTENING(so)) { 3990 SOCK_RECVBUF_LOCK(so); 3991 socantrcvmore_locked(so); 3992 SOCK_SENDBUF_LOCK(so); 3993 socantsendmore_locked(so); 3994 } 3995 SOCK_UNLOCK(so); 3996 wakeup(&so->so_timeo); 3997 } 3998 3999 void 4000 soisdisconnected(struct socket *so) 4001 { 4002 4003 SOCK_LOCK(so); 4004 4005 /* 4006 * There is at least one reader of so_state that does not 4007 * acquire socket lock, namely soreceive_generic(). Ensure 4008 * that it never sees all flags that track connection status 4009 * cleared, by ordering the update with a barrier semantic of 4010 * our release thread fence. 4011 */ 4012 so->so_state |= SS_ISDISCONNECTED; 4013 atomic_thread_fence_rel(); 4014 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING); 4015 4016 if (!SOLISTENING(so)) { 4017 SOCK_UNLOCK(so); 4018 SOCK_RECVBUF_LOCK(so); 4019 socantrcvmore_locked(so); 4020 SOCK_SENDBUF_LOCK(so); 4021 sbdrop_locked(&so->so_snd, sbused(&so->so_snd)); 4022 socantsendmore_locked(so); 4023 } else 4024 SOCK_UNLOCK(so); 4025 wakeup(&so->so_timeo); 4026 } 4027 4028 int 4029 soiolock(struct socket *so, struct sx *sx, int flags) 4030 { 4031 int error; 4032 4033 KASSERT((flags & SBL_VALID) == flags, 4034 ("soiolock: invalid flags %#x", flags)); 4035 4036 if ((flags & SBL_WAIT) != 0) { 4037 if ((flags & SBL_NOINTR) != 0) { 4038 sx_xlock(sx); 4039 } else { 4040 error = sx_xlock_sig(sx); 4041 if (error != 0) 4042 return (error); 4043 } 4044 } else if (!sx_try_xlock(sx)) { 4045 return (EWOULDBLOCK); 4046 } 4047 4048 if (__predict_false(SOLISTENING(so))) { 4049 sx_xunlock(sx); 4050 return (ENOTCONN); 4051 } 4052 return (0); 4053 } 4054 4055 void 4056 soiounlock(struct sx *sx) 4057 { 4058 sx_xunlock(sx); 4059 } 4060 4061 /* 4062 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME. 4063 */ 4064 struct sockaddr * 4065 sodupsockaddr(const struct sockaddr *sa, int mflags) 4066 { 4067 struct sockaddr *sa2; 4068 4069 sa2 = malloc(sa->sa_len, M_SONAME, mflags); 4070 if (sa2) 4071 bcopy(sa, sa2, sa->sa_len); 4072 return sa2; 4073 } 4074 4075 /* 4076 * Register per-socket destructor. 4077 */ 4078 void 4079 sodtor_set(struct socket *so, so_dtor_t *func) 4080 { 4081 4082 SOCK_LOCK_ASSERT(so); 4083 so->so_dtor = func; 4084 } 4085 4086 /* 4087 * Register per-socket buffer upcalls. 4088 */ 4089 void 4090 soupcall_set(struct socket *so, sb_which which, so_upcall_t func, void *arg) 4091 { 4092 struct sockbuf *sb; 4093 4094 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so)); 4095 4096 switch (which) { 4097 case SO_RCV: 4098 sb = &so->so_rcv; 4099 break; 4100 case SO_SND: 4101 sb = &so->so_snd; 4102 break; 4103 } 4104 SOCK_BUF_LOCK_ASSERT(so, which); 4105 sb->sb_upcall = func; 4106 sb->sb_upcallarg = arg; 4107 sb->sb_flags |= SB_UPCALL; 4108 } 4109 4110 void 4111 soupcall_clear(struct socket *so, sb_which which) 4112 { 4113 struct sockbuf *sb; 4114 4115 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so)); 4116 4117 switch (which) { 4118 case SO_RCV: 4119 sb = &so->so_rcv; 4120 break; 4121 case SO_SND: 4122 sb = &so->so_snd; 4123 break; 4124 } 4125 SOCK_BUF_LOCK_ASSERT(so, which); 4126 KASSERT(sb->sb_upcall != NULL, 4127 ("%s: so %p no upcall to clear", __func__, so)); 4128 sb->sb_upcall = NULL; 4129 sb->sb_upcallarg = NULL; 4130 sb->sb_flags &= ~SB_UPCALL; 4131 } 4132 4133 void 4134 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg) 4135 { 4136 4137 SOLISTEN_LOCK_ASSERT(so); 4138 so->sol_upcall = func; 4139 so->sol_upcallarg = arg; 4140 } 4141 4142 static void 4143 so_rdknl_lock(void *arg) 4144 { 4145 struct socket *so = arg; 4146 4147 retry: 4148 if (SOLISTENING(so)) { 4149 SOLISTEN_LOCK(so); 4150 } else { 4151 SOCK_RECVBUF_LOCK(so); 4152 if (__predict_false(SOLISTENING(so))) { 4153 SOCK_RECVBUF_UNLOCK(so); 4154 goto retry; 4155 } 4156 } 4157 } 4158 4159 static void 4160 so_rdknl_unlock(void *arg) 4161 { 4162 struct socket *so = arg; 4163 4164 if (SOLISTENING(so)) 4165 SOLISTEN_UNLOCK(so); 4166 else 4167 SOCK_RECVBUF_UNLOCK(so); 4168 } 4169 4170 static void 4171 so_rdknl_assert_lock(void *arg, int what) 4172 { 4173 struct socket *so = arg; 4174 4175 if (what == LA_LOCKED) { 4176 if (SOLISTENING(so)) 4177 SOLISTEN_LOCK_ASSERT(so); 4178 else 4179 SOCK_RECVBUF_LOCK_ASSERT(so); 4180 } else { 4181 if (SOLISTENING(so)) 4182 SOLISTEN_UNLOCK_ASSERT(so); 4183 else 4184 SOCK_RECVBUF_UNLOCK_ASSERT(so); 4185 } 4186 } 4187 4188 static void 4189 so_wrknl_lock(void *arg) 4190 { 4191 struct socket *so = arg; 4192 4193 retry: 4194 if (SOLISTENING(so)) { 4195 SOLISTEN_LOCK(so); 4196 } else { 4197 SOCK_SENDBUF_LOCK(so); 4198 if (__predict_false(SOLISTENING(so))) { 4199 SOCK_SENDBUF_UNLOCK(so); 4200 goto retry; 4201 } 4202 } 4203 } 4204 4205 static void 4206 so_wrknl_unlock(void *arg) 4207 { 4208 struct socket *so = arg; 4209 4210 if (SOLISTENING(so)) 4211 SOLISTEN_UNLOCK(so); 4212 else 4213 SOCK_SENDBUF_UNLOCK(so); 4214 } 4215 4216 static void 4217 so_wrknl_assert_lock(void *arg, int what) 4218 { 4219 struct socket *so = arg; 4220 4221 if (what == LA_LOCKED) { 4222 if (SOLISTENING(so)) 4223 SOLISTEN_LOCK_ASSERT(so); 4224 else 4225 SOCK_SENDBUF_LOCK_ASSERT(so); 4226 } else { 4227 if (SOLISTENING(so)) 4228 SOLISTEN_UNLOCK_ASSERT(so); 4229 else 4230 SOCK_SENDBUF_UNLOCK_ASSERT(so); 4231 } 4232 } 4233 4234 /* 4235 * Create an external-format (``xsocket'') structure using the information in 4236 * the kernel-format socket structure pointed to by so. This is done to 4237 * reduce the spew of irrelevant information over this interface, to isolate 4238 * user code from changes in the kernel structure, and potentially to provide 4239 * information-hiding if we decide that some of this information should be 4240 * hidden from users. 4241 */ 4242 void 4243 sotoxsocket(struct socket *so, struct xsocket *xso) 4244 { 4245 4246 bzero(xso, sizeof(*xso)); 4247 xso->xso_len = sizeof *xso; 4248 xso->xso_so = (uintptr_t)so; 4249 xso->so_type = so->so_type; 4250 xso->so_options = so->so_options; 4251 xso->so_linger = so->so_linger; 4252 xso->so_state = so->so_state; 4253 xso->so_pcb = (uintptr_t)so->so_pcb; 4254 xso->xso_protocol = so->so_proto->pr_protocol; 4255 xso->xso_family = so->so_proto->pr_domain->dom_family; 4256 xso->so_timeo = so->so_timeo; 4257 xso->so_error = so->so_error; 4258 xso->so_uid = so->so_cred->cr_uid; 4259 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0; 4260 if (SOLISTENING(so)) { 4261 xso->so_qlen = so->sol_qlen; 4262 xso->so_incqlen = so->sol_incqlen; 4263 xso->so_qlimit = so->sol_qlimit; 4264 xso->so_oobmark = 0; 4265 } else { 4266 xso->so_state |= so->so_qstate; 4267 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0; 4268 xso->so_oobmark = so->so_oobmark; 4269 sbtoxsockbuf(&so->so_snd, &xso->so_snd); 4270 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv); 4271 } 4272 } 4273 4274 struct sockbuf * 4275 so_sockbuf_rcv(struct socket *so) 4276 { 4277 4278 return (&so->so_rcv); 4279 } 4280 4281 struct sockbuf * 4282 so_sockbuf_snd(struct socket *so) 4283 { 4284 4285 return (&so->so_snd); 4286 } 4287 4288 int 4289 so_state_get(const struct socket *so) 4290 { 4291 4292 return (so->so_state); 4293 } 4294 4295 void 4296 so_state_set(struct socket *so, int val) 4297 { 4298 4299 so->so_state = val; 4300 } 4301 4302 int 4303 so_options_get(const struct socket *so) 4304 { 4305 4306 return (so->so_options); 4307 } 4308 4309 void 4310 so_options_set(struct socket *so, int val) 4311 { 4312 4313 so->so_options = val; 4314 } 4315 4316 int 4317 so_error_get(const struct socket *so) 4318 { 4319 4320 return (so->so_error); 4321 } 4322 4323 void 4324 so_error_set(struct socket *so, int val) 4325 { 4326 4327 so->so_error = val; 4328 } 4329 4330 int 4331 so_linger_get(const struct socket *so) 4332 { 4333 4334 return (so->so_linger); 4335 } 4336 4337 void 4338 so_linger_set(struct socket *so, int val) 4339 { 4340 4341 KASSERT(val >= 0 && val <= USHRT_MAX && val <= (INT_MAX / hz), 4342 ("%s: val %d out of range", __func__, val)); 4343 4344 so->so_linger = val; 4345 } 4346 4347 struct protosw * 4348 so_protosw_get(const struct socket *so) 4349 { 4350 4351 return (so->so_proto); 4352 } 4353 4354 void 4355 so_protosw_set(struct socket *so, struct protosw *val) 4356 { 4357 4358 so->so_proto = val; 4359 } 4360 4361 void 4362 so_sorwakeup(struct socket *so) 4363 { 4364 4365 sorwakeup(so); 4366 } 4367 4368 void 4369 so_sowwakeup(struct socket *so) 4370 { 4371 4372 sowwakeup(so); 4373 } 4374 4375 void 4376 so_sorwakeup_locked(struct socket *so) 4377 { 4378 4379 sorwakeup_locked(so); 4380 } 4381 4382 void 4383 so_sowwakeup_locked(struct socket *so) 4384 { 4385 4386 sowwakeup_locked(so); 4387 } 4388 4389 void 4390 so_lock(struct socket *so) 4391 { 4392 4393 SOCK_LOCK(so); 4394 } 4395 4396 void 4397 so_unlock(struct socket *so) 4398 { 4399 4400 SOCK_UNLOCK(so); 4401 } 4402