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 = {
124 .sa_len = sizeof(sun_noname),
125 .sa_family = AF_LOCAL,
129 * Garbage collection of cyclic file descriptor/socket references occurs
130 * asynchronously in a taskqueue context in order to avoid recursion and
131 * reentrance in the UNIX domain socket, file descriptor, and socket layer
132 * code. See unp_gc() for a full description.
134 static struct timeout_task unp_gc_task;
137 * The close of unix domain sockets attached as SCM_RIGHTS is
138 * postponed to the taskqueue, to avoid arbitrary recursion depth.
139 * The attached sockets might have another sockets attached.
141 static struct task unp_defer_task;
144 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
145 * stream sockets, although the total for sender and receiver is actually
148 * Datagram sockets really use the sendspace as the maximum datagram size,
149 * and don't really want to reserve the sendspace. Their recvspace should be
150 * large enough for at least one max-size datagram plus address.
155 static u_long unpst_sendspace = PIPSIZ;
156 static u_long unpst_recvspace = PIPSIZ;
157 static u_long unpdg_maxdgram = 8*1024; /* support 8KB syslog msgs */
158 static u_long unpdg_recvspace = 16*1024;
159 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
160 static u_long unpsp_recvspace = PIPSIZ;
162 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
164 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
165 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
168 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
171 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
174 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
175 &unpst_sendspace, 0, "Default stream send space.");
176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
177 &unpst_recvspace, 0, "Default stream receive space.");
178 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
179 &unpdg_maxdgram, 0, "Maximum datagram size.");
180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
181 &unpdg_recvspace, 0, "Default datagram receive space.");
182 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
183 &unpsp_sendspace, 0, "Default seqpacket send space.");
184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
185 &unpsp_recvspace, 0, "Default seqpacket receive space.");
186 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
187 "File descriptors in flight.");
188 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
189 &unp_defers_count, 0,
190 "File descriptors deferred to taskqueue for close.");
193 * Locking and synchronization:
195 * Several types of locks exist in the local domain socket implementation:
196 * - a global linkage lock
197 * - a global connection list lock
199 * - per-unpcb mutexes
201 * The linkage lock protects the global socket lists, the generation number
202 * counter and garbage collector state.
204 * The connection list lock protects the list of referring sockets in a datagram
205 * socket PCB. This lock is also overloaded to protect a global list of
206 * sockets whose buffers contain socket references in the form of SCM_RIGHTS
207 * messages. To avoid recursion, such references are released by a dedicated
210 * The mtxpool lock protects the vnode from being modified while referenced.
211 * Lock ordering rules require that it be acquired before any PCB locks.
213 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
214 * unpcb. This includes the unp_conn field, which either links two connected
215 * PCBs together (for connected socket types) or points at the destination
216 * socket (for connectionless socket types). The operations of creating or
217 * destroying a connection therefore involve locking multiple PCBs. To avoid
218 * lock order reversals, in some cases this involves dropping a PCB lock and
219 * using a reference counter to maintain liveness.
221 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
222 * allocated in pr_attach() and freed in pr_detach(). The validity of that
223 * pointer is an invariant, so no lock is required to dereference the so_pcb
224 * pointer if a valid socket reference is held by the caller. In practice,
225 * this is always true during operations performed on a socket. Each unpcb
226 * has a back-pointer to its socket, unp_socket, which will be stable under
227 * the same circumstances.
229 * This pointer may only be safely dereferenced as long as a valid reference
230 * to the unpcb is held. Typically, this reference will be from the socket,
231 * or from another unpcb when the referring unpcb's lock is held (in order
232 * that the reference not be invalidated during use). For example, to follow
233 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
234 * that detach is not run clearing unp_socket.
236 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
237 * protocols, bind() is a non-atomic operation, and connect() requires
238 * potential sleeping in the protocol, due to potentially waiting on local or
239 * distributed file systems. We try to separate "lookup" operations, which
240 * may sleep, and the IPC operations themselves, which typically can occur
241 * with relative atomicity as locks can be held over the entire operation.
243 * Another tricky issue is simultaneous multi-threaded or multi-process
244 * access to a single UNIX domain socket. These are handled by the flags
245 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
246 * binding, both of which involve dropping UNIX domain socket locks in order
247 * to perform namei() and other file system operations.
249 static struct rwlock unp_link_rwlock;
250 static struct mtx unp_defers_lock;
252 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
255 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
257 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
260 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
261 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
262 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
263 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
264 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
266 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
268 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
269 "unp_defer", NULL, MTX_DEF)
270 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
271 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
273 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
274 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
276 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
279 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
280 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx)
281 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
282 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
283 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
284 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
285 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
286 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
288 static int uipc_connect2(struct socket *, struct socket *);
289 static int uipc_ctloutput(struct socket *, struct sockopt *);
290 static int unp_connect(struct socket *, struct sockaddr *,
292 static int unp_connectat(int, struct socket *, struct sockaddr *,
293 struct thread *, bool);
294 typedef enum { PRU_CONNECT, PRU_CONNECT2 } conn2_how;
295 static void unp_connect2(struct socket *so, struct socket *so2, conn2_how);
296 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
297 static void unp_dispose(struct socket *so);
298 static void unp_shutdown(struct unpcb *);
299 static void unp_drop(struct unpcb *);
300 static void unp_gc(__unused void *, int);
301 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
302 static void unp_discard(struct file *);
303 static void unp_freerights(struct filedescent **, int);
304 static int unp_internalize(struct mbuf **, struct thread *,
305 struct mbuf **, u_int *, u_int *);
306 static void unp_internalize_fp(struct file *);
307 static int unp_externalize(struct mbuf *, struct mbuf **, int);
308 static int unp_externalize_fp(struct file *);
309 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *,
310 int, struct mbuf **, u_int *, u_int *);
311 static void unp_process_defers(void * __unused, int);
314 unp_pcb_hold(struct unpcb *unp)
318 old = refcount_acquire(&unp->unp_refcount);
319 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
322 static __result_use_check bool
323 unp_pcb_rele(struct unpcb *unp)
327 UNP_PCB_LOCK_ASSERT(unp);
329 if ((ret = refcount_release(&unp->unp_refcount))) {
331 UNP_PCB_LOCK_DESTROY(unp);
332 uma_zfree(unp_zone, unp);
338 unp_pcb_rele_notlast(struct unpcb *unp)
342 ret = refcount_release(&unp->unp_refcount);
343 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
347 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
349 UNP_PCB_UNLOCK_ASSERT(unp);
350 UNP_PCB_UNLOCK_ASSERT(unp2);
354 } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
364 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
368 UNP_PCB_UNLOCK(unp2);
372 * Try to lock the connected peer of an already locked socket. In some cases
373 * this requires that we unlock the current socket. The pairbusy counter is
374 * used to block concurrent connection attempts while the lock is dropped. The
375 * caller must be careful to revalidate PCB state.
377 static struct unpcb *
378 unp_pcb_lock_peer(struct unpcb *unp)
382 UNP_PCB_LOCK_ASSERT(unp);
383 unp2 = unp->unp_conn;
386 if (__predict_false(unp == unp2))
389 UNP_PCB_UNLOCK_ASSERT(unp2);
391 if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
393 if ((uintptr_t)unp2 > (uintptr_t)unp) {
403 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
404 ("%s: socket %p was reconnected", __func__, unp));
405 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
406 unp->unp_flags &= ~UNP_WAITING;
409 if (unp_pcb_rele(unp2)) {
410 /* unp2 is unlocked. */
413 if (unp->unp_conn == NULL) {
414 UNP_PCB_UNLOCK(unp2);
421 uipc_abort(struct socket *so)
423 struct unpcb *unp, *unp2;
426 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
427 UNP_PCB_UNLOCK_ASSERT(unp);
430 unp2 = unp->unp_conn;
440 uipc_attach(struct socket *so, int proto, struct thread *td)
442 u_long sendspace, recvspace;
447 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
448 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
449 switch (so->so_type) {
451 sendspace = unpst_sendspace;
452 recvspace = unpst_recvspace;
456 STAILQ_INIT(&so->so_rcv.uxdg_mb);
457 STAILQ_INIT(&so->so_snd.uxdg_mb);
458 TAILQ_INIT(&so->so_rcv.uxdg_conns);
460 * Since send buffer is either bypassed or is a part
461 * of one-to-many receive buffer, we assign both space
462 * limits to unpdg_recvspace.
464 sendspace = recvspace = unpdg_recvspace;
468 sendspace = unpsp_sendspace;
469 recvspace = unpsp_recvspace;
473 panic("uipc_attach");
475 error = soreserve(so, sendspace, recvspace);
479 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
482 LIST_INIT(&unp->unp_refs);
483 UNP_PCB_LOCK_INIT(unp);
484 unp->unp_socket = so;
486 refcount_init(&unp->unp_refcount, 1);
488 if ((locked = UNP_LINK_WOWNED()) == false)
491 unp->unp_gencnt = ++unp_gencnt;
492 unp->unp_ino = ++unp_ino;
494 switch (so->so_type) {
496 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
500 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
504 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
508 panic("uipc_attach");
518 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
520 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
530 if (nam->sa_family != AF_UNIX)
531 return (EAFNOSUPPORT);
534 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
536 if (soun->sun_len > sizeof(struct sockaddr_un))
538 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
543 * We don't allow simultaneous bind() calls on a single UNIX domain
544 * socket, so flag in-progress operations, and return an error if an
545 * operation is already in progress.
547 * Historically, we have not allowed a socket to be rebound, so this
548 * also returns an error. Not allowing re-binding simplifies the
549 * implementation and avoids a great many possible failure modes.
552 if (unp->unp_vnode != NULL) {
556 if (unp->unp_flags & UNP_BINDING) {
560 unp->unp_flags |= UNP_BINDING;
563 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
564 bcopy(soun->sun_path, buf, namelen);
568 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | NOCACHE,
569 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
570 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
575 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
586 error = vn_start_write(NULL, &mp, V_XSLEEP | V_PCATCH);
592 vattr.va_type = VSOCK;
593 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
595 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
599 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
602 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
603 vn_finished_write(mp);
604 if (error == ERELOOKUP)
609 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
610 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
613 VOP_UNP_BIND(vp, unp);
615 unp->unp_addr = soun;
616 unp->unp_flags &= ~UNP_BINDING;
619 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
620 vn_finished_write(mp);
626 unp->unp_flags &= ~UNP_BINDING;
633 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
636 return (uipc_bindat(AT_FDCWD, so, nam, td));
640 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
644 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
645 error = unp_connect(so, nam, td);
650 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
655 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
656 error = unp_connectat(fd, so, nam, td, false);
661 uipc_close(struct socket *so)
663 struct unpcb *unp, *unp2;
664 struct vnode *vp = NULL;
668 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
671 if ((vp = unp->unp_vnode) != NULL) {
672 vplock = mtx_pool_find(mtxpool_sleep, vp);
676 if (vp && unp->unp_vnode == NULL) {
682 unp->unp_vnode = NULL;
684 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
685 unp_disconnect(unp, unp2);
695 uipc_connect2(struct socket *so1, struct socket *so2)
697 struct unpcb *unp, *unp2;
699 if (so1->so_type != so2->so_type)
703 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
705 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
706 unp_pcb_lock_pair(unp, unp2);
707 unp_connect2(so1, so2, PRU_CONNECT2);
708 unp_pcb_unlock_pair(unp, unp2);
714 uipc_detach(struct socket *so)
716 struct unpcb *unp, *unp2;
719 int local_unp_rights;
722 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
728 LIST_REMOVE(unp, unp_link);
729 if (unp->unp_gcflag & UNPGC_DEAD)
730 LIST_REMOVE(unp, unp_dead);
731 unp->unp_gencnt = ++unp_gencnt;
735 UNP_PCB_UNLOCK_ASSERT(unp);
737 if ((vp = unp->unp_vnode) != NULL) {
738 vplock = mtx_pool_find(mtxpool_sleep, vp);
742 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
748 if ((vp = unp->unp_vnode) != NULL) {
750 unp->unp_vnode = NULL;
752 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
753 unp_disconnect(unp, unp2);
758 while (!LIST_EMPTY(&unp->unp_refs)) {
759 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
762 UNP_REF_LIST_UNLOCK();
765 UNP_PCB_UNLOCK_ASSERT(ref);
769 UNP_REF_LIST_UNLOCK();
772 local_unp_rights = unp_rights;
773 unp->unp_socket->so_pcb = NULL;
774 unp->unp_socket = NULL;
775 free(unp->unp_addr, M_SONAME);
776 unp->unp_addr = NULL;
777 if (!unp_pcb_rele(unp))
783 if (local_unp_rights)
784 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
786 switch (so->so_type) {
789 * Everything should have been unlinked/freed by unp_dispose()
790 * and/or unp_disconnect().
792 MPASS(so->so_rcv.uxdg_peeked == NULL);
793 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
794 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
795 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
800 uipc_disconnect(struct socket *so)
802 struct unpcb *unp, *unp2;
805 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
808 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
809 unp_disconnect(unp, unp2);
816 uipc_listen(struct socket *so, int backlog, struct thread *td)
821 MPASS(so->so_type != SOCK_DGRAM);
824 * Synchronize with concurrent connection attempts.
829 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
831 else if (unp->unp_vnode == NULL)
832 error = EDESTADDRREQ;
839 error = solisten_proto_check(so);
841 cru2xt(td, &unp->unp_peercred);
842 solisten_proto(so, backlog);
850 uipc_peeraddr(struct socket *so, struct sockaddr *ret)
852 struct unpcb *unp, *unp2;
853 const struct sockaddr *sa;
856 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
859 unp2 = unp_pcb_lock_peer(unp);
861 if (unp2->unp_addr != NULL)
862 sa = (struct sockaddr *)unp2->unp_addr;
865 bcopy(sa, ret, sa->sa_len);
866 unp_pcb_unlock_pair(unp, unp2);
870 bcopy(sa, ret, sa->sa_len);
876 uipc_rcvd(struct socket *so, int flags)
878 struct unpcb *unp, *unp2;
883 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
884 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
885 ("%s: socktype %d", __func__, so->so_type));
888 * Adjust backpressure on sender and wakeup any waiting to write.
890 * The unp lock is acquired to maintain the validity of the unp_conn
891 * pointer; no lock on unp2 is required as unp2->unp_socket will be
892 * static as long as we don't permit unp2 to disconnect from unp,
893 * which is prevented by the lock on unp. We cache values from
894 * so_rcv to avoid holding the so_rcv lock over the entire
895 * transaction on the remote so_snd.
897 SOCKBUF_LOCK(&so->so_rcv);
898 mbcnt = so->so_rcv.sb_mbcnt;
899 sbcc = sbavail(&so->so_rcv);
900 SOCKBUF_UNLOCK(&so->so_rcv);
902 * There is a benign race condition at this point. If we're planning to
903 * clear SB_STOP, but uipc_send is called on the connected socket at
904 * this instant, it might add data to the sockbuf and set SB_STOP. Then
905 * we would erroneously clear SB_STOP below, even though the sockbuf is
906 * full. The race is benign because the only ill effect is to allow the
907 * sockbuf to exceed its size limit, and the size limits are not
908 * strictly guaranteed anyway.
911 unp2 = unp->unp_conn;
916 so2 = unp2->unp_socket;
917 SOCKBUF_LOCK(&so2->so_snd);
918 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
919 so2->so_snd.sb_flags &= ~SB_STOP;
920 sowwakeup_locked(so2);
926 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
927 struct mbuf *control, struct thread *td)
929 struct unpcb *unp, *unp2;
935 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
936 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
937 ("%s: socktype %d", __func__, so->so_type));
940 if (flags & PRUS_OOB) {
944 if (control != NULL &&
945 (error = unp_internalize(&control, td, NULL, NULL, NULL)))
949 if ((so->so_state & SS_ISCONNECTED) == 0) {
951 if ((error = unp_connect(so, nam, td)) != 0)
960 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
964 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
965 unp_pcb_unlock_pair(unp, unp2);
970 if ((so2 = unp2->unp_socket) == NULL) {
971 UNP_PCB_UNLOCK(unp2);
975 SOCKBUF_LOCK(&so2->so_rcv);
976 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
978 * Credentials are passed only once on SOCK_STREAM and
979 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
980 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
982 control = unp_addsockcred(td, control, unp2->unp_flags, NULL,
984 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
988 * Send to paired receive port and wake up readers. Don't
989 * check for space available in the receive buffer if we're
990 * attaching ancillary data; Unix domain sockets only check
991 * for space in the sending sockbuf, and that check is
992 * performed one level up the stack. At that level we cannot
993 * precisely account for the amount of buffer space used
994 * (e.g., because control messages are not yet internalized).
996 switch (so->so_type) {
998 if (control != NULL) {
999 sbappendcontrol_locked(&so2->so_rcv, m,
1003 sbappend_locked(&so2->so_rcv, m, flags);
1006 case SOCK_SEQPACKET:
1007 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1008 &sun_noname, m, control))
1013 mbcnt = so2->so_rcv.sb_mbcnt;
1014 sbcc = sbavail(&so2->so_rcv);
1016 sorwakeup_locked(so2);
1018 SOCKBUF_UNLOCK(&so2->so_rcv);
1021 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1022 * it would be possible for uipc_rcvd to be called at this
1023 * point, drain the receiving sockbuf, clear SB_STOP, and then
1024 * we would set SB_STOP below. That could lead to an empty
1025 * sockbuf having SB_STOP set
1027 SOCKBUF_LOCK(&so->so_snd);
1028 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1029 so->so_snd.sb_flags |= SB_STOP;
1030 SOCKBUF_UNLOCK(&so->so_snd);
1031 UNP_PCB_UNLOCK(unp2);
1035 * PRUS_EOF is equivalent to pr_send followed by pr_shutdown.
1037 if (flags & PRUS_EOF) {
1041 UNP_PCB_UNLOCK(unp);
1043 if (control != NULL && error != 0)
1044 unp_scan(control, unp_freerights);
1047 if (control != NULL)
1050 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1051 * for freeing memory.
1053 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1058 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1060 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1065 * Negative space may happen if send(2) is followed by
1066 * setsockopt(SO_SNDBUF/SO_RCVBUF) that shrinks maximum.
1068 if (__predict_false(sb->sb_hiwat < sb->uxdg_cc ||
1069 sb->sb_mbmax < sb->uxdg_mbcnt))
1072 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1075 bleft = sb->sb_hiwat - sb->uxdg_cc;
1076 mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1078 return (bleft >= cc && mleft >= mbcnt);
1082 * PF_UNIX/SOCK_DGRAM send
1084 * Allocate a record consisting of 3 mbufs in the sequence of
1085 * from -> control -> data and append it to the socket buffer.
1087 * The first mbuf carries sender's name and is a pkthdr that stores
1088 * overall length of datagram, its memory consumption and control length.
1090 #define ctllen PH_loc.thirtytwo[1]
1091 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1092 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1094 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1095 struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1097 struct unpcb *unp, *unp2;
1098 const struct sockaddr *from;
1101 struct mbuf *f, *clast;
1102 u_int cc, ctl, mbcnt;
1103 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1106 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1112 if (__predict_false(flags & MSG_OOB)) {
1117 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1121 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1122 if (__predict_false(m == NULL)) {
1126 f = m_gethdr(M_WAITOK, MT_SONAME);
1127 cc = m->m_pkthdr.len;
1128 mbcnt = MSIZE + m->m_pkthdr.memlen;
1130 (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt)))
1133 /* pr_sosend() with mbuf usually is a kernel thread. */
1136 if (__predict_false(c != NULL))
1137 panic("%s: control from a kernel thread", __func__);
1139 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1143 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1147 /* Condition the foreign mbuf to our standards. */
1149 m_tag_delete_chain(m, NULL);
1150 m->m_pkthdr.rcvif = NULL;
1151 m->m_pkthdr.flowid = 0;
1152 m->m_pkthdr.csum_flags = 0;
1153 m->m_pkthdr.fibnum = 0;
1154 m->m_pkthdr.rsstype = 0;
1156 cc = m->m_pkthdr.len;
1158 for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) {
1160 if (mb->m_flags & M_EXT)
1161 mbcnt += mb->m_ext.ext_size;
1165 unp = sotounpcb(so);
1169 * XXXGL: would be cool to fully remove so_snd out of the equation
1170 * and avoid this lock, which is not only extraneous, but also being
1171 * released, thus still leaving possibility for a race. We can easily
1172 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1173 * is more difficult to invent something to handle so_error.
1175 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1178 SOCK_SENDBUF_LOCK(so);
1179 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1180 SOCK_SENDBUF_UNLOCK(so);
1184 if (so->so_error != 0) {
1185 error = so->so_error;
1187 SOCK_SENDBUF_UNLOCK(so);
1190 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1191 SOCK_SENDBUF_UNLOCK(so);
1192 error = EDESTADDRREQ;
1195 SOCK_SENDBUF_UNLOCK(so);
1198 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1200 UNP_PCB_LOCK_ASSERT(unp);
1201 unp2 = unp->unp_conn;
1202 UNP_PCB_LOCK_ASSERT(unp2);
1205 unp2 = unp_pcb_lock_peer(unp);
1207 UNP_PCB_UNLOCK(unp);
1213 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1214 c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl,
1216 if (unp->unp_addr != NULL)
1217 from = (struct sockaddr *)unp->unp_addr;
1220 f->m_len = from->sa_len;
1221 MPASS(from->sa_len <= MLEN);
1222 bcopy(from, mtod(f, void *), from->sa_len);
1226 * Concatenate mbufs: from -> control -> data.
1227 * Save overall cc and mbcnt in "from" mbuf.
1233 for (mc = c; mc->m_next != NULL; mc = mc->m_next);
1243 dcc = dctl = dmbcnt = 0;
1244 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
1245 if (mb->m_type == MT_DATA)
1250 if (mb->m_flags & M_EXT)
1251 dmbcnt += mb->m_ext.ext_size;
1255 MPASS(dmbcnt == mbcnt);
1257 f->m_pkthdr.len = cc + ctl;
1258 f->m_pkthdr.memlen = mbcnt;
1259 f->m_pkthdr.ctllen = ctl;
1262 * Destination socket buffer selection.
1264 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
1265 * destination address is supplied, create a temporary connection for
1266 * the run time of the function (see call to unp_connectat() above and
1267 * to unp_disconnect() below). We distinguish them by condition of
1268 * (addr != NULL). We intentionally avoid adding 'bool connected' for
1269 * that condition, since, again, through the run time of this code we
1270 * are always connected. For such "unconnected" sends, the destination
1271 * buffer would be the receive buffer of destination socket so2.
1273 * For connected sends, data lands on the send buffer of the sender's
1274 * socket "so". Then, if we just added the very first datagram
1275 * on this send buffer, we need to add the send buffer on to the
1276 * receiving socket's buffer list. We put ourselves on top of the
1277 * list. Such logic gives infrequent senders priority over frequent
1280 * Note on byte count management. As long as event methods kevent(2),
1281 * select(2) are not protocol specific (yet), we need to maintain
1282 * meaningful values on the receive buffer. So, the receive buffer
1283 * would accumulate counters from all connected buffers potentially
1284 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
1286 so2 = unp2->unp_socket;
1287 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
1288 SOCK_RECVBUF_LOCK(so2);
1289 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
1290 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
1291 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
1293 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1294 sb->uxdg_cc += cc + ctl;
1295 sb->uxdg_ctl += ctl;
1296 sb->uxdg_mbcnt += mbcnt;
1297 so2->so_rcv.sb_acc += cc + ctl;
1298 so2->so_rcv.sb_ccc += cc + ctl;
1299 so2->so_rcv.sb_ctl += ctl;
1300 so2->so_rcv.sb_mbcnt += mbcnt;
1301 sorwakeup_locked(so2);
1304 soroverflow_locked(so2);
1306 if (f->m_next->m_type == MT_CONTROL) {
1313 unp_disconnect(unp, unp2);
1315 unp_pcb_unlock_pair(unp, unp2);
1317 td->td_ru.ru_msgsnd++;
1320 SOCK_IO_SEND_UNLOCK(so);
1323 unp_scan(c, unp_freerights);
1336 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
1337 * The mbuf has already been unlinked from the uxdg_mb of socket buffer
1338 * and needs to be linked onto uxdg_peeked of receive socket buffer.
1341 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
1342 struct uio *uio, struct mbuf **controlp, int *flagsp)
1347 so->so_rcv.uxdg_peeked = m;
1348 so->so_rcv.uxdg_cc += m->m_pkthdr.len;
1349 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
1350 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
1351 SOCK_RECVBUF_UNLOCK(so);
1353 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1355 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1358 KASSERT(m, ("%s: no data or control after soname", __func__));
1361 * With MSG_PEEK the control isn't executed, just copied.
1363 while (m != NULL && m->m_type == MT_CONTROL) {
1364 if (controlp != NULL) {
1365 *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1366 controlp = &(*controlp)->m_next;
1370 KASSERT(m == NULL || m->m_type == MT_DATA,
1371 ("%s: not MT_DATA mbuf %p", __func__, m));
1372 while (m != NULL && uio->uio_resid > 0) {
1373 len = uio->uio_resid;
1376 error = uiomove(mtod(m, char *), (int)len, uio);
1378 SOCK_IO_RECV_UNLOCK(so);
1381 if (len == m->m_len)
1384 SOCK_IO_RECV_UNLOCK(so);
1386 if (flagsp != NULL) {
1388 if (*flagsp & MSG_TRUNC) {
1389 /* Report real length of the packet */
1390 uio->uio_resid -= m_length(m, NULL) - len;
1392 *flagsp |= MSG_TRUNC;
1394 *flagsp &= ~MSG_TRUNC;
1401 * PF_UNIX/SOCK_DGRAM receive
1404 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1405 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1407 struct sockbuf *sb = NULL;
1417 if (controlp != NULL)
1420 flags = flagsp != NULL ? *flagsp : 0;
1421 nonblock = (so->so_state & SS_NBIO) ||
1422 (flags & (MSG_DONTWAIT | MSG_NBIO));
1424 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1425 if (__predict_false(error))
1429 * Loop blocking while waiting for a datagram. Prioritize connected
1430 * peers over unconnected sends. Set sb to selected socket buffer
1431 * containing an mbuf on exit from the wait loop. A datagram that
1432 * had already been peeked at has top priority.
1434 SOCK_RECVBUF_LOCK(so);
1435 while ((m = so->so_rcv.uxdg_peeked) == NULL &&
1436 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
1437 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1439 error = so->so_error;
1441 SOCK_RECVBUF_UNLOCK(so);
1442 SOCK_IO_RECV_UNLOCK(so);
1445 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1446 uio->uio_resid == 0) {
1447 SOCK_RECVBUF_UNLOCK(so);
1448 SOCK_IO_RECV_UNLOCK(so);
1452 SOCK_RECVBUF_UNLOCK(so);
1453 SOCK_IO_RECV_UNLOCK(so);
1454 return (EWOULDBLOCK);
1456 error = sbwait(so, SO_RCV);
1458 SOCK_RECVBUF_UNLOCK(so);
1459 SOCK_IO_RECV_UNLOCK(so);
1467 m = STAILQ_FIRST(&sb->uxdg_mb);
1469 MPASS(m == so->so_rcv.uxdg_peeked);
1471 MPASS(sb->uxdg_cc > 0);
1473 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1476 uio->uio_td->td_ru.ru_msgrcv++;
1478 if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
1479 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
1480 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
1481 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
1483 so->so_rcv.uxdg_peeked = NULL;
1485 sb->uxdg_cc -= m->m_pkthdr.len;
1486 sb->uxdg_ctl -= m->m_pkthdr.ctllen;
1487 sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
1489 if (__predict_false(flags & MSG_PEEK))
1490 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
1492 so->so_rcv.sb_acc -= m->m_pkthdr.len;
1493 so->so_rcv.sb_ccc -= m->m_pkthdr.len;
1494 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
1495 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
1496 SOCK_RECVBUF_UNLOCK(so);
1499 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1501 KASSERT(m, ("%s: no data or control after soname", __func__));
1504 * Packet to copyout() is now in 'm' and it is disconnected from the
1507 * Process one or more MT_CONTROL mbufs present before any data mbufs
1508 * in the first mbuf chain on the socket buffer. We call into the
1509 * unp_externalize() to perform externalization (or freeing if
1510 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1511 * without MT_DATA mbufs.
1513 while (m != NULL && m->m_type == MT_CONTROL) {
1516 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1517 * it frees whole chain, so we must disconnect the mbuf.
1519 cm = m; m = m->m_next; cm->m_next = NULL;
1520 error = unp_externalize(cm, controlp, flags);
1522 SOCK_IO_RECV_UNLOCK(so);
1523 unp_scan(m, unp_freerights);
1527 if (controlp != NULL) {
1528 while (*controlp != NULL)
1529 controlp = &(*controlp)->m_next;
1532 KASSERT(m == NULL || m->m_type == MT_DATA,
1533 ("%s: not MT_DATA mbuf %p", __func__, m));
1534 while (m != NULL && uio->uio_resid > 0) {
1535 len = uio->uio_resid;
1538 error = uiomove(mtod(m, char *), (int)len, uio);
1540 SOCK_IO_RECV_UNLOCK(so);
1544 if (len == m->m_len)
1551 SOCK_IO_RECV_UNLOCK(so);
1554 if (flagsp != NULL) {
1555 if (flags & MSG_TRUNC) {
1556 /* Report real length of the packet */
1557 uio->uio_resid -= m_length(m, NULL);
1559 *flagsp |= MSG_TRUNC;
1562 } else if (flagsp != NULL)
1563 *flagsp &= ~MSG_TRUNC;
1569 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1571 struct mbuf *mb, *n;
1575 if (SOLISTENING(so)) {
1582 if (sb->sb_fnrdy != NULL) {
1583 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1585 *errorp = sbready(sb, m, count);
1598 return (mb != NULL);
1602 uipc_ready(struct socket *so, struct mbuf *m, int count)
1604 struct unpcb *unp, *unp2;
1608 unp = sotounpcb(so);
1610 KASSERT(so->so_type == SOCK_STREAM,
1611 ("%s: unexpected socket type for %p", __func__, so));
1614 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1615 UNP_PCB_UNLOCK(unp);
1616 so2 = unp2->unp_socket;
1617 SOCKBUF_LOCK(&so2->so_rcv);
1618 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1619 sorwakeup_locked(so2);
1621 SOCKBUF_UNLOCK(&so2->so_rcv);
1622 UNP_PCB_UNLOCK(unp2);
1625 UNP_PCB_UNLOCK(unp);
1628 * The receiving socket has been disconnected, but may still be valid.
1629 * In this case, the now-ready mbufs are still present in its socket
1630 * buffer, so perform an exhaustive search before giving up and freeing
1634 LIST_FOREACH(unp, &unp_shead, unp_link) {
1635 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1641 for (i = 0; i < count; i++)
1649 uipc_sense(struct socket *so, struct stat *sb)
1653 unp = sotounpcb(so);
1654 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1656 sb->st_blksize = so->so_snd.sb_hiwat;
1658 sb->st_ino = unp->unp_ino;
1663 uipc_shutdown(struct socket *so)
1667 unp = sotounpcb(so);
1668 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1673 UNP_PCB_UNLOCK(unp);
1678 uipc_sockaddr(struct socket *so, struct sockaddr *ret)
1681 const struct sockaddr *sa;
1683 unp = sotounpcb(so);
1684 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1687 if (unp->unp_addr != NULL)
1688 sa = (struct sockaddr *) unp->unp_addr;
1691 bcopy(sa, ret, sa->sa_len);
1692 UNP_PCB_UNLOCK(unp);
1697 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1703 if (sopt->sopt_level != SOL_LOCAL)
1706 unp = sotounpcb(so);
1707 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1709 switch (sopt->sopt_dir) {
1711 switch (sopt->sopt_name) {
1712 case LOCAL_PEERCRED:
1714 if (unp->unp_flags & UNP_HAVEPC)
1715 xu = unp->unp_peercred;
1717 if (so->so_type == SOCK_STREAM)
1722 UNP_PCB_UNLOCK(unp);
1724 error = sooptcopyout(sopt, &xu, sizeof(xu));
1728 /* Unlocked read. */
1729 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1730 error = sooptcopyout(sopt, &optval, sizeof(optval));
1733 case LOCAL_CREDS_PERSISTENT:
1734 /* Unlocked read. */
1735 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1736 error = sooptcopyout(sopt, &optval, sizeof(optval));
1739 case LOCAL_CONNWAIT:
1740 /* Unlocked read. */
1741 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1742 error = sooptcopyout(sopt, &optval, sizeof(optval));
1752 switch (sopt->sopt_name) {
1754 case LOCAL_CREDS_PERSISTENT:
1755 case LOCAL_CONNWAIT:
1756 error = sooptcopyin(sopt, &optval, sizeof(optval),
1761 #define OPTSET(bit, exclusive) do { \
1762 UNP_PCB_LOCK(unp); \
1764 if ((unp->unp_flags & (exclusive)) != 0) { \
1765 UNP_PCB_UNLOCK(unp); \
1769 unp->unp_flags |= (bit); \
1771 unp->unp_flags &= ~(bit); \
1772 UNP_PCB_UNLOCK(unp); \
1775 switch (sopt->sopt_name) {
1777 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1780 case LOCAL_CREDS_PERSISTENT:
1781 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1784 case LOCAL_CONNWAIT:
1785 OPTSET(UNP_CONNWAIT, 0);
1794 error = ENOPROTOOPT;
1807 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1810 return (unp_connectat(AT_FDCWD, so, nam, td, false));
1814 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1815 struct thread *td, bool return_locked)
1818 struct sockaddr_un *soun;
1821 struct unpcb *unp, *unp2, *unp3;
1822 struct nameidata nd;
1823 char buf[SOCK_MAXADDRLEN];
1824 struct sockaddr *sa;
1825 cap_rights_t rights;
1829 if (nam->sa_family != AF_UNIX)
1830 return (EAFNOSUPPORT);
1831 if (nam->sa_len > sizeof(struct sockaddr_un))
1833 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1836 soun = (struct sockaddr_un *)nam;
1837 bcopy(soun->sun_path, buf, len);
1841 unp = sotounpcb(so);
1845 * Wait for connection state to stabilize. If a connection
1846 * already exists, give up. For datagram sockets, which permit
1847 * multiple consecutive connect(2) calls, upper layers are
1848 * responsible for disconnecting in advance of a subsequent
1849 * connect(2), but this is not synchronized with PCB connection
1852 * Also make sure that no threads are currently attempting to
1853 * lock the peer socket, to ensure that unp_conn cannot
1854 * transition between two valid sockets while locks are dropped.
1856 if (SOLISTENING(so))
1858 else if (unp->unp_conn != NULL)
1860 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1864 UNP_PCB_UNLOCK(unp);
1867 if (unp->unp_pairbusy > 0) {
1868 unp->unp_flags |= UNP_WAITING;
1869 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1874 unp->unp_flags |= UNP_CONNECTING;
1875 UNP_PCB_UNLOCK(unp);
1877 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1879 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1882 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1883 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1889 ASSERT_VOP_LOCKED(vp, "unp_connect");
1894 if (vp->v_type != VSOCK) {
1899 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1903 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1907 unp = sotounpcb(so);
1908 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1910 vplock = mtx_pool_find(mtxpool_sleep, vp);
1912 VOP_UNP_CONNECT(vp, &unp2);
1914 error = ECONNREFUSED;
1917 so2 = unp2->unp_socket;
1918 if (so->so_type != so2->so_type) {
1923 if (SOLISTENING(so2)) {
1924 CURVNET_SET(so2->so_vnet);
1925 so2 = sonewconn(so2, 0);
1930 error = ECONNREFUSED;
1933 unp3 = sotounpcb(so2);
1934 unp_pcb_lock_pair(unp2, unp3);
1935 if (unp2->unp_addr != NULL) {
1936 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1937 unp3->unp_addr = (struct sockaddr_un *) sa;
1941 unp_copy_peercred(td, unp3, unp, unp2);
1943 UNP_PCB_UNLOCK(unp2);
1947 * It is safe to block on the PCB lock here since unp2 is
1948 * nascent and cannot be connected to any other sockets.
1952 mac_socketpeer_set_from_socket(so, so2);
1953 mac_socketpeer_set_from_socket(so2, so);
1956 unp_pcb_lock_pair(unp, unp2);
1958 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1959 sotounpcb(so2) == unp2,
1960 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1961 unp_connect2(so, so2, PRU_CONNECT);
1962 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1963 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1964 unp->unp_flags &= ~UNP_CONNECTING;
1966 unp_pcb_unlock_pair(unp, unp2);
1972 * If we are returning locked (called via uipc_sosend_dgram()),
1973 * we need to be sure that vput() won't sleep. This is
1974 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
1975 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
1977 MPASS(!(return_locked && connreq));
1981 if (__predict_false(error)) {
1983 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1984 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1985 unp->unp_flags &= ~UNP_CONNECTING;
1986 UNP_PCB_UNLOCK(unp);
1992 * Set socket peer credentials at connection time.
1994 * The client's PCB credentials are copied from its process structure. The
1995 * server's PCB credentials are copied from the socket on which it called
1996 * listen(2). uipc_listen cached that process's credentials at the time.
1999 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2000 struct unpcb *server_unp, struct unpcb *listen_unp)
2002 cru2xt(td, &client_unp->unp_peercred);
2003 client_unp->unp_flags |= UNP_HAVEPC;
2005 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2006 sizeof(server_unp->unp_peercred));
2007 server_unp->unp_flags |= UNP_HAVEPC;
2008 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2012 unp_connect2(struct socket *so, struct socket *so2, conn2_how req)
2017 MPASS(so2->so_type == so->so_type);
2018 unp = sotounpcb(so);
2019 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2020 unp2 = sotounpcb(so2);
2021 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2023 UNP_PCB_LOCK_ASSERT(unp);
2024 UNP_PCB_LOCK_ASSERT(unp2);
2025 KASSERT(unp->unp_conn == NULL,
2026 ("%s: socket %p is already connected", __func__, unp));
2028 unp->unp_conn = unp2;
2031 switch (so->so_type) {
2033 UNP_REF_LIST_LOCK();
2034 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2035 UNP_REF_LIST_UNLOCK();
2040 case SOCK_SEQPACKET:
2041 KASSERT(unp2->unp_conn == NULL,
2042 ("%s: socket %p is already connected", __func__, unp2));
2043 unp2->unp_conn = unp;
2044 if (req == PRU_CONNECT &&
2045 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2053 panic("unp_connect2");
2058 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2060 struct socket *so, *so2;
2061 struct mbuf *m = NULL;
2063 struct unpcb *unptmp;
2066 UNP_PCB_LOCK_ASSERT(unp);
2067 UNP_PCB_LOCK_ASSERT(unp2);
2068 KASSERT(unp->unp_conn == unp2,
2069 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2071 unp->unp_conn = NULL;
2072 so = unp->unp_socket;
2073 so2 = unp2->unp_socket;
2074 switch (unp->unp_socket->so_type) {
2077 * Remove our send socket buffer from the peer's receive buffer.
2078 * Move the data to the receive buffer only if it is empty.
2079 * This is a protection against a scenario where a peer
2080 * connects, floods and disconnects, effectively blocking
2081 * sendto() from unconnected sockets.
2083 SOCK_RECVBUF_LOCK(so2);
2084 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
2085 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
2087 if (__predict_true((so2->so_rcv.sb_state &
2088 SBS_CANTRCVMORE) == 0) &&
2089 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
2090 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
2091 &so->so_snd.uxdg_mb);
2092 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
2093 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
2094 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
2096 m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
2097 STAILQ_INIT(&so->so_snd.uxdg_mb);
2098 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
2099 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
2100 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
2101 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
2103 /* Note: so may reconnect. */
2104 so->so_snd.uxdg_cc = 0;
2105 so->so_snd.uxdg_ctl = 0;
2106 so->so_snd.uxdg_mbcnt = 0;
2108 SOCK_RECVBUF_UNLOCK(so2);
2109 UNP_REF_LIST_LOCK();
2111 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2115 KASSERT(unptmp != NULL,
2116 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2118 LIST_REMOVE(unp, unp_reflink);
2119 UNP_REF_LIST_UNLOCK();
2122 so->so_state &= ~SS_ISCONNECTED;
2128 case SOCK_SEQPACKET:
2130 soisdisconnected(so);
2131 MPASS(unp2->unp_conn == unp);
2132 unp2->unp_conn = NULL;
2134 soisdisconnected(so2);
2139 unp_pcb_rele_notlast(unp);
2140 if (!unp_pcb_rele(unp))
2141 UNP_PCB_UNLOCK(unp);
2143 if (!unp_pcb_rele(unp))
2144 UNP_PCB_UNLOCK(unp);
2145 if (!unp_pcb_rele(unp2))
2146 UNP_PCB_UNLOCK(unp2);
2150 unp_scan(m, unp_freerights);
2156 * unp_pcblist() walks the global list of struct unpcb's to generate a
2157 * pointer list, bumping the refcount on each unpcb. It then copies them out
2158 * sequentially, validating the generation number on each to see if it has
2159 * been detached. All of this is necessary because copyout() may sleep on
2163 unp_pcblist(SYSCTL_HANDLER_ARGS)
2165 struct unpcb *unp, **unp_list;
2167 struct xunpgen *xug;
2168 struct unp_head *head;
2173 switch ((intptr_t)arg1) {
2182 case SOCK_SEQPACKET:
2187 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2191 * The process of preparing the PCB list is too time-consuming and
2192 * resource-intensive to repeat twice on every request.
2194 if (req->oldptr == NULL) {
2196 req->oldidx = 2 * (sizeof *xug)
2197 + (n + n/8) * sizeof(struct xunpcb);
2201 if (req->newptr != NULL)
2205 * OK, now we're committed to doing something.
2207 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2209 gencnt = unp_gencnt;
2213 xug->xug_len = sizeof *xug;
2215 xug->xug_gen = gencnt;
2216 xug->xug_sogen = so_gencnt;
2217 error = SYSCTL_OUT(req, xug, sizeof *xug);
2223 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2226 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2227 unp = LIST_NEXT(unp, unp_link)) {
2229 if (unp->unp_gencnt <= gencnt) {
2230 if (cr_cansee(req->td->td_ucred,
2231 unp->unp_socket->so_cred)) {
2232 UNP_PCB_UNLOCK(unp);
2235 unp_list[i++] = unp;
2238 UNP_PCB_UNLOCK(unp);
2241 n = i; /* In case we lost some during malloc. */
2244 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2245 for (i = 0; i < n; i++) {
2248 if (unp_pcb_rele(unp))
2251 if (unp->unp_gencnt <= gencnt) {
2252 xu->xu_len = sizeof *xu;
2253 xu->xu_unpp = (uintptr_t)unp;
2255 * XXX - need more locking here to protect against
2256 * connect/disconnect races for SMP.
2258 if (unp->unp_addr != NULL)
2259 bcopy(unp->unp_addr, &xu->xu_addr,
2260 unp->unp_addr->sun_len);
2262 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2263 if (unp->unp_conn != NULL &&
2264 unp->unp_conn->unp_addr != NULL)
2265 bcopy(unp->unp_conn->unp_addr,
2267 unp->unp_conn->unp_addr->sun_len);
2269 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2270 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2271 xu->unp_conn = (uintptr_t)unp->unp_conn;
2272 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2273 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2274 xu->unp_gencnt = unp->unp_gencnt;
2275 sotoxsocket(unp->unp_socket, &xu->xu_socket);
2276 UNP_PCB_UNLOCK(unp);
2277 error = SYSCTL_OUT(req, xu, sizeof *xu);
2279 UNP_PCB_UNLOCK(unp);
2285 * Give the user an updated idea of our state. If the
2286 * generation differs from what we told her before, she knows
2287 * that something happened while we were processing this
2288 * request, and it might be necessary to retry.
2290 xug->xug_gen = unp_gencnt;
2291 xug->xug_sogen = so_gencnt;
2292 xug->xug_count = unp_count;
2293 error = SYSCTL_OUT(req, xug, sizeof *xug);
2295 free(unp_list, M_TEMP);
2300 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2301 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2302 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2303 "List of active local datagram sockets");
2304 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2305 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2306 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2307 "List of active local stream sockets");
2308 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2309 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2310 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2311 "List of active local seqpacket sockets");
2314 unp_shutdown(struct unpcb *unp)
2319 UNP_PCB_LOCK_ASSERT(unp);
2321 unp2 = unp->unp_conn;
2322 if ((unp->unp_socket->so_type == SOCK_STREAM ||
2323 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2324 so = unp2->unp_socket;
2331 unp_drop(struct unpcb *unp)
2337 * Regardless of whether the socket's peer dropped the connection
2338 * with this socket by aborting or disconnecting, POSIX requires
2339 * that ECONNRESET is returned.
2343 so = unp->unp_socket;
2345 so->so_error = ECONNRESET;
2346 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2347 /* Last reference dropped in unp_disconnect(). */
2348 unp_pcb_rele_notlast(unp);
2349 unp_disconnect(unp, unp2);
2350 } else if (!unp_pcb_rele(unp)) {
2351 UNP_PCB_UNLOCK(unp);
2356 unp_freerights(struct filedescent **fdep, int fdcount)
2361 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2363 for (i = 0; i < fdcount; i++) {
2364 fp = fdep[i]->fde_file;
2365 filecaps_free(&fdep[i]->fde_caps);
2368 free(fdep[0], M_FILECAPS);
2372 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2374 struct thread *td = curthread; /* XXX */
2375 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2378 struct filedesc *fdesc = td->td_proc->p_fd;
2379 struct filedescent **fdep;
2381 socklen_t clen = control->m_len, datalen;
2385 UNP_LINK_UNLOCK_ASSERT();
2388 if (controlp != NULL) /* controlp == NULL => free control messages */
2390 while (cm != NULL) {
2391 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2393 data = CMSG_DATA(cm);
2394 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2395 if (cm->cmsg_level == SOL_SOCKET
2396 && cm->cmsg_type == SCM_RIGHTS) {
2397 newfds = datalen / sizeof(*fdep);
2402 /* If we're not outputting the descriptors free them. */
2403 if (error || controlp == NULL) {
2404 unp_freerights(fdep, newfds);
2407 FILEDESC_XLOCK(fdesc);
2410 * Now change each pointer to an fd in the global
2411 * table to an integer that is the index to the local
2412 * fd table entry that we set up to point to the
2413 * global one we are transferring.
2415 newlen = newfds * sizeof(int);
2416 *controlp = sbcreatecontrol(NULL, newlen,
2417 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2420 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2421 if ((error = fdallocn(td, 0, fdp, newfds))) {
2422 FILEDESC_XUNLOCK(fdesc);
2423 unp_freerights(fdep, newfds);
2428 for (i = 0; i < newfds; i++, fdp++) {
2429 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2430 (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2431 &fdep[i]->fde_caps);
2432 unp_externalize_fp(fdep[i]->fde_file);
2436 * The new type indicates that the mbuf data refers to
2437 * kernel resources that may need to be released before
2438 * the mbuf is freed.
2440 m_chtype(*controlp, MT_EXTCONTROL);
2441 FILEDESC_XUNLOCK(fdesc);
2442 free(fdep[0], M_FILECAPS);
2444 /* We can just copy anything else across. */
2445 if (error || controlp == NULL)
2447 *controlp = sbcreatecontrol(NULL, datalen,
2448 cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2450 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2453 controlp = &(*controlp)->m_next;
2456 if (CMSG_SPACE(datalen) < clen) {
2457 clen -= CMSG_SPACE(datalen);
2458 cm = (struct cmsghdr *)
2459 ((caddr_t)cm + CMSG_SPACE(datalen));
2471 unp_zone_change(void *tag)
2474 uma_zone_set_max(unp_zone, maxsockets);
2479 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2485 KASSERT(LIST_EMPTY(&unp->unp_refs),
2486 ("%s: unpcb %p has lingering refs", __func__, unp));
2487 KASSERT(unp->unp_socket == NULL,
2488 ("%s: unpcb %p has socket backpointer", __func__, unp));
2489 KASSERT(unp->unp_vnode == NULL,
2490 ("%s: unpcb %p has vnode references", __func__, unp));
2491 KASSERT(unp->unp_conn == NULL,
2492 ("%s: unpcb %p is still connected", __func__, unp));
2493 KASSERT(unp->unp_addr == NULL,
2494 ("%s: unpcb %p has leaked addr", __func__, unp));
2499 unp_init(void *arg __unused)
2508 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2509 NULL, NULL, UMA_ALIGN_CACHE, 0);
2510 uma_zone_set_max(unp_zone, maxsockets);
2511 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2512 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2513 NULL, EVENTHANDLER_PRI_ANY);
2514 LIST_INIT(&unp_dhead);
2515 LIST_INIT(&unp_shead);
2516 LIST_INIT(&unp_sphead);
2517 SLIST_INIT(&unp_defers);
2518 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2519 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2520 UNP_LINK_LOCK_INIT();
2521 UNP_DEFERRED_LOCK_INIT();
2523 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2526 unp_internalize_cleanup_rights(struct mbuf *control)
2533 for (m = control; m != NULL; m = m->m_next) {
2534 cp = mtod(m, struct cmsghdr *);
2535 if (cp->cmsg_level != SOL_SOCKET ||
2536 cp->cmsg_type != SCM_RIGHTS)
2538 data = CMSG_DATA(cp);
2539 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2540 unp_freerights(data, datalen / sizeof(struct filedesc *));
2545 unp_internalize(struct mbuf **controlp, struct thread *td,
2546 struct mbuf **clast, u_int *space, u_int *mbcnt)
2548 struct mbuf *control, **initial_controlp;
2550 struct filedesc *fdesc;
2553 struct cmsgcred *cmcred;
2554 struct filedescent *fde, **fdep, *fdev;
2557 struct timespec *ts;
2559 socklen_t clen, datalen;
2560 int i, j, error, *fdp, oldfds;
2563 MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */
2564 UNP_LINK_UNLOCK_ASSERT();
2569 control = *controlp;
2571 initial_controlp = controlp;
2572 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2573 data = CMSG_DATA(cm);
2575 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2576 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2577 (char *)cm + cm->cmsg_len >= (char *)data;
2579 clen -= min(CMSG_SPACE(datalen), clen),
2580 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2581 data = CMSG_DATA(cm)) {
2582 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2583 switch (cm->cmsg_type) {
2585 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2586 SCM_CREDS, SOL_SOCKET, M_WAITOK);
2587 cmcred = (struct cmsgcred *)
2588 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2589 cmcred->cmcred_pid = p->p_pid;
2590 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2591 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2592 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2593 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2595 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2596 cmcred->cmcred_groups[i] =
2597 td->td_ucred->cr_groups[i];
2601 oldfds = datalen / sizeof (int);
2604 /* On some machines sizeof pointer is bigger than
2605 * sizeof int, so we need to check if data fits into
2606 * single mbuf. We could allocate several mbufs, and
2607 * unp_externalize() should even properly handle that.
2608 * But it is not worth to complicate the code for an
2609 * insane scenario of passing over 200 file descriptors
2612 newlen = oldfds * sizeof(fdep[0]);
2613 if (CMSG_SPACE(newlen) > MCLBYTES) {
2618 * Check that all the FDs passed in refer to legal
2619 * files. If not, reject the entire operation.
2622 FILEDESC_SLOCK(fdesc);
2623 for (i = 0; i < oldfds; i++, fdp++) {
2624 fp = fget_noref(fdesc, *fdp);
2626 FILEDESC_SUNLOCK(fdesc);
2630 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2631 FILEDESC_SUNLOCK(fdesc);
2638 * Now replace the integer FDs with pointers to the
2639 * file structure and capability rights.
2641 *controlp = sbcreatecontrol(NULL, newlen,
2642 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2644 for (i = 0; i < oldfds; i++, fdp++) {
2645 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2647 for (j = 0; j < i; j++, fdp++) {
2648 fdrop(fdesc->fd_ofiles[*fdp].
2651 FILEDESC_SUNLOCK(fdesc);
2657 fdep = (struct filedescent **)
2658 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2659 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2661 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2662 fde = &fdesc->fd_ofiles[*fdp];
2664 fdep[i]->fde_file = fde->fde_file;
2665 filecaps_copy(&fde->fde_caps,
2666 &fdep[i]->fde_caps, true);
2667 unp_internalize_fp(fdep[i]->fde_file);
2669 FILEDESC_SUNLOCK(fdesc);
2673 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2674 SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2675 tv = (struct timeval *)
2676 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2681 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2682 SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2683 bt = (struct bintime *)
2684 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2689 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2690 SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2691 ts = (struct timespec *)
2692 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2697 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2698 SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2699 ts = (struct timespec *)
2700 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2709 if (space != NULL) {
2710 *space += (*controlp)->m_len;
2712 if ((*controlp)->m_flags & M_EXT)
2713 *mbcnt += (*controlp)->m_ext.ext_size;
2716 controlp = &(*controlp)->m_next;
2722 if (error != 0 && initial_controlp != NULL)
2723 unp_internalize_cleanup_rights(*initial_controlp);
2728 static struct mbuf *
2729 unp_addsockcred(struct thread *td, struct mbuf *control, int mode,
2730 struct mbuf **clast, u_int *space, u_int *mbcnt)
2732 struct mbuf *m, *n, *n_prev;
2733 const struct cmsghdr *cm;
2734 int ngroups, i, cmsgtype;
2737 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2738 if (mode & UNP_WANTCRED_ALWAYS) {
2739 ctrlsz = SOCKCRED2SIZE(ngroups);
2740 cmsgtype = SCM_CREDS2;
2742 ctrlsz = SOCKCREDSIZE(ngroups);
2743 cmsgtype = SCM_CREDS;
2746 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2749 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
2751 if (mode & UNP_WANTCRED_ALWAYS) {
2752 struct sockcred2 *sc;
2754 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2756 sc->sc_pid = td->td_proc->p_pid;
2757 sc->sc_uid = td->td_ucred->cr_ruid;
2758 sc->sc_euid = td->td_ucred->cr_uid;
2759 sc->sc_gid = td->td_ucred->cr_rgid;
2760 sc->sc_egid = td->td_ucred->cr_gid;
2761 sc->sc_ngroups = ngroups;
2762 for (i = 0; i < sc->sc_ngroups; i++)
2763 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2765 struct sockcred *sc;
2767 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2768 sc->sc_uid = td->td_ucred->cr_ruid;
2769 sc->sc_euid = td->td_ucred->cr_uid;
2770 sc->sc_gid = td->td_ucred->cr_rgid;
2771 sc->sc_egid = td->td_ucred->cr_gid;
2772 sc->sc_ngroups = ngroups;
2773 for (i = 0; i < sc->sc_ngroups; i++)
2774 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2778 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2779 * created SCM_CREDS control message (struct sockcred) has another
2782 if (control != NULL && cmsgtype == SCM_CREDS)
2783 for (n = control, n_prev = NULL; n != NULL;) {
2784 cm = mtod(n, struct cmsghdr *);
2785 if (cm->cmsg_level == SOL_SOCKET &&
2786 cm->cmsg_type == SCM_CREDS) {
2788 control = n->m_next;
2790 n_prev->m_next = n->m_next;
2791 if (space != NULL) {
2792 MPASS(*space >= n->m_len);
2794 MPASS(*mbcnt >= MSIZE);
2796 if (n->m_flags & M_EXT) {
2799 *mbcnt -= n->m_ext.ext_size;
2803 MPASS(n->m_next == NULL);
2817 /* Prepend it to the head. */
2818 m->m_next = control;
2819 if (space != NULL) {
2822 if (control == NULL)
2828 static struct unpcb *
2829 fptounp(struct file *fp)
2833 if (fp->f_type != DTYPE_SOCKET)
2835 if ((so = fp->f_data) == NULL)
2837 if (so->so_proto->pr_domain != &localdomain)
2839 return sotounpcb(so);
2843 unp_discard(struct file *fp)
2845 struct unp_defer *dr;
2847 if (unp_externalize_fp(fp)) {
2848 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2850 UNP_DEFERRED_LOCK();
2851 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2852 UNP_DEFERRED_UNLOCK();
2853 atomic_add_int(&unp_defers_count, 1);
2854 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2856 closef_nothread(fp);
2860 unp_process_defers(void *arg __unused, int pending)
2862 struct unp_defer *dr;
2863 SLIST_HEAD(, unp_defer) drl;
2868 UNP_DEFERRED_LOCK();
2869 if (SLIST_FIRST(&unp_defers) == NULL) {
2870 UNP_DEFERRED_UNLOCK();
2873 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2874 UNP_DEFERRED_UNLOCK();
2876 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2877 SLIST_REMOVE_HEAD(&drl, ud_link);
2878 closef_nothread(dr->ud_fp);
2882 atomic_add_int(&unp_defers_count, -count);
2887 unp_internalize_fp(struct file *fp)
2892 if ((unp = fptounp(fp)) != NULL) {
2894 unp->unp_msgcount++;
2901 unp_externalize_fp(struct file *fp)
2907 if ((unp = fptounp(fp)) != NULL) {
2908 unp->unp_msgcount--;
2918 * unp_defer indicates whether additional work has been defered for a future
2919 * pass through unp_gc(). It is thread local and does not require explicit
2922 static int unp_marked;
2925 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2932 * This function can only be called from the gc task.
2934 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2935 ("%s: not on gc callout", __func__));
2936 UNP_LINK_LOCK_ASSERT();
2938 for (i = 0; i < fdcount; i++) {
2939 fp = fdep[i]->fde_file;
2940 if ((unp = fptounp(fp)) == NULL)
2942 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2949 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2956 * This function can only be called from the gc task.
2958 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2959 ("%s: not on gc callout", __func__));
2960 UNP_LINK_LOCK_ASSERT();
2962 for (i = 0; i < fdcount; i++) {
2963 fp = fdep[i]->fde_file;
2964 if ((unp = fptounp(fp)) == NULL)
2966 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2974 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
2978 SOCK_LOCK_ASSERT(so);
2980 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2983 SOCK_RECVBUF_LOCK(so);
2984 switch (so->so_type) {
2986 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
2987 unp_scan(so->so_rcv.uxdg_peeked, op);
2988 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
2989 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
2992 case SOCK_SEQPACKET:
2993 unp_scan(so->so_rcv.sb_mb, op);
2996 SOCK_RECVBUF_UNLOCK(so);
3000 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
3002 struct socket *so, *soa;
3004 so = unp->unp_socket;
3006 if (SOLISTENING(so)) {
3008 * Mark all sockets in our accept queue.
3010 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
3011 unp_scan_socket(soa, op);
3014 * Mark all sockets we reference with RIGHTS.
3016 unp_scan_socket(so, op);
3021 static int unp_recycled;
3022 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
3023 "Number of unreachable sockets claimed by the garbage collector.");
3025 static int unp_taskcount;
3026 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
3027 "Number of times the garbage collector has run.");
3029 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
3030 "Number of active local sockets.");
3033 unp_gc(__unused void *arg, int pending)
3035 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
3037 struct unp_head **head;
3038 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
3039 struct file *f, **unref;
3040 struct unpcb *unp, *unptmp;
3041 int i, total, unp_unreachable;
3043 LIST_INIT(&unp_deadhead);
3047 * First determine which sockets may be in cycles.
3049 unp_unreachable = 0;
3051 for (head = heads; *head != NULL; head++)
3052 LIST_FOREACH(unp, *head, unp_link) {
3053 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
3054 ("%s: unp %p has unexpected gc flags 0x%x",
3055 __func__, unp, (unsigned int)unp->unp_gcflag));
3060 * Check for an unreachable socket potentially in a
3061 * cycle. It must be in a queue as indicated by
3062 * msgcount, and this must equal the file reference
3063 * count. Note that when msgcount is 0 the file is
3066 if (f != NULL && unp->unp_msgcount != 0 &&
3067 refcount_load(&f->f_count) == unp->unp_msgcount) {
3068 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
3069 unp->unp_gcflag |= UNPGC_DEAD;
3070 unp->unp_gcrefs = unp->unp_msgcount;
3076 * Scan all sockets previously marked as potentially being in a cycle
3077 * and remove the references each socket holds on any UNPGC_DEAD
3078 * sockets in its queue. After this step, all remaining references on
3079 * sockets marked UNPGC_DEAD should not be part of any cycle.
3081 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3082 unp_gc_scan(unp, unp_remove_dead_ref);
3085 * If a socket still has a non-negative refcount, it cannot be in a
3086 * cycle. In this case increment refcount of all children iteratively.
3087 * Stop the scan once we do a complete loop without discovering
3088 * a new reachable socket.
3092 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3093 if (unp->unp_gcrefs > 0) {
3094 unp->unp_gcflag &= ~UNPGC_DEAD;
3095 LIST_REMOVE(unp, unp_dead);
3096 KASSERT(unp_unreachable > 0,
3097 ("%s: unp_unreachable underflow.",
3100 unp_gc_scan(unp, unp_restore_undead_ref);
3102 } while (unp_marked);
3106 if (unp_unreachable == 0)
3110 * Allocate space for a local array of dead unpcbs.
3111 * TODO: can this path be simplified by instead using the local
3112 * dead list at unp_deadhead, after taking out references
3113 * on the file object and/or unpcb and dropping the link lock?
3115 unref = malloc(unp_unreachable * sizeof(struct file *),
3119 * Iterate looking for sockets which have been specifically marked
3120 * as unreachable and store them locally.
3124 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3125 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3126 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3127 unp->unp_gcflag &= ~UNPGC_DEAD;
3129 if (unp->unp_msgcount == 0 || f == NULL ||
3130 refcount_load(&f->f_count) != unp->unp_msgcount ||
3134 KASSERT(total <= unp_unreachable,
3135 ("%s: incorrect unreachable count.", __func__));
3140 * Now flush all sockets, free'ing rights. This will free the
3141 * struct files associated with these sockets but leave each socket
3142 * with one remaining ref.
3144 for (i = 0; i < total; i++) {
3147 so = unref[i]->f_data;
3148 CURVNET_SET(so->so_vnet);
3154 * And finally release the sockets so they can be reclaimed.
3156 for (i = 0; i < total; i++)
3157 fdrop(unref[i], NULL);
3158 unp_recycled += total;
3159 free(unref, M_TEMP);
3163 * Synchronize against unp_gc, which can trip over data as we are freeing it.
3166 unp_dispose(struct socket *so)
3172 MPASS(!SOLISTENING(so));
3174 unp = sotounpcb(so);
3176 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3180 * Grab our special mbufs before calling sbrelease().
3182 SOCK_RECVBUF_LOCK(so);
3183 switch (so->so_type) {
3185 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
3186 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
3187 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
3188 /* Note: socket of sb may reconnect. */
3189 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
3192 if (sb->uxdg_peeked != NULL) {
3193 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
3195 sb->uxdg_peeked = NULL;
3197 m = STAILQ_FIRST(&sb->uxdg_mb);
3198 STAILQ_INIT(&sb->uxdg_mb);
3199 /* XXX: our shortened sbrelease() */
3200 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3203 * XXXGL Mark sb with SBS_CANTRCVMORE. This is needed to
3204 * prevent uipc_sosend_dgram() or unp_disconnect() adding more
3205 * data to the socket.
3206 * We are now in dom_dispose and it could be a call from
3207 * soshutdown() or from the final sofree(). The sofree() case
3208 * is simple as it guarantees that no more sends will happen,
3209 * however we can race with unp_disconnect() from our peer.
3210 * The shutdown(2) case is more exotic. It would call into
3211 * dom_dispose() only if socket is SS_ISCONNECTED. This is
3212 * possible if we did connect(2) on this socket and we also
3213 * had it bound with bind(2) and receive connections from other
3214 * sockets. Because soshutdown() violates POSIX (see comment
3215 * there) we will end up here shutting down our receive side.
3216 * Of course this will have affect not only on the peer we
3217 * connect(2)ed to, but also on all of the peers who had
3218 * connect(2)ed to us. Their sends would end up with ENOBUFS.
3220 sb->sb_state |= SBS_CANTRCVMORE;
3223 case SOCK_SEQPACKET:
3225 m = sbcut_locked(sb, sb->sb_ccc);
3226 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3227 ("%s: ccc %u mb %p mbcnt %u", __func__,
3228 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3229 sbrelease_locked(so, SO_RCV);
3232 SOCK_RECVBUF_UNLOCK(so);
3233 if (SOCK_IO_RECV_OWNED(so))
3234 SOCK_IO_RECV_UNLOCK(so);
3237 unp_scan(m, unp_freerights);
3243 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3248 socklen_t clen, datalen;
3250 while (m0 != NULL) {
3251 for (m = m0; m; m = m->m_next) {
3252 if (m->m_type != MT_CONTROL)
3255 cm = mtod(m, struct cmsghdr *);
3258 while (cm != NULL) {
3259 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3262 data = CMSG_DATA(cm);
3263 datalen = (caddr_t)cm + cm->cmsg_len
3266 if (cm->cmsg_level == SOL_SOCKET &&
3267 cm->cmsg_type == SCM_RIGHTS) {
3268 (*op)(data, datalen /
3269 sizeof(struct filedescent *));
3272 if (CMSG_SPACE(datalen) < clen) {
3273 clen -= CMSG_SPACE(datalen);
3274 cm = (struct cmsghdr *)
3275 ((caddr_t)cm + CMSG_SPACE(datalen));
3287 * Definitions of protocols supported in the LOCAL domain.
3289 static struct protosw streamproto = {
3290 .pr_type = SOCK_STREAM,
3291 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
3293 .pr_ctloutput = &uipc_ctloutput,
3294 .pr_abort = uipc_abort,
3295 .pr_accept = uipc_peeraddr,
3296 .pr_attach = uipc_attach,
3297 .pr_bind = uipc_bind,
3298 .pr_bindat = uipc_bindat,
3299 .pr_connect = uipc_connect,
3300 .pr_connectat = uipc_connectat,
3301 .pr_connect2 = uipc_connect2,
3302 .pr_detach = uipc_detach,
3303 .pr_disconnect = uipc_disconnect,
3304 .pr_listen = uipc_listen,
3305 .pr_peeraddr = uipc_peeraddr,
3306 .pr_rcvd = uipc_rcvd,
3307 .pr_send = uipc_send,
3308 .pr_ready = uipc_ready,
3309 .pr_sense = uipc_sense,
3310 .pr_shutdown = uipc_shutdown,
3311 .pr_sockaddr = uipc_sockaddr,
3312 .pr_soreceive = soreceive_generic,
3313 .pr_close = uipc_close,
3316 static struct protosw dgramproto = {
3317 .pr_type = SOCK_DGRAM,
3318 .pr_flags = PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
3320 .pr_ctloutput = &uipc_ctloutput,
3321 .pr_abort = uipc_abort,
3322 .pr_accept = uipc_peeraddr,
3323 .pr_attach = uipc_attach,
3324 .pr_bind = uipc_bind,
3325 .pr_bindat = uipc_bindat,
3326 .pr_connect = uipc_connect,
3327 .pr_connectat = uipc_connectat,
3328 .pr_connect2 = uipc_connect2,
3329 .pr_detach = uipc_detach,
3330 .pr_disconnect = uipc_disconnect,
3331 .pr_peeraddr = uipc_peeraddr,
3332 .pr_sosend = uipc_sosend_dgram,
3333 .pr_sense = uipc_sense,
3334 .pr_shutdown = uipc_shutdown,
3335 .pr_sockaddr = uipc_sockaddr,
3336 .pr_soreceive = uipc_soreceive_dgram,
3337 .pr_close = uipc_close,
3340 static struct protosw seqpacketproto = {
3341 .pr_type = SOCK_SEQPACKET,
3343 * XXXRW: For now, PR_ADDR because soreceive will bump into them
3344 * due to our use of sbappendaddr. A new sbappend variants is needed
3345 * that supports both atomic record writes and control data.
3347 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
3348 PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
3349 .pr_ctloutput = &uipc_ctloutput,
3350 .pr_abort = uipc_abort,
3351 .pr_accept = uipc_peeraddr,
3352 .pr_attach = uipc_attach,
3353 .pr_bind = uipc_bind,
3354 .pr_bindat = uipc_bindat,
3355 .pr_connect = uipc_connect,
3356 .pr_connectat = uipc_connectat,
3357 .pr_connect2 = uipc_connect2,
3358 .pr_detach = uipc_detach,
3359 .pr_disconnect = uipc_disconnect,
3360 .pr_listen = uipc_listen,
3361 .pr_peeraddr = uipc_peeraddr,
3362 .pr_rcvd = uipc_rcvd,
3363 .pr_send = uipc_send,
3364 .pr_sense = uipc_sense,
3365 .pr_shutdown = uipc_shutdown,
3366 .pr_sockaddr = uipc_sockaddr,
3367 .pr_soreceive = soreceive_generic, /* XXX: or...? */
3368 .pr_close = uipc_close,
3371 static struct domain localdomain = {
3372 .dom_family = AF_LOCAL,
3373 .dom_name = "local",
3374 .dom_externalize = unp_externalize,
3375 .dom_dispose = unp_dispose,
3386 * A helper function called by VFS before socket-type vnode reclamation.
3387 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3391 vfs_unp_reclaim(struct vnode *vp)
3397 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3398 KASSERT(vp->v_type == VSOCK,
3399 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3402 vplock = mtx_pool_find(mtxpool_sleep, vp);
3404 VOP_UNP_CONNECT(vp, &unp);
3408 if (unp->unp_vnode == vp) {
3410 unp->unp_vnode = NULL;
3413 UNP_PCB_UNLOCK(unp);
3422 db_print_indent(int indent)
3426 for (i = 0; i < indent; i++)
3431 db_print_unpflags(int unp_flags)
3436 if (unp_flags & UNP_HAVEPC) {
3437 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3440 if (unp_flags & UNP_WANTCRED_ALWAYS) {
3441 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3444 if (unp_flags & UNP_WANTCRED_ONESHOT) {
3445 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3448 if (unp_flags & UNP_CONNWAIT) {
3449 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3452 if (unp_flags & UNP_CONNECTING) {
3453 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3456 if (unp_flags & UNP_BINDING) {
3457 db_printf("%sUNP_BINDING", comma ? ", " : "");
3463 db_print_xucred(int indent, struct xucred *xu)
3467 db_print_indent(indent);
3468 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
3469 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3470 db_print_indent(indent);
3471 db_printf("cr_groups: ");
3473 for (i = 0; i < xu->cr_ngroups; i++) {
3474 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3481 db_print_unprefs(int indent, struct unp_head *uh)
3487 LIST_FOREACH(unp, uh, unp_reflink) {
3488 if (counter % 4 == 0)
3489 db_print_indent(indent);
3490 db_printf("%p ", unp);
3491 if (counter % 4 == 3)
3495 if (counter != 0 && counter % 4 != 0)
3499 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3504 db_printf("usage: show unpcb <addr>\n");
3507 unp = (struct unpcb *)addr;
3509 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
3512 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3515 db_printf("unp_refs:\n");
3516 db_print_unprefs(2, &unp->unp_refs);
3518 /* XXXRW: Would be nice to print the full address, if any. */
3519 db_printf("unp_addr: %p\n", unp->unp_addr);
3521 db_printf("unp_gencnt: %llu\n",
3522 (unsigned long long)unp->unp_gencnt);
3524 db_printf("unp_flags: %x (", unp->unp_flags);
3525 db_print_unpflags(unp->unp_flags);
3528 db_printf("unp_peercred:\n");
3529 db_print_xucred(2, &unp->unp_peercred);
3531 db_printf("unp_refcount: %u\n", unp->unp_refcount);