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