2 * SPDX-License-Identifier: BSD-3-Clause
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
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
37 * UNIX Domain (Local) Sockets
39 * This is an implementation of UNIX (local) domain sockets. Each socket has
40 * an associated struct unpcb (UNIX protocol control block). Stream sockets
41 * may be connected to 0 or 1 other socket. Datagram sockets may be
42 * connected to 0, 1, or many other sockets. Sockets may be created and
43 * connected in pairs (socketpair(2)), or bound/connected to using the file
44 * system name space. For most purposes, only the receive socket buffer is
45 * used, as sending on one socket delivers directly to the receive socket
46 * buffer of a second socket.
48 * The implementation is substantially complicated by the fact that
49 * "ancillary data", such as file descriptors or credentials, may be passed
50 * across UNIX domain sockets. The potential for passing UNIX domain sockets
51 * over other UNIX domain sockets requires the implementation of a simple
52 * garbage collector to find and tear down cycles of disconnected sockets.
56 * rethink name space problems
57 * need a proper out-of-band
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/domain.h>
68 #include <sys/fcntl.h>
69 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
70 #include <sys/eventhandler.h>
72 #include <sys/filedesc.h>
73 #include <sys/kernel.h>
76 #include <sys/mount.h>
77 #include <sys/mutex.h>
78 #include <sys/namei.h>
80 #include <sys/protosw.h>
81 #include <sys/queue.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 #include <sys/taskqueue.h>
93 #include <sys/unpcb.h>
94 #include <sys/vnode.h>
102 #include <security/mac/mac_framework.h>
106 MALLOC_DECLARE(M_FILECAPS);
110 * (l) Locked using list lock
111 * (g) Locked using linkage lock
114 static uma_zone_t unp_zone;
115 static unp_gen_t unp_gencnt; /* (l) */
116 static u_int unp_count; /* (l) Count of local sockets. */
117 static ino_t unp_ino; /* Prototype for fake inode numbers. */
118 static int unp_rights; /* (g) File descriptors in flight. */
119 static struct unp_head unp_shead; /* (l) List of stream sockets. */
120 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
121 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
124 SLIST_ENTRY(unp_defer) ud_link;
127 static SLIST_HEAD(, unp_defer) unp_defers;
128 static int unp_defers_count;
130 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
133 * Garbage collection of cyclic file descriptor/socket references occurs
134 * asynchronously in a taskqueue context in order to avoid recursion and
135 * reentrance in the UNIX domain socket, file descriptor, and socket layer
136 * code. See unp_gc() for a full description.
138 static struct timeout_task unp_gc_task;
141 * The close of unix domain sockets attached as SCM_RIGHTS is
142 * postponed to the taskqueue, to avoid arbitrary recursion depth.
143 * The attached sockets might have another sockets attached.
145 static struct task unp_defer_task;
148 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
149 * stream sockets, although the total for sender and receiver is actually
152 * Datagram sockets really use the sendspace as the maximum datagram size,
153 * and don't really want to reserve the sendspace. Their recvspace should be
154 * large enough for at least one max-size datagram plus address.
159 static u_long unpst_sendspace = PIPSIZ;
160 static u_long unpst_recvspace = PIPSIZ;
161 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
162 static u_long unpdg_recvspace = 4*1024;
163 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
164 static u_long unpsp_recvspace = PIPSIZ;
166 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
168 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
169 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
171 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
172 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
174 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
175 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
178 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
179 &unpst_sendspace, 0, "Default stream send space.");
180 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
181 &unpst_recvspace, 0, "Default stream receive space.");
182 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
183 &unpdg_sendspace, 0, "Default datagram send space.");
184 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
185 &unpdg_recvspace, 0, "Default datagram receive space.");
186 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
187 &unpsp_sendspace, 0, "Default seqpacket send space.");
188 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
189 &unpsp_recvspace, 0, "Default seqpacket receive space.");
190 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
191 "File descriptors in flight.");
192 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
193 &unp_defers_count, 0,
194 "File descriptors deferred to taskqueue for close.");
197 * Locking and synchronization:
199 * Three types of locks exist in the local domain socket implementation: a
200 * a global linkage rwlock, the mtxpool lock, and per-unpcb mutexes.
201 * The linkage lock protects the socket count, global generation number,
202 * and stream/datagram global lists.
204 * The mtxpool lock protects the vnode from being modified while referenced.
205 * Lock ordering requires that it be acquired before any unpcb locks.
207 * The unpcb lock (unp_mtx) protects all fields in the unpcb. Of particular
208 * note is that this includes the unp_conn field. So long as the unpcb lock
209 * is held the reference to the unpcb pointed to by unp_conn is valid. If we
210 * require that the unpcb pointed to by unp_conn remain live in cases where
211 * we need to drop the unp_mtx as when we need to acquire the lock for a
212 * second unpcb the caller must first acquire an additional reference on the
213 * second unpcb and then revalidate any state (typically check that unp_conn
214 * is non-NULL) upon requiring the initial unpcb lock. The lock ordering
215 * between unpcbs is the conventional ascending address order. Two helper
216 * routines exist for this:
218 * - unp_pcb_lock2(unp, unp2) - which just acquires the two locks in the
221 * - unp_pcb_owned_lock2(unp, unp2, freed) - the lock for unp is held
222 * when called. If unp is unlocked and unp2 is subsequently freed
223 * freed will be set to 1.
225 * The helper routines for references are:
227 * - unp_pcb_hold(unp): Can be called any time we currently hold a valid
230 * - unp_pcb_rele(unp): The caller must hold the unp lock. If we are
231 * releasing the last reference, detach must have been called thus
232 * unp->unp_socket be NULL.
234 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
235 * allocated in pru_attach() and freed in pru_detach(). The validity of that
236 * pointer is an invariant, so no lock is required to dereference the so_pcb
237 * pointer if a valid socket reference is held by the caller. In practice,
238 * this is always true during operations performed on a socket. Each unpcb
239 * has a back-pointer to its socket, unp_socket, which will be stable under
240 * the same circumstances.
242 * This pointer may only be safely dereferenced as long as a valid reference
243 * to the unpcb is held. Typically, this reference will be from the socket,
244 * or from another unpcb when the referring unpcb's lock is held (in order
245 * that the reference not be invalidated during use). For example, to follow
246 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
247 * that detach is not run clearing unp_socket.
249 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
250 * protocols, bind() is a non-atomic operation, and connect() requires
251 * potential sleeping in the protocol, due to potentially waiting on local or
252 * distributed file systems. We try to separate "lookup" operations, which
253 * may sleep, and the IPC operations themselves, which typically can occur
254 * with relative atomicity as locks can be held over the entire operation.
256 * Another tricky issue is simultaneous multi-threaded or multi-process
257 * access to a single UNIX domain socket. These are handled by the flags
258 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
259 * binding, both of which involve dropping UNIX domain socket locks in order
260 * to perform namei() and other file system operations.
262 static struct rwlock unp_link_rwlock;
263 static struct mtx unp_defers_lock;
265 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
268 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
270 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
273 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
274 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
275 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
276 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
277 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
279 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
281 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
282 "unp_defer", NULL, MTX_DEF)
283 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
284 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
286 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
287 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
289 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
292 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
293 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
294 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
295 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
296 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
297 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
298 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
300 static int uipc_connect2(struct socket *, struct socket *);
301 static int uipc_ctloutput(struct socket *, struct sockopt *);
302 static int unp_connect(struct socket *, struct sockaddr *,
304 static int unp_connectat(int, struct socket *, struct sockaddr *,
306 static int unp_connect2(struct socket *so, struct socket *so2, int);
307 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
308 static void unp_dispose(struct socket *so);
309 static void unp_dispose_mbuf(struct mbuf *);
310 static void unp_shutdown(struct unpcb *);
311 static void unp_drop(struct unpcb *);
312 static void unp_gc(__unused void *, int);
313 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
314 static void unp_discard(struct file *);
315 static void unp_freerights(struct filedescent **, int);
316 static void unp_init(void);
317 static int unp_internalize(struct mbuf **, struct thread *);
318 static void unp_internalize_fp(struct file *);
319 static int unp_externalize(struct mbuf *, struct mbuf **, int);
320 static int unp_externalize_fp(struct file *);
321 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
322 static void unp_process_defers(void * __unused, int);
325 unp_pcb_hold(struct unpcb *unp)
327 MPASS(unp->unp_refcount);
328 refcount_acquire(&unp->unp_refcount);
332 unp_pcb_rele(struct unpcb *unp)
336 UNP_PCB_LOCK_ASSERT(unp);
337 MPASS(unp->unp_refcount);
338 if ((freed = refcount_release(&unp->unp_refcount))) {
339 /* we got here with having detached? */
340 MPASS(unp->unp_socket == NULL);
342 UNP_PCB_LOCK_DESTROY(unp);
343 uma_zfree(unp_zone, unp);
349 unp_pcb_lock2(struct unpcb *unp, struct unpcb *unp2)
352 UNP_PCB_UNLOCK_ASSERT(unp);
353 UNP_PCB_UNLOCK_ASSERT(unp2);
354 if ((uintptr_t)unp2 > (uintptr_t)unp) {
363 static __noinline void
364 unp_pcb_owned_lock2_slowpath(struct unpcb *unp, struct unpcb **unp2p,
374 *freed = unp_pcb_rele(unp2);
379 #define unp_pcb_owned_lock2(unp, unp2, freed) do { \
381 UNP_PCB_LOCK_ASSERT(unp); \
382 UNP_PCB_UNLOCK_ASSERT(unp2); \
383 MPASS((unp) != (unp2)); \
384 if (__predict_true(UNP_PCB_TRYLOCK(unp2))) \
386 else if ((uintptr_t)(unp2) > (uintptr_t)(unp)) \
387 UNP_PCB_LOCK(unp2); \
389 unp_pcb_owned_lock2_slowpath((unp), &(unp2), &freed); \
393 * Definitions of protocols supported in the LOCAL domain.
395 static struct domain localdomain;
396 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
397 static struct pr_usrreqs uipc_usrreqs_seqpacket;
398 static struct protosw localsw[] = {
400 .pr_type = SOCK_STREAM,
401 .pr_domain = &localdomain,
402 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
403 .pr_ctloutput = &uipc_ctloutput,
404 .pr_usrreqs = &uipc_usrreqs_stream
407 .pr_type = SOCK_DGRAM,
408 .pr_domain = &localdomain,
409 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
410 .pr_ctloutput = &uipc_ctloutput,
411 .pr_usrreqs = &uipc_usrreqs_dgram
414 .pr_type = SOCK_SEQPACKET,
415 .pr_domain = &localdomain,
418 * XXXRW: For now, PR_ADDR because soreceive will bump into them
419 * due to our use of sbappendaddr. A new sbappend variants is needed
420 * that supports both atomic record writes and control data.
422 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
424 .pr_ctloutput = &uipc_ctloutput,
425 .pr_usrreqs = &uipc_usrreqs_seqpacket,
429 static struct domain localdomain = {
430 .dom_family = AF_LOCAL,
432 .dom_init = unp_init,
433 .dom_externalize = unp_externalize,
434 .dom_dispose = unp_dispose,
435 .dom_protosw = localsw,
436 .dom_protoswNPROTOSW = &localsw[nitems(localsw)]
441 uipc_abort(struct socket *so)
443 struct unpcb *unp, *unp2;
446 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
447 UNP_PCB_UNLOCK_ASSERT(unp);
450 unp2 = unp->unp_conn;
460 uipc_accept(struct socket *so, struct sockaddr **nam)
462 struct unpcb *unp, *unp2;
463 const struct sockaddr *sa;
466 * Pass back name of connected socket, if it was bound and we are
467 * still connected (our peer may have closed already!).
470 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
472 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
474 unp2 = unp->unp_conn;
475 if (unp2 != NULL && unp2->unp_addr != NULL) {
477 sa = (struct sockaddr *) unp2->unp_addr;
478 bcopy(sa, *nam, sa->sa_len);
479 UNP_PCB_UNLOCK(unp2);
482 bcopy(sa, *nam, sa->sa_len);
489 uipc_attach(struct socket *so, int proto, struct thread *td)
491 u_long sendspace, recvspace;
496 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
497 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
498 switch (so->so_type) {
500 sendspace = unpst_sendspace;
501 recvspace = unpst_recvspace;
505 sendspace = unpdg_sendspace;
506 recvspace = unpdg_recvspace;
510 sendspace = unpsp_sendspace;
511 recvspace = unpsp_recvspace;
515 panic("uipc_attach");
517 error = soreserve(so, sendspace, recvspace);
521 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
524 LIST_INIT(&unp->unp_refs);
525 UNP_PCB_LOCK_INIT(unp);
526 unp->unp_socket = so;
528 unp->unp_refcount = 1;
530 if ((locked = UNP_LINK_WOWNED()) == false)
533 unp->unp_gencnt = ++unp_gencnt;
534 unp->unp_ino = ++unp_ino;
536 switch (so->so_type) {
538 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
542 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
546 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
550 panic("uipc_attach");
560 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
562 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
572 if (nam->sa_family != AF_UNIX)
573 return (EAFNOSUPPORT);
576 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
578 if (soun->sun_len > sizeof(struct sockaddr_un))
580 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
585 * We don't allow simultaneous bind() calls on a single UNIX domain
586 * socket, so flag in-progress operations, and return an error if an
587 * operation is already in progress.
589 * Historically, we have not allowed a socket to be rebound, so this
590 * also returns an error. Not allowing re-binding simplifies the
591 * implementation and avoids a great many possible failure modes.
594 if (unp->unp_vnode != NULL) {
598 if (unp->unp_flags & UNP_BINDING) {
602 unp->unp_flags |= UNP_BINDING;
605 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
606 bcopy(soun->sun_path, buf, namelen);
610 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
611 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
612 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
617 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
618 NDFREE(&nd, NDF_ONLY_PNBUF);
628 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
634 vattr.va_type = VSOCK;
635 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
637 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
641 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
642 NDFREE(&nd, NDF_ONLY_PNBUF);
645 vn_finished_write(mp);
649 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
650 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
653 VOP_UNP_BIND(vp, unp);
655 unp->unp_addr = soun;
656 unp->unp_flags &= ~UNP_BINDING;
659 vn_finished_write(mp);
665 unp->unp_flags &= ~UNP_BINDING;
672 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
675 return (uipc_bindat(AT_FDCWD, so, nam, td));
679 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
683 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
684 error = unp_connect(so, nam, td);
689 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
694 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
695 error = unp_connectat(fd, so, nam, td);
700 uipc_close(struct socket *so)
702 struct unpcb *unp, *unp2;
703 struct vnode *vp = NULL;
707 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
710 if ((vp = unp->unp_vnode) != NULL) {
711 vplock = mtx_pool_find(mtxpool_sleep, vp);
715 if (vp && unp->unp_vnode == NULL) {
721 unp->unp_vnode = NULL;
723 unp2 = unp->unp_conn;
725 if (__predict_false(unp == unp2)) {
726 unp_disconnect(unp, unp2);
727 } else if (unp2 != NULL) {
729 unp_pcb_owned_lock2(unp, unp2, freed);
730 unp_disconnect(unp, unp2);
731 if (unp_pcb_rele(unp2) == 0)
732 UNP_PCB_UNLOCK(unp2);
734 if (unp_pcb_rele(unp) == 0)
743 uipc_connect2(struct socket *so1, struct socket *so2)
745 struct unpcb *unp, *unp2;
749 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
751 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
753 unp_pcb_lock2(unp, unp2);
756 error = unp_connect2(so1, so2, PRU_CONNECT2);
758 UNP_PCB_UNLOCK(unp2);
764 uipc_detach(struct socket *so)
766 struct unpcb *unp, *unp2;
769 int freeunp, local_unp_rights;
772 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
776 local_unp_rights = 0;
779 if (!SOLISTENING(so)) {
781 * Once the socket is removed from the global lists,
782 * uipc_ready() will not be able to locate its socket buffer, so
783 * clear the buffer now. At this point internalized rights have
784 * already been disposed of.
786 sbrelease(&so->so_rcv, so);
791 LIST_REMOVE(unp, unp_link);
792 if (unp->unp_gcflag & UNPGC_DEAD)
793 LIST_REMOVE(unp, unp_dead);
794 unp->unp_gencnt = ++unp_gencnt;
798 UNP_PCB_UNLOCK_ASSERT(unp);
800 if ((vp = unp->unp_vnode) != NULL) {
801 vplock = mtx_pool_find(mtxpool_sleep, vp);
805 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
811 if ((vp = unp->unp_vnode) != NULL) {
813 unp->unp_vnode = NULL;
815 if (__predict_false(unp == unp->unp_conn)) {
816 unp_disconnect(unp, unp);
819 if ((unp2 = unp->unp_conn) != NULL) {
820 unp_pcb_owned_lock2(unp, unp2, freeunp);
827 unp_disconnect(unp, unp2);
828 if (unp_pcb_rele(unp2) == 0)
829 UNP_PCB_UNLOCK(unp2);
834 while (!LIST_EMPTY(&unp->unp_refs)) {
835 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
838 UNP_REF_LIST_UNLOCK();
841 UNP_PCB_UNLOCK_ASSERT(ref);
846 UNP_REF_LIST_UNLOCK();
848 freeunp = unp_pcb_rele(unp);
850 local_unp_rights = unp_rights;
851 unp->unp_socket->so_pcb = NULL;
852 unp->unp_socket = NULL;
853 free(unp->unp_addr, M_SONAME);
854 unp->unp_addr = NULL;
855 if (!unp_pcb_rele(unp))
861 if (local_unp_rights)
862 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
866 uipc_disconnect(struct socket *so)
868 struct unpcb *unp, *unp2;
872 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
875 if ((unp2 = unp->unp_conn) == NULL) {
879 if (__predict_true(unp != unp2)) {
880 unp_pcb_owned_lock2(unp, unp2, freed);
881 if (__predict_false(freed)) {
888 unp_disconnect(unp, unp2);
889 if (unp_pcb_rele(unp) == 0)
891 if ((unp != unp2) && unp_pcb_rele(unp2) == 0)
892 UNP_PCB_UNLOCK(unp2);
897 uipc_listen(struct socket *so, int backlog, struct thread *td)
902 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
906 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
909 if (unp->unp_vnode == NULL) {
910 /* Already connected or not bound to an address. */
911 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
917 error = solisten_proto_check(so);
919 cru2xt(td, &unp->unp_peercred);
920 solisten_proto(so, backlog);
928 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
930 struct unpcb *unp, *unp2;
931 const struct sockaddr *sa;
934 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
936 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
939 * XXX: It seems that this test always fails even when connection is
940 * established. So, this else clause is added as workaround to
941 * return PF_LOCAL sockaddr.
943 unp2 = unp->unp_conn;
946 if (unp2->unp_addr != NULL)
947 sa = (struct sockaddr *) unp2->unp_addr;
950 bcopy(sa, *nam, sa->sa_len);
951 UNP_PCB_UNLOCK(unp2);
954 bcopy(sa, *nam, sa->sa_len);
961 uipc_rcvd(struct socket *so, int flags)
963 struct unpcb *unp, *unp2;
968 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
969 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
970 ("%s: socktype %d", __func__, so->so_type));
973 * Adjust backpressure on sender and wakeup any waiting to write.
975 * The unp lock is acquired to maintain the validity of the unp_conn
976 * pointer; no lock on unp2 is required as unp2->unp_socket will be
977 * static as long as we don't permit unp2 to disconnect from unp,
978 * which is prevented by the lock on unp. We cache values from
979 * so_rcv to avoid holding the so_rcv lock over the entire
980 * transaction on the remote so_snd.
982 SOCKBUF_LOCK(&so->so_rcv);
983 mbcnt = so->so_rcv.sb_mbcnt;
984 sbcc = sbavail(&so->so_rcv);
985 SOCKBUF_UNLOCK(&so->so_rcv);
987 * There is a benign race condition at this point. If we're planning to
988 * clear SB_STOP, but uipc_send is called on the connected socket at
989 * this instant, it might add data to the sockbuf and set SB_STOP. Then
990 * we would erroneously clear SB_STOP below, even though the sockbuf is
991 * full. The race is benign because the only ill effect is to allow the
992 * sockbuf to exceed its size limit, and the size limits are not
993 * strictly guaranteed anyway.
996 unp2 = unp->unp_conn;
1001 so2 = unp2->unp_socket;
1002 SOCKBUF_LOCK(&so2->so_snd);
1003 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
1004 so2->so_snd.sb_flags &= ~SB_STOP;
1005 sowwakeup_locked(so2);
1006 UNP_PCB_UNLOCK(unp);
1011 connect_internal(struct socket *so, struct sockaddr *nam, struct thread *td)
1017 if (unp->unp_conn != NULL)
1019 error = unp_connect(so, nam, td);
1023 if (unp->unp_conn == NULL) {
1024 UNP_PCB_UNLOCK(unp);
1032 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1033 struct mbuf *control, struct thread *td)
1035 struct unpcb *unp, *unp2;
1040 unp = sotounpcb(so);
1041 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1042 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
1043 so->so_type == SOCK_SEQPACKET,
1044 ("%s: socktype %d", __func__, so->so_type));
1047 if (flags & PRUS_OOB) {
1051 if (control != NULL && (error = unp_internalize(&control, td)))
1055 switch (so->so_type) {
1058 const struct sockaddr *from;
1062 * We return with UNP_PCB_LOCK_HELD so we know that
1063 * the reference is live if the pointer is valid.
1065 if ((error = connect_internal(so, nam, td)))
1067 MPASS(unp->unp_conn != NULL);
1068 unp2 = unp->unp_conn;
1073 * Because connect() and send() are non-atomic in a sendto()
1074 * with a target address, it's possible that the socket will
1075 * have disconnected before the send() can run. In that case
1076 * return the slightly counter-intuitive but otherwise
1077 * correct error that the socket is not connected.
1079 if ((unp2 = unp->unp_conn) == NULL) {
1080 UNP_PCB_UNLOCK(unp);
1085 if (__predict_false(unp == unp2)) {
1086 if (unp->unp_socket == NULL) {
1092 unp_pcb_owned_lock2(unp, unp2, freed);
1093 if (__predict_false(freed)) {
1094 UNP_PCB_UNLOCK(unp);
1099 * The socket referencing unp2 may have been closed
1100 * or unp may have been disconnected if the unp lock
1101 * was dropped to acquire unp2.
1103 if (__predict_false(unp->unp_conn == NULL) ||
1104 unp2->unp_socket == NULL) {
1105 UNP_PCB_UNLOCK(unp);
1106 if (unp_pcb_rele(unp2) == 0)
1107 UNP_PCB_UNLOCK(unp2);
1112 if (unp2->unp_flags & UNP_WANTCRED)
1113 control = unp_addsockcred(td, control);
1114 if (unp->unp_addr != NULL)
1115 from = (struct sockaddr *)unp->unp_addr;
1118 so2 = unp2->unp_socket;
1119 SOCKBUF_LOCK(&so2->so_rcv);
1120 if (sbappendaddr_locked(&so2->so_rcv, from, m,
1122 sorwakeup_locked(so2);
1126 SOCKBUF_UNLOCK(&so2->so_rcv);
1130 unp_disconnect(unp, unp2);
1131 if (__predict_true(unp != unp2))
1132 UNP_PCB_UNLOCK(unp2);
1133 UNP_PCB_UNLOCK(unp);
1137 case SOCK_SEQPACKET:
1139 if ((so->so_state & SS_ISCONNECTED) == 0) {
1141 error = connect_internal(so, nam, td);
1152 if ((unp2 = unp->unp_conn) == NULL) {
1153 UNP_PCB_UNLOCK(unp);
1156 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1157 UNP_PCB_UNLOCK(unp);
1160 } else if ((unp2 = unp->unp_conn) == NULL) {
1161 UNP_PCB_UNLOCK(unp);
1165 unp_pcb_owned_lock2(unp, unp2, freed);
1166 UNP_PCB_UNLOCK(unp);
1167 if (__predict_false(freed)) {
1171 if ((so2 = unp2->unp_socket) == NULL) {
1172 UNP_PCB_UNLOCK(unp2);
1176 SOCKBUF_LOCK(&so2->so_rcv);
1177 if (unp2->unp_flags & UNP_WANTCRED) {
1179 * Credentials are passed only once on SOCK_STREAM
1180 * and SOCK_SEQPACKET.
1182 unp2->unp_flags &= ~UNP_WANTCRED;
1183 control = unp_addsockcred(td, control);
1187 * Send to paired receive port and wake up readers. Don't
1188 * check for space available in the receive buffer if we're
1189 * attaching ancillary data; Unix domain sockets only check
1190 * for space in the sending sockbuf, and that check is
1191 * performed one level up the stack. At that level we cannot
1192 * precisely account for the amount of buffer space used
1193 * (e.g., because control messages are not yet internalized).
1195 switch (so->so_type) {
1197 if (control != NULL) {
1198 sbappendcontrol_locked(&so2->so_rcv, m,
1202 sbappend_locked(&so2->so_rcv, m, flags);
1205 case SOCK_SEQPACKET:
1206 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1207 &sun_noname, m, control))
1212 mbcnt = so2->so_rcv.sb_mbcnt;
1213 sbcc = sbavail(&so2->so_rcv);
1215 sorwakeup_locked(so2);
1217 SOCKBUF_UNLOCK(&so2->so_rcv);
1220 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1221 * it would be possible for uipc_rcvd to be called at this
1222 * point, drain the receiving sockbuf, clear SB_STOP, and then
1223 * we would set SB_STOP below. That could lead to an empty
1224 * sockbuf having SB_STOP set
1226 SOCKBUF_LOCK(&so->so_snd);
1227 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1228 so->so_snd.sb_flags |= SB_STOP;
1229 SOCKBUF_UNLOCK(&so->so_snd);
1230 UNP_PCB_UNLOCK(unp2);
1236 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1238 if (flags & PRUS_EOF) {
1242 UNP_PCB_UNLOCK(unp);
1244 if (control != NULL && error != 0)
1245 unp_dispose_mbuf(control);
1248 if (control != NULL)
1251 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1252 * for freeing memory.
1254 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1260 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1262 struct mbuf *mb, *n;
1266 if (SOLISTENING(so)) {
1273 if (sb->sb_fnrdy != NULL) {
1274 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1276 *errorp = sbready(sb, m, count);
1289 return (mb != NULL);
1293 uipc_ready(struct socket *so, struct mbuf *m, int count)
1295 struct unpcb *unp, *unp2;
1299 unp = sotounpcb(so);
1301 KASSERT(so->so_type == SOCK_STREAM,
1302 ("%s: unexpected socket type for %p", __func__, so));
1305 if ((unp2 = unp->unp_conn) == NULL) {
1306 UNP_PCB_UNLOCK(unp);
1310 if (UNP_PCB_TRYLOCK(unp2) == 0) {
1312 UNP_PCB_UNLOCK(unp);
1314 if (unp_pcb_rele(unp2))
1317 UNP_PCB_UNLOCK(unp);
1319 so2 = unp2->unp_socket;
1320 SOCKBUF_LOCK(&so2->so_rcv);
1321 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1322 sorwakeup_locked(so2);
1324 SOCKBUF_UNLOCK(&so2->so_rcv);
1325 UNP_PCB_UNLOCK(unp2);
1330 * The receiving socket has been disconnected, but may still be valid.
1331 * In this case, the now-ready mbufs are still present in its socket
1332 * buffer, so perform an exhaustive search before giving up and freeing
1336 LIST_FOREACH(unp, &unp_shead, unp_link) {
1337 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1343 for (i = 0; i < count; i++)
1351 uipc_sense(struct socket *so, struct stat *sb)
1355 unp = sotounpcb(so);
1356 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1358 sb->st_blksize = so->so_snd.sb_hiwat;
1360 sb->st_ino = unp->unp_ino;
1365 uipc_shutdown(struct socket *so)
1369 unp = sotounpcb(so);
1370 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1375 UNP_PCB_UNLOCK(unp);
1380 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1383 const struct sockaddr *sa;
1385 unp = sotounpcb(so);
1386 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1388 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1390 if (unp->unp_addr != NULL)
1391 sa = (struct sockaddr *) unp->unp_addr;
1394 bcopy(sa, *nam, sa->sa_len);
1395 UNP_PCB_UNLOCK(unp);
1399 static struct pr_usrreqs uipc_usrreqs_dgram = {
1400 .pru_abort = uipc_abort,
1401 .pru_accept = uipc_accept,
1402 .pru_attach = uipc_attach,
1403 .pru_bind = uipc_bind,
1404 .pru_bindat = uipc_bindat,
1405 .pru_connect = uipc_connect,
1406 .pru_connectat = uipc_connectat,
1407 .pru_connect2 = uipc_connect2,
1408 .pru_detach = uipc_detach,
1409 .pru_disconnect = uipc_disconnect,
1410 .pru_listen = uipc_listen,
1411 .pru_peeraddr = uipc_peeraddr,
1412 .pru_rcvd = uipc_rcvd,
1413 .pru_send = uipc_send,
1414 .pru_sense = uipc_sense,
1415 .pru_shutdown = uipc_shutdown,
1416 .pru_sockaddr = uipc_sockaddr,
1417 .pru_soreceive = soreceive_dgram,
1418 .pru_close = uipc_close,
1421 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1422 .pru_abort = uipc_abort,
1423 .pru_accept = uipc_accept,
1424 .pru_attach = uipc_attach,
1425 .pru_bind = uipc_bind,
1426 .pru_bindat = uipc_bindat,
1427 .pru_connect = uipc_connect,
1428 .pru_connectat = uipc_connectat,
1429 .pru_connect2 = uipc_connect2,
1430 .pru_detach = uipc_detach,
1431 .pru_disconnect = uipc_disconnect,
1432 .pru_listen = uipc_listen,
1433 .pru_peeraddr = uipc_peeraddr,
1434 .pru_rcvd = uipc_rcvd,
1435 .pru_send = uipc_send,
1436 .pru_sense = uipc_sense,
1437 .pru_shutdown = uipc_shutdown,
1438 .pru_sockaddr = uipc_sockaddr,
1439 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1440 .pru_close = uipc_close,
1443 static struct pr_usrreqs uipc_usrreqs_stream = {
1444 .pru_abort = uipc_abort,
1445 .pru_accept = uipc_accept,
1446 .pru_attach = uipc_attach,
1447 .pru_bind = uipc_bind,
1448 .pru_bindat = uipc_bindat,
1449 .pru_connect = uipc_connect,
1450 .pru_connectat = uipc_connectat,
1451 .pru_connect2 = uipc_connect2,
1452 .pru_detach = uipc_detach,
1453 .pru_disconnect = uipc_disconnect,
1454 .pru_listen = uipc_listen,
1455 .pru_peeraddr = uipc_peeraddr,
1456 .pru_rcvd = uipc_rcvd,
1457 .pru_send = uipc_send,
1458 .pru_ready = uipc_ready,
1459 .pru_sense = uipc_sense,
1460 .pru_shutdown = uipc_shutdown,
1461 .pru_sockaddr = uipc_sockaddr,
1462 .pru_soreceive = soreceive_generic,
1463 .pru_close = uipc_close,
1467 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1473 if (sopt->sopt_level != SOL_LOCAL)
1476 unp = sotounpcb(so);
1477 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1479 switch (sopt->sopt_dir) {
1481 switch (sopt->sopt_name) {
1482 case LOCAL_PEERCRED:
1484 if (unp->unp_flags & UNP_HAVEPC)
1485 xu = unp->unp_peercred;
1487 if (so->so_type == SOCK_STREAM)
1492 UNP_PCB_UNLOCK(unp);
1494 error = sooptcopyout(sopt, &xu, sizeof(xu));
1498 /* Unlocked read. */
1499 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1500 error = sooptcopyout(sopt, &optval, sizeof(optval));
1503 case LOCAL_CONNWAIT:
1504 /* Unlocked read. */
1505 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1506 error = sooptcopyout(sopt, &optval, sizeof(optval));
1516 switch (sopt->sopt_name) {
1518 case LOCAL_CONNWAIT:
1519 error = sooptcopyin(sopt, &optval, sizeof(optval),
1524 #define OPTSET(bit) do { \
1525 UNP_PCB_LOCK(unp); \
1527 unp->unp_flags |= bit; \
1529 unp->unp_flags &= ~bit; \
1530 UNP_PCB_UNLOCK(unp); \
1533 switch (sopt->sopt_name) {
1535 OPTSET(UNP_WANTCRED);
1538 case LOCAL_CONNWAIT:
1539 OPTSET(UNP_CONNWAIT);
1548 error = ENOPROTOOPT;
1561 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1564 return (unp_connectat(AT_FDCWD, so, nam, td));
1568 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1571 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1574 struct unpcb *unp, *unp2, *unp3;
1575 struct nameidata nd;
1576 char buf[SOCK_MAXADDRLEN];
1577 struct sockaddr *sa;
1578 cap_rights_t rights;
1579 int error, len, freed;
1582 if (nam->sa_family != AF_UNIX)
1583 return (EAFNOSUPPORT);
1584 if (nam->sa_len > sizeof(struct sockaddr_un))
1586 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1589 bcopy(soun->sun_path, buf, len);
1592 unp = sotounpcb(so);
1594 if (unp->unp_flags & UNP_CONNECTING) {
1595 UNP_PCB_UNLOCK(unp);
1598 unp->unp_flags |= UNP_CONNECTING;
1599 UNP_PCB_UNLOCK(unp);
1601 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1602 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1603 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1609 ASSERT_VOP_LOCKED(vp, "unp_connect");
1610 NDFREE(&nd, NDF_ONLY_PNBUF);
1614 if (vp->v_type != VSOCK) {
1619 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1623 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1627 unp = sotounpcb(so);
1628 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1630 vplock = mtx_pool_find(mtxpool_sleep, vp);
1632 VOP_UNP_CONNECT(vp, &unp2);
1634 error = ECONNREFUSED;
1637 so2 = unp2->unp_socket;
1638 if (so->so_type != so2->so_type) {
1642 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1643 if (so2->so_options & SO_ACCEPTCONN) {
1644 CURVNET_SET(so2->so_vnet);
1645 so2 = sonewconn(so2, 0);
1650 error = ECONNREFUSED;
1653 unp3 = sotounpcb(so2);
1654 unp_pcb_lock2(unp2, unp3);
1655 if (unp2->unp_addr != NULL) {
1656 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1657 unp3->unp_addr = (struct sockaddr_un *) sa;
1661 unp_copy_peercred(td, unp3, unp, unp2);
1663 UNP_PCB_UNLOCK(unp2);
1665 unp_pcb_owned_lock2(unp2, unp, freed);
1666 if (__predict_false(freed)) {
1667 UNP_PCB_UNLOCK(unp2);
1668 error = ECONNREFUSED;
1672 mac_socketpeer_set_from_socket(so, so2);
1673 mac_socketpeer_set_from_socket(so2, so);
1679 unp_pcb_lock2(unp, unp2);
1681 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1682 sotounpcb(so2) == unp2,
1683 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1684 error = unp_connect2(so, so2, PRU_CONNECT);
1686 UNP_PCB_UNLOCK(unp2);
1687 UNP_PCB_UNLOCK(unp);
1696 unp->unp_flags &= ~UNP_CONNECTING;
1697 UNP_PCB_UNLOCK(unp);
1702 * Set socket peer credentials at connection time.
1704 * The client's PCB credentials are copied from its process structure. The
1705 * server's PCB credentials are copied from the socket on which it called
1706 * listen(2). uipc_listen cached that process's credentials at the time.
1709 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1710 struct unpcb *server_unp, struct unpcb *listen_unp)
1712 cru2xt(td, &client_unp->unp_peercred);
1713 client_unp->unp_flags |= UNP_HAVEPC;
1715 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1716 sizeof(server_unp->unp_peercred));
1717 server_unp->unp_flags |= UNP_HAVEPC;
1718 if (listen_unp->unp_flags & UNP_WANTCRED)
1719 client_unp->unp_flags |= UNP_WANTCRED;
1723 unp_connect2(struct socket *so, struct socket *so2, int req)
1728 unp = sotounpcb(so);
1729 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1730 unp2 = sotounpcb(so2);
1731 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1733 UNP_PCB_LOCK_ASSERT(unp);
1734 UNP_PCB_LOCK_ASSERT(unp2);
1736 if (so2->so_type != so->so_type)
1737 return (EPROTOTYPE);
1738 unp->unp_conn = unp2;
1741 switch (so->so_type) {
1743 UNP_REF_LIST_LOCK();
1744 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1745 UNP_REF_LIST_UNLOCK();
1750 case SOCK_SEQPACKET:
1751 unp2->unp_conn = unp;
1752 if (req == PRU_CONNECT &&
1753 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1761 panic("unp_connect2");
1767 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1769 struct socket *so, *so2;
1772 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1774 UNP_PCB_LOCK_ASSERT(unp);
1775 UNP_PCB_LOCK_ASSERT(unp2);
1777 if (unp->unp_conn == NULL && unp2->unp_conn == NULL)
1780 MPASS(unp->unp_conn == unp2);
1781 unp->unp_conn = NULL;
1782 so = unp->unp_socket;
1783 so2 = unp2->unp_socket;
1784 switch (unp->unp_socket->so_type) {
1786 UNP_REF_LIST_LOCK();
1787 LIST_REMOVE(unp, unp_reflink);
1788 UNP_REF_LIST_UNLOCK();
1791 so->so_state &= ~SS_ISCONNECTED;
1797 case SOCK_SEQPACKET:
1799 soisdisconnected(so);
1800 MPASS(unp2->unp_conn == unp);
1801 unp2->unp_conn = NULL;
1803 soisdisconnected(so2);
1806 freed = unp_pcb_rele(unp);
1808 freed = unp_pcb_rele(unp2);
1813 * unp_pcblist() walks the global list of struct unpcb's to generate a
1814 * pointer list, bumping the refcount on each unpcb. It then copies them out
1815 * sequentially, validating the generation number on each to see if it has
1816 * been detached. All of this is necessary because copyout() may sleep on
1820 unp_pcblist(SYSCTL_HANDLER_ARGS)
1822 struct unpcb *unp, **unp_list;
1824 struct xunpgen *xug;
1825 struct unp_head *head;
1828 int error, freeunp, n;
1830 switch ((intptr_t)arg1) {
1839 case SOCK_SEQPACKET:
1844 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1848 * The process of preparing the PCB list is too time-consuming and
1849 * resource-intensive to repeat twice on every request.
1851 if (req->oldptr == NULL) {
1853 req->oldidx = 2 * (sizeof *xug)
1854 + (n + n/8) * sizeof(struct xunpcb);
1858 if (req->newptr != NULL)
1862 * OK, now we're committed to doing something.
1864 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1866 gencnt = unp_gencnt;
1870 xug->xug_len = sizeof *xug;
1872 xug->xug_gen = gencnt;
1873 xug->xug_sogen = so_gencnt;
1874 error = SYSCTL_OUT(req, xug, sizeof *xug);
1880 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1883 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1884 unp = LIST_NEXT(unp, unp_link)) {
1886 if (unp->unp_gencnt <= gencnt) {
1887 if (cr_cansee(req->td->td_ucred,
1888 unp->unp_socket->so_cred)) {
1889 UNP_PCB_UNLOCK(unp);
1892 unp_list[i++] = unp;
1895 UNP_PCB_UNLOCK(unp);
1898 n = i; /* In case we lost some during malloc. */
1901 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1902 for (i = 0; i < n; i++) {
1905 freeunp = unp_pcb_rele(unp);
1907 if (freeunp == 0 && unp->unp_gencnt <= gencnt) {
1908 xu->xu_len = sizeof *xu;
1909 xu->xu_unpp = (uintptr_t)unp;
1911 * XXX - need more locking here to protect against
1912 * connect/disconnect races for SMP.
1914 if (unp->unp_addr != NULL)
1915 bcopy(unp->unp_addr, &xu->xu_addr,
1916 unp->unp_addr->sun_len);
1918 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1919 if (unp->unp_conn != NULL &&
1920 unp->unp_conn->unp_addr != NULL)
1921 bcopy(unp->unp_conn->unp_addr,
1923 unp->unp_conn->unp_addr->sun_len);
1925 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1926 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
1927 xu->unp_conn = (uintptr_t)unp->unp_conn;
1928 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
1929 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
1930 xu->unp_gencnt = unp->unp_gencnt;
1931 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1932 UNP_PCB_UNLOCK(unp);
1933 error = SYSCTL_OUT(req, xu, sizeof *xu);
1934 } else if (freeunp == 0)
1935 UNP_PCB_UNLOCK(unp);
1940 * Give the user an updated idea of our state. If the
1941 * generation differs from what we told her before, she knows
1942 * that something happened while we were processing this
1943 * request, and it might be necessary to retry.
1945 xug->xug_gen = unp_gencnt;
1946 xug->xug_sogen = so_gencnt;
1947 xug->xug_count = unp_count;
1948 error = SYSCTL_OUT(req, xug, sizeof *xug);
1950 free(unp_list, M_TEMP);
1955 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
1956 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1957 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1958 "List of active local datagram sockets");
1959 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
1960 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1961 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1962 "List of active local stream sockets");
1963 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1964 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1965 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1966 "List of active local seqpacket sockets");
1969 unp_shutdown(struct unpcb *unp)
1974 UNP_PCB_LOCK_ASSERT(unp);
1976 unp2 = unp->unp_conn;
1977 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1978 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1979 so = unp2->unp_socket;
1986 unp_drop(struct unpcb *unp)
1988 struct socket *so = unp->unp_socket;
1993 * Regardless of whether the socket's peer dropped the connection
1994 * with this socket by aborting or disconnecting, POSIX requires
1995 * that ECONNRESET is returned.
1997 /* acquire a reference so that unp isn't freed from underneath us */
2001 so->so_error = ECONNRESET;
2002 unp2 = unp->unp_conn;
2004 unp_disconnect(unp, unp2);
2005 } else if (unp2 != NULL) {
2007 unp_pcb_owned_lock2(unp, unp2, freed);
2008 unp_disconnect(unp, unp2);
2009 if (unp_pcb_rele(unp2) == 0)
2010 UNP_PCB_UNLOCK(unp2);
2012 if (unp_pcb_rele(unp) == 0)
2013 UNP_PCB_UNLOCK(unp);
2017 unp_freerights(struct filedescent **fdep, int fdcount)
2022 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2024 for (i = 0; i < fdcount; i++) {
2025 fp = fdep[i]->fde_file;
2026 filecaps_free(&fdep[i]->fde_caps);
2029 free(fdep[0], M_FILECAPS);
2033 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2035 struct thread *td = curthread; /* XXX */
2036 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2039 struct filedesc *fdesc = td->td_proc->p_fd;
2040 struct filedescent **fdep;
2042 socklen_t clen = control->m_len, datalen;
2046 UNP_LINK_UNLOCK_ASSERT();
2049 if (controlp != NULL) /* controlp == NULL => free control messages */
2051 while (cm != NULL) {
2052 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
2056 data = CMSG_DATA(cm);
2057 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2058 if (cm->cmsg_level == SOL_SOCKET
2059 && cm->cmsg_type == SCM_RIGHTS) {
2060 newfds = datalen / sizeof(*fdep);
2065 /* If we're not outputting the descriptors free them. */
2066 if (error || controlp == NULL) {
2067 unp_freerights(fdep, newfds);
2070 FILEDESC_XLOCK(fdesc);
2073 * Now change each pointer to an fd in the global
2074 * table to an integer that is the index to the local
2075 * fd table entry that we set up to point to the
2076 * global one we are transferring.
2078 newlen = newfds * sizeof(int);
2079 *controlp = sbcreatecontrol(NULL, newlen,
2080 SCM_RIGHTS, SOL_SOCKET);
2081 if (*controlp == NULL) {
2082 FILEDESC_XUNLOCK(fdesc);
2084 unp_freerights(fdep, newfds);
2089 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2090 if (fdallocn(td, 0, fdp, newfds) != 0) {
2091 FILEDESC_XUNLOCK(fdesc);
2093 unp_freerights(fdep, newfds);
2098 for (i = 0; i < newfds; i++, fdp++) {
2099 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2100 (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2101 &fdep[i]->fde_caps);
2102 unp_externalize_fp(fdep[i]->fde_file);
2106 * The new type indicates that the mbuf data refers to
2107 * kernel resources that may need to be released before
2108 * the mbuf is freed.
2110 m_chtype(*controlp, MT_EXTCONTROL);
2111 FILEDESC_XUNLOCK(fdesc);
2112 free(fdep[0], M_FILECAPS);
2114 /* We can just copy anything else across. */
2115 if (error || controlp == NULL)
2117 *controlp = sbcreatecontrol(NULL, datalen,
2118 cm->cmsg_type, cm->cmsg_level);
2119 if (*controlp == NULL) {
2124 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2127 controlp = &(*controlp)->m_next;
2130 if (CMSG_SPACE(datalen) < clen) {
2131 clen -= CMSG_SPACE(datalen);
2132 cm = (struct cmsghdr *)
2133 ((caddr_t)cm + CMSG_SPACE(datalen));
2145 unp_zone_change(void *tag)
2148 uma_zone_set_max(unp_zone, maxsockets);
2156 if (!IS_DEFAULT_VNET(curvnet))
2159 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
2160 NULL, NULL, UMA_ALIGN_CACHE, 0);
2161 if (unp_zone == NULL)
2163 uma_zone_set_max(unp_zone, maxsockets);
2164 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2165 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2166 NULL, EVENTHANDLER_PRI_ANY);
2167 LIST_INIT(&unp_dhead);
2168 LIST_INIT(&unp_shead);
2169 LIST_INIT(&unp_sphead);
2170 SLIST_INIT(&unp_defers);
2171 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2172 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2173 UNP_LINK_LOCK_INIT();
2174 UNP_DEFERRED_LOCK_INIT();
2178 unp_internalize_cleanup_rights(struct mbuf *control)
2185 for (m = control; m != NULL; m = m->m_next) {
2186 cp = mtod(m, struct cmsghdr *);
2187 if (cp->cmsg_level != SOL_SOCKET ||
2188 cp->cmsg_type != SCM_RIGHTS)
2190 data = CMSG_DATA(cp);
2191 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2192 unp_freerights(data, datalen / sizeof(struct filedesc *));
2197 unp_internalize(struct mbuf **controlp, struct thread *td)
2199 struct mbuf *control, **initial_controlp;
2201 struct filedesc *fdesc;
2204 struct cmsgcred *cmcred;
2205 struct filedescent *fde, **fdep, *fdev;
2208 struct timespec *ts;
2210 socklen_t clen, datalen;
2211 int i, j, error, *fdp, oldfds;
2214 UNP_LINK_UNLOCK_ASSERT();
2219 control = *controlp;
2220 clen = control->m_len;
2222 initial_controlp = controlp;
2223 for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
2224 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2225 || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2229 data = CMSG_DATA(cm);
2230 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2232 switch (cm->cmsg_type) {
2234 * Fill in credential information.
2237 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2238 SCM_CREDS, SOL_SOCKET);
2239 if (*controlp == NULL) {
2243 cmcred = (struct cmsgcred *)
2244 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2245 cmcred->cmcred_pid = p->p_pid;
2246 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2247 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2248 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2249 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2251 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2252 cmcred->cmcred_groups[i] =
2253 td->td_ucred->cr_groups[i];
2257 oldfds = datalen / sizeof (int);
2261 * Check that all the FDs passed in refer to legal
2262 * files. If not, reject the entire operation.
2265 FILEDESC_SLOCK(fdesc);
2266 for (i = 0; i < oldfds; i++, fdp++) {
2267 fp = fget_locked(fdesc, *fdp);
2269 FILEDESC_SUNLOCK(fdesc);
2273 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2274 FILEDESC_SUNLOCK(fdesc);
2281 * Now replace the integer FDs with pointers to the
2282 * file structure and capability rights.
2284 newlen = oldfds * sizeof(fdep[0]);
2285 *controlp = sbcreatecontrol(NULL, newlen,
2286 SCM_RIGHTS, SOL_SOCKET);
2287 if (*controlp == NULL) {
2288 FILEDESC_SUNLOCK(fdesc);
2293 for (i = 0; i < oldfds; i++, fdp++) {
2294 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2296 for (j = 0; j < i; j++, fdp++) {
2297 fdrop(fdesc->fd_ofiles[*fdp].
2300 FILEDESC_SUNLOCK(fdesc);
2306 fdep = (struct filedescent **)
2307 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2308 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2310 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2311 fde = &fdesc->fd_ofiles[*fdp];
2313 fdep[i]->fde_file = fde->fde_file;
2314 filecaps_copy(&fde->fde_caps,
2315 &fdep[i]->fde_caps, true);
2316 unp_internalize_fp(fdep[i]->fde_file);
2318 FILEDESC_SUNLOCK(fdesc);
2322 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2323 SCM_TIMESTAMP, SOL_SOCKET);
2324 if (*controlp == NULL) {
2328 tv = (struct timeval *)
2329 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2334 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2335 SCM_BINTIME, SOL_SOCKET);
2336 if (*controlp == NULL) {
2340 bt = (struct bintime *)
2341 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2346 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2347 SCM_REALTIME, SOL_SOCKET);
2348 if (*controlp == NULL) {
2352 ts = (struct timespec *)
2353 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2358 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2359 SCM_MONOTONIC, SOL_SOCKET);
2360 if (*controlp == NULL) {
2364 ts = (struct timespec *)
2365 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2374 if (*controlp != NULL)
2375 controlp = &(*controlp)->m_next;
2376 if (CMSG_SPACE(datalen) < clen) {
2377 clen -= CMSG_SPACE(datalen);
2378 cm = (struct cmsghdr *)
2379 ((caddr_t)cm + CMSG_SPACE(datalen));
2387 if (error != 0 && initial_controlp != NULL)
2388 unp_internalize_cleanup_rights(*initial_controlp);
2393 static struct mbuf *
2394 unp_addsockcred(struct thread *td, struct mbuf *control)
2396 struct mbuf *m, *n, *n_prev;
2397 struct sockcred *sc;
2398 const struct cmsghdr *cm;
2402 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2403 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2407 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2408 sc->sc_uid = td->td_ucred->cr_ruid;
2409 sc->sc_euid = td->td_ucred->cr_uid;
2410 sc->sc_gid = td->td_ucred->cr_rgid;
2411 sc->sc_egid = td->td_ucred->cr_gid;
2412 sc->sc_ngroups = ngroups;
2413 for (i = 0; i < sc->sc_ngroups; i++)
2414 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2417 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2418 * created SCM_CREDS control message (struct sockcred) has another
2421 if (control != NULL)
2422 for (n = control, n_prev = NULL; n != NULL;) {
2423 cm = mtod(n, struct cmsghdr *);
2424 if (cm->cmsg_level == SOL_SOCKET &&
2425 cm->cmsg_type == SCM_CREDS) {
2427 control = n->m_next;
2429 n_prev->m_next = n->m_next;
2437 /* Prepend it to the head. */
2438 m->m_next = control;
2442 static struct unpcb *
2443 fptounp(struct file *fp)
2447 if (fp->f_type != DTYPE_SOCKET)
2449 if ((so = fp->f_data) == NULL)
2451 if (so->so_proto->pr_domain != &localdomain)
2453 return sotounpcb(so);
2457 unp_discard(struct file *fp)
2459 struct unp_defer *dr;
2461 if (unp_externalize_fp(fp)) {
2462 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2464 UNP_DEFERRED_LOCK();
2465 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2466 UNP_DEFERRED_UNLOCK();
2467 atomic_add_int(&unp_defers_count, 1);
2468 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2470 (void) closef(fp, (struct thread *)NULL);
2474 unp_process_defers(void *arg __unused, int pending)
2476 struct unp_defer *dr;
2477 SLIST_HEAD(, unp_defer) drl;
2482 UNP_DEFERRED_LOCK();
2483 if (SLIST_FIRST(&unp_defers) == NULL) {
2484 UNP_DEFERRED_UNLOCK();
2487 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2488 UNP_DEFERRED_UNLOCK();
2490 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2491 SLIST_REMOVE_HEAD(&drl, ud_link);
2492 closef(dr->ud_fp, NULL);
2496 atomic_add_int(&unp_defers_count, -count);
2501 unp_internalize_fp(struct file *fp)
2506 if ((unp = fptounp(fp)) != NULL) {
2508 unp->unp_msgcount++;
2515 unp_externalize_fp(struct file *fp)
2521 if ((unp = fptounp(fp)) != NULL) {
2522 unp->unp_msgcount--;
2532 * unp_defer indicates whether additional work has been defered for a future
2533 * pass through unp_gc(). It is thread local and does not require explicit
2536 static int unp_marked;
2539 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2546 * This function can only be called from the gc task.
2548 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2549 ("%s: not on gc callout", __func__));
2550 UNP_LINK_LOCK_ASSERT();
2552 for (i = 0; i < fdcount; i++) {
2553 fp = fdep[i]->fde_file;
2554 if ((unp = fptounp(fp)) == NULL)
2556 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2563 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2570 * This function can only be called from the gc task.
2572 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2573 ("%s: not on gc callout", __func__));
2574 UNP_LINK_LOCK_ASSERT();
2576 for (i = 0; i < fdcount; i++) {
2577 fp = fdep[i]->fde_file;
2578 if ((unp = fptounp(fp)) == NULL)
2580 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2588 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2590 struct socket *so, *soa;
2592 so = unp->unp_socket;
2594 if (SOLISTENING(so)) {
2596 * Mark all sockets in our accept queue.
2598 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2599 if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2601 SOCKBUF_LOCK(&soa->so_rcv);
2602 unp_scan(soa->so_rcv.sb_mb, op);
2603 SOCKBUF_UNLOCK(&soa->so_rcv);
2607 * Mark all sockets we reference with RIGHTS.
2609 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2610 SOCKBUF_LOCK(&so->so_rcv);
2611 unp_scan(so->so_rcv.sb_mb, op);
2612 SOCKBUF_UNLOCK(&so->so_rcv);
2618 static int unp_recycled;
2619 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2620 "Number of unreachable sockets claimed by the garbage collector.");
2622 static int unp_taskcount;
2623 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2624 "Number of times the garbage collector has run.");
2626 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2627 "Number of active local sockets.");
2630 unp_gc(__unused void *arg, int pending)
2632 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2634 struct unp_head **head;
2635 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
2636 struct file *f, **unref;
2637 struct unpcb *unp, *unptmp;
2638 int i, total, unp_unreachable;
2640 LIST_INIT(&unp_deadhead);
2644 * First determine which sockets may be in cycles.
2646 unp_unreachable = 0;
2648 for (head = heads; *head != NULL; head++)
2649 LIST_FOREACH(unp, *head, unp_link) {
2650 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2651 ("%s: unp %p has unexpected gc flags 0x%x",
2652 __func__, unp, (unsigned int)unp->unp_gcflag));
2657 * Check for an unreachable socket potentially in a
2658 * cycle. It must be in a queue as indicated by
2659 * msgcount, and this must equal the file reference
2660 * count. Note that when msgcount is 0 the file is
2663 if (f != NULL && unp->unp_msgcount != 0 &&
2664 f->f_count == unp->unp_msgcount) {
2665 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2666 unp->unp_gcflag |= UNPGC_DEAD;
2667 unp->unp_gcrefs = unp->unp_msgcount;
2673 * Scan all sockets previously marked as potentially being in a cycle
2674 * and remove the references each socket holds on any UNPGC_DEAD
2675 * sockets in its queue. After this step, all remaining references on
2676 * sockets marked UNPGC_DEAD should not be part of any cycle.
2678 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2679 unp_gc_scan(unp, unp_remove_dead_ref);
2682 * If a socket still has a non-negative refcount, it cannot be in a
2683 * cycle. In this case increment refcount of all children iteratively.
2684 * Stop the scan once we do a complete loop without discovering
2685 * a new reachable socket.
2689 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2690 if (unp->unp_gcrefs > 0) {
2691 unp->unp_gcflag &= ~UNPGC_DEAD;
2692 LIST_REMOVE(unp, unp_dead);
2693 KASSERT(unp_unreachable > 0,
2694 ("%s: unp_unreachable underflow.",
2697 unp_gc_scan(unp, unp_restore_undead_ref);
2699 } while (unp_marked);
2703 if (unp_unreachable == 0)
2707 * Allocate space for a local array of dead unpcbs.
2708 * TODO: can this path be simplified by instead using the local
2709 * dead list at unp_deadhead, after taking out references
2710 * on the file object and/or unpcb and dropping the link lock?
2712 unref = malloc(unp_unreachable * sizeof(struct file *),
2716 * Iterate looking for sockets which have been specifically marked
2717 * as unreachable and store them locally.
2721 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2722 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2723 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2724 unp->unp_gcflag &= ~UNPGC_DEAD;
2726 if (unp->unp_msgcount == 0 || f == NULL ||
2727 f->f_count != unp->unp_msgcount ||
2731 KASSERT(total <= unp_unreachable,
2732 ("%s: incorrect unreachable count.", __func__));
2737 * Now flush all sockets, free'ing rights. This will free the
2738 * struct files associated with these sockets but leave each socket
2739 * with one remaining ref.
2741 for (i = 0; i < total; i++) {
2744 so = unref[i]->f_data;
2745 CURVNET_SET(so->so_vnet);
2751 * And finally release the sockets so they can be reclaimed.
2753 for (i = 0; i < total; i++)
2754 fdrop(unref[i], NULL);
2755 unp_recycled += total;
2756 free(unref, M_TEMP);
2760 unp_dispose_mbuf(struct mbuf *m)
2764 unp_scan(m, unp_freerights);
2768 * Synchronize against unp_gc, which can trip over data as we are freeing it.
2771 unp_dispose(struct socket *so)
2775 unp = sotounpcb(so);
2777 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2779 if (!SOLISTENING(so))
2780 unp_dispose_mbuf(so->so_rcv.sb_mb);
2784 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2789 socklen_t clen, datalen;
2791 while (m0 != NULL) {
2792 for (m = m0; m; m = m->m_next) {
2793 if (m->m_type != MT_CONTROL)
2796 cm = mtod(m, struct cmsghdr *);
2799 while (cm != NULL) {
2800 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2803 data = CMSG_DATA(cm);
2804 datalen = (caddr_t)cm + cm->cmsg_len
2807 if (cm->cmsg_level == SOL_SOCKET &&
2808 cm->cmsg_type == SCM_RIGHTS) {
2809 (*op)(data, datalen /
2810 sizeof(struct filedescent *));
2813 if (CMSG_SPACE(datalen) < clen) {
2814 clen -= CMSG_SPACE(datalen);
2815 cm = (struct cmsghdr *)
2816 ((caddr_t)cm + CMSG_SPACE(datalen));
2828 * A helper function called by VFS before socket-type vnode reclamation.
2829 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2833 vfs_unp_reclaim(struct vnode *vp)
2839 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2840 KASSERT(vp->v_type == VSOCK,
2841 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2844 vplock = mtx_pool_find(mtxpool_sleep, vp);
2846 VOP_UNP_CONNECT(vp, &unp);
2850 if (unp->unp_vnode == vp) {
2852 unp->unp_vnode = NULL;
2855 UNP_PCB_UNLOCK(unp);
2864 db_print_indent(int indent)
2868 for (i = 0; i < indent; i++)
2873 db_print_unpflags(int unp_flags)
2878 if (unp_flags & UNP_HAVEPC) {
2879 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2882 if (unp_flags & UNP_WANTCRED) {
2883 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2886 if (unp_flags & UNP_CONNWAIT) {
2887 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2890 if (unp_flags & UNP_CONNECTING) {
2891 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2894 if (unp_flags & UNP_BINDING) {
2895 db_printf("%sUNP_BINDING", comma ? ", " : "");
2901 db_print_xucred(int indent, struct xucred *xu)
2905 db_print_indent(indent);
2906 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
2907 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
2908 db_print_indent(indent);
2909 db_printf("cr_groups: ");
2911 for (i = 0; i < xu->cr_ngroups; i++) {
2912 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2919 db_print_unprefs(int indent, struct unp_head *uh)
2925 LIST_FOREACH(unp, uh, unp_reflink) {
2926 if (counter % 4 == 0)
2927 db_print_indent(indent);
2928 db_printf("%p ", unp);
2929 if (counter % 4 == 3)
2933 if (counter != 0 && counter % 4 != 0)
2937 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2942 db_printf("usage: show unpcb <addr>\n");
2945 unp = (struct unpcb *)addr;
2947 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2950 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2953 db_printf("unp_refs:\n");
2954 db_print_unprefs(2, &unp->unp_refs);
2956 /* XXXRW: Would be nice to print the full address, if any. */
2957 db_printf("unp_addr: %p\n", unp->unp_addr);
2959 db_printf("unp_gencnt: %llu\n",
2960 (unsigned long long)unp->unp_gencnt);
2962 db_printf("unp_flags: %x (", unp->unp_flags);
2963 db_print_unpflags(unp->unp_flags);
2966 db_printf("unp_peercred:\n");
2967 db_print_xucred(2, &unp->unp_peercred);
2969 db_printf("unp_refcount: %u\n", unp->unp_refcount);