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/eventhandler.h>
69 #include <sys/fcntl.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
74 #include <sys/malloc.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);
109 * See unpcb.h for the locking key.
112 static uma_zone_t unp_zone;
113 static unp_gen_t unp_gencnt; /* (l) */
114 static u_int unp_count; /* (l) Count of local sockets. */
115 static ino_t unp_ino; /* Prototype for fake inode numbers. */
116 static int unp_rights; /* (g) File descriptors in flight. */
117 static struct unp_head unp_shead; /* (l) List of stream sockets. */
118 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
119 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
122 SLIST_ENTRY(unp_defer) ud_link;
125 static SLIST_HEAD(, unp_defer) unp_defers;
126 static int unp_defers_count;
128 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
131 * Garbage collection of cyclic file descriptor/socket references occurs
132 * asynchronously in a taskqueue context in order to avoid recursion and
133 * reentrance in the UNIX domain socket, file descriptor, and socket layer
134 * code. See unp_gc() for a full description.
136 static struct timeout_task unp_gc_task;
139 * The close of unix domain sockets attached as SCM_RIGHTS is
140 * postponed to the taskqueue, to avoid arbitrary recursion depth.
141 * The attached sockets might have another sockets attached.
143 static struct task unp_defer_task;
146 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
147 * stream sockets, although the total for sender and receiver is actually
150 * Datagram sockets really use the sendspace as the maximum datagram size,
151 * and don't really want to reserve the sendspace. Their recvspace should be
152 * large enough for at least one max-size datagram plus address.
157 static u_long unpst_sendspace = PIPSIZ;
158 static u_long unpst_recvspace = PIPSIZ;
159 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
160 static u_long unpdg_recvspace = 4*1024;
161 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
162 static u_long unpsp_recvspace = PIPSIZ;
164 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
166 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
167 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
169 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
170 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
173 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
177 &unpst_sendspace, 0, "Default stream send space.");
178 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
179 &unpst_recvspace, 0, "Default stream receive space.");
180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
181 &unpdg_sendspace, 0, "Default datagram send space.");
182 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
183 &unpdg_recvspace, 0, "Default datagram receive space.");
184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
185 &unpsp_sendspace, 0, "Default seqpacket send space.");
186 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
187 &unpsp_recvspace, 0, "Default seqpacket receive space.");
188 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
189 "File descriptors in flight.");
190 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
191 &unp_defers_count, 0,
192 "File descriptors deferred to taskqueue for close.");
195 * Locking and synchronization:
197 * Several types of locks exist in the local domain socket implementation:
198 * - a global linkage lock
199 * - a global connection list lock
201 * - per-unpcb mutexes
203 * The linkage lock protects the global socket lists, the generation number
204 * counter and garbage collector state.
206 * The connection list lock protects the list of referring sockets in a datagram
207 * socket PCB. This lock is also overloaded to protect a global list of
208 * sockets whose buffers contain socket references in the form of SCM_RIGHTS
209 * messages. To avoid recursion, such references are released by a dedicated
212 * The mtxpool lock protects the vnode from being modified while referenced.
213 * Lock ordering rules require that it be acquired before any PCB locks.
215 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
216 * unpcb. This includes the unp_conn field, which either links two connected
217 * PCBs together (for connected socket types) or points at the destination
218 * socket (for connectionless socket types). The operations of creating or
219 * destroying a connection therefore involve locking multiple PCBs. To avoid
220 * lock order reversals, in some cases this involves dropping a PCB lock and
221 * using a reference counter to maintain liveness.
223 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
224 * allocated in pru_attach() and freed in pru_detach(). The validity of that
225 * pointer is an invariant, so no lock is required to dereference the so_pcb
226 * pointer if a valid socket reference is held by the caller. In practice,
227 * this is always true during operations performed on a socket. Each unpcb
228 * has a back-pointer to its socket, unp_socket, which will be stable under
229 * the same circumstances.
231 * This pointer may only be safely dereferenced as long as a valid reference
232 * to the unpcb is held. Typically, this reference will be from the socket,
233 * or from another unpcb when the referring unpcb's lock is held (in order
234 * that the reference not be invalidated during use). For example, to follow
235 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
236 * that detach is not run clearing unp_socket.
238 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
239 * protocols, bind() is a non-atomic operation, and connect() requires
240 * potential sleeping in the protocol, due to potentially waiting on local or
241 * distributed file systems. We try to separate "lookup" operations, which
242 * may sleep, and the IPC operations themselves, which typically can occur
243 * with relative atomicity as locks can be held over the entire operation.
245 * Another tricky issue is simultaneous multi-threaded or multi-process
246 * access to a single UNIX domain socket. These are handled by the flags
247 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
248 * binding, both of which involve dropping UNIX domain socket locks in order
249 * to perform namei() and other file system operations.
251 static struct rwlock unp_link_rwlock;
252 static struct mtx unp_defers_lock;
254 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
257 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
259 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
262 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
263 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
264 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
265 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
266 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
268 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
270 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
271 "unp_defer", NULL, MTX_DEF)
272 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
273 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
275 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
276 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
278 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
281 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
282 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx)
283 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
284 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
285 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
286 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
287 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
288 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
290 static int uipc_connect2(struct socket *, struct socket *);
291 static int uipc_ctloutput(struct socket *, struct sockopt *);
292 static int unp_connect(struct socket *, struct sockaddr *,
294 static int unp_connectat(int, struct socket *, struct sockaddr *,
296 static int unp_connect2(struct socket *so, struct socket *so2, int);
297 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
298 static void unp_dispose(struct socket *so);
299 static void unp_dispose_mbuf(struct mbuf *);
300 static void unp_shutdown(struct unpcb *);
301 static void unp_drop(struct unpcb *);
302 static void unp_gc(__unused void *, int);
303 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
304 static void unp_discard(struct file *);
305 static void unp_freerights(struct filedescent **, int);
306 static void unp_init(void);
307 static int unp_internalize(struct mbuf **, struct thread *);
308 static void unp_internalize_fp(struct file *);
309 static int unp_externalize(struct mbuf *, struct mbuf **, int);
310 static int unp_externalize_fp(struct file *);
311 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
312 static void unp_process_defers(void * __unused, int);
315 unp_pcb_hold(struct unpcb *unp)
319 old = refcount_acquire(&unp->unp_refcount);
320 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
323 static __result_use_check bool
324 unp_pcb_rele(struct unpcb *unp)
328 UNP_PCB_LOCK_ASSERT(unp);
330 if ((ret = refcount_release(&unp->unp_refcount))) {
332 UNP_PCB_LOCK_DESTROY(unp);
333 uma_zfree(unp_zone, unp);
339 unp_pcb_rele_notlast(struct unpcb *unp)
343 ret = refcount_release(&unp->unp_refcount);
344 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
348 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
350 UNP_PCB_UNLOCK_ASSERT(unp);
351 UNP_PCB_UNLOCK_ASSERT(unp2);
355 } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
365 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
369 UNP_PCB_UNLOCK(unp2);
373 * Try to lock the connected peer of an already locked socket. In some cases
374 * this requires that we unlock the current socket. The pairbusy counter is
375 * used to block concurrent connection attempts while the lock is dropped. The
376 * caller must be careful to revalidate PCB state.
378 static struct unpcb *
379 unp_pcb_lock_peer(struct unpcb *unp)
383 UNP_PCB_LOCK_ASSERT(unp);
384 unp2 = unp->unp_conn;
385 if (__predict_false(unp2 == NULL))
387 if (__predict_false(unp == unp2))
390 UNP_PCB_UNLOCK_ASSERT(unp2);
392 if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
394 if ((uintptr_t)unp2 > (uintptr_t)unp) {
404 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
405 ("%s: socket %p was reconnected", __func__, unp));
406 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
407 unp->unp_flags &= ~UNP_WAITING;
410 if (unp_pcb_rele(unp2)) {
411 /* unp2 is unlocked. */
414 if (unp->unp_conn == NULL) {
415 UNP_PCB_UNLOCK(unp2);
422 * Definitions of protocols supported in the LOCAL domain.
424 static struct domain localdomain;
425 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
426 static struct pr_usrreqs uipc_usrreqs_seqpacket;
427 static struct protosw localsw[] = {
429 .pr_type = SOCK_STREAM,
430 .pr_domain = &localdomain,
431 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
432 .pr_ctloutput = &uipc_ctloutput,
433 .pr_usrreqs = &uipc_usrreqs_stream
436 .pr_type = SOCK_DGRAM,
437 .pr_domain = &localdomain,
438 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
439 .pr_ctloutput = &uipc_ctloutput,
440 .pr_usrreqs = &uipc_usrreqs_dgram
443 .pr_type = SOCK_SEQPACKET,
444 .pr_domain = &localdomain,
447 * XXXRW: For now, PR_ADDR because soreceive will bump into them
448 * due to our use of sbappendaddr. A new sbappend variants is needed
449 * that supports both atomic record writes and control data.
451 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
453 .pr_ctloutput = &uipc_ctloutput,
454 .pr_usrreqs = &uipc_usrreqs_seqpacket,
458 static struct domain localdomain = {
459 .dom_family = AF_LOCAL,
461 .dom_init = unp_init,
462 .dom_externalize = unp_externalize,
463 .dom_dispose = unp_dispose,
464 .dom_protosw = localsw,
465 .dom_protoswNPROTOSW = &localsw[nitems(localsw)]
470 uipc_abort(struct socket *so)
472 struct unpcb *unp, *unp2;
475 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
476 UNP_PCB_UNLOCK_ASSERT(unp);
479 unp2 = unp->unp_conn;
489 uipc_accept(struct socket *so, struct sockaddr **nam)
491 struct unpcb *unp, *unp2;
492 const struct sockaddr *sa;
495 * Pass back name of connected socket, if it was bound and we are
496 * still connected (our peer may have closed already!).
499 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
501 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
503 unp2 = unp_pcb_lock_peer(unp);
504 if (unp2 != NULL && unp2->unp_addr != NULL)
505 sa = (struct sockaddr *)unp2->unp_addr;
508 bcopy(sa, *nam, sa->sa_len);
510 unp_pcb_unlock_pair(unp, unp2);
517 uipc_attach(struct socket *so, int proto, struct thread *td)
519 u_long sendspace, recvspace;
524 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
525 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
526 switch (so->so_type) {
528 sendspace = unpst_sendspace;
529 recvspace = unpst_recvspace;
533 sendspace = unpdg_sendspace;
534 recvspace = unpdg_recvspace;
538 sendspace = unpsp_sendspace;
539 recvspace = unpsp_recvspace;
543 panic("uipc_attach");
545 error = soreserve(so, sendspace, recvspace);
549 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
552 LIST_INIT(&unp->unp_refs);
553 UNP_PCB_LOCK_INIT(unp);
554 unp->unp_socket = so;
556 refcount_init(&unp->unp_refcount, 1);
558 if ((locked = UNP_LINK_WOWNED()) == false)
561 unp->unp_gencnt = ++unp_gencnt;
562 unp->unp_ino = ++unp_ino;
564 switch (so->so_type) {
566 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
570 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
574 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
578 panic("uipc_attach");
588 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
590 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
600 if (nam->sa_family != AF_UNIX)
601 return (EAFNOSUPPORT);
604 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
606 if (soun->sun_len > sizeof(struct sockaddr_un))
608 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
613 * We don't allow simultaneous bind() calls on a single UNIX domain
614 * socket, so flag in-progress operations, and return an error if an
615 * operation is already in progress.
617 * Historically, we have not allowed a socket to be rebound, so this
618 * also returns an error. Not allowing re-binding simplifies the
619 * implementation and avoids a great many possible failure modes.
622 if (unp->unp_vnode != NULL) {
626 if (unp->unp_flags & UNP_BINDING) {
630 unp->unp_flags |= UNP_BINDING;
633 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
634 bcopy(soun->sun_path, buf, namelen);
638 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
639 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
640 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
645 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
646 NDFREE(&nd, NDF_ONLY_PNBUF);
656 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
662 vattr.va_type = VSOCK;
663 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
665 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
669 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
670 NDFREE(&nd, NDF_ONLY_PNBUF);
673 vn_finished_write(mp);
674 if (error == ERELOOKUP)
679 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
680 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
683 VOP_UNP_BIND(vp, unp);
685 unp->unp_addr = soun;
686 unp->unp_flags &= ~UNP_BINDING;
689 vn_finished_write(mp);
695 unp->unp_flags &= ~UNP_BINDING;
702 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
705 return (uipc_bindat(AT_FDCWD, so, nam, td));
709 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
713 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
714 error = unp_connect(so, nam, td);
719 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
724 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
725 error = unp_connectat(fd, so, nam, td);
730 uipc_close(struct socket *so)
732 struct unpcb *unp, *unp2;
733 struct vnode *vp = NULL;
737 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
740 if ((vp = unp->unp_vnode) != NULL) {
741 vplock = mtx_pool_find(mtxpool_sleep, vp);
745 if (vp && unp->unp_vnode == NULL) {
751 unp->unp_vnode = NULL;
753 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
754 unp_disconnect(unp, unp2);
764 uipc_connect2(struct socket *so1, struct socket *so2)
766 struct unpcb *unp, *unp2;
770 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
772 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
773 unp_pcb_lock_pair(unp, unp2);
774 error = unp_connect2(so1, so2, PRU_CONNECT2);
775 unp_pcb_unlock_pair(unp, unp2);
780 uipc_detach(struct socket *so)
782 struct unpcb *unp, *unp2;
785 int local_unp_rights;
788 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
794 if (!SOLISTENING(so)) {
796 * Once the socket is removed from the global lists,
797 * uipc_ready() will not be able to locate its socket buffer, so
798 * clear the buffer now. At this point internalized rights have
799 * already been disposed of.
801 sbrelease(&so->so_rcv, so);
806 LIST_REMOVE(unp, unp_link);
807 if (unp->unp_gcflag & UNPGC_DEAD)
808 LIST_REMOVE(unp, unp_dead);
809 unp->unp_gencnt = ++unp_gencnt;
813 UNP_PCB_UNLOCK_ASSERT(unp);
815 if ((vp = unp->unp_vnode) != NULL) {
816 vplock = mtx_pool_find(mtxpool_sleep, vp);
820 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
826 if ((vp = unp->unp_vnode) != NULL) {
828 unp->unp_vnode = NULL;
830 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
831 unp_disconnect(unp, unp2);
836 while (!LIST_EMPTY(&unp->unp_refs)) {
837 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
840 UNP_REF_LIST_UNLOCK();
843 UNP_PCB_UNLOCK_ASSERT(ref);
847 UNP_REF_LIST_UNLOCK();
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;
871 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
874 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
875 unp_disconnect(unp, unp2);
882 uipc_listen(struct socket *so, int backlog, struct thread *td)
887 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
891 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
894 if (unp->unp_vnode == NULL) {
895 /* Already connected or not bound to an address. */
896 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
902 error = solisten_proto_check(so);
904 cru2xt(td, &unp->unp_peercred);
905 solisten_proto(so, backlog);
913 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
915 struct unpcb *unp, *unp2;
916 const struct sockaddr *sa;
919 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
921 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
924 * XXX: It seems that this test always fails even when connection is
925 * established. So, this else clause is added as workaround to
926 * return PF_LOCAL sockaddr.
928 unp2 = unp->unp_conn;
931 if (unp2->unp_addr != NULL)
932 sa = (struct sockaddr *) unp2->unp_addr;
935 bcopy(sa, *nam, sa->sa_len);
936 UNP_PCB_UNLOCK(unp2);
939 bcopy(sa, *nam, sa->sa_len);
946 uipc_rcvd(struct socket *so, int flags)
948 struct unpcb *unp, *unp2;
953 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
954 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
955 ("%s: socktype %d", __func__, so->so_type));
958 * Adjust backpressure on sender and wakeup any waiting to write.
960 * The unp lock is acquired to maintain the validity of the unp_conn
961 * pointer; no lock on unp2 is required as unp2->unp_socket will be
962 * static as long as we don't permit unp2 to disconnect from unp,
963 * which is prevented by the lock on unp. We cache values from
964 * so_rcv to avoid holding the so_rcv lock over the entire
965 * transaction on the remote so_snd.
967 SOCKBUF_LOCK(&so->so_rcv);
968 mbcnt = so->so_rcv.sb_mbcnt;
969 sbcc = sbavail(&so->so_rcv);
970 SOCKBUF_UNLOCK(&so->so_rcv);
972 * There is a benign race condition at this point. If we're planning to
973 * clear SB_STOP, but uipc_send is called on the connected socket at
974 * this instant, it might add data to the sockbuf and set SB_STOP. Then
975 * we would erroneously clear SB_STOP below, even though the sockbuf is
976 * full. The race is benign because the only ill effect is to allow the
977 * sockbuf to exceed its size limit, and the size limits are not
978 * strictly guaranteed anyway.
981 unp2 = unp->unp_conn;
986 so2 = unp2->unp_socket;
987 SOCKBUF_LOCK(&so2->so_snd);
988 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
989 so2->so_snd.sb_flags &= ~SB_STOP;
990 sowwakeup_locked(so2);
996 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
997 struct mbuf *control, struct thread *td)
999 struct unpcb *unp, *unp2;
1004 unp = sotounpcb(so);
1005 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1006 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
1007 so->so_type == SOCK_SEQPACKET,
1008 ("%s: socktype %d", __func__, so->so_type));
1011 if (flags & PRUS_OOB) {
1015 if (control != NULL && (error = unp_internalize(&control, td)))
1019 switch (so->so_type) {
1022 const struct sockaddr *from;
1025 error = unp_connect(so, nam, td);
1032 * Because connect() and send() are non-atomic in a sendto()
1033 * with a target address, it's possible that the socket will
1034 * have disconnected before the send() can run. In that case
1035 * return the slightly counter-intuitive but otherwise
1036 * correct error that the socket is not connected.
1038 unp2 = unp_pcb_lock_peer(unp);
1040 UNP_PCB_UNLOCK(unp);
1045 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1046 control = unp_addsockcred(td, control);
1047 if (unp->unp_addr != NULL)
1048 from = (struct sockaddr *)unp->unp_addr;
1051 so2 = unp2->unp_socket;
1052 SOCKBUF_LOCK(&so2->so_rcv);
1053 if (sbappendaddr_locked(&so2->so_rcv, from, m,
1055 sorwakeup_locked(so2);
1059 SOCKBUF_UNLOCK(&so2->so_rcv);
1063 unp_disconnect(unp, unp2);
1065 unp_pcb_unlock_pair(unp, unp2);
1069 case SOCK_SEQPACKET:
1071 if ((so->so_state & SS_ISCONNECTED) == 0) {
1073 error = unp_connect(so, nam, td);
1083 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
1084 UNP_PCB_UNLOCK(unp);
1087 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1088 unp_pcb_unlock_pair(unp, unp2);
1092 UNP_PCB_UNLOCK(unp);
1093 if ((so2 = unp2->unp_socket) == NULL) {
1094 UNP_PCB_UNLOCK(unp2);
1098 SOCKBUF_LOCK(&so2->so_rcv);
1099 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1101 * Credentials are passed only once on SOCK_STREAM and
1102 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1103 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1105 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1106 control = unp_addsockcred(td, control);
1110 * Send to paired receive port and wake up readers. Don't
1111 * check for space available in the receive buffer if we're
1112 * attaching ancillary data; Unix domain sockets only check
1113 * for space in the sending sockbuf, and that check is
1114 * performed one level up the stack. At that level we cannot
1115 * precisely account for the amount of buffer space used
1116 * (e.g., because control messages are not yet internalized).
1118 switch (so->so_type) {
1120 if (control != NULL) {
1121 sbappendcontrol_locked(&so2->so_rcv, m,
1125 sbappend_locked(&so2->so_rcv, m, flags);
1128 case SOCK_SEQPACKET:
1129 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1130 &sun_noname, m, control))
1135 mbcnt = so2->so_rcv.sb_mbcnt;
1136 sbcc = sbavail(&so2->so_rcv);
1138 sorwakeup_locked(so2);
1140 SOCKBUF_UNLOCK(&so2->so_rcv);
1143 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1144 * it would be possible for uipc_rcvd to be called at this
1145 * point, drain the receiving sockbuf, clear SB_STOP, and then
1146 * we would set SB_STOP below. That could lead to an empty
1147 * sockbuf having SB_STOP set
1149 SOCKBUF_LOCK(&so->so_snd);
1150 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1151 so->so_snd.sb_flags |= SB_STOP;
1152 SOCKBUF_UNLOCK(&so->so_snd);
1153 UNP_PCB_UNLOCK(unp2);
1159 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1161 if (flags & PRUS_EOF) {
1165 UNP_PCB_UNLOCK(unp);
1167 if (control != NULL && error != 0)
1168 unp_dispose_mbuf(control);
1171 if (control != NULL)
1174 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1175 * for freeing memory.
1177 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1183 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1185 struct mbuf *mb, *n;
1189 if (SOLISTENING(so)) {
1196 if (sb->sb_fnrdy != NULL) {
1197 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1199 *errorp = sbready(sb, m, count);
1212 return (mb != NULL);
1216 uipc_ready(struct socket *so, struct mbuf *m, int count)
1218 struct unpcb *unp, *unp2;
1222 unp = sotounpcb(so);
1224 KASSERT(so->so_type == SOCK_STREAM,
1225 ("%s: unexpected socket type for %p", __func__, so));
1228 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1229 UNP_PCB_UNLOCK(unp);
1230 so2 = unp2->unp_socket;
1231 SOCKBUF_LOCK(&so2->so_rcv);
1232 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1233 sorwakeup_locked(so2);
1235 SOCKBUF_UNLOCK(&so2->so_rcv);
1236 UNP_PCB_UNLOCK(unp2);
1239 UNP_PCB_UNLOCK(unp);
1242 * The receiving socket has been disconnected, but may still be valid.
1243 * In this case, the now-ready mbufs are still present in its socket
1244 * buffer, so perform an exhaustive search before giving up and freeing
1248 LIST_FOREACH(unp, &unp_shead, unp_link) {
1249 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1255 for (i = 0; i < count; i++)
1263 uipc_sense(struct socket *so, struct stat *sb)
1267 unp = sotounpcb(so);
1268 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1270 sb->st_blksize = so->so_snd.sb_hiwat;
1272 sb->st_ino = unp->unp_ino;
1277 uipc_shutdown(struct socket *so)
1281 unp = sotounpcb(so);
1282 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1287 UNP_PCB_UNLOCK(unp);
1292 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1295 const struct sockaddr *sa;
1297 unp = sotounpcb(so);
1298 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1300 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1302 if (unp->unp_addr != NULL)
1303 sa = (struct sockaddr *) unp->unp_addr;
1306 bcopy(sa, *nam, sa->sa_len);
1307 UNP_PCB_UNLOCK(unp);
1311 static struct pr_usrreqs uipc_usrreqs_dgram = {
1312 .pru_abort = uipc_abort,
1313 .pru_accept = uipc_accept,
1314 .pru_attach = uipc_attach,
1315 .pru_bind = uipc_bind,
1316 .pru_bindat = uipc_bindat,
1317 .pru_connect = uipc_connect,
1318 .pru_connectat = uipc_connectat,
1319 .pru_connect2 = uipc_connect2,
1320 .pru_detach = uipc_detach,
1321 .pru_disconnect = uipc_disconnect,
1322 .pru_listen = uipc_listen,
1323 .pru_peeraddr = uipc_peeraddr,
1324 .pru_rcvd = uipc_rcvd,
1325 .pru_send = uipc_send,
1326 .pru_sense = uipc_sense,
1327 .pru_shutdown = uipc_shutdown,
1328 .pru_sockaddr = uipc_sockaddr,
1329 .pru_soreceive = soreceive_dgram,
1330 .pru_close = uipc_close,
1333 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1334 .pru_abort = uipc_abort,
1335 .pru_accept = uipc_accept,
1336 .pru_attach = uipc_attach,
1337 .pru_bind = uipc_bind,
1338 .pru_bindat = uipc_bindat,
1339 .pru_connect = uipc_connect,
1340 .pru_connectat = uipc_connectat,
1341 .pru_connect2 = uipc_connect2,
1342 .pru_detach = uipc_detach,
1343 .pru_disconnect = uipc_disconnect,
1344 .pru_listen = uipc_listen,
1345 .pru_peeraddr = uipc_peeraddr,
1346 .pru_rcvd = uipc_rcvd,
1347 .pru_send = uipc_send,
1348 .pru_sense = uipc_sense,
1349 .pru_shutdown = uipc_shutdown,
1350 .pru_sockaddr = uipc_sockaddr,
1351 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1352 .pru_close = uipc_close,
1355 static struct pr_usrreqs uipc_usrreqs_stream = {
1356 .pru_abort = uipc_abort,
1357 .pru_accept = uipc_accept,
1358 .pru_attach = uipc_attach,
1359 .pru_bind = uipc_bind,
1360 .pru_bindat = uipc_bindat,
1361 .pru_connect = uipc_connect,
1362 .pru_connectat = uipc_connectat,
1363 .pru_connect2 = uipc_connect2,
1364 .pru_detach = uipc_detach,
1365 .pru_disconnect = uipc_disconnect,
1366 .pru_listen = uipc_listen,
1367 .pru_peeraddr = uipc_peeraddr,
1368 .pru_rcvd = uipc_rcvd,
1369 .pru_send = uipc_send,
1370 .pru_ready = uipc_ready,
1371 .pru_sense = uipc_sense,
1372 .pru_shutdown = uipc_shutdown,
1373 .pru_sockaddr = uipc_sockaddr,
1374 .pru_soreceive = soreceive_generic,
1375 .pru_close = uipc_close,
1379 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1385 if (sopt->sopt_level != SOL_LOCAL)
1388 unp = sotounpcb(so);
1389 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1391 switch (sopt->sopt_dir) {
1393 switch (sopt->sopt_name) {
1394 case LOCAL_PEERCRED:
1396 if (unp->unp_flags & UNP_HAVEPC)
1397 xu = unp->unp_peercred;
1399 if (so->so_type == SOCK_STREAM)
1404 UNP_PCB_UNLOCK(unp);
1406 error = sooptcopyout(sopt, &xu, sizeof(xu));
1410 /* Unlocked read. */
1411 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1412 error = sooptcopyout(sopt, &optval, sizeof(optval));
1415 case LOCAL_CREDS_PERSISTENT:
1416 /* Unlocked read. */
1417 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1418 error = sooptcopyout(sopt, &optval, sizeof(optval));
1421 case LOCAL_CONNWAIT:
1422 /* Unlocked read. */
1423 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1424 error = sooptcopyout(sopt, &optval, sizeof(optval));
1434 switch (sopt->sopt_name) {
1436 case LOCAL_CREDS_PERSISTENT:
1437 case LOCAL_CONNWAIT:
1438 error = sooptcopyin(sopt, &optval, sizeof(optval),
1443 #define OPTSET(bit, exclusive) do { \
1444 UNP_PCB_LOCK(unp); \
1446 if ((unp->unp_flags & (exclusive)) != 0) { \
1447 UNP_PCB_UNLOCK(unp); \
1451 unp->unp_flags |= (bit); \
1453 unp->unp_flags &= ~(bit); \
1454 UNP_PCB_UNLOCK(unp); \
1457 switch (sopt->sopt_name) {
1459 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1462 case LOCAL_CREDS_PERSISTENT:
1463 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1466 case LOCAL_CONNWAIT:
1467 OPTSET(UNP_CONNWAIT, 0);
1476 error = ENOPROTOOPT;
1489 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1492 return (unp_connectat(AT_FDCWD, so, nam, td));
1496 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1500 struct sockaddr_un *soun;
1503 struct unpcb *unp, *unp2, *unp3;
1504 struct nameidata nd;
1505 char buf[SOCK_MAXADDRLEN];
1506 struct sockaddr *sa;
1507 cap_rights_t rights;
1511 if (nam->sa_family != AF_UNIX)
1512 return (EAFNOSUPPORT);
1513 if (nam->sa_len > sizeof(struct sockaddr_un))
1515 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1518 soun = (struct sockaddr_un *)nam;
1519 bcopy(soun->sun_path, buf, len);
1522 unp = sotounpcb(so);
1526 * Wait for connection state to stabilize. If a connection
1527 * already exists, give up. For datagram sockets, which permit
1528 * multiple consecutive connect(2) calls, upper layers are
1529 * responsible for disconnecting in advance of a subsequent
1530 * connect(2), but this is not synchronized with PCB connection
1533 * Also make sure that no threads are currently attempting to
1534 * lock the peer socket, to ensure that unp_conn cannot
1535 * transition between two valid sockets while locks are dropped.
1537 if (unp->unp_conn != NULL) {
1538 UNP_PCB_UNLOCK(unp);
1541 if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1542 UNP_PCB_UNLOCK(unp);
1545 if (unp->unp_pairbusy > 0) {
1546 unp->unp_flags |= UNP_WAITING;
1547 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1552 unp->unp_flags |= UNP_CONNECTING;
1553 UNP_PCB_UNLOCK(unp);
1555 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1557 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1560 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1561 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1567 ASSERT_VOP_LOCKED(vp, "unp_connect");
1568 NDFREE(&nd, NDF_ONLY_PNBUF);
1572 if (vp->v_type != VSOCK) {
1577 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1581 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1585 unp = sotounpcb(so);
1586 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1588 vplock = mtx_pool_find(mtxpool_sleep, vp);
1590 VOP_UNP_CONNECT(vp, &unp2);
1592 error = ECONNREFUSED;
1595 so2 = unp2->unp_socket;
1596 if (so->so_type != so2->so_type) {
1601 if (so2->so_options & SO_ACCEPTCONN) {
1602 CURVNET_SET(so2->so_vnet);
1603 so2 = sonewconn(so2, 0);
1608 error = ECONNREFUSED;
1611 unp3 = sotounpcb(so2);
1612 unp_pcb_lock_pair(unp2, unp3);
1613 if (unp2->unp_addr != NULL) {
1614 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1615 unp3->unp_addr = (struct sockaddr_un *) sa;
1619 unp_copy_peercred(td, unp3, unp, unp2);
1621 UNP_PCB_UNLOCK(unp2);
1625 * It is safe to block on the PCB lock here since unp2 is
1626 * nascent and cannot be connected to any other sockets.
1630 mac_socketpeer_set_from_socket(so, so2);
1631 mac_socketpeer_set_from_socket(so2, so);
1634 unp_pcb_lock_pair(unp, unp2);
1636 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1637 sotounpcb(so2) == unp2,
1638 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1639 error = unp_connect2(so, so2, PRU_CONNECT);
1640 unp_pcb_unlock_pair(unp, unp2);
1649 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1650 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1651 unp->unp_flags &= ~UNP_CONNECTING;
1652 UNP_PCB_UNLOCK(unp);
1657 * Set socket peer credentials at connection time.
1659 * The client's PCB credentials are copied from its process structure. The
1660 * server's PCB credentials are copied from the socket on which it called
1661 * listen(2). uipc_listen cached that process's credentials at the time.
1664 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1665 struct unpcb *server_unp, struct unpcb *listen_unp)
1667 cru2xt(td, &client_unp->unp_peercred);
1668 client_unp->unp_flags |= UNP_HAVEPC;
1670 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1671 sizeof(server_unp->unp_peercred));
1672 server_unp->unp_flags |= UNP_HAVEPC;
1673 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
1677 unp_connect2(struct socket *so, struct socket *so2, int req)
1682 unp = sotounpcb(so);
1683 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1684 unp2 = sotounpcb(so2);
1685 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1687 UNP_PCB_LOCK_ASSERT(unp);
1688 UNP_PCB_LOCK_ASSERT(unp2);
1689 KASSERT(unp->unp_conn == NULL,
1690 ("%s: socket %p is already connected", __func__, unp));
1692 if (so2->so_type != so->so_type)
1693 return (EPROTOTYPE);
1694 unp->unp_conn = unp2;
1697 switch (so->so_type) {
1699 UNP_REF_LIST_LOCK();
1700 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1701 UNP_REF_LIST_UNLOCK();
1706 case SOCK_SEQPACKET:
1707 KASSERT(unp2->unp_conn == NULL,
1708 ("%s: socket %p is already connected", __func__, unp2));
1709 unp2->unp_conn = unp;
1710 if (req == PRU_CONNECT &&
1711 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1719 panic("unp_connect2");
1725 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1727 struct socket *so, *so2;
1729 struct unpcb *unptmp;
1732 UNP_PCB_LOCK_ASSERT(unp);
1733 UNP_PCB_LOCK_ASSERT(unp2);
1734 KASSERT(unp->unp_conn == unp2,
1735 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
1737 unp->unp_conn = NULL;
1738 so = unp->unp_socket;
1739 so2 = unp2->unp_socket;
1740 switch (unp->unp_socket->so_type) {
1742 UNP_REF_LIST_LOCK();
1744 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
1748 KASSERT(unptmp != NULL,
1749 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
1751 LIST_REMOVE(unp, unp_reflink);
1752 UNP_REF_LIST_UNLOCK();
1755 so->so_state &= ~SS_ISCONNECTED;
1761 case SOCK_SEQPACKET:
1763 soisdisconnected(so);
1764 MPASS(unp2->unp_conn == unp);
1765 unp2->unp_conn = NULL;
1767 soisdisconnected(so2);
1772 unp_pcb_rele_notlast(unp);
1773 if (!unp_pcb_rele(unp))
1774 UNP_PCB_UNLOCK(unp);
1776 if (!unp_pcb_rele(unp))
1777 UNP_PCB_UNLOCK(unp);
1778 if (!unp_pcb_rele(unp2))
1779 UNP_PCB_UNLOCK(unp2);
1784 * unp_pcblist() walks the global list of struct unpcb's to generate a
1785 * pointer list, bumping the refcount on each unpcb. It then copies them out
1786 * sequentially, validating the generation number on each to see if it has
1787 * been detached. All of this is necessary because copyout() may sleep on
1791 unp_pcblist(SYSCTL_HANDLER_ARGS)
1793 struct unpcb *unp, **unp_list;
1795 struct xunpgen *xug;
1796 struct unp_head *head;
1801 switch ((intptr_t)arg1) {
1810 case SOCK_SEQPACKET:
1815 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1819 * The process of preparing the PCB list is too time-consuming and
1820 * resource-intensive to repeat twice on every request.
1822 if (req->oldptr == NULL) {
1824 req->oldidx = 2 * (sizeof *xug)
1825 + (n + n/8) * sizeof(struct xunpcb);
1829 if (req->newptr != NULL)
1833 * OK, now we're committed to doing something.
1835 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
1837 gencnt = unp_gencnt;
1841 xug->xug_len = sizeof *xug;
1843 xug->xug_gen = gencnt;
1844 xug->xug_sogen = so_gencnt;
1845 error = SYSCTL_OUT(req, xug, sizeof *xug);
1851 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1854 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1855 unp = LIST_NEXT(unp, unp_link)) {
1857 if (unp->unp_gencnt <= gencnt) {
1858 if (cr_cansee(req->td->td_ucred,
1859 unp->unp_socket->so_cred)) {
1860 UNP_PCB_UNLOCK(unp);
1863 unp_list[i++] = unp;
1866 UNP_PCB_UNLOCK(unp);
1869 n = i; /* In case we lost some during malloc. */
1872 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1873 for (i = 0; i < n; i++) {
1876 if (unp_pcb_rele(unp))
1879 if (unp->unp_gencnt <= gencnt) {
1880 xu->xu_len = sizeof *xu;
1881 xu->xu_unpp = (uintptr_t)unp;
1883 * XXX - need more locking here to protect against
1884 * connect/disconnect races for SMP.
1886 if (unp->unp_addr != NULL)
1887 bcopy(unp->unp_addr, &xu->xu_addr,
1888 unp->unp_addr->sun_len);
1890 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1891 if (unp->unp_conn != NULL &&
1892 unp->unp_conn->unp_addr != NULL)
1893 bcopy(unp->unp_conn->unp_addr,
1895 unp->unp_conn->unp_addr->sun_len);
1897 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1898 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
1899 xu->unp_conn = (uintptr_t)unp->unp_conn;
1900 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
1901 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
1902 xu->unp_gencnt = unp->unp_gencnt;
1903 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1904 UNP_PCB_UNLOCK(unp);
1905 error = SYSCTL_OUT(req, xu, sizeof *xu);
1907 UNP_PCB_UNLOCK(unp);
1913 * Give the user an updated idea of our state. If the
1914 * generation differs from what we told her before, she knows
1915 * that something happened while we were processing this
1916 * request, and it might be necessary to retry.
1918 xug->xug_gen = unp_gencnt;
1919 xug->xug_sogen = so_gencnt;
1920 xug->xug_count = unp_count;
1921 error = SYSCTL_OUT(req, xug, sizeof *xug);
1923 free(unp_list, M_TEMP);
1928 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
1929 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1930 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1931 "List of active local datagram sockets");
1932 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
1933 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1934 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1935 "List of active local stream sockets");
1936 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1937 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
1938 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1939 "List of active local seqpacket sockets");
1942 unp_shutdown(struct unpcb *unp)
1947 UNP_PCB_LOCK_ASSERT(unp);
1949 unp2 = unp->unp_conn;
1950 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1951 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1952 so = unp2->unp_socket;
1959 unp_drop(struct unpcb *unp)
1961 struct socket *so = unp->unp_socket;
1965 * Regardless of whether the socket's peer dropped the connection
1966 * with this socket by aborting or disconnecting, POSIX requires
1967 * that ECONNRESET is returned.
1972 so->so_error = ECONNRESET;
1973 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1974 /* Last reference dropped in unp_disconnect(). */
1975 unp_pcb_rele_notlast(unp);
1976 unp_disconnect(unp, unp2);
1977 } else if (!unp_pcb_rele(unp)) {
1978 UNP_PCB_UNLOCK(unp);
1983 unp_freerights(struct filedescent **fdep, int fdcount)
1988 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1990 for (i = 0; i < fdcount; i++) {
1991 fp = fdep[i]->fde_file;
1992 filecaps_free(&fdep[i]->fde_caps);
1995 free(fdep[0], M_FILECAPS);
1999 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2001 struct thread *td = curthread; /* XXX */
2002 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2005 struct filedesc *fdesc = td->td_proc->p_fd;
2006 struct filedescent **fdep;
2008 socklen_t clen = control->m_len, datalen;
2012 UNP_LINK_UNLOCK_ASSERT();
2015 if (controlp != NULL) /* controlp == NULL => free control messages */
2017 while (cm != NULL) {
2018 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
2022 data = CMSG_DATA(cm);
2023 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2024 if (cm->cmsg_level == SOL_SOCKET
2025 && cm->cmsg_type == SCM_RIGHTS) {
2026 newfds = datalen / sizeof(*fdep);
2031 /* If we're not outputting the descriptors free them. */
2032 if (error || controlp == NULL) {
2033 unp_freerights(fdep, newfds);
2036 FILEDESC_XLOCK(fdesc);
2039 * Now change each pointer to an fd in the global
2040 * table to an integer that is the index to the local
2041 * fd table entry that we set up to point to the
2042 * global one we are transferring.
2044 newlen = newfds * sizeof(int);
2045 *controlp = sbcreatecontrol(NULL, newlen,
2046 SCM_RIGHTS, SOL_SOCKET);
2047 if (*controlp == NULL) {
2048 FILEDESC_XUNLOCK(fdesc);
2050 unp_freerights(fdep, newfds);
2055 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2056 if (fdallocn(td, 0, fdp, newfds) != 0) {
2057 FILEDESC_XUNLOCK(fdesc);
2059 unp_freerights(fdep, newfds);
2064 for (i = 0; i < newfds; i++, fdp++) {
2065 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2066 (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
2067 &fdep[i]->fde_caps);
2068 unp_externalize_fp(fdep[i]->fde_file);
2072 * The new type indicates that the mbuf data refers to
2073 * kernel resources that may need to be released before
2074 * the mbuf is freed.
2076 m_chtype(*controlp, MT_EXTCONTROL);
2077 FILEDESC_XUNLOCK(fdesc);
2078 free(fdep[0], M_FILECAPS);
2080 /* We can just copy anything else across. */
2081 if (error || controlp == NULL)
2083 *controlp = sbcreatecontrol(NULL, datalen,
2084 cm->cmsg_type, cm->cmsg_level);
2085 if (*controlp == NULL) {
2090 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2093 controlp = &(*controlp)->m_next;
2096 if (CMSG_SPACE(datalen) < clen) {
2097 clen -= CMSG_SPACE(datalen);
2098 cm = (struct cmsghdr *)
2099 ((caddr_t)cm + CMSG_SPACE(datalen));
2111 unp_zone_change(void *tag)
2114 uma_zone_set_max(unp_zone, maxsockets);
2119 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2125 KASSERT(LIST_EMPTY(&unp->unp_refs),
2126 ("%s: unpcb %p has lingering refs", __func__, unp));
2127 KASSERT(unp->unp_socket == NULL,
2128 ("%s: unpcb %p has socket backpointer", __func__, unp));
2129 KASSERT(unp->unp_vnode == NULL,
2130 ("%s: unpcb %p has vnode references", __func__, unp));
2131 KASSERT(unp->unp_conn == NULL,
2132 ("%s: unpcb %p is still connected", __func__, unp));
2133 KASSERT(unp->unp_addr == NULL,
2134 ("%s: unpcb %p has leaked addr", __func__, unp));
2144 if (!IS_DEFAULT_VNET(curvnet))
2153 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2154 NULL, NULL, UMA_ALIGN_CACHE, 0);
2155 uma_zone_set_max(unp_zone, maxsockets);
2156 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2157 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2158 NULL, EVENTHANDLER_PRI_ANY);
2159 LIST_INIT(&unp_dhead);
2160 LIST_INIT(&unp_shead);
2161 LIST_INIT(&unp_sphead);
2162 SLIST_INIT(&unp_defers);
2163 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2164 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2165 UNP_LINK_LOCK_INIT();
2166 UNP_DEFERRED_LOCK_INIT();
2170 unp_internalize_cleanup_rights(struct mbuf *control)
2177 for (m = control; m != NULL; m = m->m_next) {
2178 cp = mtod(m, struct cmsghdr *);
2179 if (cp->cmsg_level != SOL_SOCKET ||
2180 cp->cmsg_type != SCM_RIGHTS)
2182 data = CMSG_DATA(cp);
2183 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2184 unp_freerights(data, datalen / sizeof(struct filedesc *));
2189 unp_internalize(struct mbuf **controlp, struct thread *td)
2191 struct mbuf *control, **initial_controlp;
2193 struct filedesc *fdesc;
2196 struct cmsgcred *cmcred;
2197 struct filedescent *fde, **fdep, *fdev;
2200 struct timespec *ts;
2202 socklen_t clen, datalen;
2203 int i, j, error, *fdp, oldfds;
2206 UNP_LINK_UNLOCK_ASSERT();
2211 control = *controlp;
2212 clen = control->m_len;
2214 initial_controlp = controlp;
2215 for (cm = mtod(control, struct cmsghdr *); cm != NULL;) {
2216 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
2217 || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
2221 data = CMSG_DATA(cm);
2222 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2224 switch (cm->cmsg_type) {
2226 * Fill in credential information.
2229 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2230 SCM_CREDS, SOL_SOCKET);
2231 if (*controlp == NULL) {
2235 cmcred = (struct cmsgcred *)
2236 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2237 cmcred->cmcred_pid = p->p_pid;
2238 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2239 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2240 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2241 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2243 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2244 cmcred->cmcred_groups[i] =
2245 td->td_ucred->cr_groups[i];
2249 oldfds = datalen / sizeof (int);
2253 * Check that all the FDs passed in refer to legal
2254 * files. If not, reject the entire operation.
2257 FILEDESC_SLOCK(fdesc);
2258 for (i = 0; i < oldfds; i++, fdp++) {
2259 fp = fget_locked(fdesc, *fdp);
2261 FILEDESC_SUNLOCK(fdesc);
2265 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2266 FILEDESC_SUNLOCK(fdesc);
2273 * Now replace the integer FDs with pointers to the
2274 * file structure and capability rights.
2276 newlen = oldfds * sizeof(fdep[0]);
2277 *controlp = sbcreatecontrol(NULL, newlen,
2278 SCM_RIGHTS, SOL_SOCKET);
2279 if (*controlp == NULL) {
2280 FILEDESC_SUNLOCK(fdesc);
2285 for (i = 0; i < oldfds; i++, fdp++) {
2286 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2288 for (j = 0; j < i; j++, fdp++) {
2289 fdrop(fdesc->fd_ofiles[*fdp].
2292 FILEDESC_SUNLOCK(fdesc);
2298 fdep = (struct filedescent **)
2299 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2300 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2302 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2303 fde = &fdesc->fd_ofiles[*fdp];
2305 fdep[i]->fde_file = fde->fde_file;
2306 filecaps_copy(&fde->fde_caps,
2307 &fdep[i]->fde_caps, true);
2308 unp_internalize_fp(fdep[i]->fde_file);
2310 FILEDESC_SUNLOCK(fdesc);
2314 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2315 SCM_TIMESTAMP, SOL_SOCKET);
2316 if (*controlp == NULL) {
2320 tv = (struct timeval *)
2321 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2326 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2327 SCM_BINTIME, SOL_SOCKET);
2328 if (*controlp == NULL) {
2332 bt = (struct bintime *)
2333 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2338 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2339 SCM_REALTIME, SOL_SOCKET);
2340 if (*controlp == NULL) {
2344 ts = (struct timespec *)
2345 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2350 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2351 SCM_MONOTONIC, SOL_SOCKET);
2352 if (*controlp == NULL) {
2356 ts = (struct timespec *)
2357 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2366 if (*controlp != NULL)
2367 controlp = &(*controlp)->m_next;
2368 if (CMSG_SPACE(datalen) < clen) {
2369 clen -= CMSG_SPACE(datalen);
2370 cm = (struct cmsghdr *)
2371 ((caddr_t)cm + CMSG_SPACE(datalen));
2379 if (error != 0 && initial_controlp != NULL)
2380 unp_internalize_cleanup_rights(*initial_controlp);
2385 static struct mbuf *
2386 unp_addsockcred(struct thread *td, struct mbuf *control)
2388 struct mbuf *m, *n, *n_prev;
2389 struct sockcred *sc;
2390 const struct cmsghdr *cm;
2394 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2395 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2399 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2400 sc->sc_uid = td->td_ucred->cr_ruid;
2401 sc->sc_euid = td->td_ucred->cr_uid;
2402 sc->sc_gid = td->td_ucred->cr_rgid;
2403 sc->sc_egid = td->td_ucred->cr_gid;
2404 sc->sc_ngroups = ngroups;
2405 for (i = 0; i < sc->sc_ngroups; i++)
2406 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2409 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2410 * created SCM_CREDS control message (struct sockcred) has another
2413 if (control != NULL)
2414 for (n = control, n_prev = NULL; n != NULL;) {
2415 cm = mtod(n, struct cmsghdr *);
2416 if (cm->cmsg_level == SOL_SOCKET &&
2417 cm->cmsg_type == SCM_CREDS) {
2419 control = n->m_next;
2421 n_prev->m_next = n->m_next;
2429 /* Prepend it to the head. */
2430 m->m_next = control;
2434 static struct unpcb *
2435 fptounp(struct file *fp)
2439 if (fp->f_type != DTYPE_SOCKET)
2441 if ((so = fp->f_data) == NULL)
2443 if (so->so_proto->pr_domain != &localdomain)
2445 return sotounpcb(so);
2449 unp_discard(struct file *fp)
2451 struct unp_defer *dr;
2453 if (unp_externalize_fp(fp)) {
2454 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2456 UNP_DEFERRED_LOCK();
2457 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2458 UNP_DEFERRED_UNLOCK();
2459 atomic_add_int(&unp_defers_count, 1);
2460 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2462 (void) closef(fp, (struct thread *)NULL);
2466 unp_process_defers(void *arg __unused, int pending)
2468 struct unp_defer *dr;
2469 SLIST_HEAD(, unp_defer) drl;
2474 UNP_DEFERRED_LOCK();
2475 if (SLIST_FIRST(&unp_defers) == NULL) {
2476 UNP_DEFERRED_UNLOCK();
2479 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2480 UNP_DEFERRED_UNLOCK();
2482 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2483 SLIST_REMOVE_HEAD(&drl, ud_link);
2484 closef(dr->ud_fp, NULL);
2488 atomic_add_int(&unp_defers_count, -count);
2493 unp_internalize_fp(struct file *fp)
2498 if ((unp = fptounp(fp)) != NULL) {
2500 unp->unp_msgcount++;
2507 unp_externalize_fp(struct file *fp)
2513 if ((unp = fptounp(fp)) != NULL) {
2514 unp->unp_msgcount--;
2524 * unp_defer indicates whether additional work has been defered for a future
2525 * pass through unp_gc(). It is thread local and does not require explicit
2528 static int unp_marked;
2531 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2538 * This function can only be called from the gc task.
2540 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2541 ("%s: not on gc callout", __func__));
2542 UNP_LINK_LOCK_ASSERT();
2544 for (i = 0; i < fdcount; i++) {
2545 fp = fdep[i]->fde_file;
2546 if ((unp = fptounp(fp)) == NULL)
2548 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2555 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2562 * This function can only be called from the gc task.
2564 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2565 ("%s: not on gc callout", __func__));
2566 UNP_LINK_LOCK_ASSERT();
2568 for (i = 0; i < fdcount; i++) {
2569 fp = fdep[i]->fde_file;
2570 if ((unp = fptounp(fp)) == NULL)
2572 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2580 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2582 struct socket *so, *soa;
2584 so = unp->unp_socket;
2586 if (SOLISTENING(so)) {
2588 * Mark all sockets in our accept queue.
2590 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2591 if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2593 SOCKBUF_LOCK(&soa->so_rcv);
2594 unp_scan(soa->so_rcv.sb_mb, op);
2595 SOCKBUF_UNLOCK(&soa->so_rcv);
2599 * Mark all sockets we reference with RIGHTS.
2601 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2602 SOCKBUF_LOCK(&so->so_rcv);
2603 unp_scan(so->so_rcv.sb_mb, op);
2604 SOCKBUF_UNLOCK(&so->so_rcv);
2610 static int unp_recycled;
2611 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2612 "Number of unreachable sockets claimed by the garbage collector.");
2614 static int unp_taskcount;
2615 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2616 "Number of times the garbage collector has run.");
2618 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2619 "Number of active local sockets.");
2622 unp_gc(__unused void *arg, int pending)
2624 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2626 struct unp_head **head;
2627 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
2628 struct file *f, **unref;
2629 struct unpcb *unp, *unptmp;
2630 int i, total, unp_unreachable;
2632 LIST_INIT(&unp_deadhead);
2636 * First determine which sockets may be in cycles.
2638 unp_unreachable = 0;
2640 for (head = heads; *head != NULL; head++)
2641 LIST_FOREACH(unp, *head, unp_link) {
2642 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2643 ("%s: unp %p has unexpected gc flags 0x%x",
2644 __func__, unp, (unsigned int)unp->unp_gcflag));
2649 * Check for an unreachable socket potentially in a
2650 * cycle. It must be in a queue as indicated by
2651 * msgcount, and this must equal the file reference
2652 * count. Note that when msgcount is 0 the file is
2655 if (f != NULL && unp->unp_msgcount != 0 &&
2656 refcount_load(&f->f_count) == unp->unp_msgcount) {
2657 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2658 unp->unp_gcflag |= UNPGC_DEAD;
2659 unp->unp_gcrefs = unp->unp_msgcount;
2665 * Scan all sockets previously marked as potentially being in a cycle
2666 * and remove the references each socket holds on any UNPGC_DEAD
2667 * sockets in its queue. After this step, all remaining references on
2668 * sockets marked UNPGC_DEAD should not be part of any cycle.
2670 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
2671 unp_gc_scan(unp, unp_remove_dead_ref);
2674 * If a socket still has a non-negative refcount, it cannot be in a
2675 * cycle. In this case increment refcount of all children iteratively.
2676 * Stop the scan once we do a complete loop without discovering
2677 * a new reachable socket.
2681 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
2682 if (unp->unp_gcrefs > 0) {
2683 unp->unp_gcflag &= ~UNPGC_DEAD;
2684 LIST_REMOVE(unp, unp_dead);
2685 KASSERT(unp_unreachable > 0,
2686 ("%s: unp_unreachable underflow.",
2689 unp_gc_scan(unp, unp_restore_undead_ref);
2691 } while (unp_marked);
2695 if (unp_unreachable == 0)
2699 * Allocate space for a local array of dead unpcbs.
2700 * TODO: can this path be simplified by instead using the local
2701 * dead list at unp_deadhead, after taking out references
2702 * on the file object and/or unpcb and dropping the link lock?
2704 unref = malloc(unp_unreachable * sizeof(struct file *),
2708 * Iterate looking for sockets which have been specifically marked
2709 * as unreachable and store them locally.
2713 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
2714 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
2715 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
2716 unp->unp_gcflag &= ~UNPGC_DEAD;
2718 if (unp->unp_msgcount == 0 || f == NULL ||
2719 refcount_load(&f->f_count) != unp->unp_msgcount ||
2723 KASSERT(total <= unp_unreachable,
2724 ("%s: incorrect unreachable count.", __func__));
2729 * Now flush all sockets, free'ing rights. This will free the
2730 * struct files associated with these sockets but leave each socket
2731 * with one remaining ref.
2733 for (i = 0; i < total; i++) {
2736 so = unref[i]->f_data;
2737 CURVNET_SET(so->so_vnet);
2743 * And finally release the sockets so they can be reclaimed.
2745 for (i = 0; i < total; i++)
2746 fdrop(unref[i], NULL);
2747 unp_recycled += total;
2748 free(unref, M_TEMP);
2752 unp_dispose_mbuf(struct mbuf *m)
2756 unp_scan(m, unp_freerights);
2760 * Synchronize against unp_gc, which can trip over data as we are freeing it.
2763 unp_dispose(struct socket *so)
2767 unp = sotounpcb(so);
2769 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2771 if (!SOLISTENING(so))
2772 unp_dispose_mbuf(so->so_rcv.sb_mb);
2776 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2781 socklen_t clen, datalen;
2783 while (m0 != NULL) {
2784 for (m = m0; m; m = m->m_next) {
2785 if (m->m_type != MT_CONTROL)
2788 cm = mtod(m, struct cmsghdr *);
2791 while (cm != NULL) {
2792 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2795 data = CMSG_DATA(cm);
2796 datalen = (caddr_t)cm + cm->cmsg_len
2799 if (cm->cmsg_level == SOL_SOCKET &&
2800 cm->cmsg_type == SCM_RIGHTS) {
2801 (*op)(data, datalen /
2802 sizeof(struct filedescent *));
2805 if (CMSG_SPACE(datalen) < clen) {
2806 clen -= CMSG_SPACE(datalen);
2807 cm = (struct cmsghdr *)
2808 ((caddr_t)cm + CMSG_SPACE(datalen));
2820 * A helper function called by VFS before socket-type vnode reclamation.
2821 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2825 vfs_unp_reclaim(struct vnode *vp)
2831 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2832 KASSERT(vp->v_type == VSOCK,
2833 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2836 vplock = mtx_pool_find(mtxpool_sleep, vp);
2838 VOP_UNP_CONNECT(vp, &unp);
2842 if (unp->unp_vnode == vp) {
2844 unp->unp_vnode = NULL;
2847 UNP_PCB_UNLOCK(unp);
2856 db_print_indent(int indent)
2860 for (i = 0; i < indent; i++)
2865 db_print_unpflags(int unp_flags)
2870 if (unp_flags & UNP_HAVEPC) {
2871 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2874 if (unp_flags & UNP_WANTCRED_ALWAYS) {
2875 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
2878 if (unp_flags & UNP_WANTCRED_ONESHOT) {
2879 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
2882 if (unp_flags & UNP_CONNWAIT) {
2883 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2886 if (unp_flags & UNP_CONNECTING) {
2887 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2890 if (unp_flags & UNP_BINDING) {
2891 db_printf("%sUNP_BINDING", comma ? ", " : "");
2897 db_print_xucred(int indent, struct xucred *xu)
2901 db_print_indent(indent);
2902 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
2903 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
2904 db_print_indent(indent);
2905 db_printf("cr_groups: ");
2907 for (i = 0; i < xu->cr_ngroups; i++) {
2908 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2915 db_print_unprefs(int indent, struct unp_head *uh)
2921 LIST_FOREACH(unp, uh, unp_reflink) {
2922 if (counter % 4 == 0)
2923 db_print_indent(indent);
2924 db_printf("%p ", unp);
2925 if (counter % 4 == 3)
2929 if (counter != 0 && counter % 4 != 0)
2933 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2938 db_printf("usage: show unpcb <addr>\n");
2941 unp = (struct unpcb *)addr;
2943 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2946 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2949 db_printf("unp_refs:\n");
2950 db_print_unprefs(2, &unp->unp_refs);
2952 /* XXXRW: Would be nice to print the full address, if any. */
2953 db_printf("unp_addr: %p\n", unp->unp_addr);
2955 db_printf("unp_gencnt: %llu\n",
2956 (unsigned long long)unp->unp_gencnt);
2958 db_printf("unp_flags: %x (", unp->unp_flags);
2959 db_print_unpflags(unp->unp_flags);
2962 db_printf("unp_peercred:\n");
2963 db_print_xucred(2, &unp->unp_peercred);
2965 db_printf("unp_refcount: %u\n", unp->unp_refcount);