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 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 <sys/cdefs.h> 60 #include "opt_ddb.h" 61 62 #include <sys/param.h> 63 #include <sys/capsicum.h> 64 #include <sys/domain.h> 65 #include <sys/eventhandler.h> 66 #include <sys/fcntl.h> 67 #include <sys/file.h> 68 #include <sys/filedesc.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/proc.h> 77 #include <sys/protosw.h> 78 #include <sys/queue.h> 79 #include <sys/resourcevar.h> 80 #include <sys/rwlock.h> 81 #include <sys/socket.h> 82 #include <sys/socketvar.h> 83 #include <sys/signalvar.h> 84 #include <sys/stat.h> 85 #include <sys/sx.h> 86 #include <sys/sysctl.h> 87 #include <sys/systm.h> 88 #include <sys/taskqueue.h> 89 #include <sys/un.h> 90 #include <sys/unpcb.h> 91 #include <sys/vnode.h> 92 93 #include <net/vnet.h> 94 95 #ifdef DDB 96 #include <ddb/ddb.h> 97 #endif 98 99 #include <security/mac/mac_framework.h> 100 101 #include <vm/uma.h> 102 103 MALLOC_DECLARE(M_FILECAPS); 104 105 static struct domain localdomain; 106 107 static uma_zone_t unp_zone; 108 static unp_gen_t unp_gencnt; /* (l) */ 109 static u_int unp_count; /* (l) Count of local sockets. */ 110 static ino_t unp_ino; /* Prototype for fake inode numbers. */ 111 static int unp_rights; /* (g) File descriptors in flight. */ 112 static struct unp_head unp_shead; /* (l) List of stream sockets. */ 113 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */ 114 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */ 115 116 struct unp_defer { 117 SLIST_ENTRY(unp_defer) ud_link; 118 struct file *ud_fp; 119 }; 120 static SLIST_HEAD(, unp_defer) unp_defers; 121 static int unp_defers_count; 122 123 static const struct sockaddr sun_noname = { 124 .sa_len = sizeof(sun_noname), 125 .sa_family = AF_LOCAL, 126 }; 127 128 /* 129 * Garbage collection of cyclic file descriptor/socket references occurs 130 * asynchronously in a taskqueue context in order to avoid recursion and 131 * reentrance in the UNIX domain socket, file descriptor, and socket layer 132 * code. See unp_gc() for a full description. 133 */ 134 static struct timeout_task unp_gc_task; 135 136 /* 137 * The close of unix domain sockets attached as SCM_RIGHTS is 138 * postponed to the taskqueue, to avoid arbitrary recursion depth. 139 * The attached sockets might have another sockets attached. 140 */ 141 static struct task unp_defer_task; 142 143 /* 144 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for 145 * stream sockets, although the total for sender and receiver is actually 146 * only PIPSIZ. 147 * 148 * Datagram sockets really use the sendspace as the maximum datagram size, 149 * and don't really want to reserve the sendspace. Their recvspace should be 150 * large enough for at least one max-size datagram plus address. 151 */ 152 #ifndef PIPSIZ 153 #define PIPSIZ 8192 154 #endif 155 static u_long unpst_sendspace = PIPSIZ; 156 static u_long unpst_recvspace = PIPSIZ; 157 static u_long unpdg_maxdgram = 8*1024; /* support 8KB syslog msgs */ 158 static u_long unpdg_recvspace = 16*1024; 159 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */ 160 static u_long unpsp_recvspace = PIPSIZ; 161 162 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 163 "Local domain"); 164 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, 165 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 166 "SOCK_STREAM"); 167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, 168 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 169 "SOCK_DGRAM"); 170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, 171 CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 172 "SOCK_SEQPACKET"); 173 174 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW, 175 &unpst_sendspace, 0, "Default stream send space."); 176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW, 177 &unpst_recvspace, 0, "Default stream receive space."); 178 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW, 179 &unpdg_maxdgram, 0, "Maximum datagram size."); 180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW, 181 &unpdg_recvspace, 0, "Default datagram receive space."); 182 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW, 183 &unpsp_sendspace, 0, "Default seqpacket send space."); 184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW, 185 &unpsp_recvspace, 0, "Default seqpacket receive space."); 186 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, 187 "File descriptors in flight."); 188 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD, 189 &unp_defers_count, 0, 190 "File descriptors deferred to taskqueue for close."); 191 192 /* 193 * Locking and synchronization: 194 * 195 * Several types of locks exist in the local domain socket implementation: 196 * - a global linkage lock 197 * - a global connection list lock 198 * - the mtxpool lock 199 * - per-unpcb mutexes 200 * 201 * The linkage lock protects the global socket lists, the generation number 202 * counter and garbage collector state. 203 * 204 * The connection list lock protects the list of referring sockets in a datagram 205 * socket PCB. This lock is also overloaded to protect a global list of 206 * sockets whose buffers contain socket references in the form of SCM_RIGHTS 207 * messages. To avoid recursion, such references are released by a dedicated 208 * thread. 209 * 210 * The mtxpool lock protects the vnode from being modified while referenced. 211 * Lock ordering rules require that it be acquired before any PCB locks. 212 * 213 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the 214 * unpcb. This includes the unp_conn field, which either links two connected 215 * PCBs together (for connected socket types) or points at the destination 216 * socket (for connectionless socket types). The operations of creating or 217 * destroying a connection therefore involve locking multiple PCBs. To avoid 218 * lock order reversals, in some cases this involves dropping a PCB lock and 219 * using a reference counter to maintain liveness. 220 * 221 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer, 222 * allocated in pr_attach() and freed in pr_detach(). The validity of that 223 * pointer is an invariant, so no lock is required to dereference the so_pcb 224 * pointer if a valid socket reference is held by the caller. In practice, 225 * this is always true during operations performed on a socket. Each unpcb 226 * has a back-pointer to its socket, unp_socket, which will be stable under 227 * the same circumstances. 228 * 229 * This pointer may only be safely dereferenced as long as a valid reference 230 * to the unpcb is held. Typically, this reference will be from the socket, 231 * or from another unpcb when the referring unpcb's lock is held (in order 232 * that the reference not be invalidated during use). For example, to follow 233 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee 234 * that detach is not run clearing unp_socket. 235 * 236 * Blocking with UNIX domain sockets is a tricky issue: unlike most network 237 * protocols, bind() is a non-atomic operation, and connect() requires 238 * potential sleeping in the protocol, due to potentially waiting on local or 239 * distributed file systems. We try to separate "lookup" operations, which 240 * may sleep, and the IPC operations themselves, which typically can occur 241 * with relative atomicity as locks can be held over the entire operation. 242 * 243 * Another tricky issue is simultaneous multi-threaded or multi-process 244 * access to a single UNIX domain socket. These are handled by the flags 245 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or 246 * binding, both of which involve dropping UNIX domain socket locks in order 247 * to perform namei() and other file system operations. 248 */ 249 static struct rwlock unp_link_rwlock; 250 static struct mtx unp_defers_lock; 251 252 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \ 253 "unp_link_rwlock") 254 255 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \ 256 RA_LOCKED) 257 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \ 258 RA_UNLOCKED) 259 260 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock) 261 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock) 262 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock) 263 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock) 264 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \ 265 RA_WLOCKED) 266 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock) 267 268 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \ 269 "unp_defer", NULL, MTX_DEF) 270 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock) 271 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock) 272 273 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK(); 274 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK(); 275 276 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \ 277 "unp", "unp", \ 278 MTX_DUPOK|MTX_DEF) 279 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx) 280 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx) 281 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx) 282 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx) 283 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx) 284 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx) 285 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED) 286 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED) 287 288 static int uipc_connect2(struct socket *, struct socket *); 289 static int uipc_ctloutput(struct socket *, struct sockopt *); 290 static int unp_connect(struct socket *, struct sockaddr *, 291 struct thread *); 292 static int unp_connectat(int, struct socket *, struct sockaddr *, 293 struct thread *, bool); 294 typedef enum { PRU_CONNECT, PRU_CONNECT2 } conn2_how; 295 static void unp_connect2(struct socket *so, struct socket *so2, conn2_how); 296 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2); 297 static void unp_dispose(struct socket *so); 298 static void unp_shutdown(struct unpcb *); 299 static void unp_drop(struct unpcb *); 300 static void unp_gc(__unused void *, int); 301 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int)); 302 static void unp_discard(struct file *); 303 static void unp_freerights(struct filedescent **, int); 304 static int unp_internalize(struct mbuf **, struct thread *, 305 struct mbuf **, u_int *, u_int *); 306 static void unp_internalize_fp(struct file *); 307 static int unp_externalize(struct mbuf *, struct mbuf **, int); 308 static int unp_externalize_fp(struct file *); 309 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *, 310 int, struct mbuf **, u_int *, u_int *); 311 static void unp_process_defers(void * __unused, int); 312 313 static void 314 unp_pcb_hold(struct unpcb *unp) 315 { 316 u_int old __unused; 317 318 old = refcount_acquire(&unp->unp_refcount); 319 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp)); 320 } 321 322 static __result_use_check bool 323 unp_pcb_rele(struct unpcb *unp) 324 { 325 bool ret; 326 327 UNP_PCB_LOCK_ASSERT(unp); 328 329 if ((ret = refcount_release(&unp->unp_refcount))) { 330 UNP_PCB_UNLOCK(unp); 331 UNP_PCB_LOCK_DESTROY(unp); 332 uma_zfree(unp_zone, unp); 333 } 334 return (ret); 335 } 336 337 static void 338 unp_pcb_rele_notlast(struct unpcb *unp) 339 { 340 bool ret __unused; 341 342 ret = refcount_release(&unp->unp_refcount); 343 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp)); 344 } 345 346 static void 347 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2) 348 { 349 UNP_PCB_UNLOCK_ASSERT(unp); 350 UNP_PCB_UNLOCK_ASSERT(unp2); 351 352 if (unp == unp2) { 353 UNP_PCB_LOCK(unp); 354 } else if ((uintptr_t)unp2 > (uintptr_t)unp) { 355 UNP_PCB_LOCK(unp); 356 UNP_PCB_LOCK(unp2); 357 } else { 358 UNP_PCB_LOCK(unp2); 359 UNP_PCB_LOCK(unp); 360 } 361 } 362 363 static void 364 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2) 365 { 366 UNP_PCB_UNLOCK(unp); 367 if (unp != unp2) 368 UNP_PCB_UNLOCK(unp2); 369 } 370 371 /* 372 * Try to lock the connected peer of an already locked socket. In some cases 373 * this requires that we unlock the current socket. The pairbusy counter is 374 * used to block concurrent connection attempts while the lock is dropped. The 375 * caller must be careful to revalidate PCB state. 376 */ 377 static struct unpcb * 378 unp_pcb_lock_peer(struct unpcb *unp) 379 { 380 struct unpcb *unp2; 381 382 UNP_PCB_LOCK_ASSERT(unp); 383 unp2 = unp->unp_conn; 384 if (unp2 == NULL) 385 return (NULL); 386 if (__predict_false(unp == unp2)) 387 return (unp); 388 389 UNP_PCB_UNLOCK_ASSERT(unp2); 390 391 if (__predict_true(UNP_PCB_TRYLOCK(unp2))) 392 return (unp2); 393 if ((uintptr_t)unp2 > (uintptr_t)unp) { 394 UNP_PCB_LOCK(unp2); 395 return (unp2); 396 } 397 unp->unp_pairbusy++; 398 unp_pcb_hold(unp2); 399 UNP_PCB_UNLOCK(unp); 400 401 UNP_PCB_LOCK(unp2); 402 UNP_PCB_LOCK(unp); 403 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL, 404 ("%s: socket %p was reconnected", __func__, unp)); 405 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) { 406 unp->unp_flags &= ~UNP_WAITING; 407 wakeup(unp); 408 } 409 if (unp_pcb_rele(unp2)) { 410 /* unp2 is unlocked. */ 411 return (NULL); 412 } 413 if (unp->unp_conn == NULL) { 414 UNP_PCB_UNLOCK(unp2); 415 return (NULL); 416 } 417 return (unp2); 418 } 419 420 static void 421 uipc_abort(struct socket *so) 422 { 423 struct unpcb *unp, *unp2; 424 425 unp = sotounpcb(so); 426 KASSERT(unp != NULL, ("uipc_abort: unp == NULL")); 427 UNP_PCB_UNLOCK_ASSERT(unp); 428 429 UNP_PCB_LOCK(unp); 430 unp2 = unp->unp_conn; 431 if (unp2 != NULL) { 432 unp_pcb_hold(unp2); 433 UNP_PCB_UNLOCK(unp); 434 unp_drop(unp2); 435 } else 436 UNP_PCB_UNLOCK(unp); 437 } 438 439 static int 440 uipc_attach(struct socket *so, int proto, struct thread *td) 441 { 442 u_long sendspace, recvspace; 443 struct unpcb *unp; 444 int error; 445 bool locked; 446 447 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL")); 448 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) { 449 switch (so->so_type) { 450 case SOCK_STREAM: 451 sendspace = unpst_sendspace; 452 recvspace = unpst_recvspace; 453 break; 454 455 case SOCK_DGRAM: 456 STAILQ_INIT(&so->so_rcv.uxdg_mb); 457 STAILQ_INIT(&so->so_snd.uxdg_mb); 458 TAILQ_INIT(&so->so_rcv.uxdg_conns); 459 /* 460 * Since send buffer is either bypassed or is a part 461 * of one-to-many receive buffer, we assign both space 462 * limits to unpdg_recvspace. 463 */ 464 sendspace = recvspace = unpdg_recvspace; 465 break; 466 467 case SOCK_SEQPACKET: 468 sendspace = unpsp_sendspace; 469 recvspace = unpsp_recvspace; 470 break; 471 472 default: 473 panic("uipc_attach"); 474 } 475 error = soreserve(so, sendspace, recvspace); 476 if (error) 477 return (error); 478 } 479 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO); 480 if (unp == NULL) 481 return (ENOBUFS); 482 LIST_INIT(&unp->unp_refs); 483 UNP_PCB_LOCK_INIT(unp); 484 unp->unp_socket = so; 485 so->so_pcb = unp; 486 refcount_init(&unp->unp_refcount, 1); 487 488 if ((locked = UNP_LINK_WOWNED()) == false) 489 UNP_LINK_WLOCK(); 490 491 unp->unp_gencnt = ++unp_gencnt; 492 unp->unp_ino = ++unp_ino; 493 unp_count++; 494 switch (so->so_type) { 495 case SOCK_STREAM: 496 LIST_INSERT_HEAD(&unp_shead, unp, unp_link); 497 break; 498 499 case SOCK_DGRAM: 500 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link); 501 break; 502 503 case SOCK_SEQPACKET: 504 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link); 505 break; 506 507 default: 508 panic("uipc_attach"); 509 } 510 511 if (locked == false) 512 UNP_LINK_WUNLOCK(); 513 514 return (0); 515 } 516 517 static int 518 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td) 519 { 520 struct sockaddr_un *soun = (struct sockaddr_un *)nam; 521 struct vattr vattr; 522 int error, namelen; 523 struct nameidata nd; 524 struct unpcb *unp; 525 struct vnode *vp; 526 struct mount *mp; 527 cap_rights_t rights; 528 char *buf; 529 530 if (nam->sa_family != AF_UNIX) 531 return (EAFNOSUPPORT); 532 533 unp = sotounpcb(so); 534 KASSERT(unp != NULL, ("uipc_bind: unp == NULL")); 535 536 if (soun->sun_len > sizeof(struct sockaddr_un)) 537 return (EINVAL); 538 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path); 539 if (namelen <= 0) 540 return (EINVAL); 541 542 /* 543 * We don't allow simultaneous bind() calls on a single UNIX domain 544 * socket, so flag in-progress operations, and return an error if an 545 * operation is already in progress. 546 * 547 * Historically, we have not allowed a socket to be rebound, so this 548 * also returns an error. Not allowing re-binding simplifies the 549 * implementation and avoids a great many possible failure modes. 550 */ 551 UNP_PCB_LOCK(unp); 552 if (unp->unp_vnode != NULL) { 553 UNP_PCB_UNLOCK(unp); 554 return (EINVAL); 555 } 556 if (unp->unp_flags & UNP_BINDING) { 557 UNP_PCB_UNLOCK(unp); 558 return (EALREADY); 559 } 560 unp->unp_flags |= UNP_BINDING; 561 UNP_PCB_UNLOCK(unp); 562 563 buf = malloc(namelen + 1, M_TEMP, M_WAITOK); 564 bcopy(soun->sun_path, buf, namelen); 565 buf[namelen] = 0; 566 567 restart: 568 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE, 569 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT)); 570 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */ 571 error = namei(&nd); 572 if (error) 573 goto error; 574 vp = nd.ni_vp; 575 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) { 576 NDFREE_PNBUF(&nd); 577 if (nd.ni_dvp == vp) 578 vrele(nd.ni_dvp); 579 else 580 vput(nd.ni_dvp); 581 if (vp != NULL) { 582 vrele(vp); 583 error = EADDRINUSE; 584 goto error; 585 } 586 error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH); 587 if (error) 588 goto error; 589 goto restart; 590 } 591 VATTR_NULL(&vattr); 592 vattr.va_type = VSOCK; 593 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask); 594 #ifdef MAC 595 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd, 596 &vattr); 597 #endif 598 if (error == 0) 599 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr); 600 NDFREE_PNBUF(&nd); 601 if (error) { 602 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true); 603 vn_finished_write(mp); 604 if (error == ERELOOKUP) 605 goto restart; 606 goto error; 607 } 608 vp = nd.ni_vp; 609 ASSERT_VOP_ELOCKED(vp, "uipc_bind"); 610 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK); 611 612 UNP_PCB_LOCK(unp); 613 VOP_UNP_BIND(vp, unp); 614 unp->unp_vnode = vp; 615 unp->unp_addr = soun; 616 unp->unp_flags &= ~UNP_BINDING; 617 UNP_PCB_UNLOCK(unp); 618 vref(vp); 619 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true); 620 vn_finished_write(mp); 621 free(buf, M_TEMP); 622 return (0); 623 624 error: 625 UNP_PCB_LOCK(unp); 626 unp->unp_flags &= ~UNP_BINDING; 627 UNP_PCB_UNLOCK(unp); 628 free(buf, M_TEMP); 629 return (error); 630 } 631 632 static int 633 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td) 634 { 635 636 return (uipc_bindat(AT_FDCWD, so, nam, td)); 637 } 638 639 static int 640 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td) 641 { 642 int error; 643 644 KASSERT(td == curthread, ("uipc_connect: td != curthread")); 645 error = unp_connect(so, nam, td); 646 return (error); 647 } 648 649 static int 650 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam, 651 struct thread *td) 652 { 653 int error; 654 655 KASSERT(td == curthread, ("uipc_connectat: td != curthread")); 656 error = unp_connectat(fd, so, nam, td, false); 657 return (error); 658 } 659 660 static void 661 uipc_close(struct socket *so) 662 { 663 struct unpcb *unp, *unp2; 664 struct vnode *vp = NULL; 665 struct mtx *vplock; 666 667 unp = sotounpcb(so); 668 KASSERT(unp != NULL, ("uipc_close: unp == NULL")); 669 670 vplock = NULL; 671 if ((vp = unp->unp_vnode) != NULL) { 672 vplock = mtx_pool_find(mtxpool_sleep, vp); 673 mtx_lock(vplock); 674 } 675 UNP_PCB_LOCK(unp); 676 if (vp && unp->unp_vnode == NULL) { 677 mtx_unlock(vplock); 678 vp = NULL; 679 } 680 if (vp != NULL) { 681 VOP_UNP_DETACH(vp); 682 unp->unp_vnode = NULL; 683 } 684 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) 685 unp_disconnect(unp, unp2); 686 else 687 UNP_PCB_UNLOCK(unp); 688 if (vp) { 689 mtx_unlock(vplock); 690 vrele(vp); 691 } 692 } 693 694 static int 695 uipc_connect2(struct socket *so1, struct socket *so2) 696 { 697 struct unpcb *unp, *unp2; 698 699 if (so1->so_type != so2->so_type) 700 return (EPROTOTYPE); 701 702 unp = so1->so_pcb; 703 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL")); 704 unp2 = so2->so_pcb; 705 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL")); 706 unp_pcb_lock_pair(unp, unp2); 707 unp_connect2(so1, so2, PRU_CONNECT2); 708 unp_pcb_unlock_pair(unp, unp2); 709 710 return (0); 711 } 712 713 static void 714 uipc_detach(struct socket *so) 715 { 716 struct unpcb *unp, *unp2; 717 struct mtx *vplock; 718 struct vnode *vp; 719 int local_unp_rights; 720 721 unp = sotounpcb(so); 722 KASSERT(unp != NULL, ("uipc_detach: unp == NULL")); 723 724 vp = NULL; 725 vplock = NULL; 726 727 if (!SOLISTENING(so)) 728 unp_dispose(so); 729 730 UNP_LINK_WLOCK(); 731 LIST_REMOVE(unp, unp_link); 732 if (unp->unp_gcflag & UNPGC_DEAD) 733 LIST_REMOVE(unp, unp_dead); 734 unp->unp_gencnt = ++unp_gencnt; 735 --unp_count; 736 UNP_LINK_WUNLOCK(); 737 738 UNP_PCB_UNLOCK_ASSERT(unp); 739 restart: 740 if ((vp = unp->unp_vnode) != NULL) { 741 vplock = mtx_pool_find(mtxpool_sleep, vp); 742 mtx_lock(vplock); 743 } 744 UNP_PCB_LOCK(unp); 745 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) { 746 if (vplock) 747 mtx_unlock(vplock); 748 UNP_PCB_UNLOCK(unp); 749 goto restart; 750 } 751 if ((vp = unp->unp_vnode) != NULL) { 752 VOP_UNP_DETACH(vp); 753 unp->unp_vnode = NULL; 754 } 755 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) 756 unp_disconnect(unp, unp2); 757 else 758 UNP_PCB_UNLOCK(unp); 759 760 UNP_REF_LIST_LOCK(); 761 while (!LIST_EMPTY(&unp->unp_refs)) { 762 struct unpcb *ref = LIST_FIRST(&unp->unp_refs); 763 764 unp_pcb_hold(ref); 765 UNP_REF_LIST_UNLOCK(); 766 767 MPASS(ref != unp); 768 UNP_PCB_UNLOCK_ASSERT(ref); 769 unp_drop(ref); 770 UNP_REF_LIST_LOCK(); 771 } 772 UNP_REF_LIST_UNLOCK(); 773 774 UNP_PCB_LOCK(unp); 775 local_unp_rights = unp_rights; 776 unp->unp_socket->so_pcb = NULL; 777 unp->unp_socket = NULL; 778 free(unp->unp_addr, M_SONAME); 779 unp->unp_addr = NULL; 780 if (!unp_pcb_rele(unp)) 781 UNP_PCB_UNLOCK(unp); 782 if (vp) { 783 mtx_unlock(vplock); 784 vrele(vp); 785 } 786 if (local_unp_rights) 787 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1); 788 789 switch (so->so_type) { 790 case SOCK_DGRAM: 791 /* 792 * Everything should have been unlinked/freed by unp_dispose() 793 * and/or unp_disconnect(). 794 */ 795 MPASS(so->so_rcv.uxdg_peeked == NULL); 796 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb)); 797 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns)); 798 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb)); 799 } 800 } 801 802 static int 803 uipc_disconnect(struct socket *so) 804 { 805 struct unpcb *unp, *unp2; 806 807 unp = sotounpcb(so); 808 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL")); 809 810 UNP_PCB_LOCK(unp); 811 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) 812 unp_disconnect(unp, unp2); 813 else 814 UNP_PCB_UNLOCK(unp); 815 return (0); 816 } 817 818 static int 819 uipc_listen(struct socket *so, int backlog, struct thread *td) 820 { 821 struct unpcb *unp; 822 int error; 823 824 MPASS(so->so_type != SOCK_DGRAM); 825 826 /* 827 * Synchronize with concurrent connection attempts. 828 */ 829 error = 0; 830 unp = sotounpcb(so); 831 UNP_PCB_LOCK(unp); 832 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0) 833 error = EINVAL; 834 else if (unp->unp_vnode == NULL) 835 error = EDESTADDRREQ; 836 if (error != 0) { 837 UNP_PCB_UNLOCK(unp); 838 return (error); 839 } 840 841 SOCK_LOCK(so); 842 error = solisten_proto_check(so); 843 if (error == 0) { 844 cru2xt(td, &unp->unp_peercred); 845 solisten_proto(so, backlog); 846 } 847 SOCK_UNLOCK(so); 848 UNP_PCB_UNLOCK(unp); 849 return (error); 850 } 851 852 static int 853 uipc_peeraddr(struct socket *so, struct sockaddr *ret) 854 { 855 struct unpcb *unp, *unp2; 856 const struct sockaddr *sa; 857 858 unp = sotounpcb(so); 859 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL")); 860 861 UNP_PCB_LOCK(unp); 862 unp2 = unp_pcb_lock_peer(unp); 863 if (unp2 != NULL) { 864 if (unp2->unp_addr != NULL) 865 sa = (struct sockaddr *)unp2->unp_addr; 866 else 867 sa = &sun_noname; 868 bcopy(sa, ret, sa->sa_len); 869 unp_pcb_unlock_pair(unp, unp2); 870 } else { 871 UNP_PCB_UNLOCK(unp); 872 sa = &sun_noname; 873 bcopy(sa, ret, sa->sa_len); 874 } 875 return (0); 876 } 877 878 static int 879 uipc_rcvd(struct socket *so, int flags) 880 { 881 struct unpcb *unp, *unp2; 882 struct socket *so2; 883 u_int mbcnt, sbcc; 884 885 unp = sotounpcb(so); 886 KASSERT(unp != NULL, ("%s: unp == NULL", __func__)); 887 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET, 888 ("%s: socktype %d", __func__, so->so_type)); 889 890 /* 891 * Adjust backpressure on sender and wakeup any waiting to write. 892 * 893 * The unp lock is acquired to maintain the validity of the unp_conn 894 * pointer; no lock on unp2 is required as unp2->unp_socket will be 895 * static as long as we don't permit unp2 to disconnect from unp, 896 * which is prevented by the lock on unp. We cache values from 897 * so_rcv to avoid holding the so_rcv lock over the entire 898 * transaction on the remote so_snd. 899 */ 900 SOCKBUF_LOCK(&so->so_rcv); 901 mbcnt = so->so_rcv.sb_mbcnt; 902 sbcc = sbavail(&so->so_rcv); 903 SOCKBUF_UNLOCK(&so->so_rcv); 904 /* 905 * There is a benign race condition at this point. If we're planning to 906 * clear SB_STOP, but uipc_send is called on the connected socket at 907 * this instant, it might add data to the sockbuf and set SB_STOP. Then 908 * we would erroneously clear SB_STOP below, even though the sockbuf is 909 * full. The race is benign because the only ill effect is to allow the 910 * sockbuf to exceed its size limit, and the size limits are not 911 * strictly guaranteed anyway. 912 */ 913 UNP_PCB_LOCK(unp); 914 unp2 = unp->unp_conn; 915 if (unp2 == NULL) { 916 UNP_PCB_UNLOCK(unp); 917 return (0); 918 } 919 so2 = unp2->unp_socket; 920 SOCKBUF_LOCK(&so2->so_snd); 921 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax) 922 so2->so_snd.sb_flags &= ~SB_STOP; 923 sowwakeup_locked(so2); 924 UNP_PCB_UNLOCK(unp); 925 return (0); 926 } 927 928 static int 929 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam, 930 struct mbuf *control, struct thread *td) 931 { 932 struct unpcb *unp, *unp2; 933 struct socket *so2; 934 u_int mbcnt, sbcc; 935 int error; 936 937 unp = sotounpcb(so); 938 KASSERT(unp != NULL, ("%s: unp == NULL", __func__)); 939 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET, 940 ("%s: socktype %d", __func__, so->so_type)); 941 942 error = 0; 943 if (flags & PRUS_OOB) { 944 error = EOPNOTSUPP; 945 goto release; 946 } 947 if (control != NULL && 948 (error = unp_internalize(&control, td, NULL, NULL, NULL))) 949 goto release; 950 951 unp2 = NULL; 952 if ((so->so_state & SS_ISCONNECTED) == 0) { 953 if (nam != NULL) { 954 if ((error = unp_connect(so, nam, td)) != 0) 955 goto out; 956 } else { 957 error = ENOTCONN; 958 goto out; 959 } 960 } 961 962 UNP_PCB_LOCK(unp); 963 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) { 964 UNP_PCB_UNLOCK(unp); 965 error = ENOTCONN; 966 goto out; 967 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 968 unp_pcb_unlock_pair(unp, unp2); 969 error = EPIPE; 970 goto out; 971 } 972 UNP_PCB_UNLOCK(unp); 973 if ((so2 = unp2->unp_socket) == NULL) { 974 UNP_PCB_UNLOCK(unp2); 975 error = ENOTCONN; 976 goto out; 977 } 978 SOCKBUF_LOCK(&so2->so_rcv); 979 if (unp2->unp_flags & UNP_WANTCRED_MASK) { 980 /* 981 * Credentials are passed only once on SOCK_STREAM and 982 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or 983 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS). 984 */ 985 control = unp_addsockcred(td, control, unp2->unp_flags, NULL, 986 NULL, NULL); 987 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT; 988 } 989 990 /* 991 * Send to paired receive port and wake up readers. Don't 992 * check for space available in the receive buffer if we're 993 * attaching ancillary data; Unix domain sockets only check 994 * for space in the sending sockbuf, and that check is 995 * performed one level up the stack. At that level we cannot 996 * precisely account for the amount of buffer space used 997 * (e.g., because control messages are not yet internalized). 998 */ 999 switch (so->so_type) { 1000 case SOCK_STREAM: 1001 if (control != NULL) { 1002 sbappendcontrol_locked(&so2->so_rcv, m, 1003 control, flags); 1004 control = NULL; 1005 } else 1006 sbappend_locked(&so2->so_rcv, m, flags); 1007 break; 1008 1009 case SOCK_SEQPACKET: 1010 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv, 1011 &sun_noname, m, control)) 1012 control = NULL; 1013 break; 1014 } 1015 1016 mbcnt = so2->so_rcv.sb_mbcnt; 1017 sbcc = sbavail(&so2->so_rcv); 1018 if (sbcc) 1019 sorwakeup_locked(so2); 1020 else 1021 SOCKBUF_UNLOCK(&so2->so_rcv); 1022 1023 /* 1024 * The PCB lock on unp2 protects the SB_STOP flag. Without it, 1025 * it would be possible for uipc_rcvd to be called at this 1026 * point, drain the receiving sockbuf, clear SB_STOP, and then 1027 * we would set SB_STOP below. That could lead to an empty 1028 * sockbuf having SB_STOP set 1029 */ 1030 SOCKBUF_LOCK(&so->so_snd); 1031 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax) 1032 so->so_snd.sb_flags |= SB_STOP; 1033 SOCKBUF_UNLOCK(&so->so_snd); 1034 UNP_PCB_UNLOCK(unp2); 1035 m = NULL; 1036 out: 1037 /* 1038 * PRUS_EOF is equivalent to pr_send followed by pr_shutdown. 1039 */ 1040 if (flags & PRUS_EOF) { 1041 UNP_PCB_LOCK(unp); 1042 socantsendmore(so); 1043 unp_shutdown(unp); 1044 UNP_PCB_UNLOCK(unp); 1045 } 1046 if (control != NULL && error != 0) 1047 unp_scan(control, unp_freerights); 1048 1049 release: 1050 if (control != NULL) 1051 m_freem(control); 1052 /* 1053 * In case of PRUS_NOTREADY, uipc_ready() is responsible 1054 * for freeing memory. 1055 */ 1056 if (m != NULL && (flags & PRUS_NOTREADY) == 0) 1057 m_freem(m); 1058 return (error); 1059 } 1060 1061 /* PF_UNIX/SOCK_DGRAM version of sbspace() */ 1062 static inline bool 1063 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt) 1064 { 1065 u_int bleft, mleft; 1066 1067 /* 1068 * Negative space may happen if send(2) is followed by 1069 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum. 1070 */ 1071 if (__predict_false(sb->sb_hiwat < sb->uxdg_cc || 1072 sb->sb_mbmax < sb->uxdg_mbcnt)) 1073 return (false); 1074 1075 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE)) 1076 return (false); 1077 1078 bleft = sb->sb_hiwat - sb->uxdg_cc; 1079 mleft = sb->sb_mbmax - sb->uxdg_mbcnt; 1080 1081 return (bleft >= cc && mleft >= mbcnt); 1082 } 1083 1084 /* 1085 * PF_UNIX/SOCK_DGRAM send 1086 * 1087 * Allocate a record consisting of 3 mbufs in the sequence of 1088 * from -> control -> data and append it to the socket buffer. 1089 * 1090 * The first mbuf carries sender's name and is a pkthdr that stores 1091 * overall length of datagram, its memory consumption and control length. 1092 */ 1093 #define ctllen PH_loc.thirtytwo[1] 1094 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <= 1095 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen"); 1096 static int 1097 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio, 1098 struct mbuf *m, struct mbuf *c, int flags, struct thread *td) 1099 { 1100 struct unpcb *unp, *unp2; 1101 const struct sockaddr *from; 1102 struct socket *so2; 1103 struct sockbuf *sb; 1104 struct mbuf *f, *clast; 1105 u_int cc, ctl, mbcnt; 1106 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused; 1107 int error; 1108 1109 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL)); 1110 1111 error = 0; 1112 f = NULL; 1113 ctl = 0; 1114 1115 if (__predict_false(flags & MSG_OOB)) { 1116 error = EOPNOTSUPP; 1117 goto out; 1118 } 1119 if (m == NULL) { 1120 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) { 1121 error = EMSGSIZE; 1122 goto out; 1123 } 1124 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR); 1125 if (__predict_false(m == NULL)) { 1126 error = EFAULT; 1127 goto out; 1128 } 1129 f = m_gethdr(M_WAITOK, MT_SONAME); 1130 cc = m->m_pkthdr.len; 1131 mbcnt = MSIZE + m->m_pkthdr.memlen; 1132 if (c != NULL && 1133 (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt))) 1134 goto out; 1135 } else { 1136 /* pr_sosend() with mbuf usually is a kernel thread. */ 1137 1138 M_ASSERTPKTHDR(m); 1139 if (__predict_false(c != NULL)) 1140 panic("%s: control from a kernel thread", __func__); 1141 1142 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) { 1143 error = EMSGSIZE; 1144 goto out; 1145 } 1146 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) { 1147 error = ENOBUFS; 1148 goto out; 1149 } 1150 /* Condition the foreign mbuf to our standards. */ 1151 m_clrprotoflags(m); 1152 m_tag_delete_chain(m, NULL); 1153 m->m_pkthdr.rcvif = NULL; 1154 m->m_pkthdr.flowid = 0; 1155 m->m_pkthdr.csum_flags = 0; 1156 m->m_pkthdr.fibnum = 0; 1157 m->m_pkthdr.rsstype = 0; 1158 1159 cc = m->m_pkthdr.len; 1160 mbcnt = MSIZE; 1161 for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) { 1162 mbcnt += MSIZE; 1163 if (mb->m_flags & M_EXT) 1164 mbcnt += mb->m_ext.ext_size; 1165 } 1166 } 1167 1168 unp = sotounpcb(so); 1169 MPASS(unp); 1170 1171 /* 1172 * XXXGL: would be cool to fully remove so_snd out of the equation 1173 * and avoid this lock, which is not only extraneous, but also being 1174 * released, thus still leaving possibility for a race. We can easily 1175 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it 1176 * is more difficult to invent something to handle so_error. 1177 */ 1178 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags)); 1179 if (error) 1180 goto out2; 1181 SOCK_SENDBUF_LOCK(so); 1182 if (so->so_snd.sb_state & SBS_CANTSENDMORE) { 1183 SOCK_SENDBUF_UNLOCK(so); 1184 error = EPIPE; 1185 goto out3; 1186 } 1187 if (so->so_error != 0) { 1188 error = so->so_error; 1189 so->so_error = 0; 1190 SOCK_SENDBUF_UNLOCK(so); 1191 goto out3; 1192 } 1193 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) { 1194 SOCK_SENDBUF_UNLOCK(so); 1195 error = EDESTADDRREQ; 1196 goto out3; 1197 } 1198 SOCK_SENDBUF_UNLOCK(so); 1199 1200 if (addr != NULL) { 1201 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true))) 1202 goto out3; 1203 UNP_PCB_LOCK_ASSERT(unp); 1204 unp2 = unp->unp_conn; 1205 UNP_PCB_LOCK_ASSERT(unp2); 1206 } else { 1207 UNP_PCB_LOCK(unp); 1208 unp2 = unp_pcb_lock_peer(unp); 1209 if (unp2 == NULL) { 1210 UNP_PCB_UNLOCK(unp); 1211 error = ENOTCONN; 1212 goto out3; 1213 } 1214 } 1215 1216 if (unp2->unp_flags & UNP_WANTCRED_MASK) 1217 c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl, 1218 &mbcnt); 1219 if (unp->unp_addr != NULL) 1220 from = (struct sockaddr *)unp->unp_addr; 1221 else 1222 from = &sun_noname; 1223 f->m_len = from->sa_len; 1224 MPASS(from->sa_len <= MLEN); 1225 bcopy(from, mtod(f, void *), from->sa_len); 1226 ctl += f->m_len; 1227 1228 /* 1229 * Concatenate mbufs: from -> control -> data. 1230 * Save overall cc and mbcnt in "from" mbuf. 1231 */ 1232 if (c != NULL) { 1233 #ifdef INVARIANTS 1234 struct mbuf *mc; 1235 1236 for (mc = c; mc->m_next != NULL; mc = mc->m_next); 1237 MPASS(mc == clast); 1238 #endif 1239 f->m_next = c; 1240 clast->m_next = m; 1241 c = NULL; 1242 } else 1243 f->m_next = m; 1244 m = NULL; 1245 #ifdef INVARIANTS 1246 dcc = dctl = dmbcnt = 0; 1247 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) { 1248 if (mb->m_type == MT_DATA) 1249 dcc += mb->m_len; 1250 else 1251 dctl += mb->m_len; 1252 dmbcnt += MSIZE; 1253 if (mb->m_flags & M_EXT) 1254 dmbcnt += mb->m_ext.ext_size; 1255 } 1256 MPASS(dcc == cc); 1257 MPASS(dctl == ctl); 1258 MPASS(dmbcnt == mbcnt); 1259 #endif 1260 f->m_pkthdr.len = cc + ctl; 1261 f->m_pkthdr.memlen = mbcnt; 1262 f->m_pkthdr.ctllen = ctl; 1263 1264 /* 1265 * Destination socket buffer selection. 1266 * 1267 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the 1268 * destination address is supplied, create a temporary connection for 1269 * the run time of the function (see call to unp_connectat() above and 1270 * to unp_disconnect() below). We distinguish them by condition of 1271 * (addr != NULL). We intentionally avoid adding 'bool connected' for 1272 * that condition, since, again, through the run time of this code we 1273 * are always connected. For such "unconnected" sends, the destination 1274 * buffer would be the receive buffer of destination socket so2. 1275 * 1276 * For connected sends, data lands on the send buffer of the sender's 1277 * socket "so". Then, if we just added the very first datagram 1278 * on this send buffer, we need to add the send buffer on to the 1279 * receiving socket's buffer list. We put ourselves on top of the 1280 * list. Such logic gives infrequent senders priority over frequent 1281 * senders. 1282 * 1283 * Note on byte count management. As long as event methods kevent(2), 1284 * select(2) are not protocol specific (yet), we need to maintain 1285 * meaningful values on the receive buffer. So, the receive buffer 1286 * would accumulate counters from all connected buffers potentially 1287 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax. 1288 */ 1289 so2 = unp2->unp_socket; 1290 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv; 1291 SOCK_RECVBUF_LOCK(so2); 1292 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) { 1293 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb)) 1294 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd, 1295 uxdg_clist); 1296 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt); 1297 sb->uxdg_cc += cc + ctl; 1298 sb->uxdg_ctl += ctl; 1299 sb->uxdg_mbcnt += mbcnt; 1300 so2->so_rcv.sb_acc += cc + ctl; 1301 so2->so_rcv.sb_ccc += cc + ctl; 1302 so2->so_rcv.sb_ctl += ctl; 1303 so2->so_rcv.sb_mbcnt += mbcnt; 1304 sorwakeup_locked(so2); 1305 f = NULL; 1306 } else { 1307 soroverflow_locked(so2); 1308 error = ENOBUFS; 1309 if (f->m_next->m_type == MT_CONTROL) { 1310 c = f->m_next; 1311 f->m_next = NULL; 1312 } 1313 } 1314 1315 if (addr != NULL) 1316 unp_disconnect(unp, unp2); 1317 else 1318 unp_pcb_unlock_pair(unp, unp2); 1319 1320 td->td_ru.ru_msgsnd++; 1321 1322 out3: 1323 SOCK_IO_SEND_UNLOCK(so); 1324 out2: 1325 if (c) 1326 unp_scan(c, unp_freerights); 1327 out: 1328 if (f) 1329 m_freem(f); 1330 if (c) 1331 m_freem(c); 1332 if (m) 1333 m_freem(m); 1334 1335 return (error); 1336 } 1337 1338 /* 1339 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK. 1340 * The mbuf has already been unlinked from the uxdg_mb of socket buffer 1341 * and needs to be linked onto uxdg_peeked of receive socket buffer. 1342 */ 1343 static int 1344 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa, 1345 struct uio *uio, struct mbuf **controlp, int *flagsp) 1346 { 1347 ssize_t len = 0; 1348 int error; 1349 1350 so->so_rcv.uxdg_peeked = m; 1351 so->so_rcv.uxdg_cc += m->m_pkthdr.len; 1352 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen; 1353 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen; 1354 SOCK_RECVBUF_UNLOCK(so); 1355 1356 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type)); 1357 if (psa != NULL) 1358 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK); 1359 1360 m = m->m_next; 1361 KASSERT(m, ("%s: no data or control after soname", __func__)); 1362 1363 /* 1364 * With MSG_PEEK the control isn't executed, just copied. 1365 */ 1366 while (m != NULL && m->m_type == MT_CONTROL) { 1367 if (controlp != NULL) { 1368 *controlp = m_copym(m, 0, m->m_len, M_WAITOK); 1369 controlp = &(*controlp)->m_next; 1370 } 1371 m = m->m_next; 1372 } 1373 KASSERT(m == NULL || m->m_type == MT_DATA, 1374 ("%s: not MT_DATA mbuf %p", __func__, m)); 1375 while (m != NULL && uio->uio_resid > 0) { 1376 len = uio->uio_resid; 1377 if (len > m->m_len) 1378 len = m->m_len; 1379 error = uiomove(mtod(m, char *), (int)len, uio); 1380 if (error) { 1381 SOCK_IO_RECV_UNLOCK(so); 1382 return (error); 1383 } 1384 if (len == m->m_len) 1385 m = m->m_next; 1386 } 1387 SOCK_IO_RECV_UNLOCK(so); 1388 1389 if (flagsp != NULL) { 1390 if (m != NULL) { 1391 if (*flagsp & MSG_TRUNC) { 1392 /* Report real length of the packet */ 1393 uio->uio_resid -= m_length(m, NULL) - len; 1394 } 1395 *flagsp |= MSG_TRUNC; 1396 } else 1397 *flagsp &= ~MSG_TRUNC; 1398 } 1399 1400 return (0); 1401 } 1402 1403 /* 1404 * PF_UNIX/SOCK_DGRAM receive 1405 */ 1406 static int 1407 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio, 1408 struct mbuf **mp0, struct mbuf **controlp, int *flagsp) 1409 { 1410 struct sockbuf *sb = NULL; 1411 struct mbuf *m; 1412 int flags, error; 1413 ssize_t len = 0; 1414 bool nonblock; 1415 1416 MPASS(mp0 == NULL); 1417 1418 if (psa != NULL) 1419 *psa = NULL; 1420 if (controlp != NULL) 1421 *controlp = NULL; 1422 1423 flags = flagsp != NULL ? *flagsp : 0; 1424 nonblock = (so->so_state & SS_NBIO) || 1425 (flags & (MSG_DONTWAIT | MSG_NBIO)); 1426 1427 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags)); 1428 if (__predict_false(error)) 1429 return (error); 1430 1431 /* 1432 * Loop blocking while waiting for a datagram. Prioritize connected 1433 * peers over unconnected sends. Set sb to selected socket buffer 1434 * containing an mbuf on exit from the wait loop. A datagram that 1435 * had already been peeked at has top priority. 1436 */ 1437 SOCK_RECVBUF_LOCK(so); 1438 while ((m = so->so_rcv.uxdg_peeked) == NULL && 1439 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL && 1440 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) { 1441 if (so->so_error) { 1442 error = so->so_error; 1443 so->so_error = 0; 1444 SOCK_RECVBUF_UNLOCK(so); 1445 SOCK_IO_RECV_UNLOCK(so); 1446 return (error); 1447 } 1448 if (so->so_rcv.sb_state & SBS_CANTRCVMORE || 1449 uio->uio_resid == 0) { 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 if (sb == NULL) 1468 sb = &so->so_rcv; 1469 else if (m == NULL) 1470 m = STAILQ_FIRST(&sb->uxdg_mb); 1471 else 1472 MPASS(m == so->so_rcv.uxdg_peeked); 1473 1474 MPASS(sb->uxdg_cc > 0); 1475 M_ASSERTPKTHDR(m); 1476 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type)); 1477 1478 if (uio->uio_td) 1479 uio->uio_td->td_ru.ru_msgrcv++; 1480 1481 if (__predict_true(m != so->so_rcv.uxdg_peeked)) { 1482 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt); 1483 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv) 1484 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist); 1485 } else 1486 so->so_rcv.uxdg_peeked = NULL; 1487 1488 sb->uxdg_cc -= m->m_pkthdr.len; 1489 sb->uxdg_ctl -= m->m_pkthdr.ctllen; 1490 sb->uxdg_mbcnt -= m->m_pkthdr.memlen; 1491 1492 if (__predict_false(flags & MSG_PEEK)) 1493 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp)); 1494 1495 so->so_rcv.sb_acc -= m->m_pkthdr.len; 1496 so->so_rcv.sb_ccc -= m->m_pkthdr.len; 1497 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen; 1498 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen; 1499 SOCK_RECVBUF_UNLOCK(so); 1500 1501 if (psa != NULL) 1502 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK); 1503 m = m_free(m); 1504 KASSERT(m, ("%s: no data or control after soname", __func__)); 1505 1506 /* 1507 * Packet to copyout() is now in 'm' and it is disconnected from the 1508 * queue. 1509 * 1510 * Process one or more MT_CONTROL mbufs present before any data mbufs 1511 * in the first mbuf chain on the socket buffer. We call into the 1512 * unp_externalize() to perform externalization (or freeing if 1513 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs 1514 * without MT_DATA mbufs. 1515 */ 1516 while (m != NULL && m->m_type == MT_CONTROL) { 1517 struct mbuf *cm; 1518 1519 /* XXXGL: unp_externalize() is also dom_externalize() KBI and 1520 * it frees whole chain, so we must disconnect the mbuf. 1521 */ 1522 cm = m; m = m->m_next; cm->m_next = NULL; 1523 error = unp_externalize(cm, controlp, flags); 1524 if (error != 0) { 1525 SOCK_IO_RECV_UNLOCK(so); 1526 unp_scan(m, unp_freerights); 1527 m_freem(m); 1528 return (error); 1529 } 1530 if (controlp != NULL) { 1531 while (*controlp != NULL) 1532 controlp = &(*controlp)->m_next; 1533 } 1534 } 1535 KASSERT(m == NULL || m->m_type == MT_DATA, 1536 ("%s: not MT_DATA mbuf %p", __func__, m)); 1537 while (m != NULL && uio->uio_resid > 0) { 1538 len = uio->uio_resid; 1539 if (len > m->m_len) 1540 len = m->m_len; 1541 error = uiomove(mtod(m, char *), (int)len, uio); 1542 if (error) { 1543 SOCK_IO_RECV_UNLOCK(so); 1544 m_freem(m); 1545 return (error); 1546 } 1547 if (len == m->m_len) 1548 m = m_free(m); 1549 else { 1550 m->m_data += len; 1551 m->m_len -= len; 1552 } 1553 } 1554 SOCK_IO_RECV_UNLOCK(so); 1555 1556 if (m != NULL) { 1557 if (flagsp != NULL) { 1558 if (flags & MSG_TRUNC) { 1559 /* Report real length of the packet */ 1560 uio->uio_resid -= m_length(m, NULL); 1561 } 1562 *flagsp |= MSG_TRUNC; 1563 } 1564 m_freem(m); 1565 } else if (flagsp != NULL) 1566 *flagsp &= ~MSG_TRUNC; 1567 1568 return (0); 1569 } 1570 1571 static bool 1572 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp) 1573 { 1574 struct mbuf *mb, *n; 1575 struct sockbuf *sb; 1576 1577 SOCK_LOCK(so); 1578 if (SOLISTENING(so)) { 1579 SOCK_UNLOCK(so); 1580 return (false); 1581 } 1582 mb = NULL; 1583 sb = &so->so_rcv; 1584 SOCKBUF_LOCK(sb); 1585 if (sb->sb_fnrdy != NULL) { 1586 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) { 1587 if (mb == m) { 1588 *errorp = sbready(sb, m, count); 1589 break; 1590 } 1591 mb = mb->m_next; 1592 if (mb == NULL) { 1593 mb = n; 1594 if (mb != NULL) 1595 n = mb->m_nextpkt; 1596 } 1597 } 1598 } 1599 SOCKBUF_UNLOCK(sb); 1600 SOCK_UNLOCK(so); 1601 return (mb != NULL); 1602 } 1603 1604 static int 1605 uipc_ready(struct socket *so, struct mbuf *m, int count) 1606 { 1607 struct unpcb *unp, *unp2; 1608 struct socket *so2; 1609 int error, i; 1610 1611 unp = sotounpcb(so); 1612 1613 KASSERT(so->so_type == SOCK_STREAM, 1614 ("%s: unexpected socket type for %p", __func__, so)); 1615 1616 UNP_PCB_LOCK(unp); 1617 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) { 1618 UNP_PCB_UNLOCK(unp); 1619 so2 = unp2->unp_socket; 1620 SOCKBUF_LOCK(&so2->so_rcv); 1621 if ((error = sbready(&so2->so_rcv, m, count)) == 0) 1622 sorwakeup_locked(so2); 1623 else 1624 SOCKBUF_UNLOCK(&so2->so_rcv); 1625 UNP_PCB_UNLOCK(unp2); 1626 return (error); 1627 } 1628 UNP_PCB_UNLOCK(unp); 1629 1630 /* 1631 * The receiving socket has been disconnected, but may still be valid. 1632 * In this case, the now-ready mbufs are still present in its socket 1633 * buffer, so perform an exhaustive search before giving up and freeing 1634 * the mbufs. 1635 */ 1636 UNP_LINK_RLOCK(); 1637 LIST_FOREACH(unp, &unp_shead, unp_link) { 1638 if (uipc_ready_scan(unp->unp_socket, m, count, &error)) 1639 break; 1640 } 1641 UNP_LINK_RUNLOCK(); 1642 1643 if (unp == NULL) { 1644 for (i = 0; i < count; i++) 1645 m = m_free(m); 1646 error = ECONNRESET; 1647 } 1648 return (error); 1649 } 1650 1651 static int 1652 uipc_sense(struct socket *so, struct stat *sb) 1653 { 1654 struct unpcb *unp; 1655 1656 unp = sotounpcb(so); 1657 KASSERT(unp != NULL, ("uipc_sense: unp == NULL")); 1658 1659 sb->st_blksize = so->so_snd.sb_hiwat; 1660 sb->st_dev = NODEV; 1661 sb->st_ino = unp->unp_ino; 1662 return (0); 1663 } 1664 1665 static int 1666 uipc_shutdown(struct socket *so, enum shutdown_how how) 1667 { 1668 struct unpcb *unp = sotounpcb(so); 1669 int error; 1670 1671 SOCK_LOCK(so); 1672 if ((so->so_state & 1673 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) { 1674 /* 1675 * POSIX mandates us to just return ENOTCONN when shutdown(2) is 1676 * invoked on a datagram sockets, however historically we would 1677 * actually tear socket down. This is known to be leveraged by 1678 * some applications to unblock process waiting in recv(2) by 1679 * other process that it shares that socket with. Try to meet 1680 * both backward-compatibility and POSIX requirements by forcing 1681 * ENOTCONN but still flushing buffers and performing wakeup(9). 1682 * 1683 * XXXGL: it remains unknown what applications expect this 1684 * behavior and is this isolated to unix/dgram or inet/dgram or 1685 * both. See: D10351, D3039. 1686 */ 1687 error = ENOTCONN; 1688 if (so->so_type != SOCK_DGRAM) { 1689 SOCK_UNLOCK(so); 1690 return (error); 1691 } 1692 } else 1693 error = 0; 1694 if (SOLISTENING(so)) { 1695 if (how != SHUT_WR) { 1696 so->so_error = ECONNABORTED; 1697 solisten_wakeup(so); /* unlocks so */ 1698 } else 1699 SOCK_UNLOCK(so); 1700 return (0); 1701 } 1702 SOCK_UNLOCK(so); 1703 1704 switch (how) { 1705 case SHUT_RD: 1706 socantrcvmore(so); 1707 unp_dispose(so); 1708 break; 1709 case SHUT_RDWR: 1710 socantrcvmore(so); 1711 unp_dispose(so); 1712 /* FALLTHROUGH */ 1713 case SHUT_WR: 1714 UNP_PCB_LOCK(unp); 1715 socantsendmore(so); 1716 unp_shutdown(unp); 1717 UNP_PCB_UNLOCK(unp); 1718 } 1719 wakeup(&so->so_timeo); 1720 1721 return (error); 1722 } 1723 1724 static int 1725 uipc_sockaddr(struct socket *so, struct sockaddr *ret) 1726 { 1727 struct unpcb *unp; 1728 const struct sockaddr *sa; 1729 1730 unp = sotounpcb(so); 1731 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL")); 1732 1733 UNP_PCB_LOCK(unp); 1734 if (unp->unp_addr != NULL) 1735 sa = (struct sockaddr *) unp->unp_addr; 1736 else 1737 sa = &sun_noname; 1738 bcopy(sa, ret, sa->sa_len); 1739 UNP_PCB_UNLOCK(unp); 1740 return (0); 1741 } 1742 1743 static int 1744 uipc_ctloutput(struct socket *so, struct sockopt *sopt) 1745 { 1746 struct unpcb *unp; 1747 struct xucred xu; 1748 int error, optval; 1749 1750 if (sopt->sopt_level != SOL_LOCAL) 1751 return (EINVAL); 1752 1753 unp = sotounpcb(so); 1754 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL")); 1755 error = 0; 1756 switch (sopt->sopt_dir) { 1757 case SOPT_GET: 1758 switch (sopt->sopt_name) { 1759 case LOCAL_PEERCRED: 1760 UNP_PCB_LOCK(unp); 1761 if (unp->unp_flags & UNP_HAVEPC) 1762 xu = unp->unp_peercred; 1763 else { 1764 if (so->so_type == SOCK_STREAM) 1765 error = ENOTCONN; 1766 else 1767 error = EINVAL; 1768 } 1769 UNP_PCB_UNLOCK(unp); 1770 if (error == 0) 1771 error = sooptcopyout(sopt, &xu, sizeof(xu)); 1772 break; 1773 1774 case LOCAL_CREDS: 1775 /* Unlocked read. */ 1776 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0; 1777 error = sooptcopyout(sopt, &optval, sizeof(optval)); 1778 break; 1779 1780 case LOCAL_CREDS_PERSISTENT: 1781 /* Unlocked read. */ 1782 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0; 1783 error = sooptcopyout(sopt, &optval, sizeof(optval)); 1784 break; 1785 1786 case LOCAL_CONNWAIT: 1787 /* Unlocked read. */ 1788 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0; 1789 error = sooptcopyout(sopt, &optval, sizeof(optval)); 1790 break; 1791 1792 default: 1793 error = EOPNOTSUPP; 1794 break; 1795 } 1796 break; 1797 1798 case SOPT_SET: 1799 switch (sopt->sopt_name) { 1800 case LOCAL_CREDS: 1801 case LOCAL_CREDS_PERSISTENT: 1802 case LOCAL_CONNWAIT: 1803 error = sooptcopyin(sopt, &optval, sizeof(optval), 1804 sizeof(optval)); 1805 if (error) 1806 break; 1807 1808 #define OPTSET(bit, exclusive) do { \ 1809 UNP_PCB_LOCK(unp); \ 1810 if (optval) { \ 1811 if ((unp->unp_flags & (exclusive)) != 0) { \ 1812 UNP_PCB_UNLOCK(unp); \ 1813 error = EINVAL; \ 1814 break; \ 1815 } \ 1816 unp->unp_flags |= (bit); \ 1817 } else \ 1818 unp->unp_flags &= ~(bit); \ 1819 UNP_PCB_UNLOCK(unp); \ 1820 } while (0) 1821 1822 switch (sopt->sopt_name) { 1823 case LOCAL_CREDS: 1824 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS); 1825 break; 1826 1827 case LOCAL_CREDS_PERSISTENT: 1828 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT); 1829 break; 1830 1831 case LOCAL_CONNWAIT: 1832 OPTSET(UNP_CONNWAIT, 0); 1833 break; 1834 1835 default: 1836 break; 1837 } 1838 break; 1839 #undef OPTSET 1840 default: 1841 error = ENOPROTOOPT; 1842 break; 1843 } 1844 break; 1845 1846 default: 1847 error = EOPNOTSUPP; 1848 break; 1849 } 1850 return (error); 1851 } 1852 1853 static int 1854 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td) 1855 { 1856 1857 return (unp_connectat(AT_FDCWD, so, nam, td, false)); 1858 } 1859 1860 static int 1861 unp_connectat(int fd, struct socket *so, struct sockaddr *nam, 1862 struct thread *td, bool return_locked) 1863 { 1864 struct mtx *vplock; 1865 struct sockaddr_un *soun; 1866 struct vnode *vp; 1867 struct socket *so2; 1868 struct unpcb *unp, *unp2, *unp3; 1869 struct nameidata nd; 1870 char buf[SOCK_MAXADDRLEN]; 1871 struct sockaddr *sa; 1872 cap_rights_t rights; 1873 int error, len; 1874 bool connreq; 1875 1876 if (nam->sa_family != AF_UNIX) 1877 return (EAFNOSUPPORT); 1878 if (nam->sa_len > sizeof(struct sockaddr_un)) 1879 return (EINVAL); 1880 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path); 1881 if (len <= 0) 1882 return (EINVAL); 1883 soun = (struct sockaddr_un *)nam; 1884 bcopy(soun->sun_path, buf, len); 1885 buf[len] = 0; 1886 1887 error = 0; 1888 unp = sotounpcb(so); 1889 UNP_PCB_LOCK(unp); 1890 for (;;) { 1891 /* 1892 * Wait for connection state to stabilize. If a connection 1893 * already exists, give up. For datagram sockets, which permit 1894 * multiple consecutive connect(2) calls, upper layers are 1895 * responsible for disconnecting in advance of a subsequent 1896 * connect(2), but this is not synchronized with PCB connection 1897 * state. 1898 * 1899 * Also make sure that no threads are currently attempting to 1900 * lock the peer socket, to ensure that unp_conn cannot 1901 * transition between two valid sockets while locks are dropped. 1902 */ 1903 if (SOLISTENING(so)) 1904 error = EOPNOTSUPP; 1905 else if (unp->unp_conn != NULL) 1906 error = EISCONN; 1907 else if ((unp->unp_flags & UNP_CONNECTING) != 0) { 1908 error = EALREADY; 1909 } 1910 if (error != 0) { 1911 UNP_PCB_UNLOCK(unp); 1912 return (error); 1913 } 1914 if (unp->unp_pairbusy > 0) { 1915 unp->unp_flags |= UNP_WAITING; 1916 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0); 1917 continue; 1918 } 1919 break; 1920 } 1921 unp->unp_flags |= UNP_CONNECTING; 1922 UNP_PCB_UNLOCK(unp); 1923 1924 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0; 1925 if (connreq) 1926 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK); 1927 else 1928 sa = NULL; 1929 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, 1930 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT)); 1931 error = namei(&nd); 1932 if (error) 1933 vp = NULL; 1934 else 1935 vp = nd.ni_vp; 1936 ASSERT_VOP_LOCKED(vp, "unp_connect"); 1937 if (error) 1938 goto bad; 1939 NDFREE_PNBUF(&nd); 1940 1941 if (vp->v_type != VSOCK) { 1942 error = ENOTSOCK; 1943 goto bad; 1944 } 1945 #ifdef MAC 1946 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD); 1947 if (error) 1948 goto bad; 1949 #endif 1950 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td); 1951 if (error) 1952 goto bad; 1953 1954 unp = sotounpcb(so); 1955 KASSERT(unp != NULL, ("unp_connect: unp == NULL")); 1956 1957 vplock = mtx_pool_find(mtxpool_sleep, vp); 1958 mtx_lock(vplock); 1959 VOP_UNP_CONNECT(vp, &unp2); 1960 if (unp2 == NULL) { 1961 error = ECONNREFUSED; 1962 goto bad2; 1963 } 1964 so2 = unp2->unp_socket; 1965 if (so->so_type != so2->so_type) { 1966 error = EPROTOTYPE; 1967 goto bad2; 1968 } 1969 if (connreq) { 1970 if (SOLISTENING(so2)) { 1971 CURVNET_SET(so2->so_vnet); 1972 so2 = sonewconn(so2, 0); 1973 CURVNET_RESTORE(); 1974 } else 1975 so2 = NULL; 1976 if (so2 == NULL) { 1977 error = ECONNREFUSED; 1978 goto bad2; 1979 } 1980 unp3 = sotounpcb(so2); 1981 unp_pcb_lock_pair(unp2, unp3); 1982 if (unp2->unp_addr != NULL) { 1983 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len); 1984 unp3->unp_addr = (struct sockaddr_un *) sa; 1985 sa = NULL; 1986 } 1987 1988 unp_copy_peercred(td, unp3, unp, unp2); 1989 1990 UNP_PCB_UNLOCK(unp2); 1991 unp2 = unp3; 1992 1993 /* 1994 * It is safe to block on the PCB lock here since unp2 is 1995 * nascent and cannot be connected to any other sockets. 1996 */ 1997 UNP_PCB_LOCK(unp); 1998 #ifdef MAC 1999 mac_socketpeer_set_from_socket(so, so2); 2000 mac_socketpeer_set_from_socket(so2, so); 2001 #endif 2002 } else { 2003 unp_pcb_lock_pair(unp, unp2); 2004 } 2005 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 && 2006 sotounpcb(so2) == unp2, 2007 ("%s: unp2 %p so2 %p", __func__, unp2, so2)); 2008 unp_connect2(so, so2, PRU_CONNECT); 2009 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0, 2010 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp)); 2011 unp->unp_flags &= ~UNP_CONNECTING; 2012 if (!return_locked) 2013 unp_pcb_unlock_pair(unp, unp2); 2014 bad2: 2015 mtx_unlock(vplock); 2016 bad: 2017 if (vp != NULL) { 2018 /* 2019 * If we are returning locked (called via uipc_sosend_dgram()), 2020 * we need to be sure that vput() won't sleep. This is 2021 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock. 2022 * SOCK_STREAM/SEQPACKET can't request return_locked (yet). 2023 */ 2024 MPASS(!(return_locked && connreq)); 2025 vput(vp); 2026 } 2027 free(sa, M_SONAME); 2028 if (__predict_false(error)) { 2029 UNP_PCB_LOCK(unp); 2030 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0, 2031 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp)); 2032 unp->unp_flags &= ~UNP_CONNECTING; 2033 UNP_PCB_UNLOCK(unp); 2034 } 2035 return (error); 2036 } 2037 2038 /* 2039 * Set socket peer credentials at connection time. 2040 * 2041 * The client's PCB credentials are copied from its process structure. The 2042 * server's PCB credentials are copied from the socket on which it called 2043 * listen(2). uipc_listen cached that process's credentials at the time. 2044 */ 2045 void 2046 unp_copy_peercred(struct thread *td, struct unpcb *client_unp, 2047 struct unpcb *server_unp, struct unpcb *listen_unp) 2048 { 2049 cru2xt(td, &client_unp->unp_peercred); 2050 client_unp->unp_flags |= UNP_HAVEPC; 2051 2052 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred, 2053 sizeof(server_unp->unp_peercred)); 2054 server_unp->unp_flags |= UNP_HAVEPC; 2055 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK); 2056 } 2057 2058 static void 2059 unp_connect2(struct socket *so, struct socket *so2, conn2_how req) 2060 { 2061 struct unpcb *unp; 2062 struct unpcb *unp2; 2063 2064 MPASS(so2->so_type == so->so_type); 2065 unp = sotounpcb(so); 2066 KASSERT(unp != NULL, ("unp_connect2: unp == NULL")); 2067 unp2 = sotounpcb(so2); 2068 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL")); 2069 2070 UNP_PCB_LOCK_ASSERT(unp); 2071 UNP_PCB_LOCK_ASSERT(unp2); 2072 KASSERT(unp->unp_conn == NULL, 2073 ("%s: socket %p is already connected", __func__, unp)); 2074 2075 unp->unp_conn = unp2; 2076 unp_pcb_hold(unp2); 2077 unp_pcb_hold(unp); 2078 switch (so->so_type) { 2079 case SOCK_DGRAM: 2080 UNP_REF_LIST_LOCK(); 2081 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink); 2082 UNP_REF_LIST_UNLOCK(); 2083 soisconnected(so); 2084 break; 2085 2086 case SOCK_STREAM: 2087 case SOCK_SEQPACKET: 2088 KASSERT(unp2->unp_conn == NULL, 2089 ("%s: socket %p is already connected", __func__, unp2)); 2090 unp2->unp_conn = unp; 2091 if (req == PRU_CONNECT && 2092 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT)) 2093 soisconnecting(so); 2094 else 2095 soisconnected(so); 2096 soisconnected(so2); 2097 break; 2098 2099 default: 2100 panic("unp_connect2"); 2101 } 2102 } 2103 2104 static void 2105 unp_disconnect(struct unpcb *unp, struct unpcb *unp2) 2106 { 2107 struct socket *so, *so2; 2108 struct mbuf *m = NULL; 2109 #ifdef INVARIANTS 2110 struct unpcb *unptmp; 2111 #endif 2112 2113 UNP_PCB_LOCK_ASSERT(unp); 2114 UNP_PCB_LOCK_ASSERT(unp2); 2115 KASSERT(unp->unp_conn == unp2, 2116 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2)); 2117 2118 unp->unp_conn = NULL; 2119 so = unp->unp_socket; 2120 so2 = unp2->unp_socket; 2121 switch (unp->unp_socket->so_type) { 2122 case SOCK_DGRAM: 2123 /* 2124 * Remove our send socket buffer from the peer's receive buffer. 2125 * Move the data to the receive buffer only if it is empty. 2126 * This is a protection against a scenario where a peer 2127 * connects, floods and disconnects, effectively blocking 2128 * sendto() from unconnected sockets. 2129 */ 2130 SOCK_RECVBUF_LOCK(so2); 2131 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) { 2132 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd, 2133 uxdg_clist); 2134 if (__predict_true((so2->so_rcv.sb_state & 2135 SBS_CANTRCVMORE) == 0) && 2136 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) { 2137 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb, 2138 &so->so_snd.uxdg_mb); 2139 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc; 2140 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl; 2141 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt; 2142 } else { 2143 m = STAILQ_FIRST(&so->so_snd.uxdg_mb); 2144 STAILQ_INIT(&so->so_snd.uxdg_mb); 2145 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc; 2146 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc; 2147 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl; 2148 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt; 2149 } 2150 /* Note: so may reconnect. */ 2151 so->so_snd.uxdg_cc = 0; 2152 so->so_snd.uxdg_ctl = 0; 2153 so->so_snd.uxdg_mbcnt = 0; 2154 } 2155 SOCK_RECVBUF_UNLOCK(so2); 2156 UNP_REF_LIST_LOCK(); 2157 #ifdef INVARIANTS 2158 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) { 2159 if (unptmp == unp) 2160 break; 2161 } 2162 KASSERT(unptmp != NULL, 2163 ("%s: %p not found in reflist of %p", __func__, unp, unp2)); 2164 #endif 2165 LIST_REMOVE(unp, unp_reflink); 2166 UNP_REF_LIST_UNLOCK(); 2167 if (so) { 2168 SOCK_LOCK(so); 2169 so->so_state &= ~SS_ISCONNECTED; 2170 SOCK_UNLOCK(so); 2171 } 2172 break; 2173 2174 case SOCK_STREAM: 2175 case SOCK_SEQPACKET: 2176 if (so) 2177 soisdisconnected(so); 2178 MPASS(unp2->unp_conn == unp); 2179 unp2->unp_conn = NULL; 2180 if (so2) 2181 soisdisconnected(so2); 2182 break; 2183 } 2184 2185 if (unp == unp2) { 2186 unp_pcb_rele_notlast(unp); 2187 if (!unp_pcb_rele(unp)) 2188 UNP_PCB_UNLOCK(unp); 2189 } else { 2190 if (!unp_pcb_rele(unp)) 2191 UNP_PCB_UNLOCK(unp); 2192 if (!unp_pcb_rele(unp2)) 2193 UNP_PCB_UNLOCK(unp2); 2194 } 2195 2196 if (m != NULL) { 2197 unp_scan(m, unp_freerights); 2198 m_freem(m); 2199 } 2200 } 2201 2202 /* 2203 * unp_pcblist() walks the global list of struct unpcb's to generate a 2204 * pointer list, bumping the refcount on each unpcb. It then copies them out 2205 * sequentially, validating the generation number on each to see if it has 2206 * been detached. All of this is necessary because copyout() may sleep on 2207 * disk I/O. 2208 */ 2209 static int 2210 unp_pcblist(SYSCTL_HANDLER_ARGS) 2211 { 2212 struct unpcb *unp, **unp_list; 2213 unp_gen_t gencnt; 2214 struct xunpgen *xug; 2215 struct unp_head *head; 2216 struct xunpcb *xu; 2217 u_int i; 2218 int error, n; 2219 2220 switch ((intptr_t)arg1) { 2221 case SOCK_STREAM: 2222 head = &unp_shead; 2223 break; 2224 2225 case SOCK_DGRAM: 2226 head = &unp_dhead; 2227 break; 2228 2229 case SOCK_SEQPACKET: 2230 head = &unp_sphead; 2231 break; 2232 2233 default: 2234 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1); 2235 } 2236 2237 /* 2238 * The process of preparing the PCB list is too time-consuming and 2239 * resource-intensive to repeat twice on every request. 2240 */ 2241 if (req->oldptr == NULL) { 2242 n = unp_count; 2243 req->oldidx = 2 * (sizeof *xug) 2244 + (n + n/8) * sizeof(struct xunpcb); 2245 return (0); 2246 } 2247 2248 if (req->newptr != NULL) 2249 return (EPERM); 2250 2251 /* 2252 * OK, now we're committed to doing something. 2253 */ 2254 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO); 2255 UNP_LINK_RLOCK(); 2256 gencnt = unp_gencnt; 2257 n = unp_count; 2258 UNP_LINK_RUNLOCK(); 2259 2260 xug->xug_len = sizeof *xug; 2261 xug->xug_count = n; 2262 xug->xug_gen = gencnt; 2263 xug->xug_sogen = so_gencnt; 2264 error = SYSCTL_OUT(req, xug, sizeof *xug); 2265 if (error) { 2266 free(xug, M_TEMP); 2267 return (error); 2268 } 2269 2270 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK); 2271 2272 UNP_LINK_RLOCK(); 2273 for (unp = LIST_FIRST(head), i = 0; unp && i < n; 2274 unp = LIST_NEXT(unp, unp_link)) { 2275 UNP_PCB_LOCK(unp); 2276 if (unp->unp_gencnt <= gencnt) { 2277 if (cr_cansee(req->td->td_ucred, 2278 unp->unp_socket->so_cred)) { 2279 UNP_PCB_UNLOCK(unp); 2280 continue; 2281 } 2282 unp_list[i++] = unp; 2283 unp_pcb_hold(unp); 2284 } 2285 UNP_PCB_UNLOCK(unp); 2286 } 2287 UNP_LINK_RUNLOCK(); 2288 n = i; /* In case we lost some during malloc. */ 2289 2290 error = 0; 2291 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO); 2292 for (i = 0; i < n; i++) { 2293 unp = unp_list[i]; 2294 UNP_PCB_LOCK(unp); 2295 if (unp_pcb_rele(unp)) 2296 continue; 2297 2298 if (unp->unp_gencnt <= gencnt) { 2299 xu->xu_len = sizeof *xu; 2300 xu->xu_unpp = (uintptr_t)unp; 2301 /* 2302 * XXX - need more locking here to protect against 2303 * connect/disconnect races for SMP. 2304 */ 2305 if (unp->unp_addr != NULL) 2306 bcopy(unp->unp_addr, &xu->xu_addr, 2307 unp->unp_addr->sun_len); 2308 else 2309 bzero(&xu->xu_addr, sizeof(xu->xu_addr)); 2310 if (unp->unp_conn != NULL && 2311 unp->unp_conn->unp_addr != NULL) 2312 bcopy(unp->unp_conn->unp_addr, 2313 &xu->xu_caddr, 2314 unp->unp_conn->unp_addr->sun_len); 2315 else 2316 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr)); 2317 xu->unp_vnode = (uintptr_t)unp->unp_vnode; 2318 xu->unp_conn = (uintptr_t)unp->unp_conn; 2319 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs); 2320 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink); 2321 xu->unp_gencnt = unp->unp_gencnt; 2322 sotoxsocket(unp->unp_socket, &xu->xu_socket); 2323 UNP_PCB_UNLOCK(unp); 2324 error = SYSCTL_OUT(req, xu, sizeof *xu); 2325 } else { 2326 UNP_PCB_UNLOCK(unp); 2327 } 2328 } 2329 free(xu, M_TEMP); 2330 if (!error) { 2331 /* 2332 * Give the user an updated idea of our state. If the 2333 * generation differs from what we told her before, she knows 2334 * that something happened while we were processing this 2335 * request, and it might be necessary to retry. 2336 */ 2337 xug->xug_gen = unp_gencnt; 2338 xug->xug_sogen = so_gencnt; 2339 xug->xug_count = unp_count; 2340 error = SYSCTL_OUT(req, xug, sizeof *xug); 2341 } 2342 free(unp_list, M_TEMP); 2343 free(xug, M_TEMP); 2344 return (error); 2345 } 2346 2347 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, 2348 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 2349 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb", 2350 "List of active local datagram sockets"); 2351 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, 2352 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 2353 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb", 2354 "List of active local stream sockets"); 2355 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist, 2356 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, 2357 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb", 2358 "List of active local seqpacket sockets"); 2359 2360 static void 2361 unp_shutdown(struct unpcb *unp) 2362 { 2363 struct unpcb *unp2; 2364 struct socket *so; 2365 2366 UNP_PCB_LOCK_ASSERT(unp); 2367 2368 unp2 = unp->unp_conn; 2369 if ((unp->unp_socket->so_type == SOCK_STREAM || 2370 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) { 2371 so = unp2->unp_socket; 2372 if (so != NULL) 2373 socantrcvmore(so); 2374 } 2375 } 2376 2377 static void 2378 unp_drop(struct unpcb *unp) 2379 { 2380 struct socket *so; 2381 struct unpcb *unp2; 2382 2383 /* 2384 * Regardless of whether the socket's peer dropped the connection 2385 * with this socket by aborting or disconnecting, POSIX requires 2386 * that ECONNRESET is returned. 2387 */ 2388 2389 UNP_PCB_LOCK(unp); 2390 so = unp->unp_socket; 2391 if (so) 2392 so->so_error = ECONNRESET; 2393 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) { 2394 /* Last reference dropped in unp_disconnect(). */ 2395 unp_pcb_rele_notlast(unp); 2396 unp_disconnect(unp, unp2); 2397 } else if (!unp_pcb_rele(unp)) { 2398 UNP_PCB_UNLOCK(unp); 2399 } 2400 } 2401 2402 static void 2403 unp_freerights(struct filedescent **fdep, int fdcount) 2404 { 2405 struct file *fp; 2406 int i; 2407 2408 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount)); 2409 2410 for (i = 0; i < fdcount; i++) { 2411 fp = fdep[i]->fde_file; 2412 filecaps_free(&fdep[i]->fde_caps); 2413 unp_discard(fp); 2414 } 2415 free(fdep[0], M_FILECAPS); 2416 } 2417 2418 static int 2419 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags) 2420 { 2421 struct thread *td = curthread; /* XXX */ 2422 struct cmsghdr *cm = mtod(control, struct cmsghdr *); 2423 int i; 2424 int *fdp; 2425 struct filedesc *fdesc = td->td_proc->p_fd; 2426 struct filedescent **fdep; 2427 void *data; 2428 socklen_t clen = control->m_len, datalen; 2429 int error, newfds; 2430 u_int newlen; 2431 2432 UNP_LINK_UNLOCK_ASSERT(); 2433 2434 error = 0; 2435 if (controlp != NULL) /* controlp == NULL => free control messages */ 2436 *controlp = NULL; 2437 while (cm != NULL) { 2438 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len); 2439 2440 data = CMSG_DATA(cm); 2441 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data; 2442 if (cm->cmsg_level == SOL_SOCKET 2443 && cm->cmsg_type == SCM_RIGHTS) { 2444 newfds = datalen / sizeof(*fdep); 2445 if (newfds == 0) 2446 goto next; 2447 fdep = data; 2448 2449 /* If we're not outputting the descriptors free them. */ 2450 if (error || controlp == NULL) { 2451 unp_freerights(fdep, newfds); 2452 goto next; 2453 } 2454 FILEDESC_XLOCK(fdesc); 2455 2456 /* 2457 * Now change each pointer to an fd in the global 2458 * table to an integer that is the index to the local 2459 * fd table entry that we set up to point to the 2460 * global one we are transferring. 2461 */ 2462 newlen = newfds * sizeof(int); 2463 *controlp = sbcreatecontrol(NULL, newlen, 2464 SCM_RIGHTS, SOL_SOCKET, M_WAITOK); 2465 2466 fdp = (int *) 2467 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2468 if ((error = fdallocn(td, 0, fdp, newfds))) { 2469 FILEDESC_XUNLOCK(fdesc); 2470 unp_freerights(fdep, newfds); 2471 m_freem(*controlp); 2472 *controlp = NULL; 2473 goto next; 2474 } 2475 for (i = 0; i < newfds; i++, fdp++) { 2476 _finstall(fdesc, fdep[i]->fde_file, *fdp, 2477 (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0, 2478 &fdep[i]->fde_caps); 2479 unp_externalize_fp(fdep[i]->fde_file); 2480 } 2481 2482 /* 2483 * The new type indicates that the mbuf data refers to 2484 * kernel resources that may need to be released before 2485 * the mbuf is freed. 2486 */ 2487 m_chtype(*controlp, MT_EXTCONTROL); 2488 FILEDESC_XUNLOCK(fdesc); 2489 free(fdep[0], M_FILECAPS); 2490 } else { 2491 /* We can just copy anything else across. */ 2492 if (error || controlp == NULL) 2493 goto next; 2494 *controlp = sbcreatecontrol(NULL, datalen, 2495 cm->cmsg_type, cm->cmsg_level, M_WAITOK); 2496 bcopy(data, 2497 CMSG_DATA(mtod(*controlp, struct cmsghdr *)), 2498 datalen); 2499 } 2500 controlp = &(*controlp)->m_next; 2501 2502 next: 2503 if (CMSG_SPACE(datalen) < clen) { 2504 clen -= CMSG_SPACE(datalen); 2505 cm = (struct cmsghdr *) 2506 ((caddr_t)cm + CMSG_SPACE(datalen)); 2507 } else { 2508 clen = 0; 2509 cm = NULL; 2510 } 2511 } 2512 2513 m_freem(control); 2514 return (error); 2515 } 2516 2517 static void 2518 unp_zone_change(void *tag) 2519 { 2520 2521 uma_zone_set_max(unp_zone, maxsockets); 2522 } 2523 2524 #ifdef INVARIANTS 2525 static void 2526 unp_zdtor(void *mem, int size __unused, void *arg __unused) 2527 { 2528 struct unpcb *unp; 2529 2530 unp = mem; 2531 2532 KASSERT(LIST_EMPTY(&unp->unp_refs), 2533 ("%s: unpcb %p has lingering refs", __func__, unp)); 2534 KASSERT(unp->unp_socket == NULL, 2535 ("%s: unpcb %p has socket backpointer", __func__, unp)); 2536 KASSERT(unp->unp_vnode == NULL, 2537 ("%s: unpcb %p has vnode references", __func__, unp)); 2538 KASSERT(unp->unp_conn == NULL, 2539 ("%s: unpcb %p is still connected", __func__, unp)); 2540 KASSERT(unp->unp_addr == NULL, 2541 ("%s: unpcb %p has leaked addr", __func__, unp)); 2542 } 2543 #endif 2544 2545 static void 2546 unp_init(void *arg __unused) 2547 { 2548 uma_dtor dtor; 2549 2550 #ifdef INVARIANTS 2551 dtor = unp_zdtor; 2552 #else 2553 dtor = NULL; 2554 #endif 2555 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor, 2556 NULL, NULL, UMA_ALIGN_CACHE, 0); 2557 uma_zone_set_max(unp_zone, maxsockets); 2558 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached"); 2559 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change, 2560 NULL, EVENTHANDLER_PRI_ANY); 2561 LIST_INIT(&unp_dhead); 2562 LIST_INIT(&unp_shead); 2563 LIST_INIT(&unp_sphead); 2564 SLIST_INIT(&unp_defers); 2565 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL); 2566 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL); 2567 UNP_LINK_LOCK_INIT(); 2568 UNP_DEFERRED_LOCK_INIT(); 2569 } 2570 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL); 2571 2572 static void 2573 unp_internalize_cleanup_rights(struct mbuf *control) 2574 { 2575 struct cmsghdr *cp; 2576 struct mbuf *m; 2577 void *data; 2578 socklen_t datalen; 2579 2580 for (m = control; m != NULL; m = m->m_next) { 2581 cp = mtod(m, struct cmsghdr *); 2582 if (cp->cmsg_level != SOL_SOCKET || 2583 cp->cmsg_type != SCM_RIGHTS) 2584 continue; 2585 data = CMSG_DATA(cp); 2586 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data; 2587 unp_freerights(data, datalen / sizeof(struct filedesc *)); 2588 } 2589 } 2590 2591 static int 2592 unp_internalize(struct mbuf **controlp, struct thread *td, 2593 struct mbuf **clast, u_int *space, u_int *mbcnt) 2594 { 2595 struct mbuf *control, **initial_controlp; 2596 struct proc *p; 2597 struct filedesc *fdesc; 2598 struct bintime *bt; 2599 struct cmsghdr *cm; 2600 struct cmsgcred *cmcred; 2601 struct filedescent *fde, **fdep, *fdev; 2602 struct file *fp; 2603 struct timeval *tv; 2604 struct timespec *ts; 2605 void *data; 2606 socklen_t clen, datalen; 2607 int i, j, error, *fdp, oldfds; 2608 u_int newlen; 2609 2610 MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */ 2611 UNP_LINK_UNLOCK_ASSERT(); 2612 2613 p = td->td_proc; 2614 fdesc = p->p_fd; 2615 error = 0; 2616 control = *controlp; 2617 *controlp = NULL; 2618 initial_controlp = controlp; 2619 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *), 2620 data = CMSG_DATA(cm); 2621 2622 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET && 2623 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) && 2624 (char *)cm + cm->cmsg_len >= (char *)data; 2625 2626 clen -= min(CMSG_SPACE(datalen), clen), 2627 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)), 2628 data = CMSG_DATA(cm)) { 2629 datalen = (char *)cm + cm->cmsg_len - (char *)data; 2630 switch (cm->cmsg_type) { 2631 case SCM_CREDS: 2632 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred), 2633 SCM_CREDS, SOL_SOCKET, M_WAITOK); 2634 cmcred = (struct cmsgcred *) 2635 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2636 cmcred->cmcred_pid = p->p_pid; 2637 cmcred->cmcred_uid = td->td_ucred->cr_ruid; 2638 cmcred->cmcred_gid = td->td_ucred->cr_rgid; 2639 cmcred->cmcred_euid = td->td_ucred->cr_uid; 2640 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups, 2641 CMGROUP_MAX); 2642 for (i = 0; i < cmcred->cmcred_ngroups; i++) 2643 cmcred->cmcred_groups[i] = 2644 td->td_ucred->cr_groups[i]; 2645 break; 2646 2647 case SCM_RIGHTS: 2648 oldfds = datalen / sizeof (int); 2649 if (oldfds == 0) 2650 continue; 2651 /* On some machines sizeof pointer is bigger than 2652 * sizeof int, so we need to check if data fits into 2653 * single mbuf. We could allocate several mbufs, and 2654 * unp_externalize() should even properly handle that. 2655 * But it is not worth to complicate the code for an 2656 * insane scenario of passing over 200 file descriptors 2657 * at once. 2658 */ 2659 newlen = oldfds * sizeof(fdep[0]); 2660 if (CMSG_SPACE(newlen) > MCLBYTES) { 2661 error = EMSGSIZE; 2662 goto out; 2663 } 2664 /* 2665 * Check that all the FDs passed in refer to legal 2666 * files. If not, reject the entire operation. 2667 */ 2668 fdp = data; 2669 FILEDESC_SLOCK(fdesc); 2670 for (i = 0; i < oldfds; i++, fdp++) { 2671 fp = fget_noref(fdesc, *fdp); 2672 if (fp == NULL) { 2673 FILEDESC_SUNLOCK(fdesc); 2674 error = EBADF; 2675 goto out; 2676 } 2677 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) { 2678 FILEDESC_SUNLOCK(fdesc); 2679 error = EOPNOTSUPP; 2680 goto out; 2681 } 2682 } 2683 2684 /* 2685 * Now replace the integer FDs with pointers to the 2686 * file structure and capability rights. 2687 */ 2688 *controlp = sbcreatecontrol(NULL, newlen, 2689 SCM_RIGHTS, SOL_SOCKET, M_WAITOK); 2690 fdp = data; 2691 for (i = 0; i < oldfds; i++, fdp++) { 2692 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) { 2693 fdp = data; 2694 for (j = 0; j < i; j++, fdp++) { 2695 fdrop(fdesc->fd_ofiles[*fdp]. 2696 fde_file, td); 2697 } 2698 FILEDESC_SUNLOCK(fdesc); 2699 error = EBADF; 2700 goto out; 2701 } 2702 } 2703 fdp = data; 2704 fdep = (struct filedescent **) 2705 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2706 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS, 2707 M_WAITOK); 2708 for (i = 0; i < oldfds; i++, fdev++, fdp++) { 2709 fde = &fdesc->fd_ofiles[*fdp]; 2710 fdep[i] = fdev; 2711 fdep[i]->fde_file = fde->fde_file; 2712 filecaps_copy(&fde->fde_caps, 2713 &fdep[i]->fde_caps, true); 2714 unp_internalize_fp(fdep[i]->fde_file); 2715 } 2716 FILEDESC_SUNLOCK(fdesc); 2717 break; 2718 2719 case SCM_TIMESTAMP: 2720 *controlp = sbcreatecontrol(NULL, sizeof(*tv), 2721 SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK); 2722 tv = (struct timeval *) 2723 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2724 microtime(tv); 2725 break; 2726 2727 case SCM_BINTIME: 2728 *controlp = sbcreatecontrol(NULL, sizeof(*bt), 2729 SCM_BINTIME, SOL_SOCKET, M_WAITOK); 2730 bt = (struct bintime *) 2731 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2732 bintime(bt); 2733 break; 2734 2735 case SCM_REALTIME: 2736 *controlp = sbcreatecontrol(NULL, sizeof(*ts), 2737 SCM_REALTIME, SOL_SOCKET, M_WAITOK); 2738 ts = (struct timespec *) 2739 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2740 nanotime(ts); 2741 break; 2742 2743 case SCM_MONOTONIC: 2744 *controlp = sbcreatecontrol(NULL, sizeof(*ts), 2745 SCM_MONOTONIC, SOL_SOCKET, M_WAITOK); 2746 ts = (struct timespec *) 2747 CMSG_DATA(mtod(*controlp, struct cmsghdr *)); 2748 nanouptime(ts); 2749 break; 2750 2751 default: 2752 error = EINVAL; 2753 goto out; 2754 } 2755 2756 if (space != NULL) { 2757 *space += (*controlp)->m_len; 2758 *mbcnt += MSIZE; 2759 if ((*controlp)->m_flags & M_EXT) 2760 *mbcnt += (*controlp)->m_ext.ext_size; 2761 *clast = *controlp; 2762 } 2763 controlp = &(*controlp)->m_next; 2764 } 2765 if (clen > 0) 2766 error = EINVAL; 2767 2768 out: 2769 if (error != 0 && initial_controlp != NULL) 2770 unp_internalize_cleanup_rights(*initial_controlp); 2771 m_freem(control); 2772 return (error); 2773 } 2774 2775 static struct mbuf * 2776 unp_addsockcred(struct thread *td, struct mbuf *control, int mode, 2777 struct mbuf **clast, u_int *space, u_int *mbcnt) 2778 { 2779 struct mbuf *m, *n, *n_prev; 2780 const struct cmsghdr *cm; 2781 int ngroups, i, cmsgtype; 2782 size_t ctrlsz; 2783 2784 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX); 2785 if (mode & UNP_WANTCRED_ALWAYS) { 2786 ctrlsz = SOCKCRED2SIZE(ngroups); 2787 cmsgtype = SCM_CREDS2; 2788 } else { 2789 ctrlsz = SOCKCREDSIZE(ngroups); 2790 cmsgtype = SCM_CREDS; 2791 } 2792 2793 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT); 2794 if (m == NULL) 2795 return (control); 2796 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL); 2797 2798 if (mode & UNP_WANTCRED_ALWAYS) { 2799 struct sockcred2 *sc; 2800 2801 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *)); 2802 sc->sc_version = 0; 2803 sc->sc_pid = td->td_proc->p_pid; 2804 sc->sc_uid = td->td_ucred->cr_ruid; 2805 sc->sc_euid = td->td_ucred->cr_uid; 2806 sc->sc_gid = td->td_ucred->cr_rgid; 2807 sc->sc_egid = td->td_ucred->cr_gid; 2808 sc->sc_ngroups = ngroups; 2809 for (i = 0; i < sc->sc_ngroups; i++) 2810 sc->sc_groups[i] = td->td_ucred->cr_groups[i]; 2811 } else { 2812 struct sockcred *sc; 2813 2814 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *)); 2815 sc->sc_uid = td->td_ucred->cr_ruid; 2816 sc->sc_euid = td->td_ucred->cr_uid; 2817 sc->sc_gid = td->td_ucred->cr_rgid; 2818 sc->sc_egid = td->td_ucred->cr_gid; 2819 sc->sc_ngroups = ngroups; 2820 for (i = 0; i < sc->sc_ngroups; i++) 2821 sc->sc_groups[i] = td->td_ucred->cr_groups[i]; 2822 } 2823 2824 /* 2825 * Unlink SCM_CREDS control messages (struct cmsgcred), since just 2826 * created SCM_CREDS control message (struct sockcred) has another 2827 * format. 2828 */ 2829 if (control != NULL && cmsgtype == SCM_CREDS) 2830 for (n = control, n_prev = NULL; n != NULL;) { 2831 cm = mtod(n, struct cmsghdr *); 2832 if (cm->cmsg_level == SOL_SOCKET && 2833 cm->cmsg_type == SCM_CREDS) { 2834 if (n_prev == NULL) 2835 control = n->m_next; 2836 else 2837 n_prev->m_next = n->m_next; 2838 if (space != NULL) { 2839 MPASS(*space >= n->m_len); 2840 *space -= n->m_len; 2841 MPASS(*mbcnt >= MSIZE); 2842 *mbcnt -= MSIZE; 2843 if (n->m_flags & M_EXT) { 2844 MPASS(*mbcnt >= 2845 n->m_ext.ext_size); 2846 *mbcnt -= n->m_ext.ext_size; 2847 } 2848 MPASS(clast); 2849 if (*clast == n) { 2850 MPASS(n->m_next == NULL); 2851 if (n_prev == NULL) 2852 *clast = m; 2853 else 2854 *clast = n_prev; 2855 } 2856 } 2857 n = m_free(n); 2858 } else { 2859 n_prev = n; 2860 n = n->m_next; 2861 } 2862 } 2863 2864 /* Prepend it to the head. */ 2865 m->m_next = control; 2866 if (space != NULL) { 2867 *space += m->m_len; 2868 *mbcnt += MSIZE; 2869 if (control == NULL) 2870 *clast = m; 2871 } 2872 return (m); 2873 } 2874 2875 static struct unpcb * 2876 fptounp(struct file *fp) 2877 { 2878 struct socket *so; 2879 2880 if (fp->f_type != DTYPE_SOCKET) 2881 return (NULL); 2882 if ((so = fp->f_data) == NULL) 2883 return (NULL); 2884 if (so->so_proto->pr_domain != &localdomain) 2885 return (NULL); 2886 return sotounpcb(so); 2887 } 2888 2889 static void 2890 unp_discard(struct file *fp) 2891 { 2892 struct unp_defer *dr; 2893 2894 if (unp_externalize_fp(fp)) { 2895 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK); 2896 dr->ud_fp = fp; 2897 UNP_DEFERRED_LOCK(); 2898 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link); 2899 UNP_DEFERRED_UNLOCK(); 2900 atomic_add_int(&unp_defers_count, 1); 2901 taskqueue_enqueue(taskqueue_thread, &unp_defer_task); 2902 } else 2903 closef_nothread(fp); 2904 } 2905 2906 static void 2907 unp_process_defers(void *arg __unused, int pending) 2908 { 2909 struct unp_defer *dr; 2910 SLIST_HEAD(, unp_defer) drl; 2911 int count; 2912 2913 SLIST_INIT(&drl); 2914 for (;;) { 2915 UNP_DEFERRED_LOCK(); 2916 if (SLIST_FIRST(&unp_defers) == NULL) { 2917 UNP_DEFERRED_UNLOCK(); 2918 break; 2919 } 2920 SLIST_SWAP(&unp_defers, &drl, unp_defer); 2921 UNP_DEFERRED_UNLOCK(); 2922 count = 0; 2923 while ((dr = SLIST_FIRST(&drl)) != NULL) { 2924 SLIST_REMOVE_HEAD(&drl, ud_link); 2925 closef_nothread(dr->ud_fp); 2926 free(dr, M_TEMP); 2927 count++; 2928 } 2929 atomic_add_int(&unp_defers_count, -count); 2930 } 2931 } 2932 2933 static void 2934 unp_internalize_fp(struct file *fp) 2935 { 2936 struct unpcb *unp; 2937 2938 UNP_LINK_WLOCK(); 2939 if ((unp = fptounp(fp)) != NULL) { 2940 unp->unp_file = fp; 2941 unp->unp_msgcount++; 2942 } 2943 unp_rights++; 2944 UNP_LINK_WUNLOCK(); 2945 } 2946 2947 static int 2948 unp_externalize_fp(struct file *fp) 2949 { 2950 struct unpcb *unp; 2951 int ret; 2952 2953 UNP_LINK_WLOCK(); 2954 if ((unp = fptounp(fp)) != NULL) { 2955 unp->unp_msgcount--; 2956 ret = 1; 2957 } else 2958 ret = 0; 2959 unp_rights--; 2960 UNP_LINK_WUNLOCK(); 2961 return (ret); 2962 } 2963 2964 /* 2965 * unp_defer indicates whether additional work has been defered for a future 2966 * pass through unp_gc(). It is thread local and does not require explicit 2967 * synchronization. 2968 */ 2969 static int unp_marked; 2970 2971 static void 2972 unp_remove_dead_ref(struct filedescent **fdep, int fdcount) 2973 { 2974 struct unpcb *unp; 2975 struct file *fp; 2976 int i; 2977 2978 /* 2979 * This function can only be called from the gc task. 2980 */ 2981 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0, 2982 ("%s: not on gc callout", __func__)); 2983 UNP_LINK_LOCK_ASSERT(); 2984 2985 for (i = 0; i < fdcount; i++) { 2986 fp = fdep[i]->fde_file; 2987 if ((unp = fptounp(fp)) == NULL) 2988 continue; 2989 if ((unp->unp_gcflag & UNPGC_DEAD) == 0) 2990 continue; 2991 unp->unp_gcrefs--; 2992 } 2993 } 2994 2995 static void 2996 unp_restore_undead_ref(struct filedescent **fdep, int fdcount) 2997 { 2998 struct unpcb *unp; 2999 struct file *fp; 3000 int i; 3001 3002 /* 3003 * This function can only be called from the gc task. 3004 */ 3005 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0, 3006 ("%s: not on gc callout", __func__)); 3007 UNP_LINK_LOCK_ASSERT(); 3008 3009 for (i = 0; i < fdcount; i++) { 3010 fp = fdep[i]->fde_file; 3011 if ((unp = fptounp(fp)) == NULL) 3012 continue; 3013 if ((unp->unp_gcflag & UNPGC_DEAD) == 0) 3014 continue; 3015 unp->unp_gcrefs++; 3016 unp_marked++; 3017 } 3018 } 3019 3020 static void 3021 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int)) 3022 { 3023 struct sockbuf *sb; 3024 3025 SOCK_LOCK_ASSERT(so); 3026 3027 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS) 3028 return; 3029 3030 SOCK_RECVBUF_LOCK(so); 3031 switch (so->so_type) { 3032 case SOCK_DGRAM: 3033 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op); 3034 unp_scan(so->so_rcv.uxdg_peeked, op); 3035 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist) 3036 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op); 3037 break; 3038 case SOCK_STREAM: 3039 case SOCK_SEQPACKET: 3040 unp_scan(so->so_rcv.sb_mb, op); 3041 break; 3042 } 3043 SOCK_RECVBUF_UNLOCK(so); 3044 } 3045 3046 static void 3047 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int)) 3048 { 3049 struct socket *so, *soa; 3050 3051 so = unp->unp_socket; 3052 SOCK_LOCK(so); 3053 if (SOLISTENING(so)) { 3054 /* 3055 * Mark all sockets in our accept queue. 3056 */ 3057 TAILQ_FOREACH(soa, &so->sol_comp, so_list) 3058 unp_scan_socket(soa, op); 3059 } else { 3060 /* 3061 * Mark all sockets we reference with RIGHTS. 3062 */ 3063 unp_scan_socket(so, op); 3064 } 3065 SOCK_UNLOCK(so); 3066 } 3067 3068 static int unp_recycled; 3069 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, 3070 "Number of unreachable sockets claimed by the garbage collector."); 3071 3072 static int unp_taskcount; 3073 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, 3074 "Number of times the garbage collector has run."); 3075 3076 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0, 3077 "Number of active local sockets."); 3078 3079 static void 3080 unp_gc(__unused void *arg, int pending) 3081 { 3082 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead, 3083 NULL }; 3084 struct unp_head **head; 3085 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */ 3086 struct file *f, **unref; 3087 struct unpcb *unp, *unptmp; 3088 int i, total, unp_unreachable; 3089 3090 LIST_INIT(&unp_deadhead); 3091 unp_taskcount++; 3092 UNP_LINK_RLOCK(); 3093 /* 3094 * First determine which sockets may be in cycles. 3095 */ 3096 unp_unreachable = 0; 3097 3098 for (head = heads; *head != NULL; head++) 3099 LIST_FOREACH(unp, *head, unp_link) { 3100 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0, 3101 ("%s: unp %p has unexpected gc flags 0x%x", 3102 __func__, unp, (unsigned int)unp->unp_gcflag)); 3103 3104 f = unp->unp_file; 3105 3106 /* 3107 * Check for an unreachable socket potentially in a 3108 * cycle. It must be in a queue as indicated by 3109 * msgcount, and this must equal the file reference 3110 * count. Note that when msgcount is 0 the file is 3111 * NULL. 3112 */ 3113 if (f != NULL && unp->unp_msgcount != 0 && 3114 refcount_load(&f->f_count) == unp->unp_msgcount) { 3115 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead); 3116 unp->unp_gcflag |= UNPGC_DEAD; 3117 unp->unp_gcrefs = unp->unp_msgcount; 3118 unp_unreachable++; 3119 } 3120 } 3121 3122 /* 3123 * Scan all sockets previously marked as potentially being in a cycle 3124 * and remove the references each socket holds on any UNPGC_DEAD 3125 * sockets in its queue. After this step, all remaining references on 3126 * sockets marked UNPGC_DEAD should not be part of any cycle. 3127 */ 3128 LIST_FOREACH(unp, &unp_deadhead, unp_dead) 3129 unp_gc_scan(unp, unp_remove_dead_ref); 3130 3131 /* 3132 * If a socket still has a non-negative refcount, it cannot be in a 3133 * cycle. In this case increment refcount of all children iteratively. 3134 * Stop the scan once we do a complete loop without discovering 3135 * a new reachable socket. 3136 */ 3137 do { 3138 unp_marked = 0; 3139 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp) 3140 if (unp->unp_gcrefs > 0) { 3141 unp->unp_gcflag &= ~UNPGC_DEAD; 3142 LIST_REMOVE(unp, unp_dead); 3143 KASSERT(unp_unreachable > 0, 3144 ("%s: unp_unreachable underflow.", 3145 __func__)); 3146 unp_unreachable--; 3147 unp_gc_scan(unp, unp_restore_undead_ref); 3148 } 3149 } while (unp_marked); 3150 3151 UNP_LINK_RUNLOCK(); 3152 3153 if (unp_unreachable == 0) 3154 return; 3155 3156 /* 3157 * Allocate space for a local array of dead unpcbs. 3158 * TODO: can this path be simplified by instead using the local 3159 * dead list at unp_deadhead, after taking out references 3160 * on the file object and/or unpcb and dropping the link lock? 3161 */ 3162 unref = malloc(unp_unreachable * sizeof(struct file *), 3163 M_TEMP, M_WAITOK); 3164 3165 /* 3166 * Iterate looking for sockets which have been specifically marked 3167 * as unreachable and store them locally. 3168 */ 3169 UNP_LINK_RLOCK(); 3170 total = 0; 3171 LIST_FOREACH(unp, &unp_deadhead, unp_dead) { 3172 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0, 3173 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp)); 3174 unp->unp_gcflag &= ~UNPGC_DEAD; 3175 f = unp->unp_file; 3176 if (unp->unp_msgcount == 0 || f == NULL || 3177 refcount_load(&f->f_count) != unp->unp_msgcount || 3178 !fhold(f)) 3179 continue; 3180 unref[total++] = f; 3181 KASSERT(total <= unp_unreachable, 3182 ("%s: incorrect unreachable count.", __func__)); 3183 } 3184 UNP_LINK_RUNLOCK(); 3185 3186 /* 3187 * Now flush all sockets, free'ing rights. This will free the 3188 * struct files associated with these sockets but leave each socket 3189 * with one remaining ref. 3190 */ 3191 for (i = 0; i < total; i++) { 3192 struct socket *so; 3193 3194 so = unref[i]->f_data; 3195 CURVNET_SET(so->so_vnet); 3196 socantrcvmore(so); 3197 unp_dispose(so); 3198 CURVNET_RESTORE(); 3199 } 3200 3201 /* 3202 * And finally release the sockets so they can be reclaimed. 3203 */ 3204 for (i = 0; i < total; i++) 3205 fdrop(unref[i], NULL); 3206 unp_recycled += total; 3207 free(unref, M_TEMP); 3208 } 3209 3210 /* 3211 * Synchronize against unp_gc, which can trip over data as we are freeing it. 3212 */ 3213 static void 3214 unp_dispose(struct socket *so) 3215 { 3216 struct sockbuf *sb; 3217 struct unpcb *unp; 3218 struct mbuf *m; 3219 3220 MPASS(!SOLISTENING(so)); 3221 3222 unp = sotounpcb(so); 3223 UNP_LINK_WLOCK(); 3224 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS; 3225 UNP_LINK_WUNLOCK(); 3226 3227 /* 3228 * Grab our special mbufs before calling sbrelease(). 3229 */ 3230 SOCK_RECVBUF_LOCK(so); 3231 switch (so->so_type) { 3232 case SOCK_DGRAM: 3233 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) { 3234 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb); 3235 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist); 3236 /* Note: socket of sb may reconnect. */ 3237 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0; 3238 } 3239 sb = &so->so_rcv; 3240 if (sb->uxdg_peeked != NULL) { 3241 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked, 3242 m_stailqpkt); 3243 sb->uxdg_peeked = NULL; 3244 } 3245 m = STAILQ_FIRST(&sb->uxdg_mb); 3246 STAILQ_INIT(&sb->uxdg_mb); 3247 /* XXX: our shortened sbrelease() */ 3248 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0, 3249 RLIM_INFINITY); 3250 /* 3251 * XXXGL Mark sb with SBS_CANTRCVMORE. This is needed to 3252 * prevent uipc_sosend_dgram() or unp_disconnect() adding more 3253 * data to the socket. 3254 * We came here either through shutdown(2) or from the final 3255 * sofree(). The sofree() case is simple as it guarantees 3256 * that no more sends will happen, however we can race with 3257 * unp_disconnect() from our peer. The shutdown(2) case is 3258 * more exotic. It would call into unp_dispose() only if 3259 * socket is SS_ISCONNECTED. This is possible if we did 3260 * connect(2) on this socket and we also had it bound with 3261 * bind(2) and receive connections from other sockets. 3262 * Because uipc_shutdown() violates POSIX (see comment 3263 * there) we will end up here shutting down our receive side. 3264 * Of course this will have affect not only on the peer we 3265 * connect(2)ed to, but also on all of the peers who had 3266 * connect(2)ed to us. Their sends would end up with ENOBUFS. 3267 */ 3268 sb->sb_state |= SBS_CANTRCVMORE; 3269 break; 3270 case SOCK_STREAM: 3271 case SOCK_SEQPACKET: 3272 sb = &so->so_rcv; 3273 m = sbcut_locked(sb, sb->sb_ccc); 3274 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0, 3275 ("%s: ccc %u mb %p mbcnt %u", __func__, 3276 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt)); 3277 sbrelease_locked(so, SO_RCV); 3278 break; 3279 } 3280 SOCK_RECVBUF_UNLOCK(so); 3281 if (SOCK_IO_RECV_OWNED(so)) 3282 SOCK_IO_RECV_UNLOCK(so); 3283 3284 if (m != NULL) { 3285 unp_scan(m, unp_freerights); 3286 m_freem(m); 3287 } 3288 } 3289 3290 static void 3291 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int)) 3292 { 3293 struct mbuf *m; 3294 struct cmsghdr *cm; 3295 void *data; 3296 socklen_t clen, datalen; 3297 3298 while (m0 != NULL) { 3299 for (m = m0; m; m = m->m_next) { 3300 if (m->m_type != MT_CONTROL) 3301 continue; 3302 3303 cm = mtod(m, struct cmsghdr *); 3304 clen = m->m_len; 3305 3306 while (cm != NULL) { 3307 if (sizeof(*cm) > clen || cm->cmsg_len > clen) 3308 break; 3309 3310 data = CMSG_DATA(cm); 3311 datalen = (caddr_t)cm + cm->cmsg_len 3312 - (caddr_t)data; 3313 3314 if (cm->cmsg_level == SOL_SOCKET && 3315 cm->cmsg_type == SCM_RIGHTS) { 3316 (*op)(data, datalen / 3317 sizeof(struct filedescent *)); 3318 } 3319 3320 if (CMSG_SPACE(datalen) < clen) { 3321 clen -= CMSG_SPACE(datalen); 3322 cm = (struct cmsghdr *) 3323 ((caddr_t)cm + CMSG_SPACE(datalen)); 3324 } else { 3325 clen = 0; 3326 cm = NULL; 3327 } 3328 } 3329 } 3330 m0 = m0->m_nextpkt; 3331 } 3332 } 3333 3334 /* 3335 * Definitions of protocols supported in the LOCAL domain. 3336 */ 3337 static struct protosw streamproto = { 3338 .pr_type = SOCK_STREAM, 3339 .pr_flags = PR_CONNREQUIRED | PR_WANTRCVD | PR_CAPATTACH, 3340 .pr_ctloutput = &uipc_ctloutput, 3341 .pr_abort = uipc_abort, 3342 .pr_accept = uipc_peeraddr, 3343 .pr_attach = uipc_attach, 3344 .pr_bind = uipc_bind, 3345 .pr_bindat = uipc_bindat, 3346 .pr_connect = uipc_connect, 3347 .pr_connectat = uipc_connectat, 3348 .pr_connect2 = uipc_connect2, 3349 .pr_detach = uipc_detach, 3350 .pr_disconnect = uipc_disconnect, 3351 .pr_listen = uipc_listen, 3352 .pr_peeraddr = uipc_peeraddr, 3353 .pr_rcvd = uipc_rcvd, 3354 .pr_send = uipc_send, 3355 .pr_ready = uipc_ready, 3356 .pr_sense = uipc_sense, 3357 .pr_shutdown = uipc_shutdown, 3358 .pr_sockaddr = uipc_sockaddr, 3359 .pr_soreceive = soreceive_generic, 3360 .pr_close = uipc_close, 3361 }; 3362 3363 static struct protosw dgramproto = { 3364 .pr_type = SOCK_DGRAM, 3365 .pr_flags = PR_ATOMIC | PR_ADDR | PR_CAPATTACH | PR_SOCKBUF, 3366 .pr_ctloutput = &uipc_ctloutput, 3367 .pr_abort = uipc_abort, 3368 .pr_accept = uipc_peeraddr, 3369 .pr_attach = uipc_attach, 3370 .pr_bind = uipc_bind, 3371 .pr_bindat = uipc_bindat, 3372 .pr_connect = uipc_connect, 3373 .pr_connectat = uipc_connectat, 3374 .pr_connect2 = uipc_connect2, 3375 .pr_detach = uipc_detach, 3376 .pr_disconnect = uipc_disconnect, 3377 .pr_peeraddr = uipc_peeraddr, 3378 .pr_sosend = uipc_sosend_dgram, 3379 .pr_sense = uipc_sense, 3380 .pr_shutdown = uipc_shutdown, 3381 .pr_sockaddr = uipc_sockaddr, 3382 .pr_soreceive = uipc_soreceive_dgram, 3383 .pr_close = uipc_close, 3384 }; 3385 3386 static struct protosw seqpacketproto = { 3387 .pr_type = SOCK_SEQPACKET, 3388 /* 3389 * XXXRW: For now, PR_ADDR because soreceive will bump into them 3390 * due to our use of sbappendaddr. A new sbappend variants is needed 3391 * that supports both atomic record writes and control data. 3392 */ 3393 .pr_flags = PR_ADDR | PR_ATOMIC | PR_CONNREQUIRED | 3394 PR_WANTRCVD | PR_CAPATTACH, 3395 .pr_ctloutput = &uipc_ctloutput, 3396 .pr_abort = uipc_abort, 3397 .pr_accept = uipc_peeraddr, 3398 .pr_attach = uipc_attach, 3399 .pr_bind = uipc_bind, 3400 .pr_bindat = uipc_bindat, 3401 .pr_connect = uipc_connect, 3402 .pr_connectat = uipc_connectat, 3403 .pr_connect2 = uipc_connect2, 3404 .pr_detach = uipc_detach, 3405 .pr_disconnect = uipc_disconnect, 3406 .pr_listen = uipc_listen, 3407 .pr_peeraddr = uipc_peeraddr, 3408 .pr_rcvd = uipc_rcvd, 3409 .pr_send = uipc_send, 3410 .pr_sense = uipc_sense, 3411 .pr_shutdown = uipc_shutdown, 3412 .pr_sockaddr = uipc_sockaddr, 3413 .pr_soreceive = soreceive_generic, /* XXX: or...? */ 3414 .pr_close = uipc_close, 3415 }; 3416 3417 static struct domain localdomain = { 3418 .dom_family = AF_LOCAL, 3419 .dom_name = "local", 3420 .dom_externalize = unp_externalize, 3421 .dom_nprotosw = 3, 3422 .dom_protosw = { 3423 &streamproto, 3424 &dgramproto, 3425 &seqpacketproto, 3426 } 3427 }; 3428 DOMAIN_SET(local); 3429 3430 /* 3431 * A helper function called by VFS before socket-type vnode reclamation. 3432 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode 3433 * use count. 3434 */ 3435 void 3436 vfs_unp_reclaim(struct vnode *vp) 3437 { 3438 struct unpcb *unp; 3439 int active; 3440 struct mtx *vplock; 3441 3442 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim"); 3443 KASSERT(vp->v_type == VSOCK, 3444 ("vfs_unp_reclaim: vp->v_type != VSOCK")); 3445 3446 active = 0; 3447 vplock = mtx_pool_find(mtxpool_sleep, vp); 3448 mtx_lock(vplock); 3449 VOP_UNP_CONNECT(vp, &unp); 3450 if (unp == NULL) 3451 goto done; 3452 UNP_PCB_LOCK(unp); 3453 if (unp->unp_vnode == vp) { 3454 VOP_UNP_DETACH(vp); 3455 unp->unp_vnode = NULL; 3456 active = 1; 3457 } 3458 UNP_PCB_UNLOCK(unp); 3459 done: 3460 mtx_unlock(vplock); 3461 if (active) 3462 vunref(vp); 3463 } 3464 3465 #ifdef DDB 3466 static void 3467 db_print_indent(int indent) 3468 { 3469 int i; 3470 3471 for (i = 0; i < indent; i++) 3472 db_printf(" "); 3473 } 3474 3475 static void 3476 db_print_unpflags(int unp_flags) 3477 { 3478 int comma; 3479 3480 comma = 0; 3481 if (unp_flags & UNP_HAVEPC) { 3482 db_printf("%sUNP_HAVEPC", comma ? ", " : ""); 3483 comma = 1; 3484 } 3485 if (unp_flags & UNP_WANTCRED_ALWAYS) { 3486 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : ""); 3487 comma = 1; 3488 } 3489 if (unp_flags & UNP_WANTCRED_ONESHOT) { 3490 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : ""); 3491 comma = 1; 3492 } 3493 if (unp_flags & UNP_CONNWAIT) { 3494 db_printf("%sUNP_CONNWAIT", comma ? ", " : ""); 3495 comma = 1; 3496 } 3497 if (unp_flags & UNP_CONNECTING) { 3498 db_printf("%sUNP_CONNECTING", comma ? ", " : ""); 3499 comma = 1; 3500 } 3501 if (unp_flags & UNP_BINDING) { 3502 db_printf("%sUNP_BINDING", comma ? ", " : ""); 3503 comma = 1; 3504 } 3505 } 3506 3507 static void 3508 db_print_xucred(int indent, struct xucred *xu) 3509 { 3510 int comma, i; 3511 3512 db_print_indent(indent); 3513 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n", 3514 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups); 3515 db_print_indent(indent); 3516 db_printf("cr_groups: "); 3517 comma = 0; 3518 for (i = 0; i < xu->cr_ngroups; i++) { 3519 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]); 3520 comma = 1; 3521 } 3522 db_printf("\n"); 3523 } 3524 3525 static void 3526 db_print_unprefs(int indent, struct unp_head *uh) 3527 { 3528 struct unpcb *unp; 3529 int counter; 3530 3531 counter = 0; 3532 LIST_FOREACH(unp, uh, unp_reflink) { 3533 if (counter % 4 == 0) 3534 db_print_indent(indent); 3535 db_printf("%p ", unp); 3536 if (counter % 4 == 3) 3537 db_printf("\n"); 3538 counter++; 3539 } 3540 if (counter != 0 && counter % 4 != 0) 3541 db_printf("\n"); 3542 } 3543 3544 DB_SHOW_COMMAND(unpcb, db_show_unpcb) 3545 { 3546 struct unpcb *unp; 3547 3548 if (!have_addr) { 3549 db_printf("usage: show unpcb <addr>\n"); 3550 return; 3551 } 3552 unp = (struct unpcb *)addr; 3553 3554 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket, 3555 unp->unp_vnode); 3556 3557 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino, 3558 unp->unp_conn); 3559 3560 db_printf("unp_refs:\n"); 3561 db_print_unprefs(2, &unp->unp_refs); 3562 3563 /* XXXRW: Would be nice to print the full address, if any. */ 3564 db_printf("unp_addr: %p\n", unp->unp_addr); 3565 3566 db_printf("unp_gencnt: %llu\n", 3567 (unsigned long long)unp->unp_gencnt); 3568 3569 db_printf("unp_flags: %x (", unp->unp_flags); 3570 db_print_unpflags(unp->unp_flags); 3571 db_printf(")\n"); 3572 3573 db_printf("unp_peercred:\n"); 3574 db_print_xucred(2, &unp->unp_peercred); 3575 3576 db_printf("unp_refcount: %u\n", unp->unp_refcount); 3577 } 3578 #endif 3579