1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1982, 1986, 1989, 1991, 1993 5 * The Regents of the University of California. All Rights Reserved. 6 * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved. 7 * Copyright (c) 2018 Matthew Macy 8 * Copyright (c) 2022-2025 Gleb Smirnoff <glebius@FreeBSD.org> 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 3. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 */ 34 35 /* 36 * UNIX Domain (Local) Sockets 37 * 38 * This is an implementation of UNIX (local) domain sockets. Each socket has 39 * an associated struct unpcb (UNIX protocol control block). Stream sockets 40 * may be connected to 0 or 1 other socket. Datagram sockets may be 41 * connected to 0, 1, or many other sockets. Sockets may be created and 42 * connected in pairs (socketpair(2)), or bound/connected to using the file 43 * system name space. For most purposes, only the receive socket buffer is 44 * used, as sending on one socket delivers directly to the receive socket 45 * buffer of a second socket. 46 * 47 * The implementation is substantially complicated by the fact that 48 * "ancillary data", such as file descriptors or credentials, may be passed 49 * across UNIX domain sockets. The potential for passing UNIX domain sockets 50 * over other UNIX domain sockets requires the implementation of a simple 51 * garbage collector to find and tear down cycles of disconnected sockets. 52 * 53 * TODO: 54 * RDM 55 * rethink name space problems 56 * need a proper out-of-band 57 */ 58 59 #include "opt_ddb.h" 60 61 #include <sys/param.h> 62 #include <sys/capsicum.h> 63 #include <sys/domain.h> 64 #include <sys/eventhandler.h> 65 #include <sys/fcntl.h> 66 #include <sys/file.h> 67 #include <sys/filedesc.h> 68 #include <sys/jail.h> 69 #include <sys/kernel.h> 70 #include <sys/lock.h> 71 #include <sys/malloc.h> 72 #include <sys/mbuf.h> 73 #include <sys/mount.h> 74 #include <sys/mutex.h> 75 #include <sys/namei.h> 76 #include <sys/poll.h> 77 #include <sys/proc.h> 78 #include <sys/protosw.h> 79 #include <sys/queue.h> 80 #include <sys/resourcevar.h> 81 #include <sys/rwlock.h> 82 #include <sys/socket.h> 83 #include <sys/socketvar.h> 84 #include <sys/signalvar.h> 85 #include <sys/stat.h> 86 #include <sys/sysent.h> 87 #include <sys/sx.h> 88 #include <sys/sysctl.h> 89 #include <sys/systm.h> 90 #include <sys/taskqueue.h> 91 #include <sys/un.h> 92 #include <sys/unpcb.h> 93 #include <sys/vnode.h> 94 95 #include <net/vnet.h> 96 97 #ifdef DDB 98 #include <ddb/ddb.h> 99 #endif 100 101 #include <security/mac/mac_framework.h> 102 103 #include <vm/uma.h> 104 105 MALLOC_DECLARE(M_FILECAPS); 106 107 static struct domain localdomain; 108 109 static uma_zone_t unp_zone; 110 static unp_gen_t unp_gencnt; /* (l) */ 111 static u_int unp_count; /* (l) Count of local sockets. */ 112 static ino_t unp_ino; /* Prototype for fake inode numbers. */ 113 static int unp_rights; /* (g) File descriptors in flight. */ 114 static struct unp_head unp_shead; /* (l) List of stream sockets. */ 115 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */ 116 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */ 117 static struct mtx_pool *unp_vp_mtxpool; 118 119 struct unp_defer { 120 SLIST_ENTRY(unp_defer) ud_link; 121 struct file *ud_fp; 122 }; 123 static SLIST_HEAD(, unp_defer) unp_defers; 124 static int unp_defers_count; 125 126 static const struct sockaddr sun_noname = { 127 .sa_len = sizeof(sun_noname), 128 .sa_family = AF_LOCAL, 129 }; 130 131 /* 132 * Garbage collection of cyclic file descriptor/socket references occurs 133 * asynchronously in a taskqueue context in order to avoid recursion and 134 * reentrance in the UNIX domain socket, file descriptor, and socket layer 135 * code. See unp_gc() for a full description. 136 */ 137 static struct timeout_task unp_gc_task; 138 139 /* 140 * The close of unix domain sockets attached as SCM_RIGHTS is 141 * postponed to the taskqueue, to avoid arbitrary recursion depth. 142 * The attached sockets might have another sockets attached. 143 */ 144 static struct task unp_defer_task; 145 146 /* 147 * SOCK_STREAM and SOCK_SEQPACKET unix(4) sockets fully bypass the send buffer, 148 * however the notion of send buffer still makes sense with them. Its size is 149 * the amount of space that a send(2) syscall may copyin(9) before checking 150 * with the receive buffer of a peer. Although not linked anywhere yet, 151 * pointed to by a stack variable, effectively it is a buffer that needs to be 152 * sized. 153 * 154 * SOCK_DGRAM sockets really use the sendspace as the maximum datagram size, 155 * and don't really want to reserve the sendspace. Their recvspace should be 156 * large enough for at least one max-size datagram plus address. 157 */ 158 static u_long unpst_sendspace = 64*1024; 159 static u_long unpst_recvspace = 64*1024; 160 static u_long unpdg_maxdgram = 8*1024; /* support 8KB syslog msgs */ 161 static u_long unpdg_recvspace = 16*1024; 162 static u_long unpsp_sendspace = 64*1024; 163 static u_long unpsp_recvspace = 64*1024; 164 165 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 166 "Local domain"); 167 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, 168 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 169 "SOCK_STREAM"); 170 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, 171 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 172 "SOCK_DGRAM"); 173 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, 174 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 175 "SOCK_SEQPACKET"); 176 177 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW, 178 &unpst_sendspace, 0, "Default stream send space."); 179 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW, 180 &unpst_recvspace, 0, "Default stream receive space."); 181 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW, 182 &unpdg_maxdgram, 0, "Maximum datagram size."); 183 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW, 184 &unpdg_recvspace, 0, "Default datagram receive space."); 185 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW, 186 &unpsp_sendspace, 0, "Default seqpacket send space."); 187 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW, 188 &unpsp_recvspace, 0, "Default seqpacket receive space."); 189 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, 190 "File descriptors in flight."); 191 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD, 192 &unp_defers_count, 0, 193 "File descriptors deferred to taskqueue for close."); 194 195 /* 196 * Locking and synchronization: 197 * 198 * Several types of locks exist in the local domain socket implementation: 199 * - a global linkage lock 200 * - a global connection list lock 201 * - the mtxpool lock 202 * - per-unpcb mutexes 203 * 204 * The linkage lock protects the global socket lists, the generation number 205 * counter and garbage collector state. 206 * 207 * The connection list lock protects the list of referring sockets in a datagram 208 * socket PCB. This lock is also overloaded to protect a global list of 209 * sockets whose buffers contain socket references in the form of SCM_RIGHTS 210 * messages. To avoid recursion, such references are released by a dedicated 211 * thread. 212 * 213 * The mtxpool lock protects the vnode from being modified while referenced. 214 * Lock ordering rules require that it be acquired before any PCB locks. 215 * 216 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the 217 * unpcb. This includes the unp_conn field, which either links two connected 218 * PCBs together (for connected socket types) or points at the destination 219 * socket (for connectionless socket types). The operations of creating or 220 * destroying a connection therefore involve locking multiple PCBs. To avoid 221 * lock order reversals, in some cases this involves dropping a PCB lock and 222 * using a reference counter to maintain liveness. 223 * 224 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer, 225 * allocated in pr_attach() and freed in pr_detach(). The validity of that 226 * pointer is an invariant, so no lock is required to dereference the so_pcb 227 * pointer if a valid socket reference is held by the caller. In practice, 228 * this is always true during operations performed on a socket. Each unpcb 229 * has a back-pointer to its socket, unp_socket, which will be stable under 230 * the same circumstances. 231 * 232 * This pointer may only be safely dereferenced as long as a valid reference 233 * to the unpcb is held. Typically, this reference will be from the socket, 234 * or from another unpcb when the referring unpcb's lock is held (in order 235 * that the reference not be invalidated during use). For example, to follow 236 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee 237 * that detach is not run clearing unp_socket. 238 * 239 * Blocking with UNIX domain sockets is a tricky issue: unlike most network 240 * protocols, bind() is a non-atomic operation, and connect() requires 241 * potential sleeping in the protocol, due to potentially waiting on local or 242 * distributed file systems. We try to separate "lookup" operations, which 243 * may sleep, and the IPC operations themselves, which typically can occur 244 * with relative atomicity as locks can be held over the entire operation. 245 * 246 * Another tricky issue is simultaneous multi-threaded or multi-process 247 * access to a single UNIX domain socket. These are handled by the flags 248 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or 249 * binding, both of which involve dropping UNIX domain socket locks in order 250 * to perform namei() and other file system operations. 251 */ 252 static struct rwlock unp_link_rwlock; 253 static struct mtx unp_defers_lock; 254 255 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \ 256 "unp_link_rwlock") 257 258 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \ 259 RA_LOCKED) 260 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \ 261 RA_UNLOCKED) 262 263 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock) 264 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock) 265 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock) 266 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock) 267 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \ 268 RA_WLOCKED) 269 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock) 270 271 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \ 272 "unp_defer", NULL, MTX_DEF) 273 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock) 274 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock) 275 276 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK(); 277 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK(); 278 279 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \ 280 "unp", "unp", \ 281 MTX_DUPOK|MTX_DEF) 282 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx) 283 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx) 284 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx) 285 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx) 286 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx) 287 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx) 288 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED) 289 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED) 290 291 static int uipc_connect2(struct socket *, struct socket *); 292 static int uipc_ctloutput(struct socket *, struct sockopt *); 293 static int unp_connect(struct socket *, struct sockaddr *, 294 struct thread *); 295 static int unp_connectat(int, struct socket *, struct sockaddr *, 296 struct thread *, bool); 297 static void unp_connect2(struct socket *, struct socket *, bool); 298 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2); 299 static void unp_dispose(struct socket *so); 300 static void unp_drop(struct unpcb *); 301 static void unp_gc(__unused void *, int); 302 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int)); 303 static void unp_discard(struct file *); 304 static void unp_freerights(struct filedescent **, int); 305 static int unp_internalize(struct mbuf *, struct mchain *, 306 struct thread *, int *); 307 static void unp_internalize_fp(struct file *); 308 static int unp_externalize(const struct socket *, struct mbuf *, 309 struct mbuf **, int); 310 static int unp_externalize_fp(struct file *); 311 static void unp_addsockcred(struct thread *, struct mchain *, int); 312 static void unp_process_defers(void * __unused, int); 313 314 static void uipc_wrknl_lock(void *); 315 static void uipc_wrknl_unlock(void *); 316 static void uipc_wrknl_assert_lock(void *, int); 317 318 static void 319 unp_pcb_hold(struct unpcb *unp) 320 { 321 u_int old __unused; 322 323 old = refcount_acquire(&unp->unp_refcount); 324 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp)); 325 } 326 327 static __result_use_check bool 328 unp_pcb_rele(struct unpcb *unp) 329 { 330 bool ret; 331 332 UNP_PCB_LOCK_ASSERT(unp); 333 334 if ((ret = refcount_release(&unp->unp_refcount))) { 335 UNP_PCB_UNLOCK(unp); 336 UNP_PCB_LOCK_DESTROY(unp); 337 uma_zfree(unp_zone, unp); 338 } 339 return (ret); 340 } 341 342 static void 343 unp_pcb_rele_notlast(struct unpcb *unp) 344 { 345 bool ret __unused; 346 347 ret = refcount_release(&unp->unp_refcount); 348 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp)); 349 } 350 351 static void 352 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2) 353 { 354 UNP_PCB_UNLOCK_ASSERT(unp); 355 UNP_PCB_UNLOCK_ASSERT(unp2); 356 357 if (unp == unp2) { 358 UNP_PCB_LOCK(unp); 359 } else if ((uintptr_t)unp2 > (uintptr_t)unp) { 360 UNP_PCB_LOCK(unp); 361 UNP_PCB_LOCK(unp2); 362 } else { 363 UNP_PCB_LOCK(unp2); 364 UNP_PCB_LOCK(unp); 365 } 366 } 367 368 static void 369 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2) 370 { 371 UNP_PCB_UNLOCK(unp); 372 if (unp != unp2) 373 UNP_PCB_UNLOCK(unp2); 374 } 375 376 /* 377 * Try to lock the connected peer of an already locked socket. In some cases 378 * this requires that we unlock the current socket. The pairbusy counter is 379 * used to block concurrent connection attempts while the lock is dropped. The 380 * caller must be careful to revalidate PCB state. 381 */ 382 static struct unpcb * 383 unp_pcb_lock_peer(struct unpcb *unp) 384 { 385 struct unpcb *unp2; 386 387 UNP_PCB_LOCK_ASSERT(unp); 388 unp2 = unp->unp_conn; 389 if (unp2 == NULL) 390 return (NULL); 391 if (__predict_false(unp == unp2)) 392 return (unp); 393 394 UNP_PCB_UNLOCK_ASSERT(unp2); 395 396 if (__predict_true(UNP_PCB_TRYLOCK(unp2))) 397 return (unp2); 398 if ((uintptr_t)unp2 > (uintptr_t)unp) { 399 UNP_PCB_LOCK(unp2); 400 return (unp2); 401 } 402 unp->unp_pairbusy++; 403 unp_pcb_hold(unp2); 404 UNP_PCB_UNLOCK(unp); 405 406 UNP_PCB_LOCK(unp2); 407 UNP_PCB_LOCK(unp); 408 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL, 409 ("%s: socket %p was reconnected", __func__, unp)); 410 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) { 411 unp->unp_flags &= ~UNP_WAITING; 412 wakeup(unp); 413 } 414 if (unp_pcb_rele(unp2)) { 415 /* unp2 is unlocked. */ 416 return (NULL); 417 } 418 if (unp->unp_conn == NULL) { 419 UNP_PCB_UNLOCK(unp2); 420 return (NULL); 421 } 422 return (unp2); 423 } 424 425 /* 426 * Try to lock peer of our socket for purposes of sending data to it. 427 */ 428 static int 429 uipc_lock_peer(struct socket *so, struct unpcb **unp2) 430 { 431 struct unpcb *unp; 432 int error; 433 434 unp = sotounpcb(so); 435 UNP_PCB_LOCK(unp); 436 *unp2 = unp_pcb_lock_peer(unp); 437 if (__predict_false(so->so_error != 0)) { 438 error = so->so_error; 439 so->so_error = 0; 440 UNP_PCB_UNLOCK(unp); 441 if (*unp2 != NULL) 442 UNP_PCB_UNLOCK(*unp2); 443 return (error); 444 } 445 if (__predict_false(*unp2 == NULL)) { 446 /* 447 * Different error code for a previously connected socket and 448 * a never connected one. The SS_ISDISCONNECTED is set in the 449 * unp_soisdisconnected() and is synchronized by the pcb lock. 450 */ 451 error = so->so_state & SS_ISDISCONNECTED ? EPIPE : ENOTCONN; 452 UNP_PCB_UNLOCK(unp); 453 return (error); 454 } 455 UNP_PCB_UNLOCK(unp); 456 457 return (0); 458 } 459 460 static void 461 uipc_abort(struct socket *so) 462 { 463 struct unpcb *unp, *unp2; 464 465 unp = sotounpcb(so); 466 KASSERT(unp != NULL, ("uipc_abort: unp == NULL")); 467 UNP_PCB_UNLOCK_ASSERT(unp); 468 469 UNP_PCB_LOCK(unp); 470 unp2 = unp->unp_conn; 471 if (unp2 != NULL) { 472 unp_pcb_hold(unp2); 473 UNP_PCB_UNLOCK(unp); 474 unp_drop(unp2); 475 } else 476 UNP_PCB_UNLOCK(unp); 477 } 478 479 static int 480 uipc_attach(struct socket *so, int proto, struct thread *td) 481 { 482 u_long sendspace, recvspace; 483 struct unpcb *unp; 484 int error, rcvmtxopts; 485 bool locked; 486 487 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL")); 488 switch (so->so_type) { 489 case SOCK_DGRAM: 490 STAILQ_INIT(&so->so_rcv.uxdg_mb); 491 STAILQ_INIT(&so->so_snd.uxdg_mb); 492 TAILQ_INIT(&so->so_rcv.uxdg_conns); 493 /* 494 * Since send buffer is either bypassed or is a part 495 * of one-to-many receive buffer, we assign both space 496 * limits to unpdg_recvspace. 497 */ 498 sendspace = recvspace = unpdg_recvspace; 499 rcvmtxopts = 0; 500 break; 501 502 case SOCK_STREAM: 503 sendspace = unpst_sendspace; 504 recvspace = unpst_recvspace; 505 goto common; 506 507 case SOCK_SEQPACKET: 508 sendspace = unpsp_sendspace; 509 recvspace = unpsp_recvspace; 510 common: 511 rcvmtxopts = MTX_DUPOK; 512 knlist_init(&so->so_wrsel.si_note, so, uipc_wrknl_lock, 513 uipc_wrknl_unlock, uipc_wrknl_assert_lock); 514 STAILQ_INIT(&so->so_rcv.uxst_mbq); 515 break; 516 default: 517 panic("uipc_attach"); 518 } 519 mtx_init(&so->so_rcv_mtx, "unix so_rcv", NULL, MTX_DEF | rcvmtxopts); 520 mtx_init(&so->so_snd_mtx, "unix so_snd", NULL, MTX_DEF); 521 error = soreserve(so, sendspace, recvspace); 522 if (error) 523 return (error); 524 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO); 525 if (unp == NULL) 526 return (ENOBUFS); 527 LIST_INIT(&unp->unp_refs); 528 UNP_PCB_LOCK_INIT(unp); 529 unp->unp_socket = so; 530 so->so_pcb = unp; 531 so->so_options |= SO_PASSRIGHTS; 532 refcount_init(&unp->unp_refcount, 1); 533 unp->unp_mode = ACCESSPERMS; 534 535 if ((locked = UNP_LINK_WOWNED()) == false) 536 UNP_LINK_WLOCK(); 537 538 unp->unp_gencnt = ++unp_gencnt; 539 unp->unp_ino = ++unp_ino; 540 unp_count++; 541 switch (so->so_type) { 542 case SOCK_STREAM: 543 LIST_INSERT_HEAD(&unp_shead, unp, unp_link); 544 break; 545 546 case SOCK_DGRAM: 547 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link); 548 break; 549 550 case SOCK_SEQPACKET: 551 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link); 552 break; 553 554 default: 555 panic("uipc_attach"); 556 } 557 558 if (locked == false) 559 UNP_LINK_WUNLOCK(); 560 561 return (0); 562 } 563 564 static int 565 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td) 566 { 567 struct sockaddr_un *soun = (struct sockaddr_un *)nam; 568 struct vattr vattr; 569 int error, namelen; 570 struct nameidata nd; 571 struct unpcb *unp; 572 struct vnode *vp; 573 struct mount *mp; 574 cap_rights_t rights; 575 char *buf; 576 mode_t mode; 577 578 if (nam->sa_family != AF_UNIX) 579 return (EAFNOSUPPORT); 580 581 unp = sotounpcb(so); 582 KASSERT(unp != NULL, ("uipc_bind: unp == NULL")); 583 584 if (soun->sun_len > sizeof(struct sockaddr_un)) 585 return (EINVAL); 586 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path); 587 if (namelen <= 0) 588 return (EINVAL); 589 590 /* 591 * We don't allow simultaneous bind() calls on a single UNIX domain 592 * socket, so flag in-progress operations, and return an error if an 593 * operation is already in progress. 594 * 595 * Historically, we have not allowed a socket to be rebound, so this 596 * also returns an error. Not allowing re-binding simplifies the 597 * implementation and avoids a great many possible failure modes. 598 */ 599 UNP_PCB_LOCK(unp); 600 if (unp->unp_vnode != NULL) { 601 UNP_PCB_UNLOCK(unp); 602 return (EINVAL); 603 } 604 if (unp->unp_flags & UNP_BINDING) { 605 UNP_PCB_UNLOCK(unp); 606 return (EALREADY); 607 } 608 unp->unp_flags |= UNP_BINDING; 609 mode = unp->unp_mode & ~td->td_proc->p_pd->pd_cmask; 610 UNP_PCB_UNLOCK(unp); 611 612 buf = malloc(namelen + 1, M_TEMP, M_WAITOK); 613 bcopy(soun->sun_path, buf, namelen); 614 buf[namelen] = 0; 615 616 restart: 617 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE, 618 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT)); 619 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */ 620 error = namei(&nd); 621 if (error) 622 goto error; 623 vp = nd.ni_vp; 624 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) { 625 NDFREE_PNBUF(&nd); 626 if (nd.ni_dvp == vp) 627 vrele(nd.ni_dvp); 628 else 629 vput(nd.ni_dvp); 630 if (vp != NULL) { 631 vrele(vp); 632 error = EADDRINUSE; 633 goto error; 634 } 635 error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH); 636 if (error) 637 goto error; 638 goto restart; 639 } 640 VATTR_NULL(&vattr); 641 vattr.va_type = VSOCK; 642 vattr.va_mode = mode; 643 #ifdef MAC 644 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd, 645 &vattr); 646 #endif 647 if (error == 0) { 648 /* 649 * The prior lookup may have left LK_SHARED in cn_lkflags, 650 * and VOP_CREATE technically only requires the new vnode to 651 * be locked shared. Most filesystems will return the new vnode 652 * locked exclusive regardless, but we should explicitly 653 * specify that here since we require it and assert to that 654 * effect below. 655 */ 656 nd.ni_cnd.cn_lkflags = (nd.ni_cnd.cn_lkflags & ~LK_SHARED) | 657 LK_EXCLUSIVE; 658 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr); 659 } 660 NDFREE_PNBUF(&nd); 661 if (error) { 662 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true); 663 vn_finished_write(mp); 664 if (error == ERELOOKUP) 665 goto restart; 666 goto error; 667 } 668 vp = nd.ni_vp; 669 ASSERT_VOP_ELOCKED(vp, "uipc_bind"); 670 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK); 671 672 UNP_PCB_LOCK(unp); 673 VOP_UNP_BIND(vp, unp); 674 unp->unp_vnode = vp; 675 unp->unp_addr = soun; 676 unp->unp_flags &= ~UNP_BINDING; 677 UNP_PCB_UNLOCK(unp); 678 vref(vp); 679 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true); 680 vn_finished_write(mp); 681 free(buf, M_TEMP); 682 return (0); 683 684 error: 685 UNP_PCB_LOCK(unp); 686 unp->unp_flags &= ~UNP_BINDING; 687 UNP_PCB_UNLOCK(unp); 688 free(buf, M_TEMP); 689 return (error); 690 } 691 692 static int 693 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td) 694 { 695 696 return (uipc_bindat(AT_FDCWD, so, nam, td)); 697 } 698 699 static int 700 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td) 701 { 702 int error; 703 704 KASSERT(td == curthread, ("uipc_connect: td != curthread")); 705 error = unp_connect(so, nam, td); 706 return (error); 707 } 708 709 static int 710 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam, 711 struct thread *td) 712 { 713 int error; 714 715 KASSERT(td == curthread, ("uipc_connectat: td != curthread")); 716 error = unp_connectat(fd, so, nam, td, false); 717 return (error); 718 } 719 720 static void 721 uipc_close(struct socket *so) 722 { 723 struct unpcb *unp, *unp2; 724 struct vnode *vp = NULL; 725 struct mtx *vplock; 726 727 unp = sotounpcb(so); 728 KASSERT(unp != NULL, ("uipc_close: unp == NULL")); 729 730 vplock = NULL; 731 if ((vp = unp->unp_vnode) != NULL) { 732 vplock = mtx_pool_find(unp_vp_mtxpool, vp); 733 mtx_lock(vplock); 734 } 735 UNP_PCB_LOCK(unp); 736 if (vp && unp->unp_vnode == NULL) { 737 mtx_unlock(vplock); 738 vp = NULL; 739 } 740 if (vp != NULL) { 741 VOP_UNP_DETACH(vp); 742 unp->unp_vnode = NULL; 743 } 744 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) 745 unp_disconnect(unp, unp2); 746 else 747 UNP_PCB_UNLOCK(unp); 748 if (vp) { 749 mtx_unlock(vplock); 750 vrele(vp); 751 } 752 } 753 754 static int 755 uipc_chmod(struct socket *so, mode_t mode, struct ucred *cred __unused, 756 struct thread *td __unused) 757 { 758 struct unpcb *unp; 759 int error; 760 761 if ((mode & ~ACCESSPERMS) != 0) 762 return (EINVAL); 763 764 error = 0; 765 unp = sotounpcb(so); 766 UNP_PCB_LOCK(unp); 767 if (unp->unp_vnode != NULL || (unp->unp_flags & UNP_BINDING) != 0) 768 error = EINVAL; 769 else 770 unp->unp_mode = mode; 771 UNP_PCB_UNLOCK(unp); 772 return (error); 773 } 774 775 static int 776 uipc_connect2(struct socket *so1, struct socket *so2) 777 { 778 struct unpcb *unp, *unp2; 779 780 if (so1->so_type != so2->so_type) 781 return (EPROTOTYPE); 782 783 unp = so1->so_pcb; 784 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL")); 785 unp2 = so2->so_pcb; 786 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL")); 787 unp_pcb_lock_pair(unp, unp2); 788 unp_connect2(so1, so2, false); 789 unp_pcb_unlock_pair(unp, unp2); 790 791 return (0); 792 } 793 794 static void 795 maybe_schedule_gc(void) 796 { 797 if (atomic_load_int(&unp_rights) != 0) 798 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1); 799 } 800 801 static void 802 uipc_detach(struct socket *so) 803 { 804 struct unpcb *unp, *unp2; 805 struct mtx *vplock; 806 struct vnode *vp; 807 808 unp = sotounpcb(so); 809 KASSERT(unp != NULL, ("uipc_detach: unp == NULL")); 810 811 vp = NULL; 812 vplock = NULL; 813 814 if (!SOLISTENING(so)) 815 unp_dispose(so); 816 817 UNP_LINK_WLOCK(); 818 LIST_REMOVE(unp, unp_link); 819 if (unp->unp_gcflag & UNPGC_DEAD) 820 LIST_REMOVE(unp, unp_dead); 821 unp->unp_gencnt = ++unp_gencnt; 822 --unp_count; 823 UNP_LINK_WUNLOCK(); 824 825 UNP_PCB_UNLOCK_ASSERT(unp); 826 restart: 827 if ((vp = unp->unp_vnode) != NULL) { 828 vplock = mtx_pool_find(unp_vp_mtxpool, vp); 829 mtx_lock(vplock); 830 } 831 UNP_PCB_LOCK(unp); 832 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) { 833 if (vplock) 834 mtx_unlock(vplock); 835 UNP_PCB_UNLOCK(unp); 836 goto restart; 837 } 838 if ((vp = unp->unp_vnode) != NULL) { 839 VOP_UNP_DETACH(vp); 840 unp->unp_vnode = NULL; 841 } 842 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) 843 unp_disconnect(unp, unp2); 844 else 845 UNP_PCB_UNLOCK(unp); 846 847 UNP_REF_LIST_LOCK(); 848 while (!LIST_EMPTY(&unp->unp_refs)) { 849 struct unpcb *ref = LIST_FIRST(&unp->unp_refs); 850 851 unp_pcb_hold(ref); 852 UNP_REF_LIST_UNLOCK(); 853 854 MPASS(ref != unp); 855 UNP_PCB_UNLOCK_ASSERT(ref); 856 unp_drop(ref); 857 UNP_REF_LIST_LOCK(); 858 } 859 UNP_REF_LIST_UNLOCK(); 860 861 UNP_PCB_LOCK(unp); 862 unp->unp_socket->so_pcb = NULL; 863 unp->unp_socket = NULL; 864 free(unp->unp_addr, M_SONAME); 865 unp->unp_addr = NULL; 866 if (!unp_pcb_rele(unp)) 867 UNP_PCB_UNLOCK(unp); 868 if (vp) { 869 mtx_unlock(vplock); 870 vrele(vp); 871 } 872 maybe_schedule_gc(); 873 874 switch (so->so_type) { 875 case SOCK_STREAM: 876 case SOCK_SEQPACKET: 877 MPASS(SOLISTENING(so) || (STAILQ_EMPTY(&so->so_rcv.uxst_mbq) && 878 so->so_rcv.uxst_peer == NULL)); 879 break; 880 case SOCK_DGRAM: 881 /* 882 * Everything should have been unlinked/freed by unp_dispose() 883 * and/or unp_disconnect(). 884 */ 885 MPASS(so->so_rcv.uxdg_peeked == NULL); 886 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb)); 887 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns)); 888 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb)); 889 } 890 891 mtx_destroy(&so->so_snd_mtx); 892 mtx_destroy(&so->so_rcv_mtx); 893 } 894 895 static int 896 uipc_disconnect(struct socket *so) 897 { 898 struct unpcb *unp, *unp2; 899 900 unp = sotounpcb(so); 901 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL")); 902 903 UNP_PCB_LOCK(unp); 904 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) 905 unp_disconnect(unp, unp2); 906 else 907 UNP_PCB_UNLOCK(unp); 908 return (0); 909 } 910 911 static void 912 uipc_fdclose(struct socket *so __unused) 913 { 914 /* 915 * Ensure that userspace can't create orphaned file descriptors without 916 * triggering garbage collection. Triggering GC from uipc_detach() is 917 * not sufficient, since that's only closed once a socket reference 918 * count drops to zero. 919 */ 920 maybe_schedule_gc(); 921 } 922 923 static int 924 uipc_listen(struct socket *so, int backlog, struct thread *td) 925 { 926 struct unpcb *unp; 927 int error; 928 929 MPASS(so->so_type != SOCK_DGRAM); 930 931 /* 932 * Synchronize with concurrent connection attempts. 933 */ 934 error = 0; 935 unp = sotounpcb(so); 936 UNP_PCB_LOCK(unp); 937 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0) 938 error = EINVAL; 939 else if (unp->unp_vnode == NULL) 940 error = EDESTADDRREQ; 941 if (error != 0) { 942 UNP_PCB_UNLOCK(unp); 943 return (error); 944 } 945 946 SOCK_LOCK(so); 947 error = solisten_proto_check(so); 948 if (error == 0) { 949 cru2xt(td, &unp->unp_peercred); 950 if (!SOLISTENING(so)) { 951 (void)chgsbsize(so->so_cred->cr_uidinfo, 952 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY); 953 (void)chgsbsize(so->so_cred->cr_uidinfo, 954 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY); 955 } 956 solisten_proto(so, backlog); 957 } 958 SOCK_UNLOCK(so); 959 UNP_PCB_UNLOCK(unp); 960 return (error); 961 } 962 963 static int 964 uipc_peeraddr(struct socket *so, struct sockaddr *ret) 965 { 966 struct unpcb *unp, *unp2; 967 const struct sockaddr *sa; 968 969 unp = sotounpcb(so); 970 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL")); 971 972 UNP_PCB_LOCK(unp); 973 unp2 = unp_pcb_lock_peer(unp); 974 if (unp2 != NULL) { 975 if (unp2->unp_addr != NULL) 976 sa = (struct sockaddr *)unp2->unp_addr; 977 else 978 sa = &sun_noname; 979 bcopy(sa, ret, sa->sa_len); 980 unp_pcb_unlock_pair(unp, unp2); 981 } else { 982 UNP_PCB_UNLOCK(unp); 983 sa = &sun_noname; 984 bcopy(sa, ret, sa->sa_len); 985 } 986 return (0); 987 } 988 989 /* 990 * pr_sosend() called with mbuf instead of uio is a kernel thread. NFS, 991 * netgraph(4) and other subsystems can call into socket code. The 992 * function will condition the mbuf so that it can be safely put onto socket 993 * buffer and calculate its char count and mbuf count. 994 * 995 * Note: we don't support receiving control data from a kernel thread. Our 996 * pr_sosend methods have MPASS() to check that. This may change. 997 */ 998 static void 999 uipc_reset_kernel_mbuf(struct mbuf *m, struct mchain *mc) 1000 { 1001 1002 M_ASSERTPKTHDR(m); 1003 1004 m_clrprotoflags(m); 1005 m_tag_delete_chain(m, NULL); 1006 m->m_pkthdr.rcvif = NULL; 1007 m->m_pkthdr.flowid = 0; 1008 m->m_pkthdr.csum_flags = 0; 1009 m->m_pkthdr.fibnum = 0; 1010 m->m_pkthdr.rsstype = 0; 1011 1012 mc_init_m(mc, m); 1013 MPASS(m->m_pkthdr.len == mc->mc_len); 1014 } 1015 1016 #ifdef SOCKBUF_DEBUG 1017 static inline void 1018 uipc_stream_sbcheck(struct sockbuf *sb) 1019 { 1020 struct mbuf *d; 1021 u_int dacc, dccc, dctl, dmbcnt; 1022 bool notready = false; 1023 1024 dacc = dccc = dctl = dmbcnt = 0; 1025 STAILQ_FOREACH(d, &sb->uxst_mbq, m_stailq) { 1026 if (d == sb->uxst_fnrdy) { 1027 MPASS(d->m_flags & M_NOTREADY); 1028 notready = true; 1029 } 1030 if (d->m_type == MT_CONTROL) 1031 dctl += d->m_len; 1032 else if (d->m_type == MT_DATA) { 1033 dccc += d->m_len; 1034 if (!notready) 1035 dacc += d->m_len; 1036 } else 1037 MPASS(0); 1038 dmbcnt += MSIZE; 1039 if (d->m_flags & M_EXT) 1040 dmbcnt += d->m_ext.ext_size; 1041 if (d->m_stailq.stqe_next == NULL) 1042 MPASS(sb->uxst_mbq.stqh_last == &d->m_stailq.stqe_next); 1043 } 1044 MPASS(sb->uxst_fnrdy == NULL || notready); 1045 MPASS(dacc == sb->sb_acc); 1046 MPASS(dccc == sb->sb_ccc); 1047 MPASS(dctl == sb->sb_ctl); 1048 MPASS(dmbcnt == sb->sb_mbcnt); 1049 (void)STAILQ_EMPTY(&sb->uxst_mbq); 1050 } 1051 #define UIPC_STREAM_SBCHECK(sb) uipc_stream_sbcheck(sb) 1052 #else 1053 #define UIPC_STREAM_SBCHECK(sb) do {} while (0) 1054 #endif 1055 1056 /* 1057 * uipc_stream_sbspace() returns how much a writer can send, limited by char 1058 * count or mbuf memory use, whatever ends first. 1059 * 1060 * An obvious and legitimate reason for a socket having more data than allowed, 1061 * is lowering the limit with setsockopt(SO_RCVBUF) on already full buffer. 1062 * Also, sb_mbcnt may overcommit sb_mbmax in case if previous write observed 1063 * 'space < mbspace', but mchain allocated to hold 'space' bytes of data ended 1064 * up with 'mc_mlen > mbspace'. A typical scenario would be a full buffer with 1065 * writer trying to push in a large write, and a slow reader, that reads just 1066 * a few bytes at a time. In that case writer will keep creating new mbufs 1067 * with mc_split(). These mbufs will carry little chars, but will all point at 1068 * the same cluster, thus each adding cluster size to sb_mbcnt. This means we 1069 * will count same cluster many times potentially underutilizing socket buffer. 1070 * We aren't optimizing towards ineffective readers. Classic socket buffer had 1071 * the same "feature". 1072 */ 1073 static inline u_int 1074 uipc_stream_sbspace(struct sockbuf *sb) 1075 { 1076 u_int space, mbspace; 1077 1078 if (__predict_true(sb->sb_hiwat >= sb->sb_ccc + sb->sb_ctl)) 1079 space = sb->sb_hiwat - sb->sb_ccc - sb->sb_ctl; 1080 else 1081 return (0); 1082 if (__predict_true(sb->sb_mbmax >= sb->sb_mbcnt)) 1083 mbspace = sb->sb_mbmax - sb->sb_mbcnt; 1084 else 1085 return (0); 1086 1087 return (min(space, mbspace)); 1088 } 1089 1090 /* 1091 * UNIX version of generic sbwait() for writes. We wait on peer's receive 1092 * buffer, using our timeout. 1093 */ 1094 static int 1095 uipc_stream_sbwait(struct socket *so, sbintime_t timeo) 1096 { 1097 struct sockbuf *sb = &so->so_rcv; 1098 1099 SOCK_RECVBUF_LOCK_ASSERT(so); 1100 sb->sb_flags |= SB_WAIT; 1101 return (msleep_sbt(&sb->sb_acc, SOCK_RECVBUF_MTX(so), PSOCK | PCATCH, 1102 "sbwait", timeo, 0, 0)); 1103 } 1104 1105 static int 1106 uipc_sosend_stream_or_seqpacket(struct socket *so, struct sockaddr *addr, 1107 struct uio *uio0, struct mbuf *m, struct mbuf *c, int flags, 1108 struct thread *td) 1109 { 1110 struct unpcb *unp2; 1111 struct socket *so2; 1112 struct sockbuf *sb; 1113 struct uio *uio; 1114 struct mchain mc, cmc; 1115 size_t resid, sent; 1116 bool nonblock, eor, aio; 1117 int error, needsopts; 1118 1119 MPASS((uio0 != NULL && m == NULL) || (m != NULL && uio0 == NULL)); 1120 MPASS(m == NULL || c == NULL); 1121 1122 if (__predict_false(flags & MSG_OOB)) 1123 return (EOPNOTSUPP); 1124 1125 nonblock = (so->so_state & SS_NBIO) || 1126 (flags & (MSG_DONTWAIT | MSG_NBIO)); 1127 eor = flags & MSG_EOR; 1128 1129 mc = MCHAIN_INITIALIZER(&mc); 1130 cmc = MCHAIN_INITIALIZER(&cmc); 1131 sent = 0; 1132 aio = false; 1133 needsopts = 0; 1134 1135 if (m == NULL) { 1136 if (c != NULL && 1137 (error = unp_internalize(c, &cmc, td, &needsopts))) 1138 goto out; 1139 /* 1140 * This function may read more data from the uio than it would 1141 * then place on socket. That would leave uio inconsistent 1142 * upon return. Normally uio is allocated on the stack of the 1143 * syscall thread and we don't care about leaving it consistent. 1144 * However, aio(9) will allocate a uio as part of job and will 1145 * use it to track progress. We detect aio(9) checking the 1146 * SB_AIO_RUNNING flag. It is safe to check it without lock 1147 * cause it is set and cleared in the same taskqueue thread. 1148 * 1149 * This check can also produce a false positive: there is 1150 * aio(9) job and also there is a syscall we are serving now. 1151 * No sane software does that, it would leave to a mess in 1152 * the socket buffer, as aio(9) doesn't grab the I/O sx(9). 1153 * But syzkaller can create this mess. For such false positive 1154 * our goal is just don't panic or leak memory. 1155 */ 1156 if (__predict_false(so->so_snd.sb_flags & SB_AIO_RUNNING)) { 1157 uio = cloneuio(uio0); 1158 aio = true; 1159 } else { 1160 uio = uio0; 1161 resid = uio->uio_resid; 1162 } 1163 /* 1164 * Optimization for a case when our send fits into the receive 1165 * buffer - do the copyin before taking any locks, sized to our 1166 * send buffer. Later copyins will also take into account 1167 * space in the peer's receive buffer. 1168 */ 1169 error = mc_uiotomc(&mc, uio, so->so_snd.sb_hiwat, 0, M_WAITOK, 1170 eor ? M_EOR : 0); 1171 if (__predict_false(error)) 1172 goto out2; 1173 } else 1174 uipc_reset_kernel_mbuf(m, &mc); 1175 1176 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags)); 1177 if (error) 1178 goto out2; 1179 1180 if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0)) 1181 goto out3; 1182 1183 /* Check for SO_PASS* flags */ 1184 so2 = unp2->unp_socket; 1185 if ((atomic_load_int(&so2->so_options) & needsopts) != needsopts) { 1186 error = EPERM; 1187 UNP_PCB_UNLOCK(unp2); 1188 goto out3; 1189 } 1190 1191 if (unp2->unp_flags & UNP_WANTCRED_MASK) { 1192 /* 1193 * Credentials are passed only once on SOCK_STREAM and 1194 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or 1195 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS). 1196 */ 1197 unp_addsockcred(td, &cmc, unp2->unp_flags); 1198 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT; 1199 } 1200 1201 /* 1202 * Cycle through the data to send and available space in the peer's 1203 * receive buffer. Put a reference on the peer socket, so that it 1204 * doesn't get freed while we sbwait(). If peer goes away, we will 1205 * observe the SBS_CANTRCVMORE and our sorele() will finalize peer's 1206 * socket destruction. 1207 */ 1208 soref(so2); 1209 UNP_PCB_UNLOCK(unp2); 1210 sb = &so2->so_rcv; 1211 while (mc.mc_len + cmc.mc_len > 0) { 1212 struct mchain mcnext = MCHAIN_INITIALIZER(&mcnext); 1213 u_int space; 1214 1215 SOCK_RECVBUF_LOCK(so2); 1216 restart: 1217 UIPC_STREAM_SBCHECK(sb); 1218 if (__predict_false(cmc.mc_len > sb->sb_hiwat)) { 1219 SOCK_RECVBUF_UNLOCK(so2); 1220 error = EMSGSIZE; 1221 goto out4; 1222 } 1223 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE)) { 1224 SOCK_RECVBUF_UNLOCK(so2); 1225 error = EPIPE; 1226 goto out4; 1227 } 1228 /* 1229 * Wait on the peer socket receive buffer until we have enough 1230 * space to put at least control. The data is a stream and can 1231 * be put partially, but control is really a datagram. 1232 */ 1233 space = uipc_stream_sbspace(sb); 1234 if (space < sb->sb_lowat || space < cmc.mc_len) { 1235 if (nonblock) { 1236 if (aio) 1237 sb->uxst_flags |= UXST_PEER_AIO; 1238 SOCK_RECVBUF_UNLOCK(so2); 1239 if (aio) { 1240 SOCK_SENDBUF_LOCK(so); 1241 so->so_snd.sb_ccc = 1242 so->so_snd.sb_hiwat - space; 1243 SOCK_SENDBUF_UNLOCK(so); 1244 } 1245 error = EWOULDBLOCK; 1246 goto out4; 1247 } 1248 if ((error = uipc_stream_sbwait(so2, 1249 so->so_snd.sb_timeo)) != 0) { 1250 SOCK_RECVBUF_UNLOCK(so2); 1251 goto out4; 1252 } else 1253 goto restart; 1254 } 1255 MPASS(space >= cmc.mc_len); 1256 space -= cmc.mc_len; 1257 if (space == 0) { 1258 /* There is space only to send control. */ 1259 MPASS(!STAILQ_EMPTY(&cmc.mc_q)); 1260 mcnext = mc; 1261 mc = MCHAIN_INITIALIZER(&mc); 1262 } else if (space < mc.mc_len) { 1263 /* Not enough space. */ 1264 if (__predict_false(mc_split(&mc, &mcnext, space, 1265 M_NOWAIT) == ENOMEM)) { 1266 /* 1267 * If allocation failed use M_WAITOK and merge 1268 * the chain back. Next time mc_split() will 1269 * easily split at the same place. Only if we 1270 * race with setsockopt(SO_RCVBUF) shrinking 1271 * sb_hiwat can this happen more than once. 1272 */ 1273 SOCK_RECVBUF_UNLOCK(so2); 1274 (void)mc_split(&mc, &mcnext, space, M_WAITOK); 1275 mc_concat(&mc, &mcnext); 1276 SOCK_RECVBUF_LOCK(so2); 1277 goto restart; 1278 } 1279 MPASS(mc.mc_len == space); 1280 } 1281 if (!STAILQ_EMPTY(&cmc.mc_q)) { 1282 STAILQ_CONCAT(&sb->uxst_mbq, &cmc.mc_q); 1283 sb->sb_ctl += cmc.mc_len; 1284 sb->sb_mbcnt += cmc.mc_mlen; 1285 cmc.mc_len = 0; 1286 } 1287 sent += mc.mc_len; 1288 if (sb->uxst_fnrdy == NULL) 1289 sb->sb_acc += mc.mc_len; 1290 sb->sb_ccc += mc.mc_len; 1291 sb->sb_mbcnt += mc.mc_mlen; 1292 STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q); 1293 UIPC_STREAM_SBCHECK(sb); 1294 space = uipc_stream_sbspace(sb); 1295 sorwakeup_locked(so2); 1296 if (!STAILQ_EMPTY(&mcnext.mc_q)) { 1297 /* 1298 * Such assignment is unsafe in general, but it is 1299 * safe with !STAILQ_EMPTY(&mcnext.mc_q). In C++ we 1300 * could reload = for STAILQs :) 1301 */ 1302 mc = mcnext; 1303 } else if (uio != NULL && uio->uio_resid > 0) { 1304 /* 1305 * Copyin sum of peer's receive buffer space and our 1306 * sb_hiwat, which is our virtual send buffer size. 1307 * See comment above unpst_sendspace declaration. 1308 * We are reading sb_hiwat locklessly, cause a) we 1309 * don't care about an application that does send(2) 1310 * and setsockopt(2) racing internally, and for an 1311 * application that does this in sequence we will see 1312 * the correct value cause sbsetopt() uses buffer lock 1313 * and we also have already acquired it at least once. 1314 */ 1315 error = mc_uiotomc(&mc, uio, space + 1316 atomic_load_int(&so->so_snd.sb_hiwat), 0, M_WAITOK, 1317 eor ? M_EOR : 0); 1318 if (__predict_false(error)) 1319 goto out4; 1320 } else 1321 mc = MCHAIN_INITIALIZER(&mc); 1322 } 1323 1324 MPASS(STAILQ_EMPTY(&mc.mc_q)); 1325 1326 td->td_ru.ru_msgsnd++; 1327 out4: 1328 sorele(so2); 1329 out3: 1330 SOCK_IO_SEND_UNLOCK(so); 1331 out2: 1332 if (aio) { 1333 freeuio(uio); 1334 uioadvance(uio0, sent); 1335 } else if (uio != NULL) 1336 uio->uio_resid = resid - sent; 1337 if (!mc_empty(&cmc)) 1338 unp_scan(mc_first(&cmc), unp_freerights); 1339 out: 1340 mc_freem(&mc); 1341 mc_freem(&cmc); 1342 1343 return (error); 1344 } 1345 1346 /* 1347 * Wakeup a writer, used by recv(2) and shutdown(2). 1348 * 1349 * @param so Points to a connected stream socket with receive buffer locked 1350 * 1351 * In a blocking mode peer is sleeping on our receive buffer, and we need just 1352 * wakeup(9) on it. But to wake up various event engines, we need to reach 1353 * over to peer's selinfo. This can be safely done as the socket buffer 1354 * receive lock is protecting us from the peer going away. 1355 */ 1356 static void 1357 uipc_wakeup_writer(struct socket *so) 1358 { 1359 struct sockbuf *sb = &so->so_rcv; 1360 struct selinfo *sel; 1361 1362 SOCK_RECVBUF_LOCK_ASSERT(so); 1363 MPASS(sb->uxst_peer != NULL); 1364 1365 sel = &sb->uxst_peer->so_wrsel; 1366 1367 if (sb->uxst_flags & UXST_PEER_SEL) { 1368 selwakeuppri(sel, PSOCK); 1369 /* 1370 * XXXGL: sowakeup() does SEL_WAITING() without locks. 1371 */ 1372 if (!SEL_WAITING(sel)) 1373 sb->uxst_flags &= ~UXST_PEER_SEL; 1374 } 1375 if (sb->sb_flags & SB_WAIT) { 1376 sb->sb_flags &= ~SB_WAIT; 1377 wakeup(&sb->sb_acc); 1378 } 1379 KNOTE_LOCKED(&sel->si_note, 0); 1380 SOCK_RECVBUF_UNLOCK(so); 1381 } 1382 1383 static void 1384 uipc_cantrcvmore(struct socket *so) 1385 { 1386 1387 SOCK_RECVBUF_LOCK(so); 1388 so->so_rcv.sb_state |= SBS_CANTRCVMORE; 1389 selwakeuppri(&so->so_rdsel, PSOCK); 1390 KNOTE_LOCKED(&so->so_rdsel.si_note, 0); 1391 if (so->so_rcv.uxst_peer != NULL) 1392 uipc_wakeup_writer(so); 1393 else 1394 SOCK_RECVBUF_UNLOCK(so); 1395 } 1396 1397 static int 1398 uipc_soreceive_stream_or_seqpacket(struct socket *so, struct sockaddr **psa, 1399 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 1400 { 1401 struct sockbuf *sb = &so->so_rcv; 1402 struct mbuf *control, *m, *first, *part, *next; 1403 u_int ctl, space, datalen, mbcnt, partlen; 1404 int error, flags; 1405 bool nonblock, waitall, peek; 1406 1407 MPASS(mp0 == NULL); 1408 1409 if (psa != NULL) 1410 *psa = NULL; 1411 if (controlp != NULL) 1412 *controlp = NULL; 1413 1414 flags = flagsp != NULL ? *flagsp : 0; 1415 nonblock = (so->so_state & SS_NBIO) || 1416 (flags & (MSG_DONTWAIT | MSG_NBIO)); 1417 peek = flags & MSG_PEEK; 1418 waitall = (flags & MSG_WAITALL) && !peek; 1419 1420 /* 1421 * This check may fail only on a socket that never went through 1422 * connect(2). We can check this locklessly, cause: a) for a new born 1423 * socket we don't care about applications that may race internally 1424 * between connect(2) and recv(2), and b) for a dying socket if we 1425 * miss update by unp_sosidisconnected(), we would still get the check 1426 * correct. For dying socket we would observe SBS_CANTRCVMORE later. 1427 */ 1428 if (__predict_false((atomic_load_short(&so->so_state) & 1429 (SS_ISCONNECTED|SS_ISDISCONNECTED)) == 0)) 1430 return (ENOTCONN); 1431 1432 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags)); 1433 if (__predict_false(error)) 1434 return (error); 1435 1436 restart: 1437 SOCK_RECVBUF_LOCK(so); 1438 UIPC_STREAM_SBCHECK(sb); 1439 while (sb->sb_acc < sb->sb_lowat && 1440 (sb->sb_ctl == 0 || controlp == NULL)) { 1441 if (so->so_error) { 1442 error = so->so_error; 1443 if (!peek) 1444 so->so_error = 0; 1445 SOCK_RECVBUF_UNLOCK(so); 1446 SOCK_IO_RECV_UNLOCK(so); 1447 return (error); 1448 } 1449 if (sb->sb_state & SBS_CANTRCVMORE) { 1450 SOCK_RECVBUF_UNLOCK(so); 1451 SOCK_IO_RECV_UNLOCK(so); 1452 return (0); 1453 } 1454 if (nonblock) { 1455 SOCK_RECVBUF_UNLOCK(so); 1456 SOCK_IO_RECV_UNLOCK(so); 1457 return (EWOULDBLOCK); 1458 } 1459 error = sbwait(so, SO_RCV); 1460 if (error) { 1461 SOCK_RECVBUF_UNLOCK(so); 1462 SOCK_IO_RECV_UNLOCK(so); 1463 return (error); 1464 } 1465 } 1466 1467 MPASS(STAILQ_FIRST(&sb->uxst_mbq)); 1468 MPASS(sb->sb_acc > 0 || sb->sb_ctl > 0); 1469 1470 mbcnt = 0; 1471 ctl = 0; 1472 first = STAILQ_FIRST(&sb->uxst_mbq); 1473 if (first->m_type == MT_CONTROL) { 1474 control = first; 1475 STAILQ_FOREACH_FROM(first, &sb->uxst_mbq, m_stailq) { 1476 if (first->m_type != MT_CONTROL) 1477 break; 1478 ctl += first->m_len; 1479 mbcnt += MSIZE; 1480 if (first->m_flags & M_EXT) 1481 mbcnt += first->m_ext.ext_size; 1482 } 1483 } else 1484 control = NULL; 1485 1486 /* 1487 * Find split point for the next copyout. On exit from the loop, 1488 * 'next' points to the new head of the buffer STAILQ and 'datalen' 1489 * contains the amount of data we will copy out at the end. The 1490 * copyout is protected by the I/O lock only, as writers can only 1491 * append to the buffer. We need to record the socket buffer state 1492 * and do all length adjustments before dropping the socket buffer lock. 1493 */ 1494 for (space = uio->uio_resid, m = next = first, part = NULL, datalen = 0; 1495 space > 0 && m != sb->uxst_fnrdy && m->m_type == MT_DATA; 1496 m = STAILQ_NEXT(m, m_stailq)) { 1497 if (space >= m->m_len) { 1498 space -= m->m_len; 1499 datalen += m->m_len; 1500 mbcnt += MSIZE; 1501 if (m->m_flags & M_EXT) 1502 mbcnt += m->m_ext.ext_size; 1503 if (m->m_flags & M_EOR) { 1504 flags |= MSG_EOR; 1505 next = STAILQ_NEXT(m, m_stailq); 1506 break; 1507 } 1508 } else { 1509 datalen += space; 1510 partlen = space; 1511 if (!peek) { 1512 m->m_len -= partlen; 1513 m->m_data += partlen; 1514 } 1515 next = part = m; 1516 break; 1517 } 1518 next = STAILQ_NEXT(m, m_stailq); 1519 } 1520 1521 if (!peek) { 1522 if (next == NULL) 1523 STAILQ_INIT(&sb->uxst_mbq); 1524 else 1525 STAILQ_FIRST(&sb->uxst_mbq) = next; 1526 MPASS(sb->sb_acc >= datalen); 1527 sb->sb_acc -= datalen; 1528 sb->sb_ccc -= datalen; 1529 MPASS(sb->sb_ctl >= ctl); 1530 sb->sb_ctl -= ctl; 1531 MPASS(sb->sb_mbcnt >= mbcnt); 1532 sb->sb_mbcnt -= mbcnt; 1533 UIPC_STREAM_SBCHECK(sb); 1534 if (__predict_true(sb->uxst_peer != NULL)) { 1535 struct unpcb *unp2; 1536 bool aio; 1537 1538 if ((aio = sb->uxst_flags & UXST_PEER_AIO)) 1539 sb->uxst_flags &= ~UXST_PEER_AIO; 1540 1541 uipc_wakeup_writer(so); 1542 /* 1543 * XXXGL: need to go through uipc_lock_peer() after 1544 * the receive buffer lock dropped, it was protecting 1545 * us from unp_soisdisconnected(). The aio workarounds 1546 * should be refactored to the aio(4) side. 1547 */ 1548 if (aio && uipc_lock_peer(so, &unp2) == 0) { 1549 struct socket *so2 = unp2->unp_socket; 1550 1551 SOCK_SENDBUF_LOCK(so2); 1552 so2->so_snd.sb_ccc -= datalen; 1553 sowakeup_aio(so2, SO_SND); 1554 SOCK_SENDBUF_UNLOCK(so2); 1555 UNP_PCB_UNLOCK(unp2); 1556 } 1557 } else 1558 SOCK_RECVBUF_UNLOCK(so); 1559 } else 1560 SOCK_RECVBUF_UNLOCK(so); 1561 1562 while (control != NULL && control->m_type == MT_CONTROL) { 1563 if (!peek) { 1564 /* 1565 * unp_externalize() failure must abort entire read(2). 1566 * Such failure should also free the problematic 1567 * control, but link back the remaining data to the head 1568 * of the buffer, so that socket is not left in a state 1569 * where it can't progress forward with reading. 1570 * Probability of such a failure is really low, so it 1571 * is fine that we need to perform pretty complex 1572 * operation here to reconstruct the buffer. 1573 */ 1574 error = unp_externalize(so, control, controlp, flags); 1575 control = m_free(control); 1576 if (__predict_false(error && control != NULL)) { 1577 struct mchain cmc; 1578 1579 mc_init_m(&cmc, control); 1580 1581 SOCK_RECVBUF_LOCK(so); 1582 if (__predict_false( 1583 (sb->sb_state & SBS_CANTRCVMORE) || 1584 cmc.mc_len + sb->sb_ccc + sb->sb_ctl > 1585 sb->sb_hiwat)) { 1586 /* 1587 * While the lock was dropped and we 1588 * were failing in unp_externalize(), 1589 * the peer could has a) disconnected, 1590 * b) filled the buffer so that we 1591 * can't prepend data back. 1592 * These are two edge conditions that 1593 * we just can't handle, so lose the 1594 * data and return the error. 1595 */ 1596 SOCK_RECVBUF_UNLOCK(so); 1597 SOCK_IO_RECV_UNLOCK(so); 1598 unp_scan(mc_first(&cmc), 1599 unp_freerights); 1600 mc_freem(&cmc); 1601 return (error); 1602 } 1603 1604 UIPC_STREAM_SBCHECK(sb); 1605 /* XXXGL: STAILQ_PREPEND */ 1606 STAILQ_CONCAT(&cmc.mc_q, &sb->uxst_mbq); 1607 STAILQ_SWAP(&cmc.mc_q, &sb->uxst_mbq, mbuf); 1608 1609 sb->sb_ctl = sb->sb_acc = sb->sb_ccc = 1610 sb->sb_mbcnt = 0; 1611 STAILQ_FOREACH(m, &sb->uxst_mbq, m_stailq) { 1612 if (m->m_type == MT_DATA) { 1613 sb->sb_acc += m->m_len; 1614 sb->sb_ccc += m->m_len; 1615 } else { 1616 sb->sb_ctl += m->m_len; 1617 } 1618 sb->sb_mbcnt += MSIZE; 1619 if (m->m_flags & M_EXT) 1620 sb->sb_mbcnt += 1621 m->m_ext.ext_size; 1622 } 1623 UIPC_STREAM_SBCHECK(sb); 1624 SOCK_RECVBUF_UNLOCK(so); 1625 SOCK_IO_RECV_UNLOCK(so); 1626 return (error); 1627 } 1628 if (controlp != NULL) { 1629 while (*controlp != NULL) 1630 controlp = &(*controlp)->m_next; 1631 } 1632 } else { 1633 /* 1634 * XXXGL 1635 * 1636 * In MSG_PEEK case control is not externalized. This 1637 * means we are leaking some kernel pointers to the 1638 * userland. They are useless to a law-abiding 1639 * application, but may be useful to a malware. This 1640 * is what the historical implementation in the 1641 * soreceive_generic() did. To be improved? 1642 */ 1643 if (controlp != NULL) { 1644 *controlp = m_copym(control, 0, control->m_len, 1645 M_WAITOK); 1646 controlp = &(*controlp)->m_next; 1647 } 1648 control = STAILQ_NEXT(control, m_stailq); 1649 } 1650 } 1651 1652 for (m = first; datalen > 0; m = next) { 1653 void *data; 1654 u_int len; 1655 1656 next = STAILQ_NEXT(m, m_stailq); 1657 if (m == part) { 1658 data = peek ? 1659 mtod(m, char *) : mtod(m, char *) - partlen; 1660 len = partlen; 1661 } else { 1662 data = mtod(m, char *); 1663 len = m->m_len; 1664 } 1665 error = uiomove(data, len, uio); 1666 if (__predict_false(error)) { 1667 if (!peek) 1668 for (; m != part && datalen > 0; m = next) { 1669 next = STAILQ_NEXT(m, m_stailq); 1670 MPASS(datalen >= m->m_len); 1671 datalen -= m->m_len; 1672 m_free(m); 1673 } 1674 SOCK_IO_RECV_UNLOCK(so); 1675 return (error); 1676 } 1677 datalen -= len; 1678 if (!peek && m != part) 1679 m_free(m); 1680 } 1681 if (waitall && !(flags & MSG_EOR) && uio->uio_resid > 0) 1682 goto restart; 1683 SOCK_IO_RECV_UNLOCK(so); 1684 1685 if (flagsp != NULL) 1686 *flagsp |= flags; 1687 1688 uio->uio_td->td_ru.ru_msgrcv++; 1689 1690 return (0); 1691 } 1692 1693 static int 1694 uipc_sopoll_stream_or_seqpacket(struct socket *so, int events, 1695 struct thread *td) 1696 { 1697 struct unpcb *unp = sotounpcb(so); 1698 int revents; 1699 1700 UNP_PCB_LOCK(unp); 1701 if (SOLISTENING(so)) { 1702 /* The above check is safe, since conversion to listening uses 1703 * both protocol and socket lock. 1704 */ 1705 SOCK_LOCK(so); 1706 if (!(events & (POLLIN | POLLRDNORM))) 1707 revents = 0; 1708 else if (!TAILQ_EMPTY(&so->sol_comp)) 1709 revents = events & (POLLIN | POLLRDNORM); 1710 else if (so->so_error) 1711 revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP; 1712 else { 1713 selrecord(td, &so->so_rdsel); 1714 revents = 0; 1715 } 1716 SOCK_UNLOCK(so); 1717 } else { 1718 if (so->so_state & SS_ISDISCONNECTED) 1719 revents = POLLHUP; 1720 else 1721 revents = 0; 1722 if (events & (POLLIN | POLLRDNORM | POLLRDHUP)) { 1723 SOCK_RECVBUF_LOCK(so); 1724 if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat || 1725 so->so_error || so->so_rerror) 1726 revents |= events & (POLLIN | POLLRDNORM); 1727 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) 1728 revents |= events & 1729 (POLLIN | POLLRDNORM | POLLRDHUP); 1730 if (!(revents & (POLLIN | POLLRDNORM | POLLRDHUP))) { 1731 selrecord(td, &so->so_rdsel); 1732 so->so_rcv.sb_flags |= SB_SEL; 1733 } 1734 SOCK_RECVBUF_UNLOCK(so); 1735 } 1736 if (events & (POLLOUT | POLLWRNORM)) { 1737 struct socket *so2 = so->so_rcv.uxst_peer; 1738 1739 if (so2 != NULL) { 1740 struct sockbuf *sb = &so2->so_rcv; 1741 1742 SOCK_RECVBUF_LOCK(so2); 1743 if (uipc_stream_sbspace(sb) >= sb->sb_lowat) 1744 revents |= events & 1745 (POLLOUT | POLLWRNORM); 1746 if (sb->sb_state & SBS_CANTRCVMORE) 1747 revents |= POLLHUP; 1748 if (!(revents & (POLLOUT | POLLWRNORM))) { 1749 so2->so_rcv.uxst_flags |= UXST_PEER_SEL; 1750 selrecord(td, &so->so_wrsel); 1751 } 1752 SOCK_RECVBUF_UNLOCK(so2); 1753 } else 1754 selrecord(td, &so->so_wrsel); 1755 } 1756 } 1757 UNP_PCB_UNLOCK(unp); 1758 return (revents); 1759 } 1760 1761 static void 1762 uipc_wrknl_lock(void *arg) 1763 { 1764 struct socket *so = arg; 1765 struct unpcb *unp = sotounpcb(so); 1766 1767 retry: 1768 if (SOLISTENING(so)) { 1769 SOLISTEN_LOCK(so); 1770 } else { 1771 UNP_PCB_LOCK(unp); 1772 if (__predict_false(SOLISTENING(so))) { 1773 UNP_PCB_UNLOCK(unp); 1774 goto retry; 1775 } 1776 if (so->so_rcv.uxst_peer != NULL) 1777 SOCK_RECVBUF_LOCK(so->so_rcv.uxst_peer); 1778 } 1779 } 1780 1781 static void 1782 uipc_wrknl_unlock(void *arg) 1783 { 1784 struct socket *so = arg; 1785 struct unpcb *unp = sotounpcb(so); 1786 1787 if (SOLISTENING(so)) 1788 SOLISTEN_UNLOCK(so); 1789 else { 1790 if (so->so_rcv.uxst_peer != NULL) 1791 SOCK_RECVBUF_UNLOCK(so->so_rcv.uxst_peer); 1792 UNP_PCB_UNLOCK(unp); 1793 } 1794 } 1795 1796 static void 1797 uipc_wrknl_assert_lock(void *arg, int what) 1798 { 1799 struct socket *so = arg; 1800 1801 if (SOLISTENING(so)) { 1802 if (what == LA_LOCKED) 1803 SOLISTEN_LOCK_ASSERT(so); 1804 else 1805 SOLISTEN_UNLOCK_ASSERT(so); 1806 } else { 1807 /* 1808 * The pr_soreceive method will put a note without owning the 1809 * unp lock, so we can't assert it here. But we can safely 1810 * dereference uxst_peer pointer, since receive buffer lock 1811 * is assumed to be held here. 1812 */ 1813 if (what == LA_LOCKED && so->so_rcv.uxst_peer != NULL) 1814 SOCK_RECVBUF_LOCK_ASSERT(so->so_rcv.uxst_peer); 1815 } 1816 } 1817 1818 static void 1819 uipc_filt_sowdetach(struct knote *kn) 1820 { 1821 struct socket *so = kn->kn_fp->f_data; 1822 1823 uipc_wrknl_lock(so); 1824 knlist_remove(&so->so_wrsel.si_note, kn, 1); 1825 uipc_wrknl_unlock(so); 1826 } 1827 1828 static int 1829 uipc_filt_sowrite(struct knote *kn, long hint) 1830 { 1831 struct socket *so = kn->kn_fp->f_data, *so2; 1832 struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn; 1833 1834 if (SOLISTENING(so)) 1835 return (0); 1836 1837 if (unp2 == NULL) { 1838 if (so->so_state & SS_ISDISCONNECTED) { 1839 kn->kn_flags |= EV_EOF; 1840 kn->kn_fflags = so->so_error; 1841 return (1); 1842 } else 1843 return (0); 1844 } 1845 1846 so2 = unp2->unp_socket; 1847 SOCK_RECVBUF_LOCK_ASSERT(so2); 1848 kn->kn_data = uipc_stream_sbspace(&so2->so_rcv); 1849 1850 if (so2->so_rcv.sb_state & SBS_CANTRCVMORE) { 1851 kn->kn_flags |= EV_EOF; 1852 return (1); 1853 } else if (kn->kn_sfflags & NOTE_LOWAT) 1854 return (kn->kn_data >= kn->kn_sdata); 1855 else 1856 return (kn->kn_data >= so2->so_rcv.sb_lowat); 1857 } 1858 1859 static int 1860 uipc_filt_soempty(struct knote *kn, long hint) 1861 { 1862 struct socket *so = kn->kn_fp->f_data, *so2; 1863 struct unpcb *unp = sotounpcb(so), *unp2 = unp->unp_conn; 1864 1865 if (SOLISTENING(so) || unp2 == NULL) 1866 return (1); 1867 1868 so2 = unp2->unp_socket; 1869 SOCK_RECVBUF_LOCK_ASSERT(so2); 1870 kn->kn_data = uipc_stream_sbspace(&so2->so_rcv); 1871 1872 return (kn->kn_data == 0 ? 1 : 0); 1873 } 1874 1875 static const struct filterops uipc_write_filtops = { 1876 .f_isfd = 1, 1877 .f_detach = uipc_filt_sowdetach, 1878 .f_event = uipc_filt_sowrite, 1879 .f_copy = knote_triv_copy, 1880 }; 1881 static const struct filterops uipc_empty_filtops = { 1882 .f_isfd = 1, 1883 .f_detach = uipc_filt_sowdetach, 1884 .f_event = uipc_filt_soempty, 1885 .f_copy = knote_triv_copy, 1886 }; 1887 1888 static int 1889 uipc_kqfilter_stream_or_seqpacket(struct socket *so, struct knote *kn) 1890 { 1891 struct unpcb *unp = sotounpcb(so); 1892 struct knlist *knl; 1893 1894 switch (kn->kn_filter) { 1895 case EVFILT_READ: 1896 return (sokqfilter_generic(so, kn)); 1897 case EVFILT_WRITE: 1898 kn->kn_fop = &uipc_write_filtops; 1899 break; 1900 case EVFILT_EMPTY: 1901 kn->kn_fop = &uipc_empty_filtops; 1902 break; 1903 default: 1904 return (EINVAL); 1905 } 1906 1907 knl = &so->so_wrsel.si_note; 1908 UNP_PCB_LOCK(unp); 1909 if (SOLISTENING(so)) { 1910 SOLISTEN_LOCK(so); 1911 knlist_add(knl, kn, 1); 1912 SOLISTEN_UNLOCK(so); 1913 } else { 1914 struct socket *so2 = so->so_rcv.uxst_peer; 1915 1916 if (so2 != NULL) 1917 SOCK_RECVBUF_LOCK(so2); 1918 knlist_add(knl, kn, 1); 1919 if (so2 != NULL) 1920 SOCK_RECVBUF_UNLOCK(so2); 1921 } 1922 UNP_PCB_UNLOCK(unp); 1923 return (0); 1924 } 1925 1926 /* PF_UNIX/SOCK_DGRAM version of sbspace() */ 1927 static inline bool 1928 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt) 1929 { 1930 u_int bleft, mleft; 1931 1932 /* 1933 * Negative space may happen if send(2) is followed by 1934 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum. 1935 */ 1936 if (__predict_false(sb->sb_hiwat < sb->uxdg_cc || 1937 sb->sb_mbmax < sb->uxdg_mbcnt)) 1938 return (false); 1939 1940 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE)) 1941 return (false); 1942 1943 bleft = sb->sb_hiwat - sb->uxdg_cc; 1944 mleft = sb->sb_mbmax - sb->uxdg_mbcnt; 1945 1946 return (bleft >= cc && mleft >= mbcnt); 1947 } 1948 1949 /* 1950 * PF_UNIX/SOCK_DGRAM send 1951 * 1952 * Allocate a record consisting of 3 mbufs in the sequence of 1953 * from -> control -> data and append it to the socket buffer. 1954 * 1955 * The first mbuf carries sender's name and is a pkthdr that stores 1956 * overall length of datagram, its memory consumption and control length. 1957 */ 1958 #define ctllen PH_loc.thirtytwo[1] 1959 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <= 1960 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen"); 1961 static int 1962 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio, 1963 struct mbuf *m, struct mbuf *c, int flags, struct thread *td) 1964 { 1965 struct unpcb *unp, *unp2; 1966 const struct sockaddr *from; 1967 struct socket *so2; 1968 struct sockbuf *sb; 1969 struct mchain cmc = MCHAIN_INITIALIZER(&cmc); 1970 struct mbuf *f; 1971 u_int cc, ctl, mbcnt; 1972 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused; 1973 int error, needsopts; 1974 1975 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL)); 1976 1977 error = needsopts = 0; 1978 f = NULL; 1979 1980 if (__predict_false(flags & MSG_OOB)) { 1981 error = EOPNOTSUPP; 1982 goto out; 1983 } 1984 if (m == NULL) { 1985 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) { 1986 error = EMSGSIZE; 1987 goto out; 1988 } 1989 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR); 1990 if (__predict_false(m == NULL)) { 1991 error = EFAULT; 1992 goto out; 1993 } 1994 f = m_gethdr(M_WAITOK, MT_SONAME); 1995 cc = m->m_pkthdr.len; 1996 mbcnt = MSIZE + m->m_pkthdr.memlen; 1997 if (c != NULL && 1998 (error = unp_internalize(c, &cmc, td, &needsopts))) 1999 goto out; 2000 } else { 2001 struct mchain mc; 2002 2003 uipc_reset_kernel_mbuf(m, &mc); 2004 cc = mc.mc_len; 2005 mbcnt = mc.mc_mlen; 2006 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) { 2007 error = EMSGSIZE; 2008 goto out; 2009 } 2010 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) { 2011 error = ENOBUFS; 2012 goto out; 2013 } 2014 } 2015 2016 unp = sotounpcb(so); 2017 MPASS(unp); 2018 2019 /* 2020 * XXXGL: would be cool to fully remove so_snd out of the equation 2021 * and avoid this lock, which is not only extraneous, but also being 2022 * released, thus still leaving possibility for a race. We can easily 2023 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it 2024 * is more difficult to invent something to handle so_error. 2025 */ 2026 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags)); 2027 if (error) 2028 goto out2; 2029 SOCK_SENDBUF_LOCK(so); 2030 if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 2031 SOCK_SENDBUF_UNLOCK(so); 2032 error = EPIPE; 2033 goto out3; 2034 } 2035 if (so->so_error != 0) { 2036 error = so->so_error; 2037 so->so_error = 0; 2038 SOCK_SENDBUF_UNLOCK(so); 2039 goto out3; 2040 } 2041 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) { 2042 SOCK_SENDBUF_UNLOCK(so); 2043 error = EDESTADDRREQ; 2044 goto out3; 2045 } 2046 SOCK_SENDBUF_UNLOCK(so); 2047 2048 if (addr != NULL) { 2049 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true))) 2050 goto out3; 2051 UNP_PCB_LOCK_ASSERT(unp); 2052 unp2 = unp->unp_conn; 2053 UNP_PCB_LOCK_ASSERT(unp2); 2054 } else { 2055 UNP_PCB_LOCK(unp); 2056 unp2 = unp_pcb_lock_peer(unp); 2057 if (unp2 == NULL) { 2058 UNP_PCB_UNLOCK(unp); 2059 error = ENOTCONN; 2060 goto out3; 2061 } 2062 } 2063 2064 /* Check for SO_PASS* flags */ 2065 so2 = unp2->unp_socket; 2066 if ((atomic_load_int(&so2->so_options) & needsopts) != needsopts) { 2067 error = EPERM; 2068 goto out4; 2069 } 2070 2071 if (unp2->unp_flags & UNP_WANTCRED_MASK) 2072 unp_addsockcred(td, &cmc, unp2->unp_flags); 2073 if (unp->unp_addr != NULL) 2074 from = (struct sockaddr *)unp->unp_addr; 2075 else 2076 from = &sun_noname; 2077 f->m_len = from->sa_len; 2078 MPASS(from->sa_len <= MLEN); 2079 bcopy(from, mtod(f, void *), from->sa_len); 2080 2081 /* 2082 * Concatenate mbufs: from -> control -> data. 2083 * Save overall cc and mbcnt in "from" mbuf. 2084 */ 2085 if (!STAILQ_EMPTY(&cmc.mc_q)) { 2086 f->m_next = mc_first(&cmc); 2087 mc_last(&cmc)->m_next = m; 2088 /* XXXGL: This is dirty as well as rollback after ENOBUFS. */ 2089 STAILQ_INIT(&cmc.mc_q); 2090 } else 2091 f->m_next = m; 2092 m = NULL; 2093 ctl = f->m_len + cmc.mc_len; 2094 mbcnt += cmc.mc_mlen; 2095 #ifdef INVARIANTS 2096 dcc = dctl = dmbcnt = 0; 2097 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) { 2098 if (mb->m_type == MT_DATA) 2099 dcc += mb->m_len; 2100 else 2101 dctl += mb->m_len; 2102 dmbcnt += MSIZE; 2103 if (mb->m_flags & M_EXT) 2104 dmbcnt += mb->m_ext.ext_size; 2105 } 2106 MPASS(dcc == cc); 2107 MPASS(dctl == ctl); 2108 MPASS(dmbcnt == mbcnt); 2109 #endif 2110 f->m_pkthdr.len = cc + ctl; 2111 f->m_pkthdr.memlen = mbcnt; 2112 f->m_pkthdr.ctllen = ctl; 2113 2114 /* 2115 * Destination socket buffer selection. 2116 * 2117 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the 2118 * destination address is supplied, create a temporary connection for 2119 * the run time of the function (see call to unp_connectat() above and 2120 * to unp_disconnect() below). We distinguish them by condition of 2121 * (addr != NULL). We intentionally avoid adding 'bool connected' for 2122 * that condition, since, again, through the run time of this code we 2123 * are always connected. For such "unconnected" sends, the destination 2124 * buffer would be the receive buffer of destination socket so2. 2125 * 2126 * For connected sends, data lands on the send buffer of the sender's 2127 * socket "so". Then, if we just added the very first datagram 2128 * on this send buffer, we need to add the send buffer on to the 2129 * receiving socket's buffer list. We put ourselves on top of the 2130 * list. Such logic gives infrequent senders priority over frequent 2131 * senders. 2132 * 2133 * Note on byte count management. As long as event methods kevent(2), 2134 * select(2) are not protocol specific (yet), we need to maintain 2135 * meaningful values on the receive buffer. So, the receive buffer 2136 * would accumulate counters from all connected buffers potentially 2137 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax. 2138 */ 2139 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv; 2140 SOCK_RECVBUF_LOCK(so2); 2141 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) { 2142 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb)) 2143 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd, 2144 uxdg_clist); 2145 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt); 2146 sb->uxdg_cc += cc + ctl; 2147 sb->uxdg_ctl += ctl; 2148 sb->uxdg_mbcnt += mbcnt; 2149 so2->so_rcv.sb_acc += cc + ctl; 2150 so2->so_rcv.sb_ccc += cc + ctl; 2151 so2->so_rcv.sb_ctl += ctl; 2152 so2->so_rcv.sb_mbcnt += mbcnt; 2153 sorwakeup_locked(so2); 2154 f = NULL; 2155 } else { 2156 soroverflow_locked(so2); 2157 error = ENOBUFS; 2158 if (f->m_next->m_type == MT_CONTROL) { 2159 STAILQ_FIRST(&cmc.mc_q) = f->m_next; 2160 f->m_next = NULL; 2161 } 2162 } 2163 2164 out4: 2165 if (addr != NULL) 2166 unp_disconnect(unp, unp2); 2167 else 2168 unp_pcb_unlock_pair(unp, unp2); 2169 2170 td->td_ru.ru_msgsnd++; 2171 2172 out3: 2173 SOCK_IO_SEND_UNLOCK(so); 2174 out2: 2175 if (!mc_empty(&cmc)) 2176 unp_scan(mc_first(&cmc), unp_freerights); 2177 out: 2178 if (f) 2179 m_freem(f); 2180 mc_freem(&cmc); 2181 if (m) 2182 m_freem(m); 2183 2184 return (error); 2185 } 2186 2187 /* 2188 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK. 2189 * The mbuf has already been unlinked from the uxdg_mb of socket buffer 2190 * and needs to be linked onto uxdg_peeked of receive socket buffer. 2191 */ 2192 static int 2193 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa, 2194 struct uio *uio, struct mbuf **controlp, int *flagsp) 2195 { 2196 ssize_t len = 0; 2197 int error; 2198 2199 so->so_rcv.uxdg_peeked = m; 2200 so->so_rcv.uxdg_cc += m->m_pkthdr.len; 2201 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen; 2202 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen; 2203 SOCK_RECVBUF_UNLOCK(so); 2204 2205 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type)); 2206 if (psa != NULL) 2207 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK); 2208 2209 m = m->m_next; 2210 KASSERT(m, ("%s: no data or control after soname", __func__)); 2211 2212 /* 2213 * With MSG_PEEK the control isn't executed, just copied. 2214 */ 2215 while (m != NULL && m->m_type == MT_CONTROL) { 2216 if (controlp != NULL) { 2217 *controlp = m_copym(m, 0, m->m_len, M_WAITOK); 2218 controlp = &(*controlp)->m_next; 2219 } 2220 m = m->m_next; 2221 } 2222 KASSERT(m == NULL || m->m_type == MT_DATA, 2223 ("%s: not MT_DATA mbuf %p", __func__, m)); 2224 while (m != NULL && uio->uio_resid > 0) { 2225 len = uio->uio_resid; 2226 if (len > m->m_len) 2227 len = m->m_len; 2228 error = uiomove(mtod(m, char *), (int)len, uio); 2229 if (error) { 2230 SOCK_IO_RECV_UNLOCK(so); 2231 return (error); 2232 } 2233 if (len == m->m_len) 2234 m = m->m_next; 2235 } 2236 SOCK_IO_RECV_UNLOCK(so); 2237 2238 if (flagsp != NULL) { 2239 if (m != NULL) { 2240 if (*flagsp & MSG_TRUNC) { 2241 /* Report real length of the packet */ 2242 uio->uio_resid -= m_length(m, NULL) - len; 2243 } 2244 *flagsp |= MSG_TRUNC; 2245 } else 2246 *flagsp &= ~MSG_TRUNC; 2247 } 2248 2249 return (0); 2250 } 2251 2252 /* 2253 * PF_UNIX/SOCK_DGRAM receive 2254 */ 2255 static int 2256 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio, 2257 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 2258 { 2259 struct sockbuf *sb = NULL; 2260 struct mbuf *m; 2261 int flags, error; 2262 ssize_t len = 0; 2263 bool nonblock; 2264 2265 MPASS(mp0 == NULL); 2266 2267 if (psa != NULL) 2268 *psa = NULL; 2269 if (controlp != NULL) 2270 *controlp = NULL; 2271 2272 flags = flagsp != NULL ? *flagsp : 0; 2273 nonblock = (so->so_state & SS_NBIO) || 2274 (flags & (MSG_DONTWAIT | MSG_NBIO)); 2275 2276 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags)); 2277 if (__predict_false(error)) 2278 return (error); 2279 2280 /* 2281 * Loop blocking while waiting for a datagram. Prioritize connected 2282 * peers over unconnected sends. Set sb to selected socket buffer 2283 * containing an mbuf on exit from the wait loop. A datagram that 2284 * had already been peeked at has top priority. 2285 */ 2286 SOCK_RECVBUF_LOCK(so); 2287 while ((m = so->so_rcv.uxdg_peeked) == NULL && 2288 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL && 2289 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) { 2290 if (so->so_error) { 2291 error = so->so_error; 2292 if (!(flags & MSG_PEEK)) 2293 so->so_error = 0; 2294 SOCK_RECVBUF_UNLOCK(so); 2295 SOCK_IO_RECV_UNLOCK(so); 2296 return (error); 2297 } 2298 if (so->so_rcv.sb_state & SBS_CANTRCVMORE || 2299 uio->uio_resid == 0) { 2300 SOCK_RECVBUF_UNLOCK(so); 2301 SOCK_IO_RECV_UNLOCK(so); 2302 return (0); 2303 } 2304 if (nonblock) { 2305 SOCK_RECVBUF_UNLOCK(so); 2306 SOCK_IO_RECV_UNLOCK(so); 2307 return (EWOULDBLOCK); 2308 } 2309 error = sbwait(so, SO_RCV); 2310 if (error) { 2311 SOCK_RECVBUF_UNLOCK(so); 2312 SOCK_IO_RECV_UNLOCK(so); 2313 return (error); 2314 } 2315 } 2316 2317 if (sb == NULL) 2318 sb = &so->so_rcv; 2319 else if (m == NULL) 2320 m = STAILQ_FIRST(&sb->uxdg_mb); 2321 else 2322 MPASS(m == so->so_rcv.uxdg_peeked); 2323 2324 MPASS(sb->uxdg_cc > 0); 2325 M_ASSERTPKTHDR(m); 2326 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type)); 2327 2328 if (uio->uio_td) 2329 uio->uio_td->td_ru.ru_msgrcv++; 2330 2331 if (__predict_true(m != so->so_rcv.uxdg_peeked)) { 2332 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt); 2333 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv) 2334 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist); 2335 } else 2336 so->so_rcv.uxdg_peeked = NULL; 2337 2338 sb->uxdg_cc -= m->m_pkthdr.len; 2339 sb->uxdg_ctl -= m->m_pkthdr.ctllen; 2340 sb->uxdg_mbcnt -= m->m_pkthdr.memlen; 2341 2342 if (__predict_false(flags & MSG_PEEK)) 2343 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp)); 2344 2345 so->so_rcv.sb_acc -= m->m_pkthdr.len; 2346 so->so_rcv.sb_ccc -= m->m_pkthdr.len; 2347 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen; 2348 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen; 2349 SOCK_RECVBUF_UNLOCK(so); 2350 2351 if (psa != NULL) 2352 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK); 2353 m = m_free(m); 2354 KASSERT(m, ("%s: no data or control after soname", __func__)); 2355 2356 /* 2357 * Packet to copyout() is now in 'm' and it is disconnected from the 2358 * queue. 2359 * 2360 * Process one or more MT_CONTROL mbufs present before any data mbufs 2361 * in the first mbuf chain on the socket buffer. We call into the 2362 * unp_externalize() to perform externalization (or freeing if 2363 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs 2364 * without MT_DATA mbufs. 2365 */ 2366 while (m != NULL && m->m_type == MT_CONTROL) { 2367 error = unp_externalize(so, m, controlp, flags); 2368 m = m_free(m); 2369 if (error != 0) { 2370 SOCK_IO_RECV_UNLOCK(so); 2371 unp_scan(m, unp_freerights); 2372 m_freem(m); 2373 return (error); 2374 } 2375 if (controlp != NULL) { 2376 while (*controlp != NULL) 2377 controlp = &(*controlp)->m_next; 2378 } 2379 } 2380 KASSERT(m == NULL || m->m_type == MT_DATA, 2381 ("%s: not MT_DATA mbuf %p", __func__, m)); 2382 while (m != NULL && uio->uio_resid > 0) { 2383 len = uio->uio_resid; 2384 if (len > m->m_len) 2385 len = m->m_len; 2386 error = uiomove(mtod(m, char *), (int)len, uio); 2387 if (error) { 2388 SOCK_IO_RECV_UNLOCK(so); 2389 m_freem(m); 2390 return (error); 2391 } 2392 if (len == m->m_len) 2393 m = m_free(m); 2394 else { 2395 m->m_data += len; 2396 m->m_len -= len; 2397 } 2398 } 2399 SOCK_IO_RECV_UNLOCK(so); 2400 2401 if (m != NULL) { 2402 if (flagsp != NULL) { 2403 if (flags & MSG_TRUNC) { 2404 /* Report real length of the packet */ 2405 uio->uio_resid -= m_length(m, NULL); 2406 } 2407 *flagsp |= MSG_TRUNC; 2408 } 2409 m_freem(m); 2410 } else if (flagsp != NULL) 2411 *flagsp &= ~MSG_TRUNC; 2412 2413 return (0); 2414 } 2415 2416 static int 2417 uipc_sendfile_wait(struct socket *so, off_t need, int *space) 2418 { 2419 struct unpcb *unp2; 2420 struct socket *so2; 2421 struct sockbuf *sb; 2422 bool nonblock, sockref; 2423 int error; 2424 2425 MPASS(so->so_type == SOCK_STREAM); 2426 MPASS(need > 0); 2427 MPASS(space != NULL); 2428 2429 nonblock = so->so_state & SS_NBIO; 2430 sockref = false; 2431 2432 if (__predict_false((so->so_state & SS_ISCONNECTED) == 0)) 2433 return (ENOTCONN); 2434 2435 if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0)) 2436 return (error); 2437 2438 so2 = unp2->unp_socket; 2439 sb = &so2->so_rcv; 2440 SOCK_RECVBUF_LOCK(so2); 2441 UNP_PCB_UNLOCK(unp2); 2442 while ((*space = uipc_stream_sbspace(sb)) < need && 2443 (*space < so->so_snd.sb_hiwat / 2)) { 2444 UIPC_STREAM_SBCHECK(sb); 2445 if (nonblock) { 2446 SOCK_RECVBUF_UNLOCK(so2); 2447 return (EAGAIN); 2448 } 2449 if (!sockref) 2450 soref(so2); 2451 error = uipc_stream_sbwait(so2, so->so_snd.sb_timeo); 2452 if (error == 0 && 2453 __predict_false(sb->sb_state & SBS_CANTRCVMORE)) 2454 error = EPIPE; 2455 if (error) { 2456 SOCK_RECVBUF_UNLOCK(so2); 2457 sorele(so2); 2458 return (error); 2459 } 2460 } 2461 UIPC_STREAM_SBCHECK(sb); 2462 SOCK_RECVBUF_UNLOCK(so2); 2463 if (sockref) 2464 sorele(so2); 2465 2466 return (0); 2467 } 2468 2469 /* 2470 * Although this is a pr_send method, for unix(4) it is called only via 2471 * sendfile(2) path. This means we can be sure that mbufs are clear of 2472 * any extra flags and don't require any conditioning. 2473 */ 2474 static int 2475 uipc_sendfile(struct socket *so, int flags, struct mbuf *m, 2476 struct sockaddr *from, struct mbuf *control, struct thread *td) 2477 { 2478 struct mchain mc; 2479 struct unpcb *unp2; 2480 struct socket *so2; 2481 struct sockbuf *sb; 2482 bool notready, wakeup; 2483 int error; 2484 2485 MPASS(so->so_type == SOCK_STREAM); 2486 MPASS(from == NULL && control == NULL); 2487 KASSERT(!(m->m_flags & M_EXTPG), 2488 ("unix(4): TLS sendfile(2) not supported")); 2489 2490 notready = flags & PRUS_NOTREADY; 2491 2492 if (__predict_false((so->so_state & SS_ISCONNECTED) == 0)) { 2493 error = ENOTCONN; 2494 goto out; 2495 } 2496 2497 if (__predict_false((error = uipc_lock_peer(so, &unp2)) != 0)) 2498 goto out; 2499 2500 mc_init_m(&mc, m); 2501 2502 so2 = unp2->unp_socket; 2503 sb = &so2->so_rcv; 2504 SOCK_RECVBUF_LOCK(so2); 2505 UNP_PCB_UNLOCK(unp2); 2506 UIPC_STREAM_SBCHECK(sb); 2507 sb->sb_ccc += mc.mc_len; 2508 sb->sb_mbcnt += mc.mc_mlen; 2509 if (sb->uxst_fnrdy == NULL) { 2510 if (notready) { 2511 wakeup = false; 2512 STAILQ_FOREACH(m, &mc.mc_q, m_stailq) { 2513 if (m->m_flags & M_NOTREADY) { 2514 sb->uxst_fnrdy = m; 2515 break; 2516 } else { 2517 sb->sb_acc += m->m_len; 2518 wakeup = true; 2519 } 2520 } 2521 } else { 2522 wakeup = true; 2523 sb->sb_acc += mc.mc_len; 2524 } 2525 } else { 2526 wakeup = false; 2527 } 2528 STAILQ_CONCAT(&sb->uxst_mbq, &mc.mc_q); 2529 UIPC_STREAM_SBCHECK(sb); 2530 if (wakeup) 2531 sorwakeup_locked(so2); 2532 else 2533 SOCK_RECVBUF_UNLOCK(so2); 2534 2535 return (0); 2536 out: 2537 /* 2538 * In case of not ready data, uipc_ready() is responsible 2539 * for freeing memory. 2540 */ 2541 if (m != NULL && !notready) 2542 m_freem(m); 2543 2544 return (error); 2545 } 2546 2547 static int 2548 uipc_sbready(struct sockbuf *sb, struct mbuf *m, int count) 2549 { 2550 bool blocker; 2551 2552 /* assert locked */ 2553 2554 blocker = (sb->uxst_fnrdy == m); 2555 STAILQ_FOREACH_FROM(m, &sb->uxst_mbq, m_stailq) { 2556 if (count > 0) { 2557 MPASS(m->m_flags & M_NOTREADY); 2558 m->m_flags &= ~M_NOTREADY; 2559 if (blocker) 2560 sb->sb_acc += m->m_len; 2561 count--; 2562 } else if (m->m_flags & M_NOTREADY) 2563 break; 2564 else if (blocker) 2565 sb->sb_acc += m->m_len; 2566 } 2567 if (blocker) { 2568 sb->uxst_fnrdy = m; 2569 return (0); 2570 } else 2571 return (EINPROGRESS); 2572 } 2573 2574 static bool 2575 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp) 2576 { 2577 struct mbuf *mb; 2578 struct sockbuf *sb; 2579 2580 SOCK_LOCK(so); 2581 if (SOLISTENING(so)) { 2582 SOCK_UNLOCK(so); 2583 return (false); 2584 } 2585 mb = NULL; 2586 sb = &so->so_rcv; 2587 SOCK_RECVBUF_LOCK(so); 2588 if (sb->uxst_fnrdy != NULL) { 2589 STAILQ_FOREACH(mb, &sb->uxst_mbq, m_stailq) { 2590 if (mb == m) { 2591 *errorp = uipc_sbready(sb, m, count); 2592 break; 2593 } 2594 } 2595 } 2596 SOCK_RECVBUF_UNLOCK(so); 2597 SOCK_UNLOCK(so); 2598 return (mb != NULL); 2599 } 2600 2601 static int 2602 uipc_ready(struct socket *so, struct mbuf *m, int count) 2603 { 2604 struct unpcb *unp, *unp2; 2605 int error; 2606 2607 MPASS(so->so_type == SOCK_STREAM); 2608 2609 if (__predict_true(uipc_lock_peer(so, &unp2) == 0)) { 2610 struct socket *so2; 2611 struct sockbuf *sb; 2612 2613 so2 = unp2->unp_socket; 2614 sb = &so2->so_rcv; 2615 SOCK_RECVBUF_LOCK(so2); 2616 UNP_PCB_UNLOCK(unp2); 2617 UIPC_STREAM_SBCHECK(sb); 2618 error = uipc_sbready(sb, m, count); 2619 UIPC_STREAM_SBCHECK(sb); 2620 if (error == 0) 2621 sorwakeup_locked(so2); 2622 else 2623 SOCK_RECVBUF_UNLOCK(so2); 2624 } else { 2625 /* 2626 * The receiving socket has been disconnected, but may still 2627 * be valid. In this case, the not-ready mbufs are still 2628 * present in its socket buffer, so perform an exhaustive 2629 * search before giving up and freeing the mbufs. 2630 */ 2631 UNP_LINK_RLOCK(); 2632 LIST_FOREACH(unp, &unp_shead, unp_link) { 2633 if (uipc_ready_scan(unp->unp_socket, m, count, &error)) 2634 break; 2635 } 2636 UNP_LINK_RUNLOCK(); 2637 2638 if (unp == NULL) { 2639 for (int i = 0; i < count; i++) 2640 m = m_free(m); 2641 return (ECONNRESET); 2642 } 2643 } 2644 return (error); 2645 } 2646 2647 static int 2648 uipc_sense(struct socket *so, struct stat *sb) 2649 { 2650 struct unpcb *unp; 2651 2652 unp = sotounpcb(so); 2653 KASSERT(unp != NULL, ("uipc_sense: unp == NULL")); 2654 2655 sb->st_blksize = so->so_snd.sb_hiwat; 2656 sb->st_dev = NODEV; 2657 sb->st_ino = unp->unp_ino; 2658 return (0); 2659 } 2660 2661 static int 2662 uipc_shutdown(struct socket *so, enum shutdown_how how) 2663 { 2664 struct unpcb *unp = sotounpcb(so); 2665 int error; 2666 2667 SOCK_LOCK(so); 2668 if (SOLISTENING(so)) { 2669 if (how != SHUT_WR) { 2670 so->so_error = ECONNABORTED; 2671 solisten_wakeup(so); /* unlocks so */ 2672 } else 2673 SOCK_UNLOCK(so); 2674 return (ENOTCONN); 2675 } else if ((so->so_state & 2676 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) { 2677 /* 2678 * POSIX mandates us to just return ENOTCONN when shutdown(2) is 2679 * invoked on a datagram sockets, however historically we would 2680 * actually tear socket down. This is known to be leveraged by 2681 * some applications to unblock process waiting in recv(2) by 2682 * other process that it shares that socket with. Try to meet 2683 * both backward-compatibility and POSIX requirements by forcing 2684 * ENOTCONN but still flushing buffers and performing wakeup(9). 2685 * 2686 * XXXGL: it remains unknown what applications expect this 2687 * behavior and is this isolated to unix/dgram or inet/dgram or 2688 * both. See: D10351, D3039. 2689 */ 2690 error = ENOTCONN; 2691 if (so->so_type != SOCK_DGRAM) { 2692 SOCK_UNLOCK(so); 2693 return (error); 2694 } 2695 } else 2696 error = 0; 2697 SOCK_UNLOCK(so); 2698 2699 switch (how) { 2700 case SHUT_RD: 2701 if (so->so_type == SOCK_DGRAM) 2702 socantrcvmore(so); 2703 else 2704 uipc_cantrcvmore(so); 2705 unp_dispose(so); 2706 break; 2707 case SHUT_RDWR: 2708 if (so->so_type == SOCK_DGRAM) 2709 socantrcvmore(so); 2710 else 2711 uipc_cantrcvmore(so); 2712 unp_dispose(so); 2713 /* FALLTHROUGH */ 2714 case SHUT_WR: 2715 if (so->so_type == SOCK_DGRAM) { 2716 socantsendmore(so); 2717 } else { 2718 UNP_PCB_LOCK(unp); 2719 if (unp->unp_conn != NULL) 2720 uipc_cantrcvmore(unp->unp_conn->unp_socket); 2721 UNP_PCB_UNLOCK(unp); 2722 } 2723 } 2724 wakeup(&so->so_timeo); 2725 2726 return (error); 2727 } 2728 2729 static int 2730 uipc_sockaddr(struct socket *so, struct sockaddr *ret) 2731 { 2732 struct unpcb *unp; 2733 const struct sockaddr *sa; 2734 2735 unp = sotounpcb(so); 2736 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL")); 2737 2738 UNP_PCB_LOCK(unp); 2739 if (unp->unp_addr != NULL) 2740 sa = (struct sockaddr *) unp->unp_addr; 2741 else 2742 sa = &sun_noname; 2743 bcopy(sa, ret, sa->sa_len); 2744 UNP_PCB_UNLOCK(unp); 2745 return (0); 2746 } 2747 2748 static int 2749 uipc_ctloutput(struct socket *so, struct sockopt *sopt) 2750 { 2751 struct unpcb *unp; 2752 struct xucred xu; 2753 int error, optval; 2754 2755 if (sopt->sopt_level != SOL_LOCAL) 2756 return (EINVAL); 2757 2758 unp = sotounpcb(so); 2759 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL")); 2760 error = 0; 2761 switch (sopt->sopt_dir) { 2762 case SOPT_GET: 2763 switch (sopt->sopt_name) { 2764 case LOCAL_PEERCRED: 2765 UNP_PCB_LOCK(unp); 2766 if (unp->unp_flags & UNP_HAVEPC) 2767 xu = unp->unp_peercred; 2768 else { 2769 if (so->so_proto->pr_flags & PR_CONNREQUIRED) 2770 error = ENOTCONN; 2771 else 2772 error = EINVAL; 2773 } 2774 UNP_PCB_UNLOCK(unp); 2775 if (error != 0) 2776 break; 2777 #ifdef COMPAT_FREEBSD32 2778 if (sopt->sopt_td && 2779 SV_PROC_FLAG(sopt->sopt_td->td_proc, SV_ILP32)) 2780 { 2781 struct xucred32 xu32 = {}; 2782 int i; 2783 2784 xu32.cr_version = xu.cr_version; 2785 xu32.cr_uid = xu.cr_uid; 2786 xu32.cr_ngroups = xu.cr_ngroups; 2787 for (i = 0; i < XU_NGROUPS; i++) 2788 xu32.cr_groups[i] = xu.cr_groups[i]; 2789 xu32.cr_pid = xu.cr_pid; 2790 error = sooptcopyout(sopt, &xu32, sizeof(xu32)); 2791 break; 2792 } 2793 #endif 2794 error = sooptcopyout(sopt, &xu, sizeof(xu)); 2795 break; 2796 2797 case LOCAL_CREDS: 2798 /* Unlocked read. */ 2799 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0; 2800 error = sooptcopyout(sopt, &optval, sizeof(optval)); 2801 break; 2802 2803 case LOCAL_CREDS_PERSISTENT: 2804 /* Unlocked read. */ 2805 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0; 2806 error = sooptcopyout(sopt, &optval, sizeof(optval)); 2807 break; 2808 2809 default: 2810 error = EOPNOTSUPP; 2811 break; 2812 } 2813 break; 2814 2815 case SOPT_SET: 2816 switch (sopt->sopt_name) { 2817 case LOCAL_CREDS: 2818 case LOCAL_CREDS_PERSISTENT: 2819 error = sooptcopyin(sopt, &optval, sizeof(optval), 2820 sizeof(optval)); 2821 if (error) 2822 break; 2823 2824 #define OPTSET(bit, exclusive) do { \ 2825 UNP_PCB_LOCK(unp); \ 2826 if (optval) { \ 2827 if ((unp->unp_flags & (exclusive)) != 0) { \ 2828 UNP_PCB_UNLOCK(unp); \ 2829 error = EINVAL; \ 2830 break; \ 2831 } \ 2832 unp->unp_flags |= (bit); \ 2833 } else \ 2834 unp->unp_flags &= ~(bit); \ 2835 UNP_PCB_UNLOCK(unp); \ 2836 } while (0) 2837 2838 switch (sopt->sopt_name) { 2839 case LOCAL_CREDS: 2840 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS); 2841 break; 2842 2843 case LOCAL_CREDS_PERSISTENT: 2844 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT); 2845 break; 2846 2847 default: 2848 break; 2849 } 2850 break; 2851 #undef OPTSET 2852 default: 2853 error = ENOPROTOOPT; 2854 break; 2855 } 2856 break; 2857 2858 default: 2859 error = EOPNOTSUPP; 2860 break; 2861 } 2862 return (error); 2863 } 2864 2865 static int 2866 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td) 2867 { 2868 2869 return (unp_connectat(AT_FDCWD, so, nam, td, false)); 2870 } 2871 2872 static int 2873 unp_connectat(int fd, struct socket *so, struct sockaddr *nam, 2874 struct thread *td, bool return_locked) 2875 { 2876 struct mtx *vplock; 2877 struct sockaddr_un *soun; 2878 struct vnode *vp; 2879 struct socket *so2; 2880 struct unpcb *unp, *unp2, *unp3; 2881 struct nameidata nd; 2882 char buf[SOCK_MAXADDRLEN]; 2883 struct sockaddr *sa; 2884 cap_rights_t rights; 2885 int error, len; 2886 bool connreq; 2887 2888 CURVNET_ASSERT_SET(); 2889 2890 if (nam->sa_family != AF_UNIX) 2891 return (EAFNOSUPPORT); 2892 if (nam->sa_len > sizeof(struct sockaddr_un)) 2893 return (EINVAL); 2894 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path); 2895 if (len <= 0) 2896 return (EINVAL); 2897 soun = (struct sockaddr_un *)nam; 2898 bcopy(soun->sun_path, buf, len); 2899 buf[len] = 0; 2900 2901 error = 0; 2902 unp = sotounpcb(so); 2903 UNP_PCB_LOCK(unp); 2904 for (;;) { 2905 /* 2906 * Wait for connection state to stabilize. If a connection 2907 * already exists, give up. For datagram sockets, which permit 2908 * multiple consecutive connect(2) calls, upper layers are 2909 * responsible for disconnecting in advance of a subsequent 2910 * connect(2), but this is not synchronized with PCB connection 2911 * state. 2912 * 2913 * Also make sure that no threads are currently attempting to 2914 * lock the peer socket, to ensure that unp_conn cannot 2915 * transition between two valid sockets while locks are dropped. 2916 */ 2917 if (SOLISTENING(so)) 2918 error = EOPNOTSUPP; 2919 else if (unp->unp_conn != NULL) 2920 error = EISCONN; 2921 else if ((unp->unp_flags & UNP_CONNECTING) != 0) { 2922 error = EALREADY; 2923 } 2924 if (error != 0) { 2925 UNP_PCB_UNLOCK(unp); 2926 return (error); 2927 } 2928 if (unp->unp_pairbusy > 0) { 2929 unp->unp_flags |= UNP_WAITING; 2930 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0); 2931 continue; 2932 } 2933 break; 2934 } 2935 unp->unp_flags |= UNP_CONNECTING; 2936 UNP_PCB_UNLOCK(unp); 2937 2938 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0; 2939 if (connreq) 2940 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK); 2941 else 2942 sa = NULL; 2943 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF | 2944 (fd == AT_FDCWD ? 0 : EMPTYPATH), UIO_SYSSPACE, buf, fd, 2945 cap_rights_init_one(&rights, CAP_CONNECTAT)); 2946 error = namei(&nd); 2947 if (error) 2948 vp = NULL; 2949 else 2950 vp = nd.ni_vp; 2951 ASSERT_VOP_LOCKED(vp, "unp_connect"); 2952 if (error) 2953 goto bad; 2954 NDFREE_PNBUF(&nd); 2955 2956 if (vp->v_type != VSOCK) { 2957 error = ENOTSOCK; 2958 goto bad; 2959 } 2960 #ifdef MAC 2961 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD); 2962 if (error) 2963 goto bad; 2964 #endif 2965 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td); 2966 if (error) 2967 goto bad; 2968 2969 unp = sotounpcb(so); 2970 KASSERT(unp != NULL, ("unp_connect: unp == NULL")); 2971 2972 vplock = mtx_pool_find(unp_vp_mtxpool, vp); 2973 mtx_lock(vplock); 2974 VOP_UNP_CONNECT(vp, &unp2); 2975 if (unp2 == NULL) { 2976 error = ECONNREFUSED; 2977 goto bad2; 2978 } 2979 so2 = unp2->unp_socket; 2980 if (so->so_type != so2->so_type) { 2981 error = EPROTOTYPE; 2982 goto bad2; 2983 } 2984 if (connreq) { 2985 if (SOLISTENING(so2)) 2986 so2 = solisten_clone(so2); 2987 else 2988 so2 = NULL; 2989 if (so2 == NULL) { 2990 error = ECONNREFUSED; 2991 goto bad2; 2992 } 2993 if ((error = uipc_attach(so2, 0, NULL)) != 0) { 2994 sodealloc(so2); 2995 goto bad2; 2996 } 2997 unp3 = sotounpcb(so2); 2998 unp_pcb_lock_pair(unp2, unp3); 2999 if (unp2->unp_addr != NULL) { 3000 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len); 3001 unp3->unp_addr = (struct sockaddr_un *) sa; 3002 sa = NULL; 3003 } 3004 3005 unp_copy_peercred(td, unp3, unp, unp2); 3006 3007 UNP_PCB_UNLOCK(unp2); 3008 unp2 = unp3; 3009 3010 /* 3011 * It is safe to block on the PCB lock here since unp2 is 3012 * nascent and cannot be connected to any other sockets. 3013 */ 3014 UNP_PCB_LOCK(unp); 3015 #ifdef MAC 3016 mac_socketpeer_set_from_socket(so, so2); 3017 mac_socketpeer_set_from_socket(so2, so); 3018 #endif 3019 } else { 3020 unp_pcb_lock_pair(unp, unp2); 3021 } 3022 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 && 3023 sotounpcb(so2) == unp2, 3024 ("%s: unp2 %p so2 %p", __func__, unp2, so2)); 3025 unp_connect2(so, so2, connreq); 3026 if (connreq) 3027 (void)solisten_enqueue(so2, SS_ISCONNECTED); 3028 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0, 3029 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp)); 3030 unp->unp_flags &= ~UNP_CONNECTING; 3031 if (!return_locked) 3032 unp_pcb_unlock_pair(unp, unp2); 3033 bad2: 3034 mtx_unlock(vplock); 3035 bad: 3036 if (vp != NULL) { 3037 /* 3038 * If we are returning locked (called via uipc_sosend_dgram()), 3039 * we need to be sure that vput() won't sleep. This is 3040 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock. 3041 * SOCK_STREAM/SEQPACKET can't request return_locked (yet). 3042 */ 3043 MPASS(!(return_locked && connreq)); 3044 vput(vp); 3045 } 3046 free(sa, M_SONAME); 3047 if (__predict_false(error)) { 3048 UNP_PCB_LOCK(unp); 3049 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0, 3050 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp)); 3051 unp->unp_flags &= ~UNP_CONNECTING; 3052 UNP_PCB_UNLOCK(unp); 3053 } 3054 return (error); 3055 } 3056 3057 /* 3058 * Set socket peer credentials at connection time. 3059 * 3060 * The client's PCB credentials are copied from its process structure. The 3061 * server's PCB credentials are copied from the socket on which it called 3062 * listen(2). uipc_listen cached that process's credentials at the time. 3063 */ 3064 void 3065 unp_copy_peercred(struct thread *td, struct unpcb *client_unp, 3066 struct unpcb *server_unp, struct unpcb *listen_unp) 3067 { 3068 cru2xt(td, &client_unp->unp_peercred); 3069 client_unp->unp_flags |= UNP_HAVEPC; 3070 3071 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred, 3072 sizeof(server_unp->unp_peercred)); 3073 server_unp->unp_flags |= UNP_HAVEPC; 3074 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK); 3075 } 3076 3077 /* 3078 * unix/stream & unix/seqpacket version of soisconnected(). 3079 * 3080 * The crucial thing we are doing here is setting up the uxst_peer linkage, 3081 * holding unp and receive buffer locks of the both sockets. The disconnect 3082 * procedure does the same. This gives as a safe way to access the peer in the 3083 * send(2) and recv(2) during the socket lifetime. 3084 * 3085 * The less important thing is event notification of the fact that a socket is 3086 * now connected. It is unusual for a software to put a socket into event 3087 * mechanism before connect(2), but is supposed to be supported. Note that 3088 * there can not be any sleeping I/O on the socket, yet, only presence in the 3089 * select/poll/kevent. 3090 * 3091 * This function can be called via two call paths: 3092 * 1) socketpair(2) - in this case socket has not been yet reported to userland 3093 * and just can't have any event notifications mechanisms set up. The 3094 * 'wakeup' boolean is always false. 3095 * 2) connect(2) of existing socket to a recent clone of a listener: 3096 * 2.1) Socket that connect(2)s will have 'wakeup' true. An application 3097 * could have already put it into event mechanism, is it shall be 3098 * reported as readable and as writable. 3099 * 2.2) Socket that was just cloned with solisten_clone(). Same as 1). 3100 */ 3101 static void 3102 unp_soisconnected(struct socket *so, bool wakeup) 3103 { 3104 struct socket *so2 = sotounpcb(so)->unp_conn->unp_socket; 3105 struct sockbuf *sb; 3106 3107 SOCK_LOCK_ASSERT(so); 3108 UNP_PCB_LOCK_ASSERT(sotounpcb(so)); 3109 UNP_PCB_LOCK_ASSERT(sotounpcb(so2)); 3110 SOCK_RECVBUF_LOCK_ASSERT(so); 3111 SOCK_RECVBUF_LOCK_ASSERT(so2); 3112 3113 MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET); 3114 MPASS((so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING | 3115 SS_ISDISCONNECTING)) == 0); 3116 MPASS(so->so_qstate == SQ_NONE); 3117 3118 so->so_state &= ~SS_ISDISCONNECTED; 3119 so->so_state |= SS_ISCONNECTED; 3120 3121 sb = &so2->so_rcv; 3122 sb->uxst_peer = so; 3123 3124 if (wakeup) { 3125 KNOTE_LOCKED(&sb->sb_sel->si_note, 0); 3126 sb = &so->so_rcv; 3127 selwakeuppri(sb->sb_sel, PSOCK); 3128 SOCK_SENDBUF_LOCK_ASSERT(so); 3129 sb = &so->so_snd; 3130 selwakeuppri(sb->sb_sel, PSOCK); 3131 SOCK_SENDBUF_UNLOCK(so); 3132 } 3133 } 3134 3135 static void 3136 unp_connect2(struct socket *so, struct socket *so2, bool wakeup) 3137 { 3138 struct unpcb *unp; 3139 struct unpcb *unp2; 3140 3141 MPASS(so2->so_type == so->so_type); 3142 unp = sotounpcb(so); 3143 KASSERT(unp != NULL, ("unp_connect2: unp == NULL")); 3144 unp2 = sotounpcb(so2); 3145 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL")); 3146 3147 UNP_PCB_LOCK_ASSERT(unp); 3148 UNP_PCB_LOCK_ASSERT(unp2); 3149 KASSERT(unp->unp_conn == NULL, 3150 ("%s: socket %p is already connected", __func__, unp)); 3151 3152 unp->unp_conn = unp2; 3153 unp_pcb_hold(unp2); 3154 unp_pcb_hold(unp); 3155 switch (so->so_type) { 3156 case SOCK_DGRAM: 3157 UNP_REF_LIST_LOCK(); 3158 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink); 3159 UNP_REF_LIST_UNLOCK(); 3160 soisconnected(so); 3161 break; 3162 3163 case SOCK_STREAM: 3164 case SOCK_SEQPACKET: 3165 KASSERT(unp2->unp_conn == NULL, 3166 ("%s: socket %p is already connected", __func__, unp2)); 3167 unp2->unp_conn = unp; 3168 SOCK_LOCK(so); 3169 SOCK_LOCK(so2); 3170 if (wakeup) /* Avoid LOR with receive buffer lock. */ 3171 SOCK_SENDBUF_LOCK(so); 3172 SOCK_RECVBUF_LOCK(so); 3173 SOCK_RECVBUF_LOCK(so2); 3174 unp_soisconnected(so, wakeup); /* Will unlock send buffer. */ 3175 unp_soisconnected(so2, false); 3176 SOCK_RECVBUF_UNLOCK(so); 3177 SOCK_RECVBUF_UNLOCK(so2); 3178 SOCK_UNLOCK(so); 3179 SOCK_UNLOCK(so2); 3180 break; 3181 3182 default: 3183 panic("unp_connect2"); 3184 } 3185 } 3186 3187 static void 3188 unp_soisdisconnected(struct socket *so) 3189 { 3190 SOCK_LOCK_ASSERT(so); 3191 SOCK_RECVBUF_LOCK_ASSERT(so); 3192 MPASS(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET); 3193 MPASS(!SOLISTENING(so)); 3194 MPASS((so->so_state & (SS_ISCONNECTING | SS_ISDISCONNECTING | 3195 SS_ISDISCONNECTED)) == 0); 3196 MPASS(so->so_state & SS_ISCONNECTED); 3197 3198 so->so_state |= SS_ISDISCONNECTED; 3199 so->so_state &= ~SS_ISCONNECTED; 3200 so->so_rcv.uxst_peer = NULL; 3201 selwakeuppri(&so->so_wrsel, PSOCK); 3202 KNOTE_LOCKED(&so->so_snd.sb_sel->si_note, 0); 3203 socantrcvmore_locked(so); 3204 } 3205 3206 static void 3207 unp_disconnect(struct unpcb *unp, struct unpcb *unp2) 3208 { 3209 struct socket *so, *so2; 3210 struct mbuf *m = NULL; 3211 #ifdef INVARIANTS 3212 struct unpcb *unptmp; 3213 #endif 3214 3215 UNP_PCB_LOCK_ASSERT(unp); 3216 UNP_PCB_LOCK_ASSERT(unp2); 3217 KASSERT(unp->unp_conn == unp2, 3218 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2)); 3219 3220 unp->unp_conn = NULL; 3221 so = unp->unp_socket; 3222 so2 = unp2->unp_socket; 3223 switch (unp->unp_socket->so_type) { 3224 case SOCK_DGRAM: 3225 /* 3226 * Remove our send socket buffer from the peer's receive buffer. 3227 * Move the data to the receive buffer only if it is empty. 3228 * This is a protection against a scenario where a peer 3229 * connects, floods and disconnects, effectively blocking 3230 * sendto() from unconnected sockets. 3231 */ 3232 SOCK_RECVBUF_LOCK(so2); 3233 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) { 3234 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd, 3235 uxdg_clist); 3236 if (__predict_true((so2->so_rcv.sb_state & 3237 SBS_CANTRCVMORE) == 0) && 3238 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) { 3239 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb, 3240 &so->so_snd.uxdg_mb); 3241 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc; 3242 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl; 3243 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt; 3244 } else { 3245 m = STAILQ_FIRST(&so->so_snd.uxdg_mb); 3246 STAILQ_INIT(&so->so_snd.uxdg_mb); 3247 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc; 3248 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc; 3249 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl; 3250 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt; 3251 } 3252 /* Note: so may reconnect. */ 3253 so->so_snd.uxdg_cc = 0; 3254 so->so_snd.uxdg_ctl = 0; 3255 so->so_snd.uxdg_mbcnt = 0; 3256 } 3257 SOCK_RECVBUF_UNLOCK(so2); 3258 UNP_REF_LIST_LOCK(); 3259 #ifdef INVARIANTS 3260 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) { 3261 if (unptmp == unp) 3262 break; 3263 } 3264 KASSERT(unptmp != NULL, 3265 ("%s: %p not found in reflist of %p", __func__, unp, unp2)); 3266 #endif 3267 LIST_REMOVE(unp, unp_reflink); 3268 UNP_REF_LIST_UNLOCK(); 3269 SOCK_LOCK(so); 3270 so->so_state &= ~SS_ISCONNECTED; 3271 SOCK_UNLOCK(so); 3272 break; 3273 3274 case SOCK_STREAM: 3275 case SOCK_SEQPACKET: 3276 SOCK_LOCK(so); 3277 SOCK_LOCK(so2); 3278 SOCK_RECVBUF_LOCK(so); 3279 SOCK_RECVBUF_LOCK(so2); 3280 unp_soisdisconnected(so); 3281 MPASS(unp2->unp_conn == unp); 3282 unp2->unp_conn = NULL; 3283 unp_soisdisconnected(so2); 3284 SOCK_UNLOCK(so); 3285 SOCK_UNLOCK(so2); 3286 break; 3287 } 3288 3289 if (unp == unp2) { 3290 unp_pcb_rele_notlast(unp); 3291 if (!unp_pcb_rele(unp)) 3292 UNP_PCB_UNLOCK(unp); 3293 } else { 3294 if (!unp_pcb_rele(unp)) 3295 UNP_PCB_UNLOCK(unp); 3296 if (!unp_pcb_rele(unp2)) 3297 UNP_PCB_UNLOCK(unp2); 3298 } 3299 3300 if (m != NULL) { 3301 unp_scan(m, unp_freerights); 3302 m_freemp(m); 3303 } 3304 } 3305 3306 /* 3307 * unp_pcblist() walks the global list of struct unpcb's to generate a 3308 * pointer list, bumping the refcount on each unpcb. It then copies them out 3309 * sequentially, validating the generation number on each to see if it has 3310 * been detached. All of this is necessary because copyout() may sleep on 3311 * disk I/O. 3312 */ 3313 static int 3314 unp_pcblist(SYSCTL_HANDLER_ARGS) 3315 { 3316 struct unpcb *unp, **unp_list; 3317 unp_gen_t gencnt; 3318 struct xunpgen *xug; 3319 struct unp_head *head; 3320 struct xunpcb *xu; 3321 u_int i; 3322 int error, n; 3323 3324 switch ((intptr_t)arg1) { 3325 case SOCK_STREAM: 3326 head = &unp_shead; 3327 break; 3328 3329 case SOCK_DGRAM: 3330 head = &unp_dhead; 3331 break; 3332 3333 case SOCK_SEQPACKET: 3334 head = &unp_sphead; 3335 break; 3336 3337 default: 3338 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1); 3339 } 3340 3341 /* 3342 * The process of preparing the PCB list is too time-consuming and 3343 * resource-intensive to repeat twice on every request. 3344 */ 3345 if (req->oldptr == NULL) { 3346 n = unp_count; 3347 req->oldidx = 2 * (sizeof *xug) 3348 + (n + n/8) * sizeof(struct xunpcb); 3349 return (0); 3350 } 3351 3352 if (req->newptr != NULL) 3353 return (EPERM); 3354 3355 /* 3356 * OK, now we're committed to doing something. 3357 */ 3358 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO); 3359 UNP_LINK_RLOCK(); 3360 gencnt = unp_gencnt; 3361 n = unp_count; 3362 UNP_LINK_RUNLOCK(); 3363 3364 xug->xug_len = sizeof *xug; 3365 xug->xug_count = n; 3366 xug->xug_gen = gencnt; 3367 xug->xug_sogen = so_gencnt; 3368 error = SYSCTL_OUT(req, xug, sizeof *xug); 3369 if (error) { 3370 free(xug, M_TEMP); 3371 return (error); 3372 } 3373 3374 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK); 3375 3376 UNP_LINK_RLOCK(); 3377 for (unp = LIST_FIRST(head), i = 0; unp && i < n; 3378 unp = LIST_NEXT(unp, unp_link)) { 3379 UNP_PCB_LOCK(unp); 3380 if (unp->unp_gencnt <= gencnt) { 3381 if (cr_cansee(req->td->td_ucred, 3382 unp->unp_socket->so_cred)) { 3383 UNP_PCB_UNLOCK(unp); 3384 continue; 3385 } 3386 unp_list[i++] = unp; 3387 unp_pcb_hold(unp); 3388 } 3389 UNP_PCB_UNLOCK(unp); 3390 } 3391 UNP_LINK_RUNLOCK(); 3392 n = i; /* In case we lost some during malloc. */ 3393 3394 error = 0; 3395 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO); 3396 for (i = 0; i < n; i++) { 3397 unp = unp_list[i]; 3398 UNP_PCB_LOCK(unp); 3399 if (unp_pcb_rele(unp)) 3400 continue; 3401 3402 if (unp->unp_gencnt <= gencnt) { 3403 xu->xu_len = sizeof *xu; 3404 xu->xu_unpp = (uintptr_t)unp; 3405 /* 3406 * XXX - need more locking here to protect against 3407 * connect/disconnect races for SMP. 3408 */ 3409 if (unp->unp_addr != NULL) 3410 bcopy(unp->unp_addr, &xu->xu_addr, 3411 unp->unp_addr->sun_len); 3412 else 3413 bzero(&xu->xu_addr, sizeof(xu->xu_addr)); 3414 if (unp->unp_conn != NULL && 3415 unp->unp_conn->unp_addr != NULL) 3416 bcopy(unp->unp_conn->unp_addr, 3417 &xu->xu_caddr, 3418 unp->unp_conn->unp_addr->sun_len); 3419 else 3420 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr)); 3421 xu->unp_vnode = (uintptr_t)unp->unp_vnode; 3422 xu->unp_conn = (uintptr_t)unp->unp_conn; 3423 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs); 3424 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink); 3425 xu->unp_gencnt = unp->unp_gencnt; 3426 sotoxsocket(unp->unp_socket, &xu->xu_socket); 3427 UNP_PCB_UNLOCK(unp); 3428 error = SYSCTL_OUT(req, xu, sizeof *xu); 3429 } else { 3430 UNP_PCB_UNLOCK(unp); 3431 } 3432 } 3433 free(xu, M_TEMP); 3434 if (!error) { 3435 /* 3436 * Give the user an updated idea of our state. If the 3437 * generation differs from what we told her before, she knows 3438 * that something happened while we were processing this 3439 * request, and it might be necessary to retry. 3440 */ 3441 xug->xug_gen = unp_gencnt; 3442 xug->xug_sogen = so_gencnt; 3443 xug->xug_count = unp_count; 3444 error = SYSCTL_OUT(req, xug, sizeof *xug); 3445 } 3446 free(unp_list, M_TEMP); 3447 free(xug, M_TEMP); 3448 return (error); 3449 } 3450 3451 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, 3452 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 3453 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb", 3454 "List of active local datagram sockets"); 3455 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, 3456 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 3457 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb", 3458 "List of active local stream sockets"); 3459 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, 3460 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 3461 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb", 3462 "List of active local seqpacket sockets"); 3463 3464 static void 3465 unp_drop(struct unpcb *unp) 3466 { 3467 struct socket *so; 3468 struct unpcb *unp2; 3469 3470 /* 3471 * Regardless of whether the socket's peer dropped the connection 3472 * with this socket by aborting or disconnecting, POSIX requires 3473 * that ECONNRESET is returned on next connected send(2) in case of 3474 * a SOCK_DGRAM socket and EPIPE for SOCK_STREAM. 3475 */ 3476 UNP_PCB_LOCK(unp); 3477 if ((so = unp->unp_socket) != NULL) 3478 so->so_error = 3479 so->so_proto->pr_type == SOCK_DGRAM ? ECONNRESET : EPIPE; 3480 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) { 3481 /* Last reference dropped in unp_disconnect(). */ 3482 unp_pcb_rele_notlast(unp); 3483 unp_disconnect(unp, unp2); 3484 } else if (!unp_pcb_rele(unp)) { 3485 UNP_PCB_UNLOCK(unp); 3486 } 3487 } 3488 3489 static void 3490 unp_freerights(struct filedescent **fdep, int fdcount) 3491 { 3492 struct file *fp; 3493 int i; 3494 3495 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount)); 3496 3497 for (i = 0; i < fdcount; i++) { 3498 fp = fdep[i]->fde_file; 3499 filecaps_free(&fdep[i]->fde_caps); 3500 unp_discard(fp); 3501 } 3502 free(fdep[0], M_FILECAPS); 3503 } 3504 3505 static bool 3506 restrict_rights(struct file *fp, struct thread *td) 3507 { 3508 struct prison *prison1, *prison2; 3509 3510 prison1 = fp->f_cred->cr_prison; 3511 prison2 = td->td_ucred->cr_prison; 3512 return (prison1 != prison2 && prison1->pr_root != prison2->pr_root && 3513 prison2 != &prison0); 3514 } 3515 3516 static int 3517 unp_externalize(const struct socket *so, struct mbuf *control, 3518 struct mbuf **controlp, int flags) 3519 { 3520 struct thread *td = curthread; /* XXX */ 3521 struct cmsghdr *cm = mtod(control, struct cmsghdr *); 3522 int *fdp; 3523 struct filedesc *fdesc = td->td_proc->p_fd; 3524 struct filedescent **fdep; 3525 void *data; 3526 socklen_t clen = control->m_len, datalen; 3527 int error, fdflags, newfds; 3528 u_int newlen; 3529 3530 UNP_LINK_UNLOCK_ASSERT(); 3531 3532 fdflags = ((flags & MSG_CMSG_CLOEXEC) ? O_CLOEXEC : 0) | 3533 ((flags & MSG_CMSG_CLOFORK) ? O_CLOFORK : 0); 3534 3535 error = 0; 3536 if (controlp != NULL) /* controlp == NULL => free control messages */ 3537 *controlp = NULL; 3538 while (cm != NULL) { 3539 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len); 3540 3541 data = CMSG_DATA(cm); 3542 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data; 3543 if (cm->cmsg_level == SOL_SOCKET 3544 && cm->cmsg_type == SCM_RIGHTS) { 3545 newfds = datalen / sizeof(*fdep); 3546 if (newfds == 0) 3547 goto next; 3548 fdep = data; 3549 3550 /* 3551 * If we're not outputting the descriptors, free them. 3552 * 3553 * In the case of having revoked SCM_PASSRIGHTS, the 3554 * receiver must have toggled it before trying to 3555 * receive control messages- we'll take that as a signal 3556 * that they didn't want these, but they raced against 3557 * the sender trying to pass files anyways. 3558 */ 3559 if (error || controlp == NULL || 3560 (atomic_load_int(&so->so_options) & 3561 SO_PASSRIGHTS) == 0) { 3562 unp_freerights(fdep, newfds); 3563 goto next; 3564 } 3565 FILEDESC_XLOCK(fdesc); 3566 3567 /* 3568 * Now change each pointer to an fd in the global 3569 * table to an integer that is the index to the local 3570 * fd table entry that we set up to point to the 3571 * global one we are transferring. 3572 */ 3573 newlen = newfds * sizeof(int); 3574 *controlp = sbcreatecontrol(NULL, newlen, 3575 SCM_RIGHTS, SOL_SOCKET, M_WAITOK); 3576 3577 fdp = (int *) 3578 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 3579 if ((error = fdallocn(td, 0, fdp, newfds))) { 3580 FILEDESC_XUNLOCK(fdesc); 3581 unp_freerights(fdep, newfds); 3582 m_freem(*controlp); 3583 *controlp = NULL; 3584 goto next; 3585 } 3586 for (int i = 0; i < newfds; i++, fdp++) { 3587 struct file *fp; 3588 3589 fp = fdep[i]->fde_file; 3590 _finstall(fdesc, fp, *fdp, fdflags | 3591 (restrict_rights(fp, td) ? 3592 O_RESOLVE_BENEATH : 0), &fdep[i]->fde_caps); 3593 unp_externalize_fp(fp); 3594 } 3595 3596 /* 3597 * The new type indicates that the mbuf data refers to 3598 * kernel resources that may need to be released before 3599 * the mbuf is freed. 3600 */ 3601 m_chtype(*controlp, MT_EXTCONTROL); 3602 FILEDESC_XUNLOCK(fdesc); 3603 free(fdep[0], M_FILECAPS); 3604 } else { 3605 /* We can just copy anything else across. */ 3606 if (error || controlp == NULL) 3607 goto next; 3608 *controlp = sbcreatecontrol(NULL, datalen, 3609 cm->cmsg_type, cm->cmsg_level, M_WAITOK); 3610 bcopy(data, 3611 CMSG_DATA(mtod(*controlp, struct cmsghdr *)), 3612 datalen); 3613 } 3614 controlp = &(*controlp)->m_next; 3615 3616 next: 3617 if (CMSG_SPACE(datalen) < clen) { 3618 clen -= CMSG_SPACE(datalen); 3619 cm = (struct cmsghdr *) 3620 ((caddr_t)cm + CMSG_SPACE(datalen)); 3621 } else { 3622 clen = 0; 3623 cm = NULL; 3624 } 3625 } 3626 3627 return (error); 3628 } 3629 3630 static void 3631 unp_zone_change(void *tag) 3632 { 3633 3634 uma_zone_set_max(unp_zone, maxsockets); 3635 } 3636 3637 #ifdef INVARIANTS 3638 static void 3639 unp_zdtor(void *mem, int size __unused, void *arg __unused) 3640 { 3641 struct unpcb *unp; 3642 3643 unp = mem; 3644 3645 KASSERT(LIST_EMPTY(&unp->unp_refs), 3646 ("%s: unpcb %p has lingering refs", __func__, unp)); 3647 KASSERT(unp->unp_socket == NULL, 3648 ("%s: unpcb %p has socket backpointer", __func__, unp)); 3649 KASSERT(unp->unp_vnode == NULL, 3650 ("%s: unpcb %p has vnode references", __func__, unp)); 3651 KASSERT(unp->unp_conn == NULL, 3652 ("%s: unpcb %p is still connected", __func__, unp)); 3653 KASSERT(unp->unp_addr == NULL, 3654 ("%s: unpcb %p has leaked addr", __func__, unp)); 3655 } 3656 #endif 3657 3658 static void 3659 unp_init(void *arg __unused) 3660 { 3661 uma_dtor dtor; 3662 3663 #ifdef INVARIANTS 3664 dtor = unp_zdtor; 3665 #else 3666 dtor = NULL; 3667 #endif 3668 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor, 3669 NULL, NULL, UMA_ALIGN_CACHE, 0); 3670 uma_zone_set_max(unp_zone, maxsockets); 3671 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached"); 3672 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change, 3673 NULL, EVENTHANDLER_PRI_ANY); 3674 LIST_INIT(&unp_dhead); 3675 LIST_INIT(&unp_shead); 3676 LIST_INIT(&unp_sphead); 3677 SLIST_INIT(&unp_defers); 3678 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL); 3679 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL); 3680 UNP_LINK_LOCK_INIT(); 3681 UNP_DEFERRED_LOCK_INIT(); 3682 unp_vp_mtxpool = mtx_pool_create("unp vp mtxpool", 32, MTX_DEF); 3683 } 3684 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL); 3685 3686 static void 3687 unp_internalize_cleanup_rights(struct mbuf *control) 3688 { 3689 struct cmsghdr *cp; 3690 struct mbuf *m; 3691 void *data; 3692 socklen_t datalen; 3693 3694 for (m = control; m != NULL; m = m->m_next) { 3695 cp = mtod(m, struct cmsghdr *); 3696 if (cp->cmsg_level != SOL_SOCKET || 3697 cp->cmsg_type != SCM_RIGHTS) 3698 continue; 3699 data = CMSG_DATA(cp); 3700 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data; 3701 unp_freerights(data, datalen / sizeof(struct filedesc *)); 3702 } 3703 } 3704 3705 static int 3706 unp_internalize(struct mbuf *control, struct mchain *mc, struct thread *td, 3707 int *needsopts) 3708 { 3709 struct proc *p; 3710 struct filedesc *fdesc; 3711 struct bintime *bt; 3712 struct cmsghdr *cm; 3713 struct cmsgcred *cmcred; 3714 struct mbuf *m; 3715 struct filedescent *fde, **fdep, *fdev; 3716 struct file *fp; 3717 struct timeval *tv; 3718 struct timespec *ts; 3719 void *data; 3720 socklen_t clen, datalen; 3721 int i, j, error, *fdp, oldfds; 3722 u_int newlen; 3723 3724 MPASS(control->m_next == NULL); /* COMPAT_OLDSOCK may violate */ 3725 UNP_LINK_UNLOCK_ASSERT(); 3726 3727 p = td->td_proc; 3728 fdesc = p->p_fd; 3729 error = 0; 3730 *mc = MCHAIN_INITIALIZER(mc); 3731 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *), 3732 data = CMSG_DATA(cm); 3733 3734 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET && 3735 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) && 3736 (char *)cm + cm->cmsg_len >= (char *)data; 3737 3738 clen -= min(CMSG_SPACE(datalen), clen), 3739 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)), 3740 data = CMSG_DATA(cm)) { 3741 datalen = (char *)cm + cm->cmsg_len - (char *)data; 3742 switch (cm->cmsg_type) { 3743 case SCM_CREDS: 3744 m = sbcreatecontrol(NULL, sizeof(*cmcred), SCM_CREDS, 3745 SOL_SOCKET, M_WAITOK); 3746 cmcred = (struct cmsgcred *) 3747 CMSG_DATA(mtod(m, struct cmsghdr *)); 3748 cmcred->cmcred_pid = p->p_pid; 3749 cmcred->cmcred_uid = td->td_ucred->cr_ruid; 3750 cmcred->cmcred_gid = td->td_ucred->cr_rgid; 3751 cmcred->cmcred_euid = td->td_ucred->cr_uid; 3752 _Static_assert(CMGROUP_MAX >= 1, 3753 "Room needed for the effective GID."); 3754 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups + 1, 3755 CMGROUP_MAX); 3756 cmcred->cmcred_groups[0] = td->td_ucred->cr_gid; 3757 for (i = 1; i < cmcred->cmcred_ngroups; i++) 3758 cmcred->cmcred_groups[i] = 3759 td->td_ucred->cr_groups[i - 1]; 3760 break; 3761 3762 case SCM_RIGHTS: 3763 *needsopts |= SO_PASSRIGHTS; 3764 oldfds = datalen / sizeof (int); 3765 if (oldfds == 0) 3766 continue; 3767 /* On some machines sizeof pointer is bigger than 3768 * sizeof int, so we need to check if data fits into 3769 * single mbuf. We could allocate several mbufs, and 3770 * unp_externalize() should even properly handle that. 3771 * But it is not worth to complicate the code for an 3772 * insane scenario of passing over 200 file descriptors 3773 * at once. 3774 */ 3775 newlen = oldfds * sizeof(fdep[0]); 3776 if (CMSG_SPACE(newlen) > MCLBYTES) { 3777 error = EMSGSIZE; 3778 goto out; 3779 } 3780 /* 3781 * Check that all the FDs passed in refer to legal 3782 * files. If not, reject the entire operation. 3783 */ 3784 fdp = data; 3785 FILEDESC_SLOCK(fdesc); 3786 for (i = 0; i < oldfds; i++, fdp++) { 3787 fp = fget_noref(fdesc, *fdp); 3788 if (fp == NULL) { 3789 FILEDESC_SUNLOCK(fdesc); 3790 error = EBADF; 3791 goto out; 3792 } 3793 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) { 3794 FILEDESC_SUNLOCK(fdesc); 3795 error = EOPNOTSUPP; 3796 goto out; 3797 } 3798 } 3799 3800 /* 3801 * Now replace the integer FDs with pointers to the 3802 * file structure and capability rights. 3803 */ 3804 m = sbcreatecontrol(NULL, newlen, SCM_RIGHTS, 3805 SOL_SOCKET, M_WAITOK); 3806 fdp = data; 3807 for (i = 0; i < oldfds; i++, fdp++) { 3808 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) { 3809 fdp = data; 3810 for (j = 0; j < i; j++, fdp++) { 3811 fdrop(fdesc->fd_ofiles[*fdp]. 3812 fde_file, td); 3813 } 3814 FILEDESC_SUNLOCK(fdesc); 3815 error = EBADF; 3816 goto out; 3817 } 3818 } 3819 fdp = data; 3820 fdep = (struct filedescent **) 3821 CMSG_DATA(mtod(m, struct cmsghdr *)); 3822 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS, 3823 M_WAITOK); 3824 for (i = 0; i < oldfds; i++, fdev++, fdp++) { 3825 fde = &fdesc->fd_ofiles[*fdp]; 3826 fdep[i] = fdev; 3827 fdep[i]->fde_file = fde->fde_file; 3828 filecaps_copy(&fde->fde_caps, 3829 &fdep[i]->fde_caps, true); 3830 unp_internalize_fp(fdep[i]->fde_file); 3831 } 3832 FILEDESC_SUNLOCK(fdesc); 3833 break; 3834 3835 case SCM_TIMESTAMP: 3836 m = sbcreatecontrol(NULL, sizeof(*tv), SCM_TIMESTAMP, 3837 SOL_SOCKET, M_WAITOK); 3838 tv = (struct timeval *) 3839 CMSG_DATA(mtod(m, struct cmsghdr *)); 3840 microtime(tv); 3841 break; 3842 3843 case SCM_BINTIME: 3844 m = sbcreatecontrol(NULL, sizeof(*bt), SCM_BINTIME, 3845 SOL_SOCKET, M_WAITOK); 3846 bt = (struct bintime *) 3847 CMSG_DATA(mtod(m, struct cmsghdr *)); 3848 bintime(bt); 3849 break; 3850 3851 case SCM_REALTIME: 3852 m = sbcreatecontrol(NULL, sizeof(*ts), SCM_REALTIME, 3853 SOL_SOCKET, M_WAITOK); 3854 ts = (struct timespec *) 3855 CMSG_DATA(mtod(m, struct cmsghdr *)); 3856 nanotime(ts); 3857 break; 3858 3859 case SCM_MONOTONIC: 3860 m = sbcreatecontrol(NULL, sizeof(*ts), SCM_MONOTONIC, 3861 SOL_SOCKET, M_WAITOK); 3862 ts = (struct timespec *) 3863 CMSG_DATA(mtod(m, struct cmsghdr *)); 3864 nanouptime(ts); 3865 break; 3866 3867 default: 3868 error = EINVAL; 3869 goto out; 3870 } 3871 3872 mc_append(mc, m); 3873 } 3874 if (clen > 0) 3875 error = EINVAL; 3876 3877 out: 3878 if (error != 0) 3879 unp_internalize_cleanup_rights(mc_first(mc)); 3880 m_freem(control); 3881 return (error); 3882 } 3883 3884 static void 3885 unp_addsockcred(struct thread *td, struct mchain *mc, int mode) 3886 { 3887 struct mbuf *m, *n, *n_prev; 3888 const struct cmsghdr *cm; 3889 int ngroups, i, cmsgtype; 3890 size_t ctrlsz; 3891 3892 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX); 3893 if (mode & UNP_WANTCRED_ALWAYS) { 3894 ctrlsz = SOCKCRED2SIZE(ngroups); 3895 cmsgtype = SCM_CREDS2; 3896 } else { 3897 ctrlsz = SOCKCREDSIZE(ngroups); 3898 cmsgtype = SCM_CREDS; 3899 } 3900 3901 /* XXXGL: uipc_sosend_*() need to be improved so that we can M_WAITOK */ 3902 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT); 3903 if (m == NULL) 3904 return; 3905 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL); 3906 3907 if (mode & UNP_WANTCRED_ALWAYS) { 3908 struct sockcred2 *sc; 3909 3910 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *)); 3911 sc->sc_version = 0; 3912 sc->sc_pid = td->td_proc->p_pid; 3913 sc->sc_uid = td->td_ucred->cr_ruid; 3914 sc->sc_euid = td->td_ucred->cr_uid; 3915 sc->sc_gid = td->td_ucred->cr_rgid; 3916 sc->sc_egid = td->td_ucred->cr_gid; 3917 sc->sc_ngroups = ngroups; 3918 for (i = 0; i < sc->sc_ngroups; i++) 3919 sc->sc_groups[i] = td->td_ucred->cr_groups[i]; 3920 } else { 3921 struct sockcred *sc; 3922 3923 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *)); 3924 sc->sc_uid = td->td_ucred->cr_ruid; 3925 sc->sc_euid = td->td_ucred->cr_uid; 3926 sc->sc_gid = td->td_ucred->cr_rgid; 3927 sc->sc_egid = td->td_ucred->cr_gid; 3928 sc->sc_ngroups = ngroups; 3929 for (i = 0; i < sc->sc_ngroups; i++) 3930 sc->sc_groups[i] = td->td_ucred->cr_groups[i]; 3931 } 3932 3933 /* 3934 * Unlink SCM_CREDS control messages (struct cmsgcred), since just 3935 * created SCM_CREDS control message (struct sockcred) has another 3936 * format. 3937 */ 3938 if (!STAILQ_EMPTY(&mc->mc_q) && cmsgtype == SCM_CREDS) 3939 STAILQ_FOREACH_SAFE(n, &mc->mc_q, m_stailq, n_prev) { 3940 cm = mtod(n, struct cmsghdr *); 3941 if (cm->cmsg_level == SOL_SOCKET && 3942 cm->cmsg_type == SCM_CREDS) { 3943 mc_remove(mc, n); 3944 m_free(n); 3945 } 3946 } 3947 3948 /* Prepend it to the head. */ 3949 mc_prepend(mc, m); 3950 } 3951 3952 static struct unpcb * 3953 fptounp(struct file *fp) 3954 { 3955 struct socket *so; 3956 3957 if (fp->f_type != DTYPE_SOCKET) 3958 return (NULL); 3959 if ((so = fp->f_data) == NULL) 3960 return (NULL); 3961 if (so->so_proto->pr_domain != &localdomain) 3962 return (NULL); 3963 return sotounpcb(so); 3964 } 3965 3966 static void 3967 unp_discard(struct file *fp) 3968 { 3969 struct unp_defer *dr; 3970 3971 if (unp_externalize_fp(fp)) { 3972 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK); 3973 dr->ud_fp = fp; 3974 UNP_DEFERRED_LOCK(); 3975 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link); 3976 UNP_DEFERRED_UNLOCK(); 3977 atomic_add_int(&unp_defers_count, 1); 3978 taskqueue_enqueue(taskqueue_thread, &unp_defer_task); 3979 } else 3980 closef_nothread(fp); 3981 } 3982 3983 static void 3984 unp_process_defers(void *arg __unused, int pending) 3985 { 3986 struct unp_defer *dr; 3987 SLIST_HEAD(, unp_defer) drl; 3988 int count; 3989 3990 SLIST_INIT(&drl); 3991 for (;;) { 3992 UNP_DEFERRED_LOCK(); 3993 if (SLIST_FIRST(&unp_defers) == NULL) { 3994 UNP_DEFERRED_UNLOCK(); 3995 break; 3996 } 3997 SLIST_SWAP(&unp_defers, &drl, unp_defer); 3998 UNP_DEFERRED_UNLOCK(); 3999 count = 0; 4000 while ((dr = SLIST_FIRST(&drl)) != NULL) { 4001 SLIST_REMOVE_HEAD(&drl, ud_link); 4002 closef_nothread(dr->ud_fp); 4003 free(dr, M_TEMP); 4004 count++; 4005 } 4006 atomic_add_int(&unp_defers_count, -count); 4007 } 4008 } 4009 4010 static void 4011 unp_internalize_fp(struct file *fp) 4012 { 4013 struct unpcb *unp; 4014 4015 UNP_LINK_WLOCK(); 4016 if ((unp = fptounp(fp)) != NULL) { 4017 unp->unp_file = fp; 4018 unp->unp_msgcount++; 4019 } 4020 unp_rights++; 4021 UNP_LINK_WUNLOCK(); 4022 } 4023 4024 static int 4025 unp_externalize_fp(struct file *fp) 4026 { 4027 struct unpcb *unp; 4028 int ret; 4029 4030 UNP_LINK_WLOCK(); 4031 if ((unp = fptounp(fp)) != NULL) { 4032 unp->unp_msgcount--; 4033 ret = 1; 4034 } else 4035 ret = 0; 4036 unp_rights--; 4037 UNP_LINK_WUNLOCK(); 4038 return (ret); 4039 } 4040 4041 /* 4042 * unp_defer indicates whether additional work has been defered for a future 4043 * pass through unp_gc(). It is thread local and does not require explicit 4044 * synchronization. 4045 */ 4046 static int unp_marked; 4047 4048 static void 4049 unp_remove_dead_ref(struct filedescent **fdep, int fdcount) 4050 { 4051 struct unpcb *unp; 4052 struct file *fp; 4053 int i; 4054 4055 /* 4056 * This function can only be called from the gc task. 4057 */ 4058 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0, 4059 ("%s: not on gc callout", __func__)); 4060 UNP_LINK_LOCK_ASSERT(); 4061 4062 for (i = 0; i < fdcount; i++) { 4063 fp = fdep[i]->fde_file; 4064 if ((unp = fptounp(fp)) == NULL) 4065 continue; 4066 if ((unp->unp_gcflag & UNPGC_DEAD) == 0) 4067 continue; 4068 unp->unp_gcrefs--; 4069 } 4070 } 4071 4072 static void 4073 unp_restore_undead_ref(struct filedescent **fdep, int fdcount) 4074 { 4075 struct unpcb *unp; 4076 struct file *fp; 4077 int i; 4078 4079 /* 4080 * This function can only be called from the gc task. 4081 */ 4082 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0, 4083 ("%s: not on gc callout", __func__)); 4084 UNP_LINK_LOCK_ASSERT(); 4085 4086 for (i = 0; i < fdcount; i++) { 4087 fp = fdep[i]->fde_file; 4088 if ((unp = fptounp(fp)) == NULL) 4089 continue; 4090 if ((unp->unp_gcflag & UNPGC_DEAD) == 0) 4091 continue; 4092 unp->unp_gcrefs++; 4093 unp_marked++; 4094 } 4095 } 4096 4097 static void 4098 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int)) 4099 { 4100 struct sockbuf *sb; 4101 4102 SOCK_LOCK_ASSERT(so); 4103 4104 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS) 4105 return; 4106 4107 SOCK_RECVBUF_LOCK(so); 4108 switch (so->so_type) { 4109 case SOCK_DGRAM: 4110 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op); 4111 unp_scan(so->so_rcv.uxdg_peeked, op); 4112 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist) 4113 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op); 4114 break; 4115 case SOCK_STREAM: 4116 case SOCK_SEQPACKET: 4117 unp_scan(STAILQ_FIRST(&so->so_rcv.uxst_mbq), op); 4118 break; 4119 } 4120 SOCK_RECVBUF_UNLOCK(so); 4121 } 4122 4123 static void 4124 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int)) 4125 { 4126 struct socket *so, *soa; 4127 4128 so = unp->unp_socket; 4129 SOCK_LOCK(so); 4130 if (SOLISTENING(so)) { 4131 /* 4132 * Mark all sockets in our accept queue. 4133 */ 4134 TAILQ_FOREACH(soa, &so->sol_comp, so_list) 4135 unp_scan_socket(soa, op); 4136 } else { 4137 /* 4138 * Mark all sockets we reference with RIGHTS. 4139 */ 4140 unp_scan_socket(so, op); 4141 } 4142 SOCK_UNLOCK(so); 4143 } 4144 4145 static int unp_recycled; 4146 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 4147 "Number of unreachable sockets claimed by the garbage collector."); 4148 4149 static int unp_taskcount; 4150 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 4151 "Number of times the garbage collector has run."); 4152 4153 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0, 4154 "Number of active local sockets."); 4155 4156 static void 4157 unp_gc(__unused void *arg, int pending) 4158 { 4159 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead, 4160 NULL }; 4161 struct unp_head **head; 4162 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */ 4163 struct file *f, **unref; 4164 struct unpcb *unp, *unptmp; 4165 int i, total, unp_unreachable; 4166 4167 LIST_INIT(&unp_deadhead); 4168 unp_taskcount++; 4169 UNP_LINK_RLOCK(); 4170 /* 4171 * First determine which sockets may be in cycles. 4172 */ 4173 unp_unreachable = 0; 4174 4175 for (head = heads; *head != NULL; head++) 4176 LIST_FOREACH(unp, *head, unp_link) { 4177 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0, 4178 ("%s: unp %p has unexpected gc flags 0x%x", 4179 __func__, unp, (unsigned int)unp->unp_gcflag)); 4180 4181 f = unp->unp_file; 4182 4183 /* 4184 * Check for an unreachable socket potentially in a 4185 * cycle. It must be in a queue as indicated by 4186 * msgcount, and this must equal the file reference 4187 * count. Note that when msgcount is 0 the file is 4188 * NULL. 4189 */ 4190 if (f != NULL && unp->unp_msgcount != 0 && 4191 refcount_load(&f->f_count) == unp->unp_msgcount) { 4192 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead); 4193 unp->unp_gcflag |= UNPGC_DEAD; 4194 unp->unp_gcrefs = unp->unp_msgcount; 4195 unp_unreachable++; 4196 } 4197 } 4198 4199 /* 4200 * Scan all sockets previously marked as potentially being in a cycle 4201 * and remove the references each socket holds on any UNPGC_DEAD 4202 * sockets in its queue. After this step, all remaining references on 4203 * sockets marked UNPGC_DEAD should not be part of any cycle. 4204 */ 4205 LIST_FOREACH(unp, &unp_deadhead, unp_dead) 4206 unp_gc_scan(unp, unp_remove_dead_ref); 4207 4208 /* 4209 * If a socket still has a non-negative refcount, it cannot be in a 4210 * cycle. In this case increment refcount of all children iteratively. 4211 * Stop the scan once we do a complete loop without discovering 4212 * a new reachable socket. 4213 */ 4214 do { 4215 unp_marked = 0; 4216 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp) 4217 if (unp->unp_gcrefs > 0) { 4218 unp->unp_gcflag &= ~UNPGC_DEAD; 4219 LIST_REMOVE(unp, unp_dead); 4220 KASSERT(unp_unreachable > 0, 4221 ("%s: unp_unreachable underflow.", 4222 __func__)); 4223 unp_unreachable--; 4224 unp_gc_scan(unp, unp_restore_undead_ref); 4225 } 4226 } while (unp_marked); 4227 4228 UNP_LINK_RUNLOCK(); 4229 4230 if (unp_unreachable == 0) 4231 return; 4232 4233 /* 4234 * Allocate space for a local array of dead unpcbs. 4235 * TODO: can this path be simplified by instead using the local 4236 * dead list at unp_deadhead, after taking out references 4237 * on the file object and/or unpcb and dropping the link lock? 4238 */ 4239 unref = malloc(unp_unreachable * sizeof(struct file *), 4240 M_TEMP, M_WAITOK); 4241 4242 /* 4243 * Iterate looking for sockets which have been specifically marked 4244 * as unreachable and store them locally. 4245 */ 4246 UNP_LINK_RLOCK(); 4247 total = 0; 4248 LIST_FOREACH(unp, &unp_deadhead, unp_dead) { 4249 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0, 4250 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp)); 4251 unp->unp_gcflag &= ~UNPGC_DEAD; 4252 f = unp->unp_file; 4253 if (unp->unp_msgcount == 0 || f == NULL || 4254 refcount_load(&f->f_count) != unp->unp_msgcount || 4255 !fhold(f)) 4256 continue; 4257 unref[total++] = f; 4258 KASSERT(total <= unp_unreachable, 4259 ("%s: incorrect unreachable count.", __func__)); 4260 } 4261 UNP_LINK_RUNLOCK(); 4262 4263 /* 4264 * Now flush all sockets, free'ing rights. This will free the 4265 * struct files associated with these sockets but leave each socket 4266 * with one remaining ref. 4267 */ 4268 for (i = 0; i < total; i++) { 4269 struct socket *so; 4270 4271 so = unref[i]->f_data; 4272 if (!SOLISTENING(so)) { 4273 CURVNET_SET(so->so_vnet); 4274 socantrcvmore(so); 4275 unp_dispose(so); 4276 CURVNET_RESTORE(); 4277 } 4278 } 4279 4280 /* 4281 * And finally release the sockets so they can be reclaimed. 4282 */ 4283 for (i = 0; i < total; i++) 4284 fdrop(unref[i], NULL); 4285 unp_recycled += total; 4286 free(unref, M_TEMP); 4287 } 4288 4289 /* 4290 * Synchronize against unp_gc, which can trip over data as we are freeing it. 4291 */ 4292 static void 4293 unp_dispose(struct socket *so) 4294 { 4295 struct sockbuf *sb; 4296 struct unpcb *unp; 4297 struct mbuf *m; 4298 int error __diagused; 4299 4300 MPASS(!SOLISTENING(so)); 4301 4302 unp = sotounpcb(so); 4303 UNP_LINK_WLOCK(); 4304 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS; 4305 UNP_LINK_WUNLOCK(); 4306 4307 /* 4308 * Grab our special mbufs before calling sbrelease(). 4309 */ 4310 error = SOCK_IO_RECV_LOCK(so, SBL_WAIT | SBL_NOINTR); 4311 MPASS(!error); 4312 SOCK_RECVBUF_LOCK(so); 4313 switch (so->so_type) { 4314 case SOCK_DGRAM: 4315 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) { 4316 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb); 4317 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist); 4318 /* Note: socket of sb may reconnect. */ 4319 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0; 4320 } 4321 sb = &so->so_rcv; 4322 if (sb->uxdg_peeked != NULL) { 4323 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked, 4324 m_stailqpkt); 4325 sb->uxdg_peeked = NULL; 4326 } 4327 m = STAILQ_FIRST(&sb->uxdg_mb); 4328 STAILQ_INIT(&sb->uxdg_mb); 4329 break; 4330 case SOCK_STREAM: 4331 case SOCK_SEQPACKET: 4332 sb = &so->so_rcv; 4333 m = STAILQ_FIRST(&sb->uxst_mbq); 4334 STAILQ_INIT(&sb->uxst_mbq); 4335 sb->sb_acc = sb->sb_ccc = sb->sb_ctl = sb->sb_mbcnt = 0; 4336 /* 4337 * Trim M_NOTREADY buffers from the free list. They are 4338 * referenced by the I/O thread. 4339 */ 4340 if (sb->uxst_fnrdy != NULL) { 4341 struct mbuf *n, *prev; 4342 4343 while (m != NULL && m->m_flags & M_NOTREADY) 4344 m = m->m_next; 4345 for (prev = n = m; n != NULL; n = n->m_next) { 4346 if (n->m_flags & M_NOTREADY) 4347 prev->m_next = n->m_next; 4348 else 4349 prev = n; 4350 } 4351 sb->uxst_fnrdy = NULL; 4352 } 4353 break; 4354 } 4355 /* 4356 * Mark sb with SBS_CANTRCVMORE. This is needed to prevent 4357 * uipc_sosend_*() or unp_disconnect() adding more data to the socket. 4358 * We came here either through shutdown(2) or from the final sofree(). 4359 * The sofree() case is simple as it guarantees that no more sends will 4360 * happen, however we can race with unp_disconnect() from our peer. 4361 * The shutdown(2) case is more exotic. It would call into 4362 * unp_dispose() only if socket is SS_ISCONNECTED. This is possible if 4363 * we did connect(2) on this socket and we also had it bound with 4364 * bind(2) and receive connections from other sockets. Because 4365 * uipc_shutdown() violates POSIX (see comment there) this applies to 4366 * SOCK_DGRAM as well. For SOCK_DGRAM this SBS_CANTRCVMORE will have 4367 * affect not only on the peer we connect(2)ed to, but also on all of 4368 * the peers who had connect(2)ed to us. Their sends would end up 4369 * with ENOBUFS. 4370 */ 4371 sb->sb_state |= SBS_CANTRCVMORE; 4372 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0, 4373 RLIM_INFINITY); 4374 SOCK_RECVBUF_UNLOCK(so); 4375 SOCK_IO_RECV_UNLOCK(so); 4376 4377 if (m != NULL) { 4378 unp_scan(m, unp_freerights); 4379 m_freemp(m); 4380 } 4381 } 4382 4383 static void 4384 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int)) 4385 { 4386 struct mbuf *m; 4387 struct cmsghdr *cm; 4388 void *data; 4389 socklen_t clen, datalen; 4390 4391 while (m0 != NULL) { 4392 for (m = m0; m; m = m->m_next) { 4393 if (m->m_type != MT_CONTROL) 4394 continue; 4395 4396 cm = mtod(m, struct cmsghdr *); 4397 clen = m->m_len; 4398 4399 while (cm != NULL) { 4400 if (sizeof(*cm) > clen || cm->cmsg_len > clen) 4401 break; 4402 4403 data = CMSG_DATA(cm); 4404 datalen = (caddr_t)cm + cm->cmsg_len 4405 - (caddr_t)data; 4406 4407 if (cm->cmsg_level == SOL_SOCKET && 4408 cm->cmsg_type == SCM_RIGHTS) { 4409 (*op)(data, datalen / 4410 sizeof(struct filedescent *)); 4411 } 4412 4413 if (CMSG_SPACE(datalen) < clen) { 4414 clen -= CMSG_SPACE(datalen); 4415 cm = (struct cmsghdr *) 4416 ((caddr_t)cm + CMSG_SPACE(datalen)); 4417 } else { 4418 clen = 0; 4419 cm = NULL; 4420 } 4421 } 4422 } 4423 m0 = m0->m_nextpkt; 4424 } 4425 } 4426 4427 /* 4428 * Definitions of protocols supported in the LOCAL domain. 4429 */ 4430 static struct protosw streamproto = { 4431 .pr_type = SOCK_STREAM, 4432 .pr_flags = PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF, 4433 .pr_ctloutput = &uipc_ctloutput, 4434 .pr_abort = uipc_abort, 4435 .pr_accept = uipc_peeraddr, 4436 .pr_attach = uipc_attach, 4437 .pr_bind = uipc_bind, 4438 .pr_bindat = uipc_bindat, 4439 .pr_connect = uipc_connect, 4440 .pr_connectat = uipc_connectat, 4441 .pr_connect2 = uipc_connect2, 4442 .pr_detach = uipc_detach, 4443 .pr_disconnect = uipc_disconnect, 4444 .pr_fdclose = uipc_fdclose, 4445 .pr_listen = uipc_listen, 4446 .pr_peeraddr = uipc_peeraddr, 4447 .pr_send = uipc_sendfile, 4448 .pr_sendfile_wait = uipc_sendfile_wait, 4449 .pr_ready = uipc_ready, 4450 .pr_sense = uipc_sense, 4451 .pr_shutdown = uipc_shutdown, 4452 .pr_sockaddr = uipc_sockaddr, 4453 .pr_sosend = uipc_sosend_stream_or_seqpacket, 4454 .pr_soreceive = uipc_soreceive_stream_or_seqpacket, 4455 .pr_sopoll = uipc_sopoll_stream_or_seqpacket, 4456 .pr_kqfilter = uipc_kqfilter_stream_or_seqpacket, 4457 .pr_close = uipc_close, 4458 .pr_chmod = uipc_chmod, 4459 }; 4460 4461 static struct protosw dgramproto = { 4462 .pr_type = SOCK_DGRAM, 4463 .pr_flags = PR_ATOMIC | PR_ADDR | PR_CAPATTACH | PR_SOCKBUF, 4464 .pr_ctloutput = &uipc_ctloutput, 4465 .pr_abort = uipc_abort, 4466 .pr_accept = uipc_peeraddr, 4467 .pr_attach = uipc_attach, 4468 .pr_bind = uipc_bind, 4469 .pr_bindat = uipc_bindat, 4470 .pr_connect = uipc_connect, 4471 .pr_connectat = uipc_connectat, 4472 .pr_connect2 = uipc_connect2, 4473 .pr_detach = uipc_detach, 4474 .pr_disconnect = uipc_disconnect, 4475 .pr_fdclose = uipc_fdclose, 4476 .pr_peeraddr = uipc_peeraddr, 4477 .pr_sosend = uipc_sosend_dgram, 4478 .pr_sense = uipc_sense, 4479 .pr_shutdown = uipc_shutdown, 4480 .pr_sockaddr = uipc_sockaddr, 4481 .pr_soreceive = uipc_soreceive_dgram, 4482 .pr_close = uipc_close, 4483 .pr_chmod = uipc_chmod, 4484 }; 4485 4486 static struct protosw seqpacketproto = { 4487 .pr_type = SOCK_SEQPACKET, 4488 .pr_flags = PR_CONNREQUIRED | PR_CAPATTACH | PR_SOCKBUF, 4489 .pr_ctloutput = &uipc_ctloutput, 4490 .pr_abort = uipc_abort, 4491 .pr_accept = uipc_peeraddr, 4492 .pr_attach = uipc_attach, 4493 .pr_bind = uipc_bind, 4494 .pr_bindat = uipc_bindat, 4495 .pr_connect = uipc_connect, 4496 .pr_connectat = uipc_connectat, 4497 .pr_connect2 = uipc_connect2, 4498 .pr_detach = uipc_detach, 4499 .pr_disconnect = uipc_disconnect, 4500 .pr_fdclose = uipc_fdclose, 4501 .pr_listen = uipc_listen, 4502 .pr_peeraddr = uipc_peeraddr, 4503 .pr_sense = uipc_sense, 4504 .pr_shutdown = uipc_shutdown, 4505 .pr_sockaddr = uipc_sockaddr, 4506 .pr_sosend = uipc_sosend_stream_or_seqpacket, 4507 .pr_soreceive = uipc_soreceive_stream_or_seqpacket, 4508 .pr_sopoll = uipc_sopoll_stream_or_seqpacket, 4509 .pr_kqfilter = uipc_kqfilter_stream_or_seqpacket, 4510 .pr_close = uipc_close, 4511 .pr_chmod = uipc_chmod, 4512 }; 4513 4514 static struct domain localdomain = { 4515 .dom_family = AF_LOCAL, 4516 .dom_name = "local", 4517 .dom_nprotosw = 3, 4518 .dom_protosw = { 4519 &streamproto, 4520 &dgramproto, 4521 &seqpacketproto, 4522 } 4523 }; 4524 DOMAIN_SET(local); 4525 4526 /* 4527 * A helper function called by VFS before socket-type vnode reclamation. 4528 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode 4529 * use count. 4530 */ 4531 void 4532 vfs_unp_reclaim(struct vnode *vp) 4533 { 4534 struct unpcb *unp; 4535 int active; 4536 struct mtx *vplock; 4537 4538 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim"); 4539 KASSERT(vp->v_type == VSOCK, 4540 ("vfs_unp_reclaim: vp->v_type != VSOCK")); 4541 4542 active = 0; 4543 vplock = mtx_pool_find(unp_vp_mtxpool, vp); 4544 mtx_lock(vplock); 4545 VOP_UNP_CONNECT(vp, &unp); 4546 if (unp == NULL) 4547 goto done; 4548 UNP_PCB_LOCK(unp); 4549 if (unp->unp_vnode == vp) { 4550 VOP_UNP_DETACH(vp); 4551 unp->unp_vnode = NULL; 4552 active = 1; 4553 } 4554 UNP_PCB_UNLOCK(unp); 4555 done: 4556 mtx_unlock(vplock); 4557 if (active) 4558 vunref(vp); 4559 } 4560 4561 #ifdef DDB 4562 static void 4563 db_print_indent(int indent) 4564 { 4565 int i; 4566 4567 for (i = 0; i < indent; i++) 4568 db_printf(" "); 4569 } 4570 4571 static void 4572 db_print_unpflags(int unp_flags) 4573 { 4574 int comma; 4575 4576 comma = 0; 4577 if (unp_flags & UNP_HAVEPC) { 4578 db_printf("%sUNP_HAVEPC", comma ? ", " : ""); 4579 comma = 1; 4580 } 4581 if (unp_flags & UNP_WANTCRED_ALWAYS) { 4582 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : ""); 4583 comma = 1; 4584 } 4585 if (unp_flags & UNP_WANTCRED_ONESHOT) { 4586 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : ""); 4587 comma = 1; 4588 } 4589 if (unp_flags & UNP_CONNECTING) { 4590 db_printf("%sUNP_CONNECTING", comma ? ", " : ""); 4591 comma = 1; 4592 } 4593 if (unp_flags & UNP_BINDING) { 4594 db_printf("%sUNP_BINDING", comma ? ", " : ""); 4595 comma = 1; 4596 } 4597 } 4598 4599 static void 4600 db_print_xucred(int indent, struct xucred *xu) 4601 { 4602 int comma, i; 4603 4604 db_print_indent(indent); 4605 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n", 4606 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups); 4607 db_print_indent(indent); 4608 db_printf("cr_groups: "); 4609 comma = 0; 4610 for (i = 0; i < xu->cr_ngroups; i++) { 4611 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]); 4612 comma = 1; 4613 } 4614 db_printf("\n"); 4615 } 4616 4617 static void 4618 db_print_unprefs(int indent, struct unp_head *uh) 4619 { 4620 struct unpcb *unp; 4621 int counter; 4622 4623 counter = 0; 4624 LIST_FOREACH(unp, uh, unp_reflink) { 4625 if (counter % 4 == 0) 4626 db_print_indent(indent); 4627 db_printf("%p ", unp); 4628 if (counter % 4 == 3) 4629 db_printf("\n"); 4630 counter++; 4631 } 4632 if (counter != 0 && counter % 4 != 0) 4633 db_printf("\n"); 4634 } 4635 4636 DB_SHOW_COMMAND(unpcb, db_show_unpcb) 4637 { 4638 struct unpcb *unp; 4639 4640 if (!have_addr) { 4641 db_printf("usage: show unpcb <addr>\n"); 4642 return; 4643 } 4644 unp = (struct unpcb *)addr; 4645 4646 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket, 4647 unp->unp_vnode); 4648 4649 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino, 4650 unp->unp_conn); 4651 4652 db_printf("unp_refs:\n"); 4653 db_print_unprefs(2, &unp->unp_refs); 4654 4655 /* XXXRW: Would be nice to print the full address, if any. */ 4656 db_printf("unp_addr: %p\n", unp->unp_addr); 4657 4658 db_printf("unp_gencnt: %llu\n", 4659 (unsigned long long)unp->unp_gencnt); 4660 4661 db_printf("unp_flags: %x (", unp->unp_flags); 4662 db_print_unpflags(unp->unp_flags); 4663 db_printf(")\n"); 4664 4665 db_printf("unp_peercred:\n"); 4666 db_print_xucred(2, &unp->unp_peercred); 4667 4668 db_printf("unp_refcount: %u\n", unp->unp_refcount); 4669 } 4670 #endif 4671