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
8 * Copyright (c) 2022 Gleb Smirnoff <glebius@FreeBSD.org>
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * UNIX Domain (Local) Sockets
38 * This is an implementation of UNIX (local) domain sockets. Each socket has
39 * an associated struct unpcb (UNIX protocol control block). Stream sockets
40 * may be connected to 0 or 1 other socket. Datagram sockets may be
41 * connected to 0, 1, or many other sockets. Sockets may be created and
42 * connected in pairs (socketpair(2)), or bound/connected to using the file
43 * system name space. For most purposes, only the receive socket buffer is
44 * used, as sending on one socket delivers directly to the receive socket
45 * buffer of a second socket.
47 * The implementation is substantially complicated by the fact that
48 * "ancillary data", such as file descriptors or credentials, may be passed
49 * across UNIX domain sockets. The potential for passing UNIX domain sockets
50 * over other UNIX domain sockets requires the implementation of a simple
51 * garbage collector to find and tear down cycles of disconnected sockets.
55 * rethink name space problems
56 * need a proper out-of-band
59 #include <sys/cdefs.h>
62 #include <sys/param.h>
63 #include <sys/capsicum.h>
64 #include <sys/domain.h>
65 #include <sys/eventhandler.h>
66 #include <sys/fcntl.h>
68 #include <sys/filedesc.h>
69 #include <sys/kernel.h>
71 #include <sys/malloc.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
77 #include <sys/protosw.h>
78 #include <sys/queue.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
86 #include <sys/sysctl.h>
87 #include <sys/systm.h>
88 #include <sys/taskqueue.h>
90 #include <sys/unpcb.h>
91 #include <sys/vnode.h>
99 #include <security/mac/mac_framework.h>
103 MALLOC_DECLARE(M_FILECAPS);
105 static struct domain localdomain;
107 static uma_zone_t unp_zone;
108 static unp_gen_t unp_gencnt; /* (l) */
109 static u_int unp_count; /* (l) Count of local sockets. */
110 static ino_t unp_ino; /* Prototype for fake inode numbers. */
111 static int unp_rights; /* (g) File descriptors in flight. */
112 static struct unp_head unp_shead; /* (l) List of stream sockets. */
113 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
114 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
117 SLIST_ENTRY(unp_defer) ud_link;
120 static SLIST_HEAD(, unp_defer) unp_defers;
121 static int unp_defers_count;
123 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
126 * Garbage collection of cyclic file descriptor/socket references occurs
127 * asynchronously in a taskqueue context in order to avoid recursion and
128 * reentrance in the UNIX domain socket, file descriptor, and socket layer
129 * code. See unp_gc() for a full description.
131 static struct timeout_task unp_gc_task;
134 * The close of unix domain sockets attached as SCM_RIGHTS is
135 * postponed to the taskqueue, to avoid arbitrary recursion depth.
136 * The attached sockets might have another sockets attached.
138 static struct task unp_defer_task;
141 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
142 * stream sockets, although the total for sender and receiver is actually
145 * Datagram sockets really use the sendspace as the maximum datagram size,
146 * and don't really want to reserve the sendspace. Their recvspace should be
147 * large enough for at least one max-size datagram plus address.
152 static u_long unpst_sendspace = PIPSIZ;
153 static u_long unpst_recvspace = PIPSIZ;
154 static u_long unpdg_maxdgram = 2*1024;
155 static u_long unpdg_recvspace = 16*1024; /* support 8KB syslog msgs */
156 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
157 static u_long unpsp_recvspace = PIPSIZ;
159 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
161 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
162 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
164 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
165 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
167 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
168 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
171 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
172 &unpst_sendspace, 0, "Default stream send space.");
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
174 &unpst_recvspace, 0, "Default stream receive space.");
175 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
176 &unpdg_maxdgram, 0, "Maximum datagram size.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
178 &unpdg_recvspace, 0, "Default datagram receive space.");
179 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
180 &unpsp_sendspace, 0, "Default seqpacket send space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
182 &unpsp_recvspace, 0, "Default seqpacket receive space.");
183 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
184 "File descriptors in flight.");
185 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
186 &unp_defers_count, 0,
187 "File descriptors deferred to taskqueue for close.");
190 * Locking and synchronization:
192 * Several types of locks exist in the local domain socket implementation:
193 * - a global linkage lock
194 * - a global connection list lock
196 * - per-unpcb mutexes
198 * The linkage lock protects the global socket lists, the generation number
199 * counter and garbage collector state.
201 * The connection list lock protects the list of referring sockets in a datagram
202 * socket PCB. This lock is also overloaded to protect a global list of
203 * sockets whose buffers contain socket references in the form of SCM_RIGHTS
204 * messages. To avoid recursion, such references are released by a dedicated
207 * The mtxpool lock protects the vnode from being modified while referenced.
208 * Lock ordering rules require that it be acquired before any PCB locks.
210 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
211 * unpcb. This includes the unp_conn field, which either links two connected
212 * PCBs together (for connected socket types) or points at the destination
213 * socket (for connectionless socket types). The operations of creating or
214 * destroying a connection therefore involve locking multiple PCBs. To avoid
215 * lock order reversals, in some cases this involves dropping a PCB lock and
216 * using a reference counter to maintain liveness.
218 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
219 * allocated in pr_attach() and freed in pr_detach(). The validity of that
220 * pointer is an invariant, so no lock is required to dereference the so_pcb
221 * pointer if a valid socket reference is held by the caller. In practice,
222 * this is always true during operations performed on a socket. Each unpcb
223 * has a back-pointer to its socket, unp_socket, which will be stable under
224 * the same circumstances.
226 * This pointer may only be safely dereferenced as long as a valid reference
227 * to the unpcb is held. Typically, this reference will be from the socket,
228 * or from another unpcb when the referring unpcb's lock is held (in order
229 * that the reference not be invalidated during use). For example, to follow
230 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
231 * that detach is not run clearing unp_socket.
233 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
234 * protocols, bind() is a non-atomic operation, and connect() requires
235 * potential sleeping in the protocol, due to potentially waiting on local or
236 * distributed file systems. We try to separate "lookup" operations, which
237 * may sleep, and the IPC operations themselves, which typically can occur
238 * with relative atomicity as locks can be held over the entire operation.
240 * Another tricky issue is simultaneous multi-threaded or multi-process
241 * access to a single UNIX domain socket. These are handled by the flags
242 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
243 * binding, both of which involve dropping UNIX domain socket locks in order
244 * to perform namei() and other file system operations.
246 static struct rwlock unp_link_rwlock;
247 static struct mtx unp_defers_lock;
249 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
252 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
254 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
257 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
258 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
259 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
260 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
261 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
263 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
265 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
266 "unp_defer", NULL, MTX_DEF)
267 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
268 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
270 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
271 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
273 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
276 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
277 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx)
278 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
279 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
280 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
281 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
282 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
283 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
285 static int uipc_connect2(struct socket *, struct socket *);
286 static int uipc_ctloutput(struct socket *, struct sockopt *);
287 static int unp_connect(struct socket *, struct sockaddr *,
289 static int unp_connectat(int, struct socket *, struct sockaddr *,
290 struct thread *, bool);
291 typedef enum { PRU_CONNECT, PRU_CONNECT2 } conn2_how;
292 static void unp_connect2(struct socket *so, struct socket *so2, conn2_how);
293 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
294 static void unp_dispose(struct socket *so);
295 static void unp_shutdown(struct unpcb *);
296 static void unp_drop(struct unpcb *);
297 static void unp_gc(__unused void *, int);
298 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
299 static void unp_discard(struct file *);
300 static void unp_freerights(struct filedescent **, int);
301 static int unp_internalize(struct mbuf **, struct thread *,
302 struct mbuf **, u_int *, u_int *);
303 static void unp_internalize_fp(struct file *);
304 static int unp_externalize(struct mbuf *, struct mbuf **, int);
305 static int unp_externalize_fp(struct file *);
306 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *,
307 int, struct mbuf **, u_int *, u_int *);
308 static void unp_process_defers(void * __unused, int);
311 unp_pcb_hold(struct unpcb *unp)
315 old = refcount_acquire(&unp->unp_refcount);
316 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
319 static __result_use_check bool
320 unp_pcb_rele(struct unpcb *unp)
324 UNP_PCB_LOCK_ASSERT(unp);
326 if ((ret = refcount_release(&unp->unp_refcount))) {
328 UNP_PCB_LOCK_DESTROY(unp);
329 uma_zfree(unp_zone, unp);
335 unp_pcb_rele_notlast(struct unpcb *unp)
339 ret = refcount_release(&unp->unp_refcount);
340 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
344 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
346 UNP_PCB_UNLOCK_ASSERT(unp);
347 UNP_PCB_UNLOCK_ASSERT(unp2);
351 } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
361 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
365 UNP_PCB_UNLOCK(unp2);
369 * Try to lock the connected peer of an already locked socket. In some cases
370 * this requires that we unlock the current socket. The pairbusy counter is
371 * used to block concurrent connection attempts while the lock is dropped. The
372 * caller must be careful to revalidate PCB state.
374 static struct unpcb *
375 unp_pcb_lock_peer(struct unpcb *unp)
379 UNP_PCB_LOCK_ASSERT(unp);
380 unp2 = unp->unp_conn;
383 if (__predict_false(unp == unp2))
386 UNP_PCB_UNLOCK_ASSERT(unp2);
388 if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
390 if ((uintptr_t)unp2 > (uintptr_t)unp) {
400 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
401 ("%s: socket %p was reconnected", __func__, unp));
402 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
403 unp->unp_flags &= ~UNP_WAITING;
406 if (unp_pcb_rele(unp2)) {
407 /* unp2 is unlocked. */
410 if (unp->unp_conn == NULL) {
411 UNP_PCB_UNLOCK(unp2);
418 uipc_abort(struct socket *so)
420 struct unpcb *unp, *unp2;
423 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
424 UNP_PCB_UNLOCK_ASSERT(unp);
427 unp2 = unp->unp_conn;
437 uipc_accept(struct socket *so, struct sockaddr **nam)
439 struct unpcb *unp, *unp2;
440 const struct sockaddr *sa;
443 * Pass back name of connected socket, if it was bound and we are
444 * still connected (our peer may have closed already!).
447 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
449 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
451 unp2 = unp_pcb_lock_peer(unp);
452 if (unp2 != NULL && unp2->unp_addr != NULL)
453 sa = (struct sockaddr *)unp2->unp_addr;
456 bcopy(sa, *nam, sa->sa_len);
458 unp_pcb_unlock_pair(unp, unp2);
465 uipc_attach(struct socket *so, int proto, struct thread *td)
467 u_long sendspace, recvspace;
472 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
473 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
474 switch (so->so_type) {
476 sendspace = unpst_sendspace;
477 recvspace = unpst_recvspace;
481 STAILQ_INIT(&so->so_rcv.uxdg_mb);
482 STAILQ_INIT(&so->so_snd.uxdg_mb);
483 TAILQ_INIT(&so->so_rcv.uxdg_conns);
485 * Since send buffer is either bypassed or is a part
486 * of one-to-many receive buffer, we assign both space
487 * limits to unpdg_recvspace.
489 sendspace = recvspace = unpdg_recvspace;
493 sendspace = unpsp_sendspace;
494 recvspace = unpsp_recvspace;
498 panic("uipc_attach");
500 error = soreserve(so, sendspace, recvspace);
504 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
507 LIST_INIT(&unp->unp_refs);
508 UNP_PCB_LOCK_INIT(unp);
509 unp->unp_socket = so;
511 refcount_init(&unp->unp_refcount, 1);
513 if ((locked = UNP_LINK_WOWNED()) == false)
516 unp->unp_gencnt = ++unp_gencnt;
517 unp->unp_ino = ++unp_ino;
519 switch (so->so_type) {
521 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
525 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
529 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
533 panic("uipc_attach");
543 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
545 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
555 if (nam->sa_family != AF_UNIX)
556 return (EAFNOSUPPORT);
559 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
561 if (soun->sun_len > sizeof(struct sockaddr_un))
563 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
568 * We don't allow simultaneous bind() calls on a single UNIX domain
569 * socket, so flag in-progress operations, and return an error if an
570 * operation is already in progress.
572 * Historically, we have not allowed a socket to be rebound, so this
573 * also returns an error. Not allowing re-binding simplifies the
574 * implementation and avoids a great many possible failure modes.
577 if (unp->unp_vnode != NULL) {
581 if (unp->unp_flags & UNP_BINDING) {
585 unp->unp_flags |= UNP_BINDING;
588 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
589 bcopy(soun->sun_path, buf, namelen);
593 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
594 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
595 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
600 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
611 error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
617 vattr.va_type = VSOCK;
618 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
620 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
624 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
627 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
628 vn_finished_write(mp);
629 if (error == ERELOOKUP)
634 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
635 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
638 VOP_UNP_BIND(vp, unp);
640 unp->unp_addr = soun;
641 unp->unp_flags &= ~UNP_BINDING;
644 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
645 vn_finished_write(mp);
651 unp->unp_flags &= ~UNP_BINDING;
658 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
661 return (uipc_bindat(AT_FDCWD, so, nam, td));
665 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
669 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
670 error = unp_connect(so, nam, td);
675 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
680 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
681 error = unp_connectat(fd, so, nam, td, false);
686 uipc_close(struct socket *so)
688 struct unpcb *unp, *unp2;
689 struct vnode *vp = NULL;
693 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
696 if ((vp = unp->unp_vnode) != NULL) {
697 vplock = mtx_pool_find(mtxpool_sleep, vp);
701 if (vp && unp->unp_vnode == NULL) {
707 unp->unp_vnode = NULL;
709 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
710 unp_disconnect(unp, unp2);
720 uipc_connect2(struct socket *so1, struct socket *so2)
722 struct unpcb *unp, *unp2;
724 if (so1->so_type != so2->so_type)
728 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
730 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
731 unp_pcb_lock_pair(unp, unp2);
732 unp_connect2(so1, so2, PRU_CONNECT2);
733 unp_pcb_unlock_pair(unp, unp2);
739 uipc_detach(struct socket *so)
741 struct unpcb *unp, *unp2;
744 int local_unp_rights;
747 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
753 LIST_REMOVE(unp, unp_link);
754 if (unp->unp_gcflag & UNPGC_DEAD)
755 LIST_REMOVE(unp, unp_dead);
756 unp->unp_gencnt = ++unp_gencnt;
760 UNP_PCB_UNLOCK_ASSERT(unp);
762 if ((vp = unp->unp_vnode) != NULL) {
763 vplock = mtx_pool_find(mtxpool_sleep, vp);
767 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
773 if ((vp = unp->unp_vnode) != NULL) {
775 unp->unp_vnode = NULL;
777 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
778 unp_disconnect(unp, unp2);
783 while (!LIST_EMPTY(&unp->unp_refs)) {
784 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
787 UNP_REF_LIST_UNLOCK();
790 UNP_PCB_UNLOCK_ASSERT(ref);
794 UNP_REF_LIST_UNLOCK();
797 local_unp_rights = unp_rights;
798 unp->unp_socket->so_pcb = NULL;
799 unp->unp_socket = NULL;
800 free(unp->unp_addr, M_SONAME);
801 unp->unp_addr = NULL;
802 if (!unp_pcb_rele(unp))
808 if (local_unp_rights)
809 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
811 switch (so->so_type) {
814 * Everything should have been unlinked/freed by unp_dispose()
815 * and/or unp_disconnect().
817 MPASS(so->so_rcv.uxdg_peeked == NULL);
818 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
819 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
820 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
825 uipc_disconnect(struct socket *so)
827 struct unpcb *unp, *unp2;
830 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
833 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
834 unp_disconnect(unp, unp2);
841 uipc_listen(struct socket *so, int backlog, struct thread *td)
846 MPASS(so->so_type != SOCK_DGRAM);
849 * Synchronize with concurrent connection attempts.
854 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
856 else if (unp->unp_vnode == NULL)
857 error = EDESTADDRREQ;
864 error = solisten_proto_check(so);
866 cru2xt(td, &unp->unp_peercred);
867 solisten_proto(so, backlog);
875 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
877 struct unpcb *unp, *unp2;
878 const struct sockaddr *sa;
881 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
883 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
886 unp2 = unp_pcb_lock_peer(unp);
888 if (unp2->unp_addr != NULL)
889 sa = (struct sockaddr *)unp2->unp_addr;
892 bcopy(sa, *nam, sa->sa_len);
893 unp_pcb_unlock_pair(unp, unp2);
896 bcopy(sa, *nam, sa->sa_len);
903 uipc_rcvd(struct socket *so, int flags)
905 struct unpcb *unp, *unp2;
910 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
911 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
912 ("%s: socktype %d", __func__, so->so_type));
915 * Adjust backpressure on sender and wakeup any waiting to write.
917 * The unp lock is acquired to maintain the validity of the unp_conn
918 * pointer; no lock on unp2 is required as unp2->unp_socket will be
919 * static as long as we don't permit unp2 to disconnect from unp,
920 * which is prevented by the lock on unp. We cache values from
921 * so_rcv to avoid holding the so_rcv lock over the entire
922 * transaction on the remote so_snd.
924 SOCKBUF_LOCK(&so->so_rcv);
925 mbcnt = so->so_rcv.sb_mbcnt;
926 sbcc = sbavail(&so->so_rcv);
927 SOCKBUF_UNLOCK(&so->so_rcv);
929 * There is a benign race condition at this point. If we're planning to
930 * clear SB_STOP, but uipc_send is called on the connected socket at
931 * this instant, it might add data to the sockbuf and set SB_STOP. Then
932 * we would erroneously clear SB_STOP below, even though the sockbuf is
933 * full. The race is benign because the only ill effect is to allow the
934 * sockbuf to exceed its size limit, and the size limits are not
935 * strictly guaranteed anyway.
938 unp2 = unp->unp_conn;
943 so2 = unp2->unp_socket;
944 SOCKBUF_LOCK(&so2->so_snd);
945 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
946 so2->so_snd.sb_flags &= ~SB_STOP;
947 sowwakeup_locked(so2);
953 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
954 struct mbuf *control, struct thread *td)
956 struct unpcb *unp, *unp2;
962 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
963 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
964 ("%s: socktype %d", __func__, so->so_type));
967 if (flags & PRUS_OOB) {
971 if (control != NULL &&
972 (error = unp_internalize(&control, td, NULL, NULL, NULL)))
976 if ((so->so_state & SS_ISCONNECTED) == 0) {
978 if ((error = unp_connect(so, nam, td)) != 0)
987 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
991 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
992 unp_pcb_unlock_pair(unp, unp2);
997 if ((so2 = unp2->unp_socket) == NULL) {
998 UNP_PCB_UNLOCK(unp2);
1002 SOCKBUF_LOCK(&so2->so_rcv);
1003 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1005 * Credentials are passed only once on SOCK_STREAM and
1006 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1007 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1009 control = unp_addsockcred(td, control, unp2->unp_flags, NULL,
1011 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1015 * Send to paired receive port and wake up readers. Don't
1016 * check for space available in the receive buffer if we're
1017 * attaching ancillary data; Unix domain sockets only check
1018 * for space in the sending sockbuf, and that check is
1019 * performed one level up the stack. At that level we cannot
1020 * precisely account for the amount of buffer space used
1021 * (e.g., because control messages are not yet internalized).
1023 switch (so->so_type) {
1025 if (control != NULL) {
1026 sbappendcontrol_locked(&so2->so_rcv, m,
1030 sbappend_locked(&so2->so_rcv, m, flags);
1033 case SOCK_SEQPACKET:
1034 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1035 &sun_noname, m, control))
1040 mbcnt = so2->so_rcv.sb_mbcnt;
1041 sbcc = sbavail(&so2->so_rcv);
1043 sorwakeup_locked(so2);
1045 SOCKBUF_UNLOCK(&so2->so_rcv);
1048 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1049 * it would be possible for uipc_rcvd to be called at this
1050 * point, drain the receiving sockbuf, clear SB_STOP, and then
1051 * we would set SB_STOP below. That could lead to an empty
1052 * sockbuf having SB_STOP set
1054 SOCKBUF_LOCK(&so->so_snd);
1055 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1056 so->so_snd.sb_flags |= SB_STOP;
1057 SOCKBUF_UNLOCK(&so->so_snd);
1058 UNP_PCB_UNLOCK(unp2);
1062 * PRUS_EOF is equivalent to pr_send followed by pr_shutdown.
1064 if (flags & PRUS_EOF) {
1068 UNP_PCB_UNLOCK(unp);
1070 if (control != NULL && error != 0)
1071 unp_scan(control, unp_freerights);
1074 if (control != NULL)
1077 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1078 * for freeing memory.
1080 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1085 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1087 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1092 * Negative space may happen if send(2) is followed by
1093 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1095 if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1096 sb->sb_mbmax < sb->uxdg_mbcnt))
1099 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1102 bleft = sb->sb_hiwat - sb->uxdg_cc;
1103 mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1105 return (bleft >= cc && mleft >= mbcnt);
1109 * PF_UNIX/SOCK_DGRAM send
1111 * Allocate a record consisting of 3 mbufs in the sequence of
1112 * from -> control -> data and append it to the socket buffer.
1114 * The first mbuf carries sender's name and is a pkthdr that stores
1115 * overall length of datagram, its memory consumption and control length.
1117 #define ctllen PH_loc.thirtytwo[1]
1118 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1119 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1121 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1122 struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1124 struct unpcb *unp, *unp2;
1125 const struct sockaddr *from;
1128 struct mbuf *f, *clast;
1129 u_int cc, ctl, mbcnt;
1130 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1133 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1139 if (__predict_false(flags & MSG_OOB)) {
1144 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1148 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1149 if (__predict_false(m == NULL)) {
1153 f = m_gethdr(M_WAITOK, MT_SONAME);
1154 cc = m->m_pkthdr.len;
1155 mbcnt = MSIZE + m->m_pkthdr.memlen;
1157 (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt)))
1160 /* pr_sosend() with mbuf usually is a kernel thread. */
1163 if (__predict_false(c != NULL))
1164 panic("%s: control from a kernel thread", __func__);
1166 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1170 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1174 /* Condition the foreign mbuf to our standards. */
1176 m_tag_delete_chain(m, NULL);
1177 m->m_pkthdr.rcvif = NULL;
1178 m->m_pkthdr.flowid = 0;
1179 m->m_pkthdr.csum_flags = 0;
1180 m->m_pkthdr.fibnum = 0;
1181 m->m_pkthdr.rsstype = 0;
1183 cc = m->m_pkthdr.len;
1185 for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) {
1187 if (mb->m_flags & M_EXT)
1188 mbcnt += mb->m_ext.ext_size;
1192 unp = sotounpcb(so);
1196 * XXXGL: would be cool to fully remove so_snd out of the equation
1197 * and avoid this lock, which is not only extraneous, but also being
1198 * released, thus still leaving possibility for a race. We can easily
1199 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1200 * is more difficult to invent something to handle so_error.
1202 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1205 SOCK_SENDBUF_LOCK(so);
1206 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1207 SOCK_SENDBUF_UNLOCK(so);
1211 if (so->so_error != 0) {
1212 error = so->so_error;
1214 SOCK_SENDBUF_UNLOCK(so);
1217 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1218 SOCK_SENDBUF_UNLOCK(so);
1219 error = EDESTADDRREQ;
1222 SOCK_SENDBUF_UNLOCK(so);
1225 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1227 UNP_PCB_LOCK_ASSERT(unp);
1228 unp2 = unp->unp_conn;
1229 UNP_PCB_LOCK_ASSERT(unp2);
1232 unp2 = unp_pcb_lock_peer(unp);
1234 UNP_PCB_UNLOCK(unp);
1240 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1241 c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl,
1243 if (unp->unp_addr != NULL)
1244 from = (struct sockaddr *)unp->unp_addr;
1247 f->m_len = from->sa_len;
1248 MPASS(from->sa_len <= MLEN);
1249 bcopy(from, mtod(f, void *), from->sa_len);
1253 * Concatenate mbufs: from -> control -> data.
1254 * Save overall cc and mbcnt in "from" mbuf.
1260 for (mc = c; mc->m_next != NULL; mc = mc->m_next);
1270 dcc = dctl = dmbcnt = 0;
1271 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
1272 if (mb->m_type == MT_DATA)
1277 if (mb->m_flags & M_EXT)
1278 dmbcnt += mb->m_ext.ext_size;
1282 MPASS(dmbcnt == mbcnt);
1284 f->m_pkthdr.len = cc + ctl;
1285 f->m_pkthdr.memlen = mbcnt;
1286 f->m_pkthdr.ctllen = ctl;
1289 * Destination socket buffer selection.
1291 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
1292 * destination address is supplied, create a temporary connection for
1293 * the run time of the function (see call to unp_connectat() above and
1294 * to unp_disconnect() below). We distinguish them by condition of
1295 * (addr != NULL). We intentionally avoid adding 'bool connected' for
1296 * that condition, since, again, through the run time of this code we
1297 * are always connected. For such "unconnected" sends, the destination
1298 * buffer would be the receive buffer of destination socket so2.
1300 * For connected sends, data lands on the send buffer of the sender's
1301 * socket "so". Then, if we just added the very first datagram
1302 * on this send buffer, we need to add the send buffer on to the
1303 * receiving socket's buffer list. We put ourselves on top of the
1304 * list. Such logic gives infrequent senders priority over frequent
1307 * Note on byte count management. As long as event methods kevent(2),
1308 * select(2) are not protocol specific (yet), we need to maintain
1309 * meaningful values on the receive buffer. So, the receive buffer
1310 * would accumulate counters from all connected buffers potentially
1311 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
1313 so2 = unp2->unp_socket;
1314 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
1315 SOCK_RECVBUF_LOCK(so2);
1316 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
1317 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
1318 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
1320 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1321 sb->uxdg_cc += cc + ctl;
1322 sb->uxdg_ctl += ctl;
1323 sb->uxdg_mbcnt += mbcnt;
1324 so2->so_rcv.sb_acc += cc + ctl;
1325 so2->so_rcv.sb_ccc += cc + ctl;
1326 so2->so_rcv.sb_ctl += ctl;
1327 so2->so_rcv.sb_mbcnt += mbcnt;
1328 sorwakeup_locked(so2);
1331 soroverflow_locked(so2);
1333 if (f->m_next->m_type == MT_CONTROL) {
1340 unp_disconnect(unp, unp2);
1342 unp_pcb_unlock_pair(unp, unp2);
1344 td->td_ru.ru_msgsnd++;
1347 SOCK_IO_SEND_UNLOCK(so);
1350 unp_scan(c, unp_freerights);
1363 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
1364 * The mbuf has already been unlinked from the uxdg_mb of socket buffer
1365 * and needs to be linked onto uxdg_peeked of receive socket buffer.
1368 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
1369 struct uio *uio, struct mbuf **controlp, int *flagsp)
1374 so->so_rcv.uxdg_peeked = m;
1375 so->so_rcv.uxdg_cc += m->m_pkthdr.len;
1376 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
1377 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
1378 SOCK_RECVBUF_UNLOCK(so);
1380 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1382 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1385 KASSERT(m, ("%s: no data or control after soname", __func__));
1388 * With MSG_PEEK the control isn't executed, just copied.
1390 while (m != NULL && m->m_type == MT_CONTROL) {
1391 if (controlp != NULL) {
1392 *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1393 controlp = &(*controlp)->m_next;
1397 KASSERT(m == NULL || m->m_type == MT_DATA,
1398 ("%s: not MT_DATA mbuf %p", __func__, m));
1399 while (m != NULL && uio->uio_resid > 0) {
1400 len = uio->uio_resid;
1403 error = uiomove(mtod(m, char *), (int)len, uio);
1405 SOCK_IO_RECV_UNLOCK(so);
1408 if (len == m->m_len)
1411 SOCK_IO_RECV_UNLOCK(so);
1413 if (flagsp != NULL) {
1415 if (*flagsp & MSG_TRUNC) {
1416 /* Report real length of the packet */
1417 uio->uio_resid -= m_length(m, NULL) - len;
1419 *flagsp |= MSG_TRUNC;
1421 *flagsp &= ~MSG_TRUNC;
1428 * PF_UNIX/SOCK_DGRAM receive
1431 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1432 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1434 struct sockbuf *sb = NULL;
1444 if (controlp != NULL)
1447 flags = flagsp != NULL ? *flagsp : 0;
1448 nonblock = (so->so_state & SS_NBIO) ||
1449 (flags & (MSG_DONTWAIT | MSG_NBIO));
1451 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1452 if (__predict_false(error))
1456 * Loop blocking while waiting for a datagram. Prioritize connected
1457 * peers over unconnected sends. Set sb to selected socket buffer
1458 * containing an mbuf on exit from the wait loop. A datagram that
1459 * had already been peeked at has top priority.
1461 SOCK_RECVBUF_LOCK(so);
1462 while ((m = so->so_rcv.uxdg_peeked) == NULL &&
1463 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
1464 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1466 error = so->so_error;
1468 SOCK_RECVBUF_UNLOCK(so);
1469 SOCK_IO_RECV_UNLOCK(so);
1472 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1473 uio->uio_resid == 0) {
1474 SOCK_RECVBUF_UNLOCK(so);
1475 SOCK_IO_RECV_UNLOCK(so);
1479 SOCK_RECVBUF_UNLOCK(so);
1480 SOCK_IO_RECV_UNLOCK(so);
1481 return (EWOULDBLOCK);
1483 error = sbwait(so, SO_RCV);
1485 SOCK_RECVBUF_UNLOCK(so);
1486 SOCK_IO_RECV_UNLOCK(so);
1494 m = STAILQ_FIRST(&sb->uxdg_mb);
1496 MPASS(m == so->so_rcv.uxdg_peeked);
1498 MPASS(sb->uxdg_cc > 0);
1500 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1503 uio->uio_td->td_ru.ru_msgrcv++;
1505 if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
1506 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
1507 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
1508 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
1510 so->so_rcv.uxdg_peeked = NULL;
1512 sb->uxdg_cc -= m->m_pkthdr.len;
1513 sb->uxdg_ctl -= m->m_pkthdr.ctllen;
1514 sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
1516 if (__predict_false(flags & MSG_PEEK))
1517 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
1519 so->so_rcv.sb_acc -= m->m_pkthdr.len;
1520 so->so_rcv.sb_ccc -= m->m_pkthdr.len;
1521 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
1522 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
1523 SOCK_RECVBUF_UNLOCK(so);
1526 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1528 KASSERT(m, ("%s: no data or control after soname", __func__));
1531 * Packet to copyout() is now in 'm' and it is disconnected from the
1534 * Process one or more MT_CONTROL mbufs present before any data mbufs
1535 * in the first mbuf chain on the socket buffer. We call into the
1536 * unp_externalize() to perform externalization (or freeing if
1537 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1538 * without MT_DATA mbufs.
1540 while (m != NULL && m->m_type == MT_CONTROL) {
1543 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1544 * it frees whole chain, so we must disconnect the mbuf.
1546 cm = m; m = m->m_next; cm->m_next = NULL;
1547 error = unp_externalize(cm, controlp, flags);
1549 SOCK_IO_RECV_UNLOCK(so);
1550 unp_scan(m, unp_freerights);
1554 if (controlp != NULL) {
1555 while (*controlp != NULL)
1556 controlp = &(*controlp)->m_next;
1559 KASSERT(m == NULL || m->m_type == MT_DATA,
1560 ("%s: not MT_DATA mbuf %p", __func__, m));
1561 while (m != NULL && uio->uio_resid > 0) {
1562 len = uio->uio_resid;
1565 error = uiomove(mtod(m, char *), (int)len, uio);
1567 SOCK_IO_RECV_UNLOCK(so);
1571 if (len == m->m_len)
1578 SOCK_IO_RECV_UNLOCK(so);
1581 if (flagsp != NULL) {
1582 if (flags & MSG_TRUNC) {
1583 /* Report real length of the packet */
1584 uio->uio_resid -= m_length(m, NULL);
1586 *flagsp |= MSG_TRUNC;
1589 } else if (flagsp != NULL)
1590 *flagsp &= ~MSG_TRUNC;
1596 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1598 struct mbuf *mb, *n;
1602 if (SOLISTENING(so)) {
1609 if (sb->sb_fnrdy != NULL) {
1610 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1612 *errorp = sbready(sb, m, count);
1625 return (mb != NULL);
1629 uipc_ready(struct socket *so, struct mbuf *m, int count)
1631 struct unpcb *unp, *unp2;
1635 unp = sotounpcb(so);
1637 KASSERT(so->so_type == SOCK_STREAM,
1638 ("%s: unexpected socket type for %p", __func__, so));
1641 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1642 UNP_PCB_UNLOCK(unp);
1643 so2 = unp2->unp_socket;
1644 SOCKBUF_LOCK(&so2->so_rcv);
1645 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1646 sorwakeup_locked(so2);
1648 SOCKBUF_UNLOCK(&so2->so_rcv);
1649 UNP_PCB_UNLOCK(unp2);
1652 UNP_PCB_UNLOCK(unp);
1655 * The receiving socket has been disconnected, but may still be valid.
1656 * In this case, the now-ready mbufs are still present in its socket
1657 * buffer, so perform an exhaustive search before giving up and freeing
1661 LIST_FOREACH(unp, &unp_shead, unp_link) {
1662 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1668 for (i = 0; i < count; i++)
1676 uipc_sense(struct socket *so, struct stat *sb)
1680 unp = sotounpcb(so);
1681 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1683 sb->st_blksize = so->so_snd.sb_hiwat;
1685 sb->st_ino = unp->unp_ino;
1690 uipc_shutdown(struct socket *so)
1694 unp = sotounpcb(so);
1695 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1700 UNP_PCB_UNLOCK(unp);
1705 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1708 const struct sockaddr *sa;
1710 unp = sotounpcb(so);
1711 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1713 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1715 if (unp->unp_addr != NULL)
1716 sa = (struct sockaddr *) unp->unp_addr;
1719 bcopy(sa, *nam, sa->sa_len);
1720 UNP_PCB_UNLOCK(unp);
1725 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1731 if (sopt->sopt_level != SOL_LOCAL)
1734 unp = sotounpcb(so);
1735 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1737 switch (sopt->sopt_dir) {
1739 switch (sopt->sopt_name) {
1740 case LOCAL_PEERCRED:
1742 if (unp->unp_flags & UNP_HAVEPC)
1743 xu = unp->unp_peercred;
1745 if (so->so_type == SOCK_STREAM)
1750 UNP_PCB_UNLOCK(unp);
1752 error = sooptcopyout(sopt, &xu, sizeof(xu));
1756 /* Unlocked read. */
1757 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1758 error = sooptcopyout(sopt, &optval, sizeof(optval));
1761 case LOCAL_CREDS_PERSISTENT:
1762 /* Unlocked read. */
1763 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1764 error = sooptcopyout(sopt, &optval, sizeof(optval));
1767 case LOCAL_CONNWAIT:
1768 /* Unlocked read. */
1769 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1770 error = sooptcopyout(sopt, &optval, sizeof(optval));
1780 switch (sopt->sopt_name) {
1782 case LOCAL_CREDS_PERSISTENT:
1783 case LOCAL_CONNWAIT:
1784 error = sooptcopyin(sopt, &optval, sizeof(optval),
1789 #define OPTSET(bit, exclusive) do { \
1790 UNP_PCB_LOCK(unp); \
1792 if ((unp->unp_flags & (exclusive)) != 0) { \
1793 UNP_PCB_UNLOCK(unp); \
1797 unp->unp_flags |= (bit); \
1799 unp->unp_flags &= ~(bit); \
1800 UNP_PCB_UNLOCK(unp); \
1803 switch (sopt->sopt_name) {
1805 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1808 case LOCAL_CREDS_PERSISTENT:
1809 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1812 case LOCAL_CONNWAIT:
1813 OPTSET(UNP_CONNWAIT, 0);
1822 error = ENOPROTOOPT;
1835 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1838 return (unp_connectat(AT_FDCWD, so, nam, td, false));
1842 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1843 struct thread *td, bool return_locked)
1846 struct sockaddr_un *soun;
1849 struct unpcb *unp, *unp2, *unp3;
1850 struct nameidata nd;
1851 char buf[SOCK_MAXADDRLEN];
1852 struct sockaddr *sa;
1853 cap_rights_t rights;
1857 if (nam->sa_family != AF_UNIX)
1858 return (EAFNOSUPPORT);
1859 if (nam->sa_len > sizeof(struct sockaddr_un))
1861 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1864 soun = (struct sockaddr_un *)nam;
1865 bcopy(soun->sun_path, buf, len);
1869 unp = sotounpcb(so);
1873 * Wait for connection state to stabilize. If a connection
1874 * already exists, give up. For datagram sockets, which permit
1875 * multiple consecutive connect(2) calls, upper layers are
1876 * responsible for disconnecting in advance of a subsequent
1877 * connect(2), but this is not synchronized with PCB connection
1880 * Also make sure that no threads are currently attempting to
1881 * lock the peer socket, to ensure that unp_conn cannot
1882 * transition between two valid sockets while locks are dropped.
1884 if (SOLISTENING(so))
1886 else if (unp->unp_conn != NULL)
1888 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1892 UNP_PCB_UNLOCK(unp);
1895 if (unp->unp_pairbusy > 0) {
1896 unp->unp_flags |= UNP_WAITING;
1897 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1902 unp->unp_flags |= UNP_CONNECTING;
1903 UNP_PCB_UNLOCK(unp);
1905 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1907 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1910 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1911 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1917 ASSERT_VOP_LOCKED(vp, "unp_connect");
1922 if (vp->v_type != VSOCK) {
1927 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1931 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1935 unp = sotounpcb(so);
1936 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1938 vplock = mtx_pool_find(mtxpool_sleep, vp);
1940 VOP_UNP_CONNECT(vp, &unp2);
1942 error = ECONNREFUSED;
1945 so2 = unp2->unp_socket;
1946 if (so->so_type != so2->so_type) {
1951 if (SOLISTENING(so2)) {
1952 CURVNET_SET(so2->so_vnet);
1953 so2 = sonewconn(so2, 0);
1958 error = ECONNREFUSED;
1961 unp3 = sotounpcb(so2);
1962 unp_pcb_lock_pair(unp2, unp3);
1963 if (unp2->unp_addr != NULL) {
1964 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1965 unp3->unp_addr = (struct sockaddr_un *) sa;
1969 unp_copy_peercred(td, unp3, unp, unp2);
1971 UNP_PCB_UNLOCK(unp2);
1975 * It is safe to block on the PCB lock here since unp2 is
1976 * nascent and cannot be connected to any other sockets.
1980 mac_socketpeer_set_from_socket(so, so2);
1981 mac_socketpeer_set_from_socket(so2, so);
1984 unp_pcb_lock_pair(unp, unp2);
1986 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1987 sotounpcb(so2) == unp2,
1988 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1989 unp_connect2(so, so2, PRU_CONNECT);
1990 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1991 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1992 unp->unp_flags &= ~UNP_CONNECTING;
1994 unp_pcb_unlock_pair(unp, unp2);
2000 * If we are returning locked (called via uipc_sosend_dgram()),
2001 * we need to be sure that vput() won't sleep. This is
2002 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
2003 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
2005 MPASS(!(return_locked && connreq));
2009 if (__predict_false(error)) {
2011 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2012 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2013 unp->unp_flags &= ~UNP_CONNECTING;
2014 UNP_PCB_UNLOCK(unp);
2020 * Set socket peer credentials at connection time.
2022 * The client's PCB credentials are copied from its process structure. The
2023 * server's PCB credentials are copied from the socket on which it called
2024 * listen(2). uipc_listen cached that process's credentials at the time.
2027 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2028 struct unpcb *server_unp, struct unpcb *listen_unp)
2030 cru2xt(td, &client_unp->unp_peercred);
2031 client_unp->unp_flags |= UNP_HAVEPC;
2033 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2034 sizeof(server_unp->unp_peercred));
2035 server_unp->unp_flags |= UNP_HAVEPC;
2036 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2040 unp_connect2(struct socket *so, struct socket *so2, conn2_how req)
2045 MPASS(so2->so_type == so->so_type);
2046 unp = sotounpcb(so);
2047 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2048 unp2 = sotounpcb(so2);
2049 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2051 UNP_PCB_LOCK_ASSERT(unp);
2052 UNP_PCB_LOCK_ASSERT(unp2);
2053 KASSERT(unp->unp_conn == NULL,
2054 ("%s: socket %p is already connected", __func__, unp));
2056 unp->unp_conn = unp2;
2059 switch (so->so_type) {
2061 UNP_REF_LIST_LOCK();
2062 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2063 UNP_REF_LIST_UNLOCK();
2068 case SOCK_SEQPACKET:
2069 KASSERT(unp2->unp_conn == NULL,
2070 ("%s: socket %p is already connected", __func__, unp2));
2071 unp2->unp_conn = unp;
2072 if (req == PRU_CONNECT &&
2073 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2081 panic("unp_connect2");
2086 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2088 struct socket *so, *so2;
2089 struct mbuf *m = NULL;
2091 struct unpcb *unptmp;
2094 UNP_PCB_LOCK_ASSERT(unp);
2095 UNP_PCB_LOCK_ASSERT(unp2);
2096 KASSERT(unp->unp_conn == unp2,
2097 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2099 unp->unp_conn = NULL;
2100 so = unp->unp_socket;
2101 so2 = unp2->unp_socket;
2102 switch (unp->unp_socket->so_type) {
2105 * Remove our send socket buffer from the peer's receive buffer.
2106 * Move the data to the receive buffer only if it is empty.
2107 * This is a protection against a scenario where a peer
2108 * connects, floods and disconnects, effectively blocking
2109 * sendto() from unconnected sockets.
2111 SOCK_RECVBUF_LOCK(so2);
2112 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
2113 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
2115 if (__predict_true((so2->so_rcv.sb_state &
2116 SBS_CANTRCVMORE) == 0) &&
2117 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
2118 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
2119 &so->so_snd.uxdg_mb);
2120 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
2121 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
2122 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
2124 m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
2125 STAILQ_INIT(&so->so_snd.uxdg_mb);
2126 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
2127 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
2128 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
2129 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
2131 /* Note: so may reconnect. */
2132 so->so_snd.uxdg_cc = 0;
2133 so->so_snd.uxdg_ctl = 0;
2134 so->so_snd.uxdg_mbcnt = 0;
2136 SOCK_RECVBUF_UNLOCK(so2);
2137 UNP_REF_LIST_LOCK();
2139 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2143 KASSERT(unptmp != NULL,
2144 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2146 LIST_REMOVE(unp, unp_reflink);
2147 UNP_REF_LIST_UNLOCK();
2150 so->so_state &= ~SS_ISCONNECTED;
2156 case SOCK_SEQPACKET:
2158 soisdisconnected(so);
2159 MPASS(unp2->unp_conn == unp);
2160 unp2->unp_conn = NULL;
2162 soisdisconnected(so2);
2167 unp_pcb_rele_notlast(unp);
2168 if (!unp_pcb_rele(unp))
2169 UNP_PCB_UNLOCK(unp);
2171 if (!unp_pcb_rele(unp))
2172 UNP_PCB_UNLOCK(unp);
2173 if (!unp_pcb_rele(unp2))
2174 UNP_PCB_UNLOCK(unp2);
2178 unp_scan(m, unp_freerights);
2184 * unp_pcblist() walks the global list of struct unpcb's to generate a
2185 * pointer list, bumping the refcount on each unpcb. It then copies them out
2186 * sequentially, validating the generation number on each to see if it has
2187 * been detached. All of this is necessary because copyout() may sleep on
2191 unp_pcblist(SYSCTL_HANDLER_ARGS)
2193 struct unpcb *unp, **unp_list;
2195 struct xunpgen *xug;
2196 struct unp_head *head;
2201 switch ((intptr_t)arg1) {
2210 case SOCK_SEQPACKET:
2215 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2219 * The process of preparing the PCB list is too time-consuming and
2220 * resource-intensive to repeat twice on every request.
2222 if (req->oldptr == NULL) {
2224 req->oldidx = 2 * (sizeof *xug)
2225 + (n + n/8) * sizeof(struct xunpcb);
2229 if (req->newptr != NULL)
2233 * OK, now we're committed to doing something.
2235 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2237 gencnt = unp_gencnt;
2241 xug->xug_len = sizeof *xug;
2243 xug->xug_gen = gencnt;
2244 xug->xug_sogen = so_gencnt;
2245 error = SYSCTL_OUT(req, xug, sizeof *xug);
2251 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2254 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2255 unp = LIST_NEXT(unp, unp_link)) {
2257 if (unp->unp_gencnt <= gencnt) {
2258 if (cr_cansee(req->td->td_ucred,
2259 unp->unp_socket->so_cred)) {
2260 UNP_PCB_UNLOCK(unp);
2263 unp_list[i++] = unp;
2266 UNP_PCB_UNLOCK(unp);
2269 n = i; /* In case we lost some during malloc. */
2272 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2273 for (i = 0; i < n; i++) {
2276 if (unp_pcb_rele(unp))
2279 if (unp->unp_gencnt <= gencnt) {
2280 xu->xu_len = sizeof *xu;
2281 xu->xu_unpp = (uintptr_t)unp;
2283 * XXX - need more locking here to protect against
2284 * connect/disconnect races for SMP.
2286 if (unp->unp_addr != NULL)
2287 bcopy(unp->unp_addr, &xu->xu_addr,
2288 unp->unp_addr->sun_len);
2290 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2291 if (unp->unp_conn != NULL &&
2292 unp->unp_conn->unp_addr != NULL)
2293 bcopy(unp->unp_conn->unp_addr,
2295 unp->unp_conn->unp_addr->sun_len);
2297 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2298 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2299 xu->unp_conn = (uintptr_t)unp->unp_conn;
2300 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2301 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2302 xu->unp_gencnt = unp->unp_gencnt;
2303 sotoxsocket(unp->unp_socket, &xu->xu_socket);
2304 UNP_PCB_UNLOCK(unp);
2305 error = SYSCTL_OUT(req, xu, sizeof *xu);
2307 UNP_PCB_UNLOCK(unp);
2313 * Give the user an updated idea of our state. If the
2314 * generation differs from what we told her before, she knows
2315 * that something happened while we were processing this
2316 * request, and it might be necessary to retry.
2318 xug->xug_gen = unp_gencnt;
2319 xug->xug_sogen = so_gencnt;
2320 xug->xug_count = unp_count;
2321 error = SYSCTL_OUT(req, xug, sizeof *xug);
2323 free(unp_list, M_TEMP);
2328 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2329 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2330 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2331 "List of active local datagram sockets");
2332 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2333 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2334 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2335 "List of active local stream sockets");
2336 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2337 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2338 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2339 "List of active local seqpacket sockets");
2342 unp_shutdown(struct unpcb *unp)
2347 UNP_PCB_LOCK_ASSERT(unp);
2349 unp2 = unp->unp_conn;
2350 if ((unp->unp_socket->so_type == SOCK_STREAM ||
2351 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2352 so = unp2->unp_socket;
2359 unp_drop(struct unpcb *unp)
2365 * Regardless of whether the socket's peer dropped the connection
2366 * with this socket by aborting or disconnecting, POSIX requires
2367 * that ECONNRESET is returned.
2371 so = unp->unp_socket;
2373 so->so_error = ECONNRESET;
2374 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2375 /* Last reference dropped in unp_disconnect(). */
2376 unp_pcb_rele_notlast(unp);
2377 unp_disconnect(unp, unp2);
2378 } else if (!unp_pcb_rele(unp)) {
2379 UNP_PCB_UNLOCK(unp);
2384 unp_freerights(struct filedescent **fdep, int fdcount)
2389 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2391 for (i = 0; i < fdcount; i++) {
2392 fp = fdep[i]->fde_file;
2393 filecaps_free(&fdep[i]->fde_caps);
2396 free(fdep[0], M_FILECAPS);
2400 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2402 struct thread *td = curthread; /* XXX */
2403 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2406 struct filedesc *fdesc = td->td_proc->p_fd;
2407 struct filedescent **fdep;
2409 socklen_t clen = control->m_len, datalen;
2413 UNP_LINK_UNLOCK_ASSERT();
2416 if (controlp != NULL) /* controlp == NULL => free control messages */
2418 while (cm != NULL) {
2419 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2421 data = CMSG_DATA(cm);
2422 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2423 if (cm->cmsg_level == SOL_SOCKET
2424 && cm->cmsg_type == SCM_RIGHTS) {
2425 newfds = datalen / sizeof(*fdep);
2430 /* If we're not outputting the descriptors free them. */
2431 if (error || controlp == NULL) {
2432 unp_freerights(fdep, newfds);
2435 FILEDESC_XLOCK(fdesc);
2438 * Now change each pointer to an fd in the global
2439 * table to an integer that is the index to the local
2440 * fd table entry that we set up to point to the
2441 * global one we are transferring.
2443 newlen = newfds * sizeof(int);
2444 *controlp = sbcreatecontrol(NULL, newlen,
2445 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2448 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2449 if ((error = fdallocn(td, 0, fdp, newfds))) {
2450 FILEDESC_XUNLOCK(fdesc);
2451 unp_freerights(fdep, newfds);
2456 for (i = 0; i < newfds; i++, fdp++) {
2457 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2458 (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2459 &fdep[i]->fde_caps);
2460 unp_externalize_fp(fdep[i]->fde_file);
2464 * The new type indicates that the mbuf data refers to
2465 * kernel resources that may need to be released before
2466 * the mbuf is freed.
2468 m_chtype(*controlp, MT_EXTCONTROL);
2469 FILEDESC_XUNLOCK(fdesc);
2470 free(fdep[0], M_FILECAPS);
2472 /* We can just copy anything else across. */
2473 if (error || controlp == NULL)
2475 *controlp = sbcreatecontrol(NULL, datalen,
2476 cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2478 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2481 controlp = &(*controlp)->m_next;
2484 if (CMSG_SPACE(datalen) < clen) {
2485 clen -= CMSG_SPACE(datalen);
2486 cm = (struct cmsghdr *)
2487 ((caddr_t)cm + CMSG_SPACE(datalen));
2499 unp_zone_change(void *tag)
2502 uma_zone_set_max(unp_zone, maxsockets);
2507 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2513 KASSERT(LIST_EMPTY(&unp->unp_refs),
2514 ("%s: unpcb %p has lingering refs", __func__, unp));
2515 KASSERT(unp->unp_socket == NULL,
2516 ("%s: unpcb %p has socket backpointer", __func__, unp));
2517 KASSERT(unp->unp_vnode == NULL,
2518 ("%s: unpcb %p has vnode references", __func__, unp));
2519 KASSERT(unp->unp_conn == NULL,
2520 ("%s: unpcb %p is still connected", __func__, unp));
2521 KASSERT(unp->unp_addr == NULL,
2522 ("%s: unpcb %p has leaked addr", __func__, unp));
2527 unp_init(void *arg __unused)
2536 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2537 NULL, NULL, UMA_ALIGN_CACHE, 0);
2538 uma_zone_set_max(unp_zone, maxsockets);
2539 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2540 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2541 NULL, EVENTHANDLER_PRI_ANY);
2542 LIST_INIT(&unp_dhead);
2543 LIST_INIT(&unp_shead);
2544 LIST_INIT(&unp_sphead);
2545 SLIST_INIT(&unp_defers);
2546 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2547 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2548 UNP_LINK_LOCK_INIT();
2549 UNP_DEFERRED_LOCK_INIT();
2551 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2554 unp_internalize_cleanup_rights(struct mbuf *control)
2561 for (m = control; m != NULL; m = m->m_next) {
2562 cp = mtod(m, struct cmsghdr *);
2563 if (cp->cmsg_level != SOL_SOCKET ||
2564 cp->cmsg_type != SCM_RIGHTS)
2566 data = CMSG_DATA(cp);
2567 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2568 unp_freerights(data, datalen / sizeof(struct filedesc *));
2573 unp_internalize(struct mbuf **controlp, struct thread *td,
2574 struct mbuf **clast, u_int *space, u_int *mbcnt)
2576 struct mbuf *control, **initial_controlp;
2578 struct filedesc *fdesc;
2581 struct cmsgcred *cmcred;
2582 struct filedescent *fde, **fdep, *fdev;
2585 struct timespec *ts;
2587 socklen_t clen, datalen;
2588 int i, j, error, *fdp, oldfds;
2591 MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */
2592 UNP_LINK_UNLOCK_ASSERT();
2597 control = *controlp;
2599 initial_controlp = controlp;
2600 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2601 data = CMSG_DATA(cm);
2603 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2604 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2605 (char *)cm + cm->cmsg_len >= (char *)data;
2607 clen -= min(CMSG_SPACE(datalen), clen),
2608 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2609 data = CMSG_DATA(cm)) {
2610 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2611 switch (cm->cmsg_type) {
2613 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2614 SCM_CREDS, SOL_SOCKET, M_WAITOK);
2615 cmcred = (struct cmsgcred *)
2616 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2617 cmcred->cmcred_pid = p->p_pid;
2618 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2619 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2620 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2621 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2623 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2624 cmcred->cmcred_groups[i] =
2625 td->td_ucred->cr_groups[i];
2629 oldfds = datalen / sizeof (int);
2632 /* On some machines sizeof pointer is bigger than
2633 * sizeof int, so we need to check if data fits into
2634 * single mbuf. We could allocate several mbufs, and
2635 * unp_externalize() should even properly handle that.
2636 * But it is not worth to complicate the code for an
2637 * insane scenario of passing over 200 file descriptors
2640 newlen = oldfds * sizeof(fdep[0]);
2641 if (CMSG_SPACE(newlen) > MCLBYTES) {
2646 * Check that all the FDs passed in refer to legal
2647 * files. If not, reject the entire operation.
2650 FILEDESC_SLOCK(fdesc);
2651 for (i = 0; i < oldfds; i++, fdp++) {
2652 fp = fget_noref(fdesc, *fdp);
2654 FILEDESC_SUNLOCK(fdesc);
2658 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2659 FILEDESC_SUNLOCK(fdesc);
2666 * Now replace the integer FDs with pointers to the
2667 * file structure and capability rights.
2669 *controlp = sbcreatecontrol(NULL, newlen,
2670 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2672 for (i = 0; i < oldfds; i++, fdp++) {
2673 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2675 for (j = 0; j < i; j++, fdp++) {
2676 fdrop(fdesc->fd_ofiles[*fdp].
2679 FILEDESC_SUNLOCK(fdesc);
2685 fdep = (struct filedescent **)
2686 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2687 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2689 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2690 fde = &fdesc->fd_ofiles[*fdp];
2692 fdep[i]->fde_file = fde->fde_file;
2693 filecaps_copy(&fde->fde_caps,
2694 &fdep[i]->fde_caps, true);
2695 unp_internalize_fp(fdep[i]->fde_file);
2697 FILEDESC_SUNLOCK(fdesc);
2701 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2702 SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2703 tv = (struct timeval *)
2704 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2709 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2710 SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2711 bt = (struct bintime *)
2712 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2717 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2718 SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2719 ts = (struct timespec *)
2720 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2725 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2726 SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2727 ts = (struct timespec *)
2728 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2737 if (space != NULL) {
2738 *space += (*controlp)->m_len;
2740 if ((*controlp)->m_flags & M_EXT)
2741 *mbcnt += (*controlp)->m_ext.ext_size;
2744 controlp = &(*controlp)->m_next;
2750 if (error != 0 && initial_controlp != NULL)
2751 unp_internalize_cleanup_rights(*initial_controlp);
2756 static struct mbuf *
2757 unp_addsockcred(struct thread *td, struct mbuf *control, int mode,
2758 struct mbuf **clast, u_int *space, u_int *mbcnt)
2760 struct mbuf *m, *n, *n_prev;
2761 const struct cmsghdr *cm;
2762 int ngroups, i, cmsgtype;
2765 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2766 if (mode & UNP_WANTCRED_ALWAYS) {
2767 ctrlsz = SOCKCRED2SIZE(ngroups);
2768 cmsgtype = SCM_CREDS2;
2770 ctrlsz = SOCKCREDSIZE(ngroups);
2771 cmsgtype = SCM_CREDS;
2774 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2777 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
2779 if (mode & UNP_WANTCRED_ALWAYS) {
2780 struct sockcred2 *sc;
2782 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2784 sc->sc_pid = td->td_proc->p_pid;
2785 sc->sc_uid = td->td_ucred->cr_ruid;
2786 sc->sc_euid = td->td_ucred->cr_uid;
2787 sc->sc_gid = td->td_ucred->cr_rgid;
2788 sc->sc_egid = td->td_ucred->cr_gid;
2789 sc->sc_ngroups = ngroups;
2790 for (i = 0; i < sc->sc_ngroups; i++)
2791 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2793 struct sockcred *sc;
2795 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2796 sc->sc_uid = td->td_ucred->cr_ruid;
2797 sc->sc_euid = td->td_ucred->cr_uid;
2798 sc->sc_gid = td->td_ucred->cr_rgid;
2799 sc->sc_egid = td->td_ucred->cr_gid;
2800 sc->sc_ngroups = ngroups;
2801 for (i = 0; i < sc->sc_ngroups; i++)
2802 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2806 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2807 * created SCM_CREDS control message (struct sockcred) has another
2810 if (control != NULL && cmsgtype == SCM_CREDS)
2811 for (n = control, n_prev = NULL; n != NULL;) {
2812 cm = mtod(n, struct cmsghdr *);
2813 if (cm->cmsg_level == SOL_SOCKET &&
2814 cm->cmsg_type == SCM_CREDS) {
2816 control = n->m_next;
2818 n_prev->m_next = n->m_next;
2819 if (space != NULL) {
2820 MPASS(*space >= n->m_len);
2822 MPASS(*mbcnt >= MSIZE);
2824 if (n->m_flags & M_EXT) {
2827 *mbcnt -= n->m_ext.ext_size;
2831 MPASS(n->m_next == NULL);
2845 /* Prepend it to the head. */
2846 m->m_next = control;
2847 if (space != NULL) {
2850 if (control == NULL)
2856 static struct unpcb *
2857 fptounp(struct file *fp)
2861 if (fp->f_type != DTYPE_SOCKET)
2863 if ((so = fp->f_data) == NULL)
2865 if (so->so_proto->pr_domain != &localdomain)
2867 return sotounpcb(so);
2871 unp_discard(struct file *fp)
2873 struct unp_defer *dr;
2875 if (unp_externalize_fp(fp)) {
2876 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2878 UNP_DEFERRED_LOCK();
2879 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2880 UNP_DEFERRED_UNLOCK();
2881 atomic_add_int(&unp_defers_count, 1);
2882 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2884 closef_nothread(fp);
2888 unp_process_defers(void *arg __unused, int pending)
2890 struct unp_defer *dr;
2891 SLIST_HEAD(, unp_defer) drl;
2896 UNP_DEFERRED_LOCK();
2897 if (SLIST_FIRST(&unp_defers) == NULL) {
2898 UNP_DEFERRED_UNLOCK();
2901 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2902 UNP_DEFERRED_UNLOCK();
2904 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2905 SLIST_REMOVE_HEAD(&drl, ud_link);
2906 closef_nothread(dr->ud_fp);
2910 atomic_add_int(&unp_defers_count, -count);
2915 unp_internalize_fp(struct file *fp)
2920 if ((unp = fptounp(fp)) != NULL) {
2922 unp->unp_msgcount++;
2929 unp_externalize_fp(struct file *fp)
2935 if ((unp = fptounp(fp)) != NULL) {
2936 unp->unp_msgcount--;
2946 * unp_defer indicates whether additional work has been defered for a future
2947 * pass through unp_gc(). It is thread local and does not require explicit
2950 static int unp_marked;
2953 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2960 * This function can only be called from the gc task.
2962 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2963 ("%s: not on gc callout", __func__));
2964 UNP_LINK_LOCK_ASSERT();
2966 for (i = 0; i < fdcount; i++) {
2967 fp = fdep[i]->fde_file;
2968 if ((unp = fptounp(fp)) == NULL)
2970 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2977 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2984 * This function can only be called from the gc task.
2986 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2987 ("%s: not on gc callout", __func__));
2988 UNP_LINK_LOCK_ASSERT();
2990 for (i = 0; i < fdcount; i++) {
2991 fp = fdep[i]->fde_file;
2992 if ((unp = fptounp(fp)) == NULL)
2994 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
3002 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
3006 SOCK_LOCK_ASSERT(so);
3008 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
3011 SOCK_RECVBUF_LOCK(so);
3012 switch (so->so_type) {
3014 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
3015 unp_scan(so->so_rcv.uxdg_peeked, op);
3016 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
3017 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
3020 case SOCK_SEQPACKET:
3021 unp_scan(so->so_rcv.sb_mb, op);
3024 SOCK_RECVBUF_UNLOCK(so);
3028 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
3030 struct socket *so, *soa;
3032 so = unp->unp_socket;
3034 if (SOLISTENING(so)) {
3036 * Mark all sockets in our accept queue.
3038 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
3039 unp_scan_socket(soa, op);
3042 * Mark all sockets we reference with RIGHTS.
3044 unp_scan_socket(so, op);
3049 static int unp_recycled;
3050 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
3051 "Number of unreachable sockets claimed by the garbage collector.");
3053 static int unp_taskcount;
3054 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
3055 "Number of times the garbage collector has run.");
3057 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
3058 "Number of active local sockets.");
3061 unp_gc(__unused void *arg, int pending)
3063 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
3065 struct unp_head **head;
3066 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
3067 struct file *f, **unref;
3068 struct unpcb *unp, *unptmp;
3069 int i, total, unp_unreachable;
3071 LIST_INIT(&unp_deadhead);
3075 * First determine which sockets may be in cycles.
3077 unp_unreachable = 0;
3079 for (head = heads; *head != NULL; head++)
3080 LIST_FOREACH(unp, *head, unp_link) {
3081 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
3082 ("%s: unp %p has unexpected gc flags 0x%x",
3083 __func__, unp, (unsigned int)unp->unp_gcflag));
3088 * Check for an unreachable socket potentially in a
3089 * cycle. It must be in a queue as indicated by
3090 * msgcount, and this must equal the file reference
3091 * count. Note that when msgcount is 0 the file is
3094 if (f != NULL && unp->unp_msgcount != 0 &&
3095 refcount_load(&f->f_count) == unp->unp_msgcount) {
3096 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
3097 unp->unp_gcflag |= UNPGC_DEAD;
3098 unp->unp_gcrefs = unp->unp_msgcount;
3104 * Scan all sockets previously marked as potentially being in a cycle
3105 * and remove the references each socket holds on any UNPGC_DEAD
3106 * sockets in its queue. After this step, all remaining references on
3107 * sockets marked UNPGC_DEAD should not be part of any cycle.
3109 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3110 unp_gc_scan(unp, unp_remove_dead_ref);
3113 * If a socket still has a non-negative refcount, it cannot be in a
3114 * cycle. In this case increment refcount of all children iteratively.
3115 * Stop the scan once we do a complete loop without discovering
3116 * a new reachable socket.
3120 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3121 if (unp->unp_gcrefs > 0) {
3122 unp->unp_gcflag &= ~UNPGC_DEAD;
3123 LIST_REMOVE(unp, unp_dead);
3124 KASSERT(unp_unreachable > 0,
3125 ("%s: unp_unreachable underflow.",
3128 unp_gc_scan(unp, unp_restore_undead_ref);
3130 } while (unp_marked);
3134 if (unp_unreachable == 0)
3138 * Allocate space for a local array of dead unpcbs.
3139 * TODO: can this path be simplified by instead using the local
3140 * dead list at unp_deadhead, after taking out references
3141 * on the file object and/or unpcb and dropping the link lock?
3143 unref = malloc(unp_unreachable * sizeof(struct file *),
3147 * Iterate looking for sockets which have been specifically marked
3148 * as unreachable and store them locally.
3152 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3153 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3154 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3155 unp->unp_gcflag &= ~UNPGC_DEAD;
3157 if (unp->unp_msgcount == 0 || f == NULL ||
3158 refcount_load(&f->f_count) != unp->unp_msgcount ||
3162 KASSERT(total <= unp_unreachable,
3163 ("%s: incorrect unreachable count.", __func__));
3168 * Now flush all sockets, free'ing rights. This will free the
3169 * struct files associated with these sockets but leave each socket
3170 * with one remaining ref.
3172 for (i = 0; i < total; i++) {
3175 so = unref[i]->f_data;
3176 CURVNET_SET(so->so_vnet);
3182 * And finally release the sockets so they can be reclaimed.
3184 for (i = 0; i < total; i++)
3185 fdrop(unref[i], NULL);
3186 unp_recycled += total;
3187 free(unref, M_TEMP);
3191 * Synchronize against unp_gc, which can trip over data as we are freeing it.
3194 unp_dispose(struct socket *so)
3200 MPASS(!SOLISTENING(so));
3202 unp = sotounpcb(so);
3204 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3208 * Grab our special mbufs before calling sbrelease().
3210 SOCK_RECVBUF_LOCK(so);
3211 switch (so->so_type) {
3213 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
3214 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
3215 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
3216 /* Note: socket of sb may reconnect. */
3217 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
3220 if (sb->uxdg_peeked != NULL) {
3221 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
3223 sb->uxdg_peeked = NULL;
3225 m = STAILQ_FIRST(&sb->uxdg_mb);
3226 STAILQ_INIT(&sb->uxdg_mb);
3227 /* XXX: our shortened sbrelease() */
3228 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3231 * XXXGL Mark sb with SBS_CANTRCVMORE. This is needed to
3232 * prevent uipc_sosend_dgram() or unp_disconnect() adding more
3233 * data to the socket.
3234 * We are now in dom_dispose and it could be a call from
3235 * soshutdown() or from the final sofree(). The sofree() case
3236 * is simple as it guarantees that no more sends will happen,
3237 * however we can race with unp_disconnect() from our peer.
3238 * The shutdown(2) case is more exotic. It would call into
3239 * dom_dispose() only if socket is SS_ISCONNECTED. This is
3240 * possible if we did connect(2) on this socket and we also
3241 * had it bound with bind(2) and receive connections from other
3242 * sockets. Because soshutdown() violates POSIX (see comment
3243 * there) we will end up here shutting down our receive side.
3244 * Of course this will have affect not only on the peer we
3245 * connect(2)ed to, but also on all of the peers who had
3246 * connect(2)ed to us. Their sends would end up with ENOBUFS.
3248 sb->sb_state |= SBS_CANTRCVMORE;
3251 case SOCK_SEQPACKET:
3253 m = sbcut_locked(sb, sb->sb_ccc);
3254 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3255 ("%s: ccc %u mb %p mbcnt %u", __func__,
3256 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3257 sbrelease_locked(so, SO_RCV);
3260 SOCK_RECVBUF_UNLOCK(so);
3261 if (SOCK_IO_RECV_OWNED(so))
3262 SOCK_IO_RECV_UNLOCK(so);
3265 unp_scan(m, unp_freerights);
3271 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3276 socklen_t clen, datalen;
3278 while (m0 != NULL) {
3279 for (m = m0; m; m = m->m_next) {
3280 if (m->m_type != MT_CONTROL)
3283 cm = mtod(m, struct cmsghdr *);
3286 while (cm != NULL) {
3287 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3290 data = CMSG_DATA(cm);
3291 datalen = (caddr_t)cm + cm->cmsg_len
3294 if (cm->cmsg_level == SOL_SOCKET &&
3295 cm->cmsg_type == SCM_RIGHTS) {
3296 (*op)(data, datalen /
3297 sizeof(struct filedescent *));
3300 if (CMSG_SPACE(datalen) < clen) {
3301 clen -= CMSG_SPACE(datalen);
3302 cm = (struct cmsghdr *)
3303 ((caddr_t)cm + CMSG_SPACE(datalen));
3315 * Definitions of protocols supported in the LOCAL domain.
3317 static struct protosw streamproto = {
3318 .pr_type = SOCK_STREAM,
3319 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
3321 .pr_ctloutput = &uipc_ctloutput,
3322 .pr_abort = uipc_abort,
3323 .pr_accept = uipc_accept,
3324 .pr_attach = uipc_attach,
3325 .pr_bind = uipc_bind,
3326 .pr_bindat = uipc_bindat,
3327 .pr_connect = uipc_connect,
3328 .pr_connectat = uipc_connectat,
3329 .pr_connect2 = uipc_connect2,
3330 .pr_detach = uipc_detach,
3331 .pr_disconnect = uipc_disconnect,
3332 .pr_listen = uipc_listen,
3333 .pr_peeraddr = uipc_peeraddr,
3334 .pr_rcvd = uipc_rcvd,
3335 .pr_send = uipc_send,
3336 .pr_ready = uipc_ready,
3337 .pr_sense = uipc_sense,
3338 .pr_shutdown = uipc_shutdown,
3339 .pr_sockaddr = uipc_sockaddr,
3340 .pr_soreceive = soreceive_generic,
3341 .pr_close = uipc_close,
3344 static struct protosw dgramproto = {
3345 .pr_type = SOCK_DGRAM,
3346 .pr_flags = PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
3348 .pr_ctloutput = &uipc_ctloutput,
3349 .pr_abort = uipc_abort,
3350 .pr_accept = uipc_accept,
3351 .pr_attach = uipc_attach,
3352 .pr_bind = uipc_bind,
3353 .pr_bindat = uipc_bindat,
3354 .pr_connect = uipc_connect,
3355 .pr_connectat = uipc_connectat,
3356 .pr_connect2 = uipc_connect2,
3357 .pr_detach = uipc_detach,
3358 .pr_disconnect = uipc_disconnect,
3359 .pr_peeraddr = uipc_peeraddr,
3360 .pr_sosend = uipc_sosend_dgram,
3361 .pr_sense = uipc_sense,
3362 .pr_shutdown = uipc_shutdown,
3363 .pr_sockaddr = uipc_sockaddr,
3364 .pr_soreceive = uipc_soreceive_dgram,
3365 .pr_close = uipc_close,
3368 static struct protosw seqpacketproto = {
3369 .pr_type = SOCK_SEQPACKET,
3371 * XXXRW: For now, PR_ADDR because soreceive will bump into them
3372 * due to our use of sbappendaddr. A new sbappend variants is needed
3373 * that supports both atomic record writes and control data.
3375 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
3376 PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
3377 .pr_ctloutput = &uipc_ctloutput,
3378 .pr_abort = uipc_abort,
3379 .pr_accept = uipc_accept,
3380 .pr_attach = uipc_attach,
3381 .pr_bind = uipc_bind,
3382 .pr_bindat = uipc_bindat,
3383 .pr_connect = uipc_connect,
3384 .pr_connectat = uipc_connectat,
3385 .pr_connect2 = uipc_connect2,
3386 .pr_detach = uipc_detach,
3387 .pr_disconnect = uipc_disconnect,
3388 .pr_listen = uipc_listen,
3389 .pr_peeraddr = uipc_peeraddr,
3390 .pr_rcvd = uipc_rcvd,
3391 .pr_send = uipc_send,
3392 .pr_sense = uipc_sense,
3393 .pr_shutdown = uipc_shutdown,
3394 .pr_sockaddr = uipc_sockaddr,
3395 .pr_soreceive = soreceive_generic, /* XXX: or...? */
3396 .pr_close = uipc_close,
3399 static struct domain localdomain = {
3400 .dom_family = AF_LOCAL,
3401 .dom_name = "local",
3402 .dom_externalize = unp_externalize,
3403 .dom_dispose = unp_dispose,
3414 * A helper function called by VFS before socket-type vnode reclamation.
3415 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3419 vfs_unp_reclaim(struct vnode *vp)
3425 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3426 KASSERT(vp->v_type == VSOCK,
3427 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3430 vplock = mtx_pool_find(mtxpool_sleep, vp);
3432 VOP_UNP_CONNECT(vp, &unp);
3436 if (unp->unp_vnode == vp) {
3438 unp->unp_vnode = NULL;
3441 UNP_PCB_UNLOCK(unp);
3450 db_print_indent(int indent)
3454 for (i = 0; i < indent; i++)
3459 db_print_unpflags(int unp_flags)
3464 if (unp_flags & UNP_HAVEPC) {
3465 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3468 if (unp_flags & UNP_WANTCRED_ALWAYS) {
3469 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3472 if (unp_flags & UNP_WANTCRED_ONESHOT) {
3473 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3476 if (unp_flags & UNP_CONNWAIT) {
3477 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3480 if (unp_flags & UNP_CONNECTING) {
3481 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3484 if (unp_flags & UNP_BINDING) {
3485 db_printf("%sUNP_BINDING", comma ? ", " : "");
3491 db_print_xucred(int indent, struct xucred *xu)
3495 db_print_indent(indent);
3496 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
3497 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3498 db_print_indent(indent);
3499 db_printf("cr_groups: ");
3501 for (i = 0; i < xu->cr_ngroups; i++) {
3502 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3509 db_print_unprefs(int indent, struct unp_head *uh)
3515 LIST_FOREACH(unp, uh, unp_reflink) {
3516 if (counter % 4 == 0)
3517 db_print_indent(indent);
3518 db_printf("%p ", unp);
3519 if (counter % 4 == 3)
3523 if (counter != 0 && counter % 4 != 0)
3527 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3532 db_printf("usage: show unpcb <addr>\n");
3535 unp = (struct unpcb *)addr;
3537 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
3540 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3543 db_printf("unp_refs:\n");
3544 db_print_unprefs(2, &unp->unp_refs);
3546 /* XXXRW: Would be nice to print the full address, if any. */
3547 db_printf("unp_addr: %p\n", unp->unp_addr);
3549 db_printf("unp_gencnt: %llu\n",
3550 (unsigned long long)unp->unp_gencnt);
3552 db_printf("unp_flags: %x (", unp->unp_flags);
3553 db_print_unpflags(unp->unp_flags);
3556 db_printf("unp_peercred:\n");
3557 db_print_xucred(2, &unp->unp_peercred);
3559 db_printf("unp_refcount: %u\n", unp->unp_refcount);