2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All Rights Reserved.
6 * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7 * Copyright (c) 2018 Matthew Macy
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
37 * UNIX Domain (Local) Sockets
39 * This is an implementation of UNIX (local) domain sockets. Each socket has
40 * an associated struct unpcb (UNIX protocol control block). Stream sockets
41 * may be connected to 0 or 1 other socket. Datagram sockets may be
42 * connected to 0, 1, or many other sockets. Sockets may be created and
43 * connected in pairs (socketpair(2)), or bound/connected to using the file
44 * system name space. For most purposes, only the receive socket buffer is
45 * used, as sending on one socket delivers directly to the receive socket
46 * buffer of a second socket.
48 * The implementation is substantially complicated by the fact that
49 * "ancillary data", such as file descriptors or credentials, may be passed
50 * across UNIX domain sockets. The potential for passing UNIX domain sockets
51 * over other UNIX domain sockets requires the implementation of a simple
52 * garbage collector to find and tear down cycles of disconnected sockets.
56 * rethink name space problems
57 * need a proper out-of-band
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/domain.h>
68 #include <sys/eventhandler.h>
69 #include <sys/fcntl.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
74 #include <sys/malloc.h>
76 #include <sys/mount.h>
77 #include <sys/mutex.h>
78 #include <sys/namei.h>
80 #include <sys/protosw.h>
81 #include <sys/queue.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 #include <sys/taskqueue.h>
93 #include <sys/unpcb.h>
94 #include <sys/vnode.h>
102 #include <security/mac/mac_framework.h>
106 MALLOC_DECLARE(M_FILECAPS);
108 static struct domain localdomain;
110 static uma_zone_t unp_zone;
111 static unp_gen_t unp_gencnt; /* (l) */
112 static u_int unp_count; /* (l) Count of local sockets. */
113 static ino_t unp_ino; /* Prototype for fake inode numbers. */
114 static int unp_rights; /* (g) File descriptors in flight. */
115 static struct unp_head unp_shead; /* (l) List of stream sockets. */
116 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
117 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
120 SLIST_ENTRY(unp_defer) ud_link;
123 static SLIST_HEAD(, unp_defer) unp_defers;
124 static int unp_defers_count;
126 static const struct sockaddr sun_noname = { sizeof(sun_noname), 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 = 2*1024;
158 static u_long unpdg_recvspace = 16*1024; /* support 8KB syslog msgs */
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_accept(struct socket *so, struct sockaddr **nam)
442 struct unpcb *unp, *unp2;
443 const struct sockaddr *sa;
446 * Pass back name of connected socket, if it was bound and we are
447 * still connected (our peer may have closed already!).
450 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
452 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
454 unp2 = unp_pcb_lock_peer(unp);
455 if (unp2 != NULL && unp2->unp_addr != NULL)
456 sa = (struct sockaddr *)unp2->unp_addr;
459 bcopy(sa, *nam, sa->sa_len);
461 unp_pcb_unlock_pair(unp, unp2);
468 uipc_attach(struct socket *so, int proto, struct thread *td)
470 u_long sendspace, recvspace;
475 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
476 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
477 switch (so->so_type) {
479 sendspace = unpst_sendspace;
480 recvspace = unpst_recvspace;
484 STAILQ_INIT(&so->so_rcv.uxdg_mb);
485 STAILQ_INIT(&so->so_snd.uxdg_mb);
486 TAILQ_INIT(&so->so_rcv.uxdg_conns);
488 * Since send buffer is either bypassed or is a part
489 * of one-to-many receive buffer, we assign both space
490 * limits to unpdg_recvspace.
492 sendspace = recvspace = unpdg_recvspace;
496 sendspace = unpsp_sendspace;
497 recvspace = unpsp_recvspace;
501 panic("uipc_attach");
503 error = soreserve(so, sendspace, recvspace);
507 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
510 LIST_INIT(&unp->unp_refs);
511 UNP_PCB_LOCK_INIT(unp);
512 unp->unp_socket = so;
514 refcount_init(&unp->unp_refcount, 1);
516 if ((locked = UNP_LINK_WOWNED()) == false)
519 unp->unp_gencnt = ++unp_gencnt;
520 unp->unp_ino = ++unp_ino;
522 switch (so->so_type) {
524 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
528 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
532 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
536 panic("uipc_attach");
546 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
548 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
558 if (nam->sa_family != AF_UNIX)
559 return (EAFNOSUPPORT);
562 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
564 if (soun->sun_len > sizeof(struct sockaddr_un))
566 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
571 * We don't allow simultaneous bind() calls on a single UNIX domain
572 * socket, so flag in-progress operations, and return an error if an
573 * operation is already in progress.
575 * Historically, we have not allowed a socket to be rebound, so this
576 * also returns an error. Not allowing re-binding simplifies the
577 * implementation and avoids a great many possible failure modes.
580 if (unp->unp_vnode != NULL) {
584 if (unp->unp_flags & UNP_BINDING) {
588 unp->unp_flags |= UNP_BINDING;
591 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
592 bcopy(soun->sun_path, buf, namelen);
596 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
597 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
598 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
603 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
614 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
620 vattr.va_type = VSOCK;
621 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
623 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
627 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
630 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
631 vn_finished_write(mp);
632 if (error == ERELOOKUP)
637 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
638 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
641 VOP_UNP_BIND(vp, unp);
643 unp->unp_addr = soun;
644 unp->unp_flags &= ~UNP_BINDING;
647 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
648 vn_finished_write(mp);
654 unp->unp_flags &= ~UNP_BINDING;
661 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
664 return (uipc_bindat(AT_FDCWD, so, nam, td));
668 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
672 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
673 error = unp_connect(so, nam, td);
678 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
683 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
684 error = unp_connectat(fd, so, nam, td, false);
689 uipc_close(struct socket *so)
691 struct unpcb *unp, *unp2;
692 struct vnode *vp = NULL;
696 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
699 if ((vp = unp->unp_vnode) != NULL) {
700 vplock = mtx_pool_find(mtxpool_sleep, vp);
704 if (vp && unp->unp_vnode == NULL) {
710 unp->unp_vnode = NULL;
712 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
713 unp_disconnect(unp, unp2);
723 uipc_connect2(struct socket *so1, struct socket *so2)
725 struct unpcb *unp, *unp2;
727 if (so1->so_type != so2->so_type)
731 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
733 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
734 unp_pcb_lock_pair(unp, unp2);
735 unp_connect2(so1, so2, PRU_CONNECT2);
736 unp_pcb_unlock_pair(unp, unp2);
742 uipc_detach(struct socket *so)
744 struct unpcb *unp, *unp2;
747 int local_unp_rights;
750 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
756 LIST_REMOVE(unp, unp_link);
757 if (unp->unp_gcflag & UNPGC_DEAD)
758 LIST_REMOVE(unp, unp_dead);
759 unp->unp_gencnt = ++unp_gencnt;
763 UNP_PCB_UNLOCK_ASSERT(unp);
765 if ((vp = unp->unp_vnode) != NULL) {
766 vplock = mtx_pool_find(mtxpool_sleep, vp);
770 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
776 if ((vp = unp->unp_vnode) != NULL) {
778 unp->unp_vnode = NULL;
780 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
781 unp_disconnect(unp, unp2);
786 while (!LIST_EMPTY(&unp->unp_refs)) {
787 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
790 UNP_REF_LIST_UNLOCK();
793 UNP_PCB_UNLOCK_ASSERT(ref);
797 UNP_REF_LIST_UNLOCK();
800 local_unp_rights = unp_rights;
801 unp->unp_socket->so_pcb = NULL;
802 unp->unp_socket = NULL;
803 free(unp->unp_addr, M_SONAME);
804 unp->unp_addr = NULL;
805 if (!unp_pcb_rele(unp))
811 if (local_unp_rights)
812 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
814 switch (so->so_type) {
817 * Everything should have been unlinked/freed by unp_dispose()
818 * and/or unp_disconnect().
820 MPASS(so->so_rcv.uxdg_peeked == NULL);
821 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
822 MPASS(TAILQ_EMPTY(&so->so_rcv.uxdg_conns));
823 MPASS(STAILQ_EMPTY(&so->so_snd.uxdg_mb));
828 uipc_disconnect(struct socket *so)
830 struct unpcb *unp, *unp2;
833 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
836 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
837 unp_disconnect(unp, unp2);
844 uipc_listen(struct socket *so, int backlog, struct thread *td)
849 MPASS(so->so_type != SOCK_DGRAM);
852 * Synchronize with concurrent connection attempts.
857 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
859 else if (unp->unp_vnode == NULL)
860 error = EDESTADDRREQ;
867 error = solisten_proto_check(so);
869 cru2xt(td, &unp->unp_peercred);
870 solisten_proto(so, backlog);
878 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
880 struct unpcb *unp, *unp2;
881 const struct sockaddr *sa;
884 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
886 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
889 * XXX: It seems that this test always fails even when connection is
890 * established. So, this else clause is added as workaround to
891 * return PF_LOCAL sockaddr.
893 unp2 = unp->unp_conn;
896 if (unp2->unp_addr != NULL)
897 sa = (struct sockaddr *) unp2->unp_addr;
900 bcopy(sa, *nam, sa->sa_len);
901 UNP_PCB_UNLOCK(unp2);
904 bcopy(sa, *nam, sa->sa_len);
911 uipc_rcvd(struct socket *so, int flags)
913 struct unpcb *unp, *unp2;
918 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
919 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
920 ("%s: socktype %d", __func__, so->so_type));
923 * Adjust backpressure on sender and wakeup any waiting to write.
925 * The unp lock is acquired to maintain the validity of the unp_conn
926 * pointer; no lock on unp2 is required as unp2->unp_socket will be
927 * static as long as we don't permit unp2 to disconnect from unp,
928 * which is prevented by the lock on unp. We cache values from
929 * so_rcv to avoid holding the so_rcv lock over the entire
930 * transaction on the remote so_snd.
932 SOCKBUF_LOCK(&so->so_rcv);
933 mbcnt = so->so_rcv.sb_mbcnt;
934 sbcc = sbavail(&so->so_rcv);
935 SOCKBUF_UNLOCK(&so->so_rcv);
937 * There is a benign race condition at this point. If we're planning to
938 * clear SB_STOP, but uipc_send is called on the connected socket at
939 * this instant, it might add data to the sockbuf and set SB_STOP. Then
940 * we would erroneously clear SB_STOP below, even though the sockbuf is
941 * full. The race is benign because the only ill effect is to allow the
942 * sockbuf to exceed its size limit, and the size limits are not
943 * strictly guaranteed anyway.
946 unp2 = unp->unp_conn;
951 so2 = unp2->unp_socket;
952 SOCKBUF_LOCK(&so2->so_snd);
953 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
954 so2->so_snd.sb_flags &= ~SB_STOP;
955 sowwakeup_locked(so2);
961 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
962 struct mbuf *control, struct thread *td)
964 struct unpcb *unp, *unp2;
970 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
971 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
972 ("%s: socktype %d", __func__, so->so_type));
975 if (flags & PRUS_OOB) {
979 if (control != NULL &&
980 (error = unp_internalize(&control, td, NULL, NULL, NULL)))
984 if ((so->so_state & SS_ISCONNECTED) == 0) {
986 if ((error = unp_connect(so, nam, td)) != 0)
995 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
999 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1000 unp_pcb_unlock_pair(unp, unp2);
1004 UNP_PCB_UNLOCK(unp);
1005 if ((so2 = unp2->unp_socket) == NULL) {
1006 UNP_PCB_UNLOCK(unp2);
1010 SOCKBUF_LOCK(&so2->so_rcv);
1011 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1013 * Credentials are passed only once on SOCK_STREAM and
1014 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1015 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1017 control = unp_addsockcred(td, control, unp2->unp_flags, NULL,
1019 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1023 * Send to paired receive port and wake up readers. Don't
1024 * check for space available in the receive buffer if we're
1025 * attaching ancillary data; Unix domain sockets only check
1026 * for space in the sending sockbuf, and that check is
1027 * performed one level up the stack. At that level we cannot
1028 * precisely account for the amount of buffer space used
1029 * (e.g., because control messages are not yet internalized).
1031 switch (so->so_type) {
1033 if (control != NULL) {
1034 sbappendcontrol_locked(&so2->so_rcv, m,
1038 sbappend_locked(&so2->so_rcv, m, flags);
1041 case SOCK_SEQPACKET:
1042 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1043 &sun_noname, m, control))
1048 mbcnt = so2->so_rcv.sb_mbcnt;
1049 sbcc = sbavail(&so2->so_rcv);
1051 sorwakeup_locked(so2);
1053 SOCKBUF_UNLOCK(&so2->so_rcv);
1056 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1057 * it would be possible for uipc_rcvd to be called at this
1058 * point, drain the receiving sockbuf, clear SB_STOP, and then
1059 * we would set SB_STOP below. That could lead to an empty
1060 * sockbuf having SB_STOP set
1062 SOCKBUF_LOCK(&so->so_snd);
1063 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1064 so->so_snd.sb_flags |= SB_STOP;
1065 SOCKBUF_UNLOCK(&so->so_snd);
1066 UNP_PCB_UNLOCK(unp2);
1070 * PRUS_EOF is equivalent to pr_send followed by pr_shutdown.
1072 if (flags & PRUS_EOF) {
1076 UNP_PCB_UNLOCK(unp);
1078 if (control != NULL && error != 0)
1079 unp_scan(control, unp_freerights);
1082 if (control != NULL)
1085 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1086 * for freeing memory.
1088 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1093 /* PF_UNIX/SOCK_DGRAM version of sbspace() */
1095 uipc_dgram_sbspace(struct sockbuf *sb, u_int cc, u_int mbcnt)
1099 MPASS(sb->sb_hiwat >= sb->uxdg_cc);
1100 MPASS(sb->sb_mbmax >= sb->uxdg_mbcnt);
1102 if (__predict_false(sb->sb_state & SBS_CANTRCVMORE))
1105 bleft = sb->sb_hiwat - sb->uxdg_cc;
1106 mleft = sb->sb_mbmax - sb->uxdg_mbcnt;
1108 return (bleft >= cc && mleft >= mbcnt);
1112 * PF_UNIX/SOCK_DGRAM send
1114 * Allocate a record consisting of 3 mbufs in the sequence of
1115 * from -> control -> data and append it to the socket buffer.
1117 * The first mbuf carries sender's name and is a pkthdr that stores
1118 * overall length of datagram, its memory consumption and control length.
1120 #define ctllen PH_loc.thirtytwo[1]
1121 _Static_assert(offsetof(struct pkthdr, memlen) + sizeof(u_int) <=
1122 offsetof(struct pkthdr, ctllen), "unix/dgram can not store ctllen");
1124 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1125 struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1127 struct unpcb *unp, *unp2;
1128 const struct sockaddr *from;
1131 struct mbuf *f, *clast;
1132 u_int cc, ctl, mbcnt;
1133 u_int dcc __diagused, dctl __diagused, dmbcnt __diagused;
1136 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1142 if (__predict_false(flags & MSG_OOB)) {
1147 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1151 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1152 if (__predict_false(m == NULL)) {
1156 f = m_gethdr(M_WAITOK, MT_SONAME);
1157 cc = m->m_pkthdr.len;
1158 mbcnt = MSIZE + m->m_pkthdr.memlen;
1160 (error = unp_internalize(&c, td, &clast, &ctl, &mbcnt)))
1163 /* pr_sosend() with mbuf usually is a kernel thread. */
1166 if (__predict_false(c != NULL))
1167 panic("%s: control from a kernel thread", __func__);
1169 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1173 if ((f = m_gethdr(M_NOWAIT, MT_SONAME)) == NULL) {
1177 /* Condition the foreign mbuf to our standards. */
1179 m_tag_delete_chain(m, NULL);
1180 m->m_pkthdr.rcvif = NULL;
1181 m->m_pkthdr.flowid = 0;
1182 m->m_pkthdr.csum_flags = 0;
1183 m->m_pkthdr.fibnum = 0;
1184 m->m_pkthdr.rsstype = 0;
1186 cc = m->m_pkthdr.len;
1188 for (struct mbuf *mb = m; mb != NULL; mb = mb->m_next) {
1190 if (mb->m_flags & M_EXT)
1191 mbcnt += mb->m_ext.ext_size;
1195 unp = sotounpcb(so);
1199 * XXXGL: would be cool to fully remove so_snd out of the equation
1200 * and avoid this lock, which is not only extraneous, but also being
1201 * released, thus still leaving possibility for a race. We can easily
1202 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1203 * is more difficult to invent something to handle so_error.
1205 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1208 SOCK_SENDBUF_LOCK(so);
1209 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1210 SOCK_SENDBUF_UNLOCK(so);
1214 if (so->so_error != 0) {
1215 error = so->so_error;
1217 SOCK_SENDBUF_UNLOCK(so);
1220 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1221 SOCK_SENDBUF_UNLOCK(so);
1222 error = EDESTADDRREQ;
1225 SOCK_SENDBUF_UNLOCK(so);
1228 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1230 UNP_PCB_LOCK_ASSERT(unp);
1231 unp2 = unp->unp_conn;
1232 UNP_PCB_LOCK_ASSERT(unp2);
1235 unp2 = unp_pcb_lock_peer(unp);
1237 UNP_PCB_UNLOCK(unp);
1243 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1244 c = unp_addsockcred(td, c, unp2->unp_flags, &clast, &ctl,
1246 if (unp->unp_addr != NULL)
1247 from = (struct sockaddr *)unp->unp_addr;
1250 f->m_len = from->sa_len;
1251 MPASS(from->sa_len <= MLEN);
1252 bcopy(from, mtod(f, void *), from->sa_len);
1256 * Concatenate mbufs: from -> control -> data.
1257 * Save overall cc and mbcnt in "from" mbuf.
1263 for (mc = c; mc->m_next != NULL; mc = mc->m_next);
1273 dcc = dctl = dmbcnt = 0;
1274 for (struct mbuf *mb = f; mb != NULL; mb = mb->m_next) {
1275 if (mb->m_type == MT_DATA)
1280 if (mb->m_flags & M_EXT)
1281 dmbcnt += mb->m_ext.ext_size;
1285 MPASS(dmbcnt == mbcnt);
1287 f->m_pkthdr.len = cc + ctl;
1288 f->m_pkthdr.memlen = mbcnt;
1289 f->m_pkthdr.ctllen = ctl;
1292 * Destination socket buffer selection.
1294 * Unconnected sends, when !(so->so_state & SS_ISCONNECTED) and the
1295 * destination address is supplied, create a temporary connection for
1296 * the run time of the function (see call to unp_connectat() above and
1297 * to unp_disconnect() below). We distinguish them by condition of
1298 * (addr != NULL). We intentionally avoid adding 'bool connected' for
1299 * that condition, since, again, through the run time of this code we
1300 * are always connected. For such "unconnected" sends, the destination
1301 * buffer would be the receive buffer of destination socket so2.
1303 * For connected sends, data lands on the send buffer of the sender's
1304 * socket "so". Then, if we just added the very first datagram
1305 * on this send buffer, we need to add the send buffer on to the
1306 * receiving socket's buffer list. We put ourselves on top of the
1307 * list. Such logic gives infrequent senders priority over frequent
1310 * Note on byte count management. As long as event methods kevent(2),
1311 * select(2) are not protocol specific (yet), we need to maintain
1312 * meaningful values on the receive buffer. So, the receive buffer
1313 * would accumulate counters from all connected buffers potentially
1314 * having sb_ccc > sb_hiwat or sb_mbcnt > sb_mbmax.
1316 so2 = unp2->unp_socket;
1317 sb = (addr == NULL) ? &so->so_snd : &so2->so_rcv;
1318 SOCK_RECVBUF_LOCK(so2);
1319 if (uipc_dgram_sbspace(sb, cc + ctl, mbcnt)) {
1320 if (addr == NULL && STAILQ_EMPTY(&sb->uxdg_mb))
1321 TAILQ_INSERT_HEAD(&so2->so_rcv.uxdg_conns, &so->so_snd,
1323 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1324 sb->uxdg_cc += cc + ctl;
1325 sb->uxdg_ctl += ctl;
1326 sb->uxdg_mbcnt += mbcnt;
1327 so2->so_rcv.sb_acc += cc + ctl;
1328 so2->so_rcv.sb_ccc += cc + ctl;
1329 so2->so_rcv.sb_ctl += ctl;
1330 so2->so_rcv.sb_mbcnt += mbcnt;
1331 sorwakeup_locked(so2);
1334 soroverflow_locked(so2);
1335 error = (so->so_state & SS_NBIO) ? EAGAIN : ENOBUFS;
1339 unp_disconnect(unp, unp2);
1341 unp_pcb_unlock_pair(unp, unp2);
1343 td->td_ru.ru_msgsnd++;
1346 SOCK_IO_SEND_UNLOCK(so);
1349 unp_scan(c, unp_freerights);
1362 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK.
1363 * The mbuf has already been unlinked from the uxdg_mb of socket buffer
1364 * and needs to be linked onto uxdg_peeked of receive socket buffer.
1367 uipc_peek_dgram(struct socket *so, struct mbuf *m, struct sockaddr **psa,
1368 struct uio *uio, struct mbuf **controlp, int *flagsp)
1373 so->so_rcv.uxdg_peeked = m;
1374 so->so_rcv.uxdg_cc += m->m_pkthdr.len;
1375 so->so_rcv.uxdg_ctl += m->m_pkthdr.ctllen;
1376 so->so_rcv.uxdg_mbcnt += m->m_pkthdr.memlen;
1377 SOCK_RECVBUF_UNLOCK(so);
1379 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1381 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1384 KASSERT(m, ("%s: no data or control after soname", __func__));
1387 * With MSG_PEEK the control isn't executed, just copied.
1389 while (m != NULL && m->m_type == MT_CONTROL) {
1390 if (controlp != NULL) {
1391 *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1392 controlp = &(*controlp)->m_next;
1396 KASSERT(m == NULL || m->m_type == MT_DATA,
1397 ("%s: not MT_DATA mbuf %p", __func__, m));
1398 while (m != NULL && uio->uio_resid > 0) {
1399 len = uio->uio_resid;
1402 error = uiomove(mtod(m, char *), (int)len, uio);
1404 SOCK_IO_RECV_UNLOCK(so);
1407 if (len == m->m_len)
1410 SOCK_IO_RECV_UNLOCK(so);
1412 if (flagsp != NULL) {
1414 if (*flagsp & MSG_TRUNC) {
1415 /* Report real length of the packet */
1416 uio->uio_resid -= m_length(m, NULL) - len;
1418 *flagsp |= MSG_TRUNC;
1420 *flagsp &= ~MSG_TRUNC;
1427 * PF_UNIX/SOCK_DGRAM receive
1430 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1431 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1433 struct sockbuf *sb = NULL;
1443 if (controlp != NULL)
1446 flags = flagsp != NULL ? *flagsp : 0;
1447 nonblock = (so->so_state & SS_NBIO) ||
1448 (flags & (MSG_DONTWAIT | MSG_NBIO));
1450 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1451 if (__predict_false(error))
1455 * Loop blocking while waiting for a datagram. Prioritize connected
1456 * peers over unconnected sends. Set sb to selected socket buffer
1457 * containing an mbuf on exit from the wait loop. A datagram that
1458 * had already been peeked at has top priority.
1460 SOCK_RECVBUF_LOCK(so);
1461 while ((m = so->so_rcv.uxdg_peeked) == NULL &&
1462 (sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) == NULL &&
1463 (m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1465 error = so->so_error;
1467 SOCK_RECVBUF_UNLOCK(so);
1468 SOCK_IO_RECV_UNLOCK(so);
1471 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1472 uio->uio_resid == 0) {
1473 SOCK_RECVBUF_UNLOCK(so);
1474 SOCK_IO_RECV_UNLOCK(so);
1478 SOCK_RECVBUF_UNLOCK(so);
1479 SOCK_IO_RECV_UNLOCK(so);
1480 return (EWOULDBLOCK);
1482 error = sbwait(so, SO_RCV);
1484 SOCK_RECVBUF_UNLOCK(so);
1485 SOCK_IO_RECV_UNLOCK(so);
1493 m = STAILQ_FIRST(&sb->uxdg_mb);
1495 MPASS(m == so->so_rcv.uxdg_peeked);
1497 MPASS(sb->uxdg_cc > 0);
1499 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1502 uio->uio_td->td_ru.ru_msgrcv++;
1504 if (__predict_true(m != so->so_rcv.uxdg_peeked)) {
1505 STAILQ_REMOVE_HEAD(&sb->uxdg_mb, m_stailqpkt);
1506 if (STAILQ_EMPTY(&sb->uxdg_mb) && sb != &so->so_rcv)
1507 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
1509 so->so_rcv.uxdg_peeked = NULL;
1511 sb->uxdg_cc -= m->m_pkthdr.len;
1512 sb->uxdg_ctl -= m->m_pkthdr.ctllen;
1513 sb->uxdg_mbcnt -= m->m_pkthdr.memlen;
1515 if (__predict_false(flags & MSG_PEEK))
1516 return (uipc_peek_dgram(so, m, psa, uio, controlp, flagsp));
1518 so->so_rcv.sb_acc -= m->m_pkthdr.len;
1519 so->so_rcv.sb_ccc -= m->m_pkthdr.len;
1520 so->so_rcv.sb_ctl -= m->m_pkthdr.ctllen;
1521 so->so_rcv.sb_mbcnt -= m->m_pkthdr.memlen;
1522 SOCK_RECVBUF_UNLOCK(so);
1525 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1527 KASSERT(m, ("%s: no data or control after soname", __func__));
1530 * Packet to copyout() is now in 'm' and it is disconnected from the
1533 * Process one or more MT_CONTROL mbufs present before any data mbufs
1534 * in the first mbuf chain on the socket buffer. We call into the
1535 * unp_externalize() to perform externalization (or freeing if
1536 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1537 * without MT_DATA mbufs.
1539 while (m != NULL && m->m_type == MT_CONTROL) {
1542 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1543 * it frees whole chain, so we must disconnect the mbuf.
1545 cm = m; m = m->m_next; cm->m_next = NULL;
1546 error = unp_externalize(cm, controlp, flags);
1548 SOCK_IO_RECV_UNLOCK(so);
1549 unp_scan(m, unp_freerights);
1553 if (controlp != NULL) {
1554 while (*controlp != NULL)
1555 controlp = &(*controlp)->m_next;
1558 KASSERT(m == NULL || m->m_type == MT_DATA,
1559 ("%s: not MT_DATA mbuf %p", __func__, m));
1560 while (m != NULL && uio->uio_resid > 0) {
1561 len = uio->uio_resid;
1564 error = uiomove(mtod(m, char *), (int)len, uio);
1566 SOCK_IO_RECV_UNLOCK(so);
1570 if (len == m->m_len)
1577 SOCK_IO_RECV_UNLOCK(so);
1580 if (flagsp != NULL) {
1581 if (flags & MSG_TRUNC) {
1582 /* Report real length of the packet */
1583 uio->uio_resid -= m_length(m, NULL);
1585 *flagsp |= MSG_TRUNC;
1588 } else if (flagsp != NULL)
1589 *flagsp &= ~MSG_TRUNC;
1595 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1597 struct mbuf *mb, *n;
1601 if (SOLISTENING(so)) {
1608 if (sb->sb_fnrdy != NULL) {
1609 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1611 *errorp = sbready(sb, m, count);
1624 return (mb != NULL);
1628 uipc_ready(struct socket *so, struct mbuf *m, int count)
1630 struct unpcb *unp, *unp2;
1634 unp = sotounpcb(so);
1636 KASSERT(so->so_type == SOCK_STREAM,
1637 ("%s: unexpected socket type for %p", __func__, so));
1640 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1641 UNP_PCB_UNLOCK(unp);
1642 so2 = unp2->unp_socket;
1643 SOCKBUF_LOCK(&so2->so_rcv);
1644 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1645 sorwakeup_locked(so2);
1647 SOCKBUF_UNLOCK(&so2->so_rcv);
1648 UNP_PCB_UNLOCK(unp2);
1651 UNP_PCB_UNLOCK(unp);
1654 * The receiving socket has been disconnected, but may still be valid.
1655 * In this case, the now-ready mbufs are still present in its socket
1656 * buffer, so perform an exhaustive search before giving up and freeing
1660 LIST_FOREACH(unp, &unp_shead, unp_link) {
1661 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1667 for (i = 0; i < count; i++)
1675 uipc_sense(struct socket *so, struct stat *sb)
1679 unp = sotounpcb(so);
1680 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1682 sb->st_blksize = so->so_snd.sb_hiwat;
1684 sb->st_ino = unp->unp_ino;
1689 uipc_shutdown(struct socket *so)
1693 unp = sotounpcb(so);
1694 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1699 UNP_PCB_UNLOCK(unp);
1704 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1707 const struct sockaddr *sa;
1709 unp = sotounpcb(so);
1710 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1712 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1714 if (unp->unp_addr != NULL)
1715 sa = (struct sockaddr *) unp->unp_addr;
1718 bcopy(sa, *nam, sa->sa_len);
1719 UNP_PCB_UNLOCK(unp);
1724 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1730 if (sopt->sopt_level != SOL_LOCAL)
1733 unp = sotounpcb(so);
1734 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1736 switch (sopt->sopt_dir) {
1738 switch (sopt->sopt_name) {
1739 case LOCAL_PEERCRED:
1741 if (unp->unp_flags & UNP_HAVEPC)
1742 xu = unp->unp_peercred;
1744 if (so->so_type == SOCK_STREAM)
1749 UNP_PCB_UNLOCK(unp);
1751 error = sooptcopyout(sopt, &xu, sizeof(xu));
1755 /* Unlocked read. */
1756 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1757 error = sooptcopyout(sopt, &optval, sizeof(optval));
1760 case LOCAL_CREDS_PERSISTENT:
1761 /* Unlocked read. */
1762 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1763 error = sooptcopyout(sopt, &optval, sizeof(optval));
1766 case LOCAL_CONNWAIT:
1767 /* Unlocked read. */
1768 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1769 error = sooptcopyout(sopt, &optval, sizeof(optval));
1779 switch (sopt->sopt_name) {
1781 case LOCAL_CREDS_PERSISTENT:
1782 case LOCAL_CONNWAIT:
1783 error = sooptcopyin(sopt, &optval, sizeof(optval),
1788 #define OPTSET(bit, exclusive) do { \
1789 UNP_PCB_LOCK(unp); \
1791 if ((unp->unp_flags & (exclusive)) != 0) { \
1792 UNP_PCB_UNLOCK(unp); \
1796 unp->unp_flags |= (bit); \
1798 unp->unp_flags &= ~(bit); \
1799 UNP_PCB_UNLOCK(unp); \
1802 switch (sopt->sopt_name) {
1804 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1807 case LOCAL_CREDS_PERSISTENT:
1808 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1811 case LOCAL_CONNWAIT:
1812 OPTSET(UNP_CONNWAIT, 0);
1821 error = ENOPROTOOPT;
1834 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1837 return (unp_connectat(AT_FDCWD, so, nam, td, false));
1841 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1842 struct thread *td, bool return_locked)
1845 struct sockaddr_un *soun;
1848 struct unpcb *unp, *unp2, *unp3;
1849 struct nameidata nd;
1850 char buf[SOCK_MAXADDRLEN];
1851 struct sockaddr *sa;
1852 cap_rights_t rights;
1856 if (nam->sa_family != AF_UNIX)
1857 return (EAFNOSUPPORT);
1858 if (nam->sa_len > sizeof(struct sockaddr_un))
1860 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1863 soun = (struct sockaddr_un *)nam;
1864 bcopy(soun->sun_path, buf, len);
1868 unp = sotounpcb(so);
1872 * Wait for connection state to stabilize. If a connection
1873 * already exists, give up. For datagram sockets, which permit
1874 * multiple consecutive connect(2) calls, upper layers are
1875 * responsible for disconnecting in advance of a subsequent
1876 * connect(2), but this is not synchronized with PCB connection
1879 * Also make sure that no threads are currently attempting to
1880 * lock the peer socket, to ensure that unp_conn cannot
1881 * transition between two valid sockets while locks are dropped.
1883 if (SOLISTENING(so))
1885 else if (unp->unp_conn != NULL)
1887 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1891 UNP_PCB_UNLOCK(unp);
1894 if (unp->unp_pairbusy > 0) {
1895 unp->unp_flags |= UNP_WAITING;
1896 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1901 unp->unp_flags |= UNP_CONNECTING;
1902 UNP_PCB_UNLOCK(unp);
1904 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1906 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1909 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1910 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1916 ASSERT_VOP_LOCKED(vp, "unp_connect");
1917 NDFREE_NOTHING(&nd);
1921 if (vp->v_type != VSOCK) {
1926 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1930 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1934 unp = sotounpcb(so);
1935 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1937 vplock = mtx_pool_find(mtxpool_sleep, vp);
1939 VOP_UNP_CONNECT(vp, &unp2);
1941 error = ECONNREFUSED;
1944 so2 = unp2->unp_socket;
1945 if (so->so_type != so2->so_type) {
1950 if (SOLISTENING(so2)) {
1951 CURVNET_SET(so2->so_vnet);
1952 so2 = sonewconn(so2, 0);
1957 error = ECONNREFUSED;
1960 unp3 = sotounpcb(so2);
1961 unp_pcb_lock_pair(unp2, unp3);
1962 if (unp2->unp_addr != NULL) {
1963 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1964 unp3->unp_addr = (struct sockaddr_un *) sa;
1968 unp_copy_peercred(td, unp3, unp, unp2);
1970 UNP_PCB_UNLOCK(unp2);
1974 * It is safe to block on the PCB lock here since unp2 is
1975 * nascent and cannot be connected to any other sockets.
1979 mac_socketpeer_set_from_socket(so, so2);
1980 mac_socketpeer_set_from_socket(so2, so);
1983 unp_pcb_lock_pair(unp, unp2);
1985 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1986 sotounpcb(so2) == unp2,
1987 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1988 unp_connect2(so, so2, PRU_CONNECT);
1989 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1990 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1991 unp->unp_flags &= ~UNP_CONNECTING;
1993 unp_pcb_unlock_pair(unp, unp2);
1999 * If we are returning locked (called via uipc_sosend_dgram()),
2000 * we need to be sure that vput() won't sleep. This is
2001 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
2002 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
2004 MPASS(!(return_locked && connreq));
2008 if (__predict_false(error)) {
2010 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
2011 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
2012 unp->unp_flags &= ~UNP_CONNECTING;
2013 UNP_PCB_UNLOCK(unp);
2019 * Set socket peer credentials at connection time.
2021 * The client's PCB credentials are copied from its process structure. The
2022 * server's PCB credentials are copied from the socket on which it called
2023 * listen(2). uipc_listen cached that process's credentials at the time.
2026 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2027 struct unpcb *server_unp, struct unpcb *listen_unp)
2029 cru2xt(td, &client_unp->unp_peercred);
2030 client_unp->unp_flags |= UNP_HAVEPC;
2032 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2033 sizeof(server_unp->unp_peercred));
2034 server_unp->unp_flags |= UNP_HAVEPC;
2035 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2039 unp_connect2(struct socket *so, struct socket *so2, conn2_how req)
2044 MPASS(so2->so_type == so->so_type);
2045 unp = sotounpcb(so);
2046 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2047 unp2 = sotounpcb(so2);
2048 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2050 UNP_PCB_LOCK_ASSERT(unp);
2051 UNP_PCB_LOCK_ASSERT(unp2);
2052 KASSERT(unp->unp_conn == NULL,
2053 ("%s: socket %p is already connected", __func__, unp));
2055 unp->unp_conn = unp2;
2058 switch (so->so_type) {
2060 UNP_REF_LIST_LOCK();
2061 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2062 UNP_REF_LIST_UNLOCK();
2067 case SOCK_SEQPACKET:
2068 KASSERT(unp2->unp_conn == NULL,
2069 ("%s: socket %p is already connected", __func__, unp2));
2070 unp2->unp_conn = unp;
2071 if (req == PRU_CONNECT &&
2072 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2080 panic("unp_connect2");
2085 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2087 struct socket *so, *so2;
2088 struct mbuf *m = NULL;
2090 struct unpcb *unptmp;
2093 UNP_PCB_LOCK_ASSERT(unp);
2094 UNP_PCB_LOCK_ASSERT(unp2);
2095 KASSERT(unp->unp_conn == unp2,
2096 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2098 unp->unp_conn = NULL;
2099 so = unp->unp_socket;
2100 so2 = unp2->unp_socket;
2101 switch (unp->unp_socket->so_type) {
2104 * Remove our send socket buffer from the peer's receive buffer.
2105 * Move the data to the receive buffer only if it is empty.
2106 * This is a protection against a scenario where a peer
2107 * connects, floods and disconnects, effectively blocking
2108 * sendto() from unconnected sockets.
2110 SOCK_RECVBUF_LOCK(so2);
2111 if (!STAILQ_EMPTY(&so->so_snd.uxdg_mb)) {
2112 TAILQ_REMOVE(&so2->so_rcv.uxdg_conns, &so->so_snd,
2114 if (__predict_true((so2->so_rcv.sb_state &
2115 SBS_CANTRCVMORE) == 0) &&
2116 STAILQ_EMPTY(&so2->so_rcv.uxdg_mb)) {
2117 STAILQ_CONCAT(&so2->so_rcv.uxdg_mb,
2118 &so->so_snd.uxdg_mb);
2119 so2->so_rcv.uxdg_cc += so->so_snd.uxdg_cc;
2120 so2->so_rcv.uxdg_ctl += so->so_snd.uxdg_ctl;
2121 so2->so_rcv.uxdg_mbcnt += so->so_snd.uxdg_mbcnt;
2123 m = STAILQ_FIRST(&so->so_snd.uxdg_mb);
2124 STAILQ_INIT(&so->so_snd.uxdg_mb);
2125 so2->so_rcv.sb_acc -= so->so_snd.uxdg_cc;
2126 so2->so_rcv.sb_ccc -= so->so_snd.uxdg_cc;
2127 so2->so_rcv.sb_ctl -= so->so_snd.uxdg_ctl;
2128 so2->so_rcv.sb_mbcnt -= so->so_snd.uxdg_mbcnt;
2130 /* Note: so may reconnect. */
2131 so->so_snd.uxdg_cc = 0;
2132 so->so_snd.uxdg_ctl = 0;
2133 so->so_snd.uxdg_mbcnt = 0;
2135 SOCK_RECVBUF_UNLOCK(so2);
2136 UNP_REF_LIST_LOCK();
2138 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2142 KASSERT(unptmp != NULL,
2143 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2145 LIST_REMOVE(unp, unp_reflink);
2146 UNP_REF_LIST_UNLOCK();
2149 so->so_state &= ~SS_ISCONNECTED;
2155 case SOCK_SEQPACKET:
2157 soisdisconnected(so);
2158 MPASS(unp2->unp_conn == unp);
2159 unp2->unp_conn = NULL;
2161 soisdisconnected(so2);
2166 unp_pcb_rele_notlast(unp);
2167 if (!unp_pcb_rele(unp))
2168 UNP_PCB_UNLOCK(unp);
2170 if (!unp_pcb_rele(unp))
2171 UNP_PCB_UNLOCK(unp);
2172 if (!unp_pcb_rele(unp2))
2173 UNP_PCB_UNLOCK(unp2);
2177 unp_scan(m, unp_freerights);
2183 * unp_pcblist() walks the global list of struct unpcb's to generate a
2184 * pointer list, bumping the refcount on each unpcb. It then copies them out
2185 * sequentially, validating the generation number on each to see if it has
2186 * been detached. All of this is necessary because copyout() may sleep on
2190 unp_pcblist(SYSCTL_HANDLER_ARGS)
2192 struct unpcb *unp, **unp_list;
2194 struct xunpgen *xug;
2195 struct unp_head *head;
2200 switch ((intptr_t)arg1) {
2209 case SOCK_SEQPACKET:
2214 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2218 * The process of preparing the PCB list is too time-consuming and
2219 * resource-intensive to repeat twice on every request.
2221 if (req->oldptr == NULL) {
2223 req->oldidx = 2 * (sizeof *xug)
2224 + (n + n/8) * sizeof(struct xunpcb);
2228 if (req->newptr != NULL)
2232 * OK, now we're committed to doing something.
2234 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2236 gencnt = unp_gencnt;
2240 xug->xug_len = sizeof *xug;
2242 xug->xug_gen = gencnt;
2243 xug->xug_sogen = so_gencnt;
2244 error = SYSCTL_OUT(req, xug, sizeof *xug);
2250 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2253 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2254 unp = LIST_NEXT(unp, unp_link)) {
2256 if (unp->unp_gencnt <= gencnt) {
2257 if (cr_cansee(req->td->td_ucred,
2258 unp->unp_socket->so_cred)) {
2259 UNP_PCB_UNLOCK(unp);
2262 unp_list[i++] = unp;
2265 UNP_PCB_UNLOCK(unp);
2268 n = i; /* In case we lost some during malloc. */
2271 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2272 for (i = 0; i < n; i++) {
2275 if (unp_pcb_rele(unp))
2278 if (unp->unp_gencnt <= gencnt) {
2279 xu->xu_len = sizeof *xu;
2280 xu->xu_unpp = (uintptr_t)unp;
2282 * XXX - need more locking here to protect against
2283 * connect/disconnect races for SMP.
2285 if (unp->unp_addr != NULL)
2286 bcopy(unp->unp_addr, &xu->xu_addr,
2287 unp->unp_addr->sun_len);
2289 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2290 if (unp->unp_conn != NULL &&
2291 unp->unp_conn->unp_addr != NULL)
2292 bcopy(unp->unp_conn->unp_addr,
2294 unp->unp_conn->unp_addr->sun_len);
2296 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2297 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2298 xu->unp_conn = (uintptr_t)unp->unp_conn;
2299 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2300 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2301 xu->unp_gencnt = unp->unp_gencnt;
2302 sotoxsocket(unp->unp_socket, &xu->xu_socket);
2303 UNP_PCB_UNLOCK(unp);
2304 error = SYSCTL_OUT(req, xu, sizeof *xu);
2306 UNP_PCB_UNLOCK(unp);
2312 * Give the user an updated idea of our state. If the
2313 * generation differs from what we told her before, she knows
2314 * that something happened while we were processing this
2315 * request, and it might be necessary to retry.
2317 xug->xug_gen = unp_gencnt;
2318 xug->xug_sogen = so_gencnt;
2319 xug->xug_count = unp_count;
2320 error = SYSCTL_OUT(req, xug, sizeof *xug);
2322 free(unp_list, M_TEMP);
2327 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2328 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2329 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2330 "List of active local datagram sockets");
2331 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2332 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2333 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2334 "List of active local stream sockets");
2335 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2336 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2337 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2338 "List of active local seqpacket sockets");
2341 unp_shutdown(struct unpcb *unp)
2346 UNP_PCB_LOCK_ASSERT(unp);
2348 unp2 = unp->unp_conn;
2349 if ((unp->unp_socket->so_type == SOCK_STREAM ||
2350 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2351 so = unp2->unp_socket;
2358 unp_drop(struct unpcb *unp)
2364 * Regardless of whether the socket's peer dropped the connection
2365 * with this socket by aborting or disconnecting, POSIX requires
2366 * that ECONNRESET is returned.
2370 so = unp->unp_socket;
2372 so->so_error = ECONNRESET;
2373 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2374 /* Last reference dropped in unp_disconnect(). */
2375 unp_pcb_rele_notlast(unp);
2376 unp_disconnect(unp, unp2);
2377 } else if (!unp_pcb_rele(unp)) {
2378 UNP_PCB_UNLOCK(unp);
2383 unp_freerights(struct filedescent **fdep, int fdcount)
2388 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2390 for (i = 0; i < fdcount; i++) {
2391 fp = fdep[i]->fde_file;
2392 filecaps_free(&fdep[i]->fde_caps);
2395 free(fdep[0], M_FILECAPS);
2399 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2401 struct thread *td = curthread; /* XXX */
2402 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2405 struct filedesc *fdesc = td->td_proc->p_fd;
2406 struct filedescent **fdep;
2408 socklen_t clen = control->m_len, datalen;
2412 UNP_LINK_UNLOCK_ASSERT();
2415 if (controlp != NULL) /* controlp == NULL => free control messages */
2417 while (cm != NULL) {
2418 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2420 data = CMSG_DATA(cm);
2421 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2422 if (cm->cmsg_level == SOL_SOCKET
2423 && cm->cmsg_type == SCM_RIGHTS) {
2424 newfds = datalen / sizeof(*fdep);
2429 /* If we're not outputting the descriptors free them. */
2430 if (error || controlp == NULL) {
2431 unp_freerights(fdep, newfds);
2434 FILEDESC_XLOCK(fdesc);
2437 * Now change each pointer to an fd in the global
2438 * table to an integer that is the index to the local
2439 * fd table entry that we set up to point to the
2440 * global one we are transferring.
2442 newlen = newfds * sizeof(int);
2443 *controlp = sbcreatecontrol(NULL, newlen,
2444 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2447 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2448 if ((error = fdallocn(td, 0, fdp, newfds))) {
2449 FILEDESC_XUNLOCK(fdesc);
2450 unp_freerights(fdep, newfds);
2455 for (i = 0; i < newfds; i++, fdp++) {
2456 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2457 (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2458 &fdep[i]->fde_caps);
2459 unp_externalize_fp(fdep[i]->fde_file);
2463 * The new type indicates that the mbuf data refers to
2464 * kernel resources that may need to be released before
2465 * the mbuf is freed.
2467 m_chtype(*controlp, MT_EXTCONTROL);
2468 FILEDESC_XUNLOCK(fdesc);
2469 free(fdep[0], M_FILECAPS);
2471 /* We can just copy anything else across. */
2472 if (error || controlp == NULL)
2474 *controlp = sbcreatecontrol(NULL, datalen,
2475 cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2477 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2480 controlp = &(*controlp)->m_next;
2483 if (CMSG_SPACE(datalen) < clen) {
2484 clen -= CMSG_SPACE(datalen);
2485 cm = (struct cmsghdr *)
2486 ((caddr_t)cm + CMSG_SPACE(datalen));
2498 unp_zone_change(void *tag)
2501 uma_zone_set_max(unp_zone, maxsockets);
2506 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2512 KASSERT(LIST_EMPTY(&unp->unp_refs),
2513 ("%s: unpcb %p has lingering refs", __func__, unp));
2514 KASSERT(unp->unp_socket == NULL,
2515 ("%s: unpcb %p has socket backpointer", __func__, unp));
2516 KASSERT(unp->unp_vnode == NULL,
2517 ("%s: unpcb %p has vnode references", __func__, unp));
2518 KASSERT(unp->unp_conn == NULL,
2519 ("%s: unpcb %p is still connected", __func__, unp));
2520 KASSERT(unp->unp_addr == NULL,
2521 ("%s: unpcb %p has leaked addr", __func__, unp));
2526 unp_init(void *arg __unused)
2535 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2536 NULL, NULL, UMA_ALIGN_CACHE, 0);
2537 uma_zone_set_max(unp_zone, maxsockets);
2538 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2539 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2540 NULL, EVENTHANDLER_PRI_ANY);
2541 LIST_INIT(&unp_dhead);
2542 LIST_INIT(&unp_shead);
2543 LIST_INIT(&unp_sphead);
2544 SLIST_INIT(&unp_defers);
2545 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2546 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2547 UNP_LINK_LOCK_INIT();
2548 UNP_DEFERRED_LOCK_INIT();
2550 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2553 unp_internalize_cleanup_rights(struct mbuf *control)
2560 for (m = control; m != NULL; m = m->m_next) {
2561 cp = mtod(m, struct cmsghdr *);
2562 if (cp->cmsg_level != SOL_SOCKET ||
2563 cp->cmsg_type != SCM_RIGHTS)
2565 data = CMSG_DATA(cp);
2566 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2567 unp_freerights(data, datalen / sizeof(struct filedesc *));
2572 unp_internalize(struct mbuf **controlp, struct thread *td,
2573 struct mbuf **clast, u_int *space, u_int *mbcnt)
2575 struct mbuf *control, **initial_controlp;
2577 struct filedesc *fdesc;
2580 struct cmsgcred *cmcred;
2581 struct filedescent *fde, **fdep, *fdev;
2584 struct timespec *ts;
2586 socklen_t clen, datalen;
2587 int i, j, error, *fdp, oldfds;
2590 MPASS((*controlp)->m_next == NULL); /* COMPAT_OLDSOCK may violate */
2591 UNP_LINK_UNLOCK_ASSERT();
2596 control = *controlp;
2598 initial_controlp = controlp;
2599 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2600 data = CMSG_DATA(cm);
2602 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2603 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2604 (char *)cm + cm->cmsg_len >= (char *)data;
2606 clen -= min(CMSG_SPACE(datalen), clen),
2607 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2608 data = CMSG_DATA(cm)) {
2609 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2610 switch (cm->cmsg_type) {
2612 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2613 SCM_CREDS, SOL_SOCKET, M_WAITOK);
2614 cmcred = (struct cmsgcred *)
2615 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2616 cmcred->cmcred_pid = p->p_pid;
2617 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2618 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2619 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2620 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2622 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2623 cmcred->cmcred_groups[i] =
2624 td->td_ucred->cr_groups[i];
2628 oldfds = datalen / sizeof (int);
2631 /* On some machines sizeof pointer is bigger than
2632 * sizeof int, so we need to check if data fits into
2633 * single mbuf. We could allocate several mbufs, and
2634 * unp_externalize() should even properly handle that.
2635 * But it is not worth to complicate the code for an
2636 * insane scenario of passing over 200 file descriptors
2639 newlen = oldfds * sizeof(fdep[0]);
2640 if (CMSG_SPACE(newlen) > MCLBYTES) {
2645 * Check that all the FDs passed in refer to legal
2646 * files. If not, reject the entire operation.
2649 FILEDESC_SLOCK(fdesc);
2650 for (i = 0; i < oldfds; i++, fdp++) {
2651 fp = fget_noref(fdesc, *fdp);
2653 FILEDESC_SUNLOCK(fdesc);
2657 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2658 FILEDESC_SUNLOCK(fdesc);
2665 * Now replace the integer FDs with pointers to the
2666 * file structure and capability rights.
2668 *controlp = sbcreatecontrol(NULL, newlen,
2669 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2671 for (i = 0; i < oldfds; i++, fdp++) {
2672 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2674 for (j = 0; j < i; j++, fdp++) {
2675 fdrop(fdesc->fd_ofiles[*fdp].
2678 FILEDESC_SUNLOCK(fdesc);
2684 fdep = (struct filedescent **)
2685 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2686 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2688 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2689 fde = &fdesc->fd_ofiles[*fdp];
2691 fdep[i]->fde_file = fde->fde_file;
2692 filecaps_copy(&fde->fde_caps,
2693 &fdep[i]->fde_caps, true);
2694 unp_internalize_fp(fdep[i]->fde_file);
2696 FILEDESC_SUNLOCK(fdesc);
2700 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2701 SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2702 tv = (struct timeval *)
2703 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2708 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2709 SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2710 bt = (struct bintime *)
2711 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2716 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2717 SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2718 ts = (struct timespec *)
2719 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2724 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2725 SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2726 ts = (struct timespec *)
2727 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2736 if (space != NULL) {
2737 *space += (*controlp)->m_len;
2739 if ((*controlp)->m_flags & M_EXT)
2740 *mbcnt += (*controlp)->m_ext.ext_size;
2743 controlp = &(*controlp)->m_next;
2749 if (error != 0 && initial_controlp != NULL)
2750 unp_internalize_cleanup_rights(*initial_controlp);
2755 static struct mbuf *
2756 unp_addsockcred(struct thread *td, struct mbuf *control, int mode,
2757 struct mbuf **clast, u_int *space, u_int *mbcnt)
2759 struct mbuf *m, *n, *n_prev;
2760 const struct cmsghdr *cm;
2761 int ngroups, i, cmsgtype;
2764 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2765 if (mode & UNP_WANTCRED_ALWAYS) {
2766 ctrlsz = SOCKCRED2SIZE(ngroups);
2767 cmsgtype = SCM_CREDS2;
2769 ctrlsz = SOCKCREDSIZE(ngroups);
2770 cmsgtype = SCM_CREDS;
2773 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2776 MPASS((m->m_flags & M_EXT) == 0 && m->m_next == NULL);
2778 if (mode & UNP_WANTCRED_ALWAYS) {
2779 struct sockcred2 *sc;
2781 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2783 sc->sc_pid = td->td_proc->p_pid;
2784 sc->sc_uid = td->td_ucred->cr_ruid;
2785 sc->sc_euid = td->td_ucred->cr_uid;
2786 sc->sc_gid = td->td_ucred->cr_rgid;
2787 sc->sc_egid = td->td_ucred->cr_gid;
2788 sc->sc_ngroups = ngroups;
2789 for (i = 0; i < sc->sc_ngroups; i++)
2790 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2792 struct sockcred *sc;
2794 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2795 sc->sc_uid = td->td_ucred->cr_ruid;
2796 sc->sc_euid = td->td_ucred->cr_uid;
2797 sc->sc_gid = td->td_ucred->cr_rgid;
2798 sc->sc_egid = td->td_ucred->cr_gid;
2799 sc->sc_ngroups = ngroups;
2800 for (i = 0; i < sc->sc_ngroups; i++)
2801 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2805 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2806 * created SCM_CREDS control message (struct sockcred) has another
2809 if (control != NULL && cmsgtype == SCM_CREDS)
2810 for (n = control, n_prev = NULL; n != NULL;) {
2811 cm = mtod(n, struct cmsghdr *);
2812 if (cm->cmsg_level == SOL_SOCKET &&
2813 cm->cmsg_type == SCM_CREDS) {
2815 control = n->m_next;
2817 n_prev->m_next = n->m_next;
2818 if (space != NULL) {
2819 MPASS(*space >= n->m_len);
2821 MPASS(*mbcnt >= MSIZE);
2823 if (n->m_flags & M_EXT) {
2826 *mbcnt -= n->m_ext.ext_size;
2830 MPASS(n->m_next == NULL);
2844 /* Prepend it to the head. */
2845 m->m_next = control;
2846 if (space != NULL) {
2849 if (control == NULL)
2855 static struct unpcb *
2856 fptounp(struct file *fp)
2860 if (fp->f_type != DTYPE_SOCKET)
2862 if ((so = fp->f_data) == NULL)
2864 if (so->so_proto->pr_domain != &localdomain)
2866 return sotounpcb(so);
2870 unp_discard(struct file *fp)
2872 struct unp_defer *dr;
2874 if (unp_externalize_fp(fp)) {
2875 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2877 UNP_DEFERRED_LOCK();
2878 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2879 UNP_DEFERRED_UNLOCK();
2880 atomic_add_int(&unp_defers_count, 1);
2881 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2883 closef_nothread(fp);
2887 unp_process_defers(void *arg __unused, int pending)
2889 struct unp_defer *dr;
2890 SLIST_HEAD(, unp_defer) drl;
2895 UNP_DEFERRED_LOCK();
2896 if (SLIST_FIRST(&unp_defers) == NULL) {
2897 UNP_DEFERRED_UNLOCK();
2900 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2901 UNP_DEFERRED_UNLOCK();
2903 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2904 SLIST_REMOVE_HEAD(&drl, ud_link);
2905 closef_nothread(dr->ud_fp);
2909 atomic_add_int(&unp_defers_count, -count);
2914 unp_internalize_fp(struct file *fp)
2919 if ((unp = fptounp(fp)) != NULL) {
2921 unp->unp_msgcount++;
2928 unp_externalize_fp(struct file *fp)
2934 if ((unp = fptounp(fp)) != NULL) {
2935 unp->unp_msgcount--;
2945 * unp_defer indicates whether additional work has been defered for a future
2946 * pass through unp_gc(). It is thread local and does not require explicit
2949 static int unp_marked;
2952 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2959 * This function can only be called from the gc task.
2961 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2962 ("%s: not on gc callout", __func__));
2963 UNP_LINK_LOCK_ASSERT();
2965 for (i = 0; i < fdcount; i++) {
2966 fp = fdep[i]->fde_file;
2967 if ((unp = fptounp(fp)) == NULL)
2969 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2976 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2983 * This function can only be called from the gc task.
2985 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2986 ("%s: not on gc callout", __func__));
2987 UNP_LINK_LOCK_ASSERT();
2989 for (i = 0; i < fdcount; i++) {
2990 fp = fdep[i]->fde_file;
2991 if ((unp = fptounp(fp)) == NULL)
2993 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
3001 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
3005 SOCK_LOCK_ASSERT(so);
3007 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
3010 SOCK_RECVBUF_LOCK(so);
3011 switch (so->so_type) {
3013 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
3014 unp_scan(so->so_rcv.uxdg_peeked, op);
3015 TAILQ_FOREACH(sb, &so->so_rcv.uxdg_conns, uxdg_clist)
3016 unp_scan(STAILQ_FIRST(&sb->uxdg_mb), op);
3019 case SOCK_SEQPACKET:
3020 unp_scan(so->so_rcv.sb_mb, op);
3023 SOCK_RECVBUF_UNLOCK(so);
3027 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
3029 struct socket *so, *soa;
3031 so = unp->unp_socket;
3033 if (SOLISTENING(so)) {
3035 * Mark all sockets in our accept queue.
3037 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
3038 unp_scan_socket(soa, op);
3041 * Mark all sockets we reference with RIGHTS.
3043 unp_scan_socket(so, op);
3048 static int unp_recycled;
3049 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
3050 "Number of unreachable sockets claimed by the garbage collector.");
3052 static int unp_taskcount;
3053 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
3054 "Number of times the garbage collector has run.");
3056 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
3057 "Number of active local sockets.");
3060 unp_gc(__unused void *arg, int pending)
3062 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
3064 struct unp_head **head;
3065 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
3066 struct file *f, **unref;
3067 struct unpcb *unp, *unptmp;
3068 int i, total, unp_unreachable;
3070 LIST_INIT(&unp_deadhead);
3074 * First determine which sockets may be in cycles.
3076 unp_unreachable = 0;
3078 for (head = heads; *head != NULL; head++)
3079 LIST_FOREACH(unp, *head, unp_link) {
3080 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
3081 ("%s: unp %p has unexpected gc flags 0x%x",
3082 __func__, unp, (unsigned int)unp->unp_gcflag));
3087 * Check for an unreachable socket potentially in a
3088 * cycle. It must be in a queue as indicated by
3089 * msgcount, and this must equal the file reference
3090 * count. Note that when msgcount is 0 the file is
3093 if (f != NULL && unp->unp_msgcount != 0 &&
3094 refcount_load(&f->f_count) == unp->unp_msgcount) {
3095 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
3096 unp->unp_gcflag |= UNPGC_DEAD;
3097 unp->unp_gcrefs = unp->unp_msgcount;
3103 * Scan all sockets previously marked as potentially being in a cycle
3104 * and remove the references each socket holds on any UNPGC_DEAD
3105 * sockets in its queue. After this step, all remaining references on
3106 * sockets marked UNPGC_DEAD should not be part of any cycle.
3108 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3109 unp_gc_scan(unp, unp_remove_dead_ref);
3112 * If a socket still has a non-negative refcount, it cannot be in a
3113 * cycle. In this case increment refcount of all children iteratively.
3114 * Stop the scan once we do a complete loop without discovering
3115 * a new reachable socket.
3119 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3120 if (unp->unp_gcrefs > 0) {
3121 unp->unp_gcflag &= ~UNPGC_DEAD;
3122 LIST_REMOVE(unp, unp_dead);
3123 KASSERT(unp_unreachable > 0,
3124 ("%s: unp_unreachable underflow.",
3127 unp_gc_scan(unp, unp_restore_undead_ref);
3129 } while (unp_marked);
3133 if (unp_unreachable == 0)
3137 * Allocate space for a local array of dead unpcbs.
3138 * TODO: can this path be simplified by instead using the local
3139 * dead list at unp_deadhead, after taking out references
3140 * on the file object and/or unpcb and dropping the link lock?
3142 unref = malloc(unp_unreachable * sizeof(struct file *),
3146 * Iterate looking for sockets which have been specifically marked
3147 * as unreachable and store them locally.
3151 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3152 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3153 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3154 unp->unp_gcflag &= ~UNPGC_DEAD;
3156 if (unp->unp_msgcount == 0 || f == NULL ||
3157 refcount_load(&f->f_count) != unp->unp_msgcount ||
3161 KASSERT(total <= unp_unreachable,
3162 ("%s: incorrect unreachable count.", __func__));
3167 * Now flush all sockets, free'ing rights. This will free the
3168 * struct files associated with these sockets but leave each socket
3169 * with one remaining ref.
3171 for (i = 0; i < total; i++) {
3174 so = unref[i]->f_data;
3175 CURVNET_SET(so->so_vnet);
3181 * And finally release the sockets so they can be reclaimed.
3183 for (i = 0; i < total; i++)
3184 fdrop(unref[i], NULL);
3185 unp_recycled += total;
3186 free(unref, M_TEMP);
3190 * Synchronize against unp_gc, which can trip over data as we are freeing it.
3193 unp_dispose(struct socket *so)
3199 MPASS(!SOLISTENING(so));
3201 unp = sotounpcb(so);
3203 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3207 * Grab our special mbufs before calling sbrelease().
3209 SOCK_RECVBUF_LOCK(so);
3210 switch (so->so_type) {
3212 while ((sb = TAILQ_FIRST(&so->so_rcv.uxdg_conns)) != NULL) {
3213 STAILQ_CONCAT(&so->so_rcv.uxdg_mb, &sb->uxdg_mb);
3214 TAILQ_REMOVE(&so->so_rcv.uxdg_conns, sb, uxdg_clist);
3215 /* Note: socket of sb may reconnect. */
3216 sb->uxdg_cc = sb->uxdg_ctl = sb->uxdg_mbcnt = 0;
3219 if (sb->uxdg_peeked != NULL) {
3220 STAILQ_INSERT_HEAD(&sb->uxdg_mb, sb->uxdg_peeked,
3222 sb->uxdg_peeked = NULL;
3224 m = STAILQ_FIRST(&sb->uxdg_mb);
3225 STAILQ_INIT(&sb->uxdg_mb);
3226 /* XXX: our shortened sbrelease() */
3227 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3230 * XXXGL Mark sb with SBS_CANTRCVMORE. This is needed to
3231 * prevent uipc_sosend_dgram() or unp_disconnect() adding more
3232 * data to the socket.
3233 * We are now in dom_dispose and it could be a call from
3234 * soshutdown() or from the final sofree(). The sofree() case
3235 * is simple as it guarantees that no more sends will happen,
3236 * however we can race with unp_disconnect() from our peer.
3237 * The shutdown(2) case is more exotic. It would call into
3238 * dom_dispose() only if socket is SS_ISCONNECTED. This is
3239 * possible if we did connect(2) on this socket and we also
3240 * had it bound with bind(2) and receive connections from other
3241 * sockets. Because soshutdown() violates POSIX (see comment
3242 * there) we will end up here shutting down our receive side.
3243 * Of course this will have affect not only on the peer we
3244 * connect(2)ed to, but also on all of the peers who had
3245 * connect(2)ed to us. Their sends would end up with ENOBUFS.
3247 sb->sb_state |= SBS_CANTRCVMORE;
3250 case SOCK_SEQPACKET:
3252 m = sbcut_locked(sb, sb->sb_ccc);
3253 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3254 ("%s: ccc %u mb %p mbcnt %u", __func__,
3255 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3256 sbrelease_locked(so, SO_RCV);
3259 SOCK_RECVBUF_UNLOCK(so);
3260 if (SOCK_IO_RECV_OWNED(so))
3261 SOCK_IO_RECV_UNLOCK(so);
3264 unp_scan(m, unp_freerights);
3270 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3275 socklen_t clen, datalen;
3277 while (m0 != NULL) {
3278 for (m = m0; m; m = m->m_next) {
3279 if (m->m_type != MT_CONTROL)
3282 cm = mtod(m, struct cmsghdr *);
3285 while (cm != NULL) {
3286 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3289 data = CMSG_DATA(cm);
3290 datalen = (caddr_t)cm + cm->cmsg_len
3293 if (cm->cmsg_level == SOL_SOCKET &&
3294 cm->cmsg_type == SCM_RIGHTS) {
3295 (*op)(data, datalen /
3296 sizeof(struct filedescent *));
3299 if (CMSG_SPACE(datalen) < clen) {
3300 clen -= CMSG_SPACE(datalen);
3301 cm = (struct cmsghdr *)
3302 ((caddr_t)cm + CMSG_SPACE(datalen));
3314 * Definitions of protocols supported in the LOCAL domain.
3316 static struct protosw streamproto = {
3317 .pr_type = SOCK_STREAM,
3318 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
3320 .pr_ctloutput = &uipc_ctloutput,
3321 .pr_abort = uipc_abort,
3322 .pr_accept = uipc_accept,
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_listen = uipc_listen,
3332 .pr_peeraddr = uipc_peeraddr,
3333 .pr_rcvd = uipc_rcvd,
3334 .pr_send = uipc_send,
3335 .pr_ready = uipc_ready,
3336 .pr_sense = uipc_sense,
3337 .pr_shutdown = uipc_shutdown,
3338 .pr_sockaddr = uipc_sockaddr,
3339 .pr_soreceive = soreceive_generic,
3340 .pr_close = uipc_close,
3343 static struct protosw dgramproto = {
3344 .pr_type = SOCK_DGRAM,
3345 .pr_flags = PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
3347 .pr_ctloutput = &uipc_ctloutput,
3348 .pr_abort = uipc_abort,
3349 .pr_accept = uipc_accept,
3350 .pr_attach = uipc_attach,
3351 .pr_bind = uipc_bind,
3352 .pr_bindat = uipc_bindat,
3353 .pr_connect = uipc_connect,
3354 .pr_connectat = uipc_connectat,
3355 .pr_connect2 = uipc_connect2,
3356 .pr_detach = uipc_detach,
3357 .pr_disconnect = uipc_disconnect,
3358 .pr_peeraddr = uipc_peeraddr,
3359 .pr_sosend = uipc_sosend_dgram,
3360 .pr_sense = uipc_sense,
3361 .pr_shutdown = uipc_shutdown,
3362 .pr_sockaddr = uipc_sockaddr,
3363 .pr_soreceive = uipc_soreceive_dgram,
3364 .pr_close = uipc_close,
3367 static struct protosw seqpacketproto = {
3368 .pr_type = SOCK_SEQPACKET,
3370 * XXXRW: For now, PR_ADDR because soreceive will bump into them
3371 * due to our use of sbappendaddr. A new sbappend variants is needed
3372 * that supports both atomic record writes and control data.
3374 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
3375 PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
3376 .pr_ctloutput = &uipc_ctloutput,
3377 .pr_abort = uipc_abort,
3378 .pr_accept = uipc_accept,
3379 .pr_attach = uipc_attach,
3380 .pr_bind = uipc_bind,
3381 .pr_bindat = uipc_bindat,
3382 .pr_connect = uipc_connect,
3383 .pr_connectat = uipc_connectat,
3384 .pr_connect2 = uipc_connect2,
3385 .pr_detach = uipc_detach,
3386 .pr_disconnect = uipc_disconnect,
3387 .pr_listen = uipc_listen,
3388 .pr_peeraddr = uipc_peeraddr,
3389 .pr_rcvd = uipc_rcvd,
3390 .pr_send = uipc_send,
3391 .pr_sense = uipc_sense,
3392 .pr_shutdown = uipc_shutdown,
3393 .pr_sockaddr = uipc_sockaddr,
3394 .pr_soreceive = soreceive_generic, /* XXX: or...? */
3395 .pr_close = uipc_close,
3398 static struct domain localdomain = {
3399 .dom_family = AF_LOCAL,
3400 .dom_name = "local",
3401 .dom_externalize = unp_externalize,
3402 .dom_dispose = unp_dispose,
3413 * A helper function called by VFS before socket-type vnode reclamation.
3414 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3418 vfs_unp_reclaim(struct vnode *vp)
3424 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3425 KASSERT(vp->v_type == VSOCK,
3426 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3429 vplock = mtx_pool_find(mtxpool_sleep, vp);
3431 VOP_UNP_CONNECT(vp, &unp);
3435 if (unp->unp_vnode == vp) {
3437 unp->unp_vnode = NULL;
3440 UNP_PCB_UNLOCK(unp);
3449 db_print_indent(int indent)
3453 for (i = 0; i < indent; i++)
3458 db_print_unpflags(int unp_flags)
3463 if (unp_flags & UNP_HAVEPC) {
3464 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3467 if (unp_flags & UNP_WANTCRED_ALWAYS) {
3468 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3471 if (unp_flags & UNP_WANTCRED_ONESHOT) {
3472 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3475 if (unp_flags & UNP_CONNWAIT) {
3476 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3479 if (unp_flags & UNP_CONNECTING) {
3480 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3483 if (unp_flags & UNP_BINDING) {
3484 db_printf("%sUNP_BINDING", comma ? ", " : "");
3490 db_print_xucred(int indent, struct xucred *xu)
3494 db_print_indent(indent);
3495 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
3496 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3497 db_print_indent(indent);
3498 db_printf("cr_groups: ");
3500 for (i = 0; i < xu->cr_ngroups; i++) {
3501 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3508 db_print_unprefs(int indent, struct unp_head *uh)
3514 LIST_FOREACH(unp, uh, unp_reflink) {
3515 if (counter % 4 == 0)
3516 db_print_indent(indent);
3517 db_printf("%p ", unp);
3518 if (counter % 4 == 3)
3522 if (counter != 0 && counter % 4 != 0)
3526 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3531 db_printf("usage: show unpcb <addr>\n");
3534 unp = (struct unpcb *)addr;
3536 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
3539 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3542 db_printf("unp_refs:\n");
3543 db_print_unprefs(2, &unp->unp_refs);
3545 /* XXXRW: Would be nice to print the full address, if any. */
3546 db_printf("unp_addr: %p\n", unp->unp_addr);
3548 db_printf("unp_gencnt: %llu\n",
3549 (unsigned long long)unp->unp_gencnt);
3551 db_printf("unp_flags: %x (", unp->unp_flags);
3552 db_print_unpflags(unp->unp_flags);
3555 db_printf("unp_peercred:\n");
3556 db_print_xucred(2, &unp->unp_peercred);
3558 db_printf("unp_refcount: %u\n", unp->unp_refcount);