2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California. All Rights Reserved.
6 * Copyright (c) 2004-2009 Robert N. M. Watson All Rights Reserved.
7 * Copyright (c) 2018 Matthew Macy
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
37 * UNIX Domain (Local) Sockets
39 * This is an implementation of UNIX (local) domain sockets. Each socket has
40 * an associated struct unpcb (UNIX protocol control block). Stream sockets
41 * may be connected to 0 or 1 other socket. Datagram sockets may be
42 * connected to 0, 1, or many other sockets. Sockets may be created and
43 * connected in pairs (socketpair(2)), or bound/connected to using the file
44 * system name space. For most purposes, only the receive socket buffer is
45 * used, as sending on one socket delivers directly to the receive socket
46 * buffer of a second socket.
48 * The implementation is substantially complicated by the fact that
49 * "ancillary data", such as file descriptors or credentials, may be passed
50 * across UNIX domain sockets. The potential for passing UNIX domain sockets
51 * over other UNIX domain sockets requires the implementation of a simple
52 * garbage collector to find and tear down cycles of disconnected sockets.
56 * rethink name space problems
57 * need a proper out-of-band
60 #include <sys/cdefs.h>
61 __FBSDID("$FreeBSD$");
65 #include <sys/param.h>
66 #include <sys/capsicum.h>
67 #include <sys/domain.h>
68 #include <sys/eventhandler.h>
69 #include <sys/fcntl.h>
71 #include <sys/filedesc.h>
72 #include <sys/kernel.h>
74 #include <sys/malloc.h>
76 #include <sys/mount.h>
77 #include <sys/mutex.h>
78 #include <sys/namei.h>
80 #include <sys/protosw.h>
81 #include <sys/queue.h>
82 #include <sys/resourcevar.h>
83 #include <sys/rwlock.h>
84 #include <sys/socket.h>
85 #include <sys/socketvar.h>
86 #include <sys/signalvar.h>
89 #include <sys/sysctl.h>
90 #include <sys/systm.h>
91 #include <sys/taskqueue.h>
93 #include <sys/unpcb.h>
94 #include <sys/vnode.h>
102 #include <security/mac/mac_framework.h>
106 MALLOC_DECLARE(M_FILECAPS);
109 * See unpcb.h for the locking key.
112 static uma_zone_t unp_zone;
113 static unp_gen_t unp_gencnt; /* (l) */
114 static u_int unp_count; /* (l) Count of local sockets. */
115 static ino_t unp_ino; /* Prototype for fake inode numbers. */
116 static int unp_rights; /* (g) File descriptors in flight. */
117 static struct unp_head unp_shead; /* (l) List of stream sockets. */
118 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
119 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
122 SLIST_ENTRY(unp_defer) ud_link;
125 static SLIST_HEAD(, unp_defer) unp_defers;
126 static int unp_defers_count;
128 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
131 * Garbage collection of cyclic file descriptor/socket references occurs
132 * asynchronously in a taskqueue context in order to avoid recursion and
133 * reentrance in the UNIX domain socket, file descriptor, and socket layer
134 * code. See unp_gc() for a full description.
136 static struct timeout_task unp_gc_task;
139 * The close of unix domain sockets attached as SCM_RIGHTS is
140 * postponed to the taskqueue, to avoid arbitrary recursion depth.
141 * The attached sockets might have another sockets attached.
143 static struct task unp_defer_task;
146 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
147 * stream sockets, although the total for sender and receiver is actually
150 * Datagram sockets really use the sendspace as the maximum datagram size,
151 * and don't really want to reserve the sendspace. Their recvspace should be
152 * large enough for at least one max-size datagram plus address.
157 static u_long unpst_sendspace = PIPSIZ;
158 static u_long unpst_recvspace = PIPSIZ;
159 static u_long unpdg_maxdgram = 2*1024;
160 static u_long unpdg_recvspace = 16*1024; /* support 8KB syslog msgs */
161 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
162 static u_long unpsp_recvspace = PIPSIZ;
164 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
166 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream,
167 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
169 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram,
170 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
172 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket,
173 CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
176 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
177 &unpst_sendspace, 0, "Default stream send space.");
178 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
179 &unpst_recvspace, 0, "Default stream receive space.");
180 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
181 &unpdg_maxdgram, 0, "Maximum datagram size.");
182 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
183 &unpdg_recvspace, 0, "Default datagram receive space.");
184 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
185 &unpsp_sendspace, 0, "Default seqpacket send space.");
186 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
187 &unpsp_recvspace, 0, "Default seqpacket receive space.");
188 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
189 "File descriptors in flight.");
190 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
191 &unp_defers_count, 0,
192 "File descriptors deferred to taskqueue for close.");
195 * Locking and synchronization:
197 * Several types of locks exist in the local domain socket implementation:
198 * - a global linkage lock
199 * - a global connection list lock
201 * - per-unpcb mutexes
203 * The linkage lock protects the global socket lists, the generation number
204 * counter and garbage collector state.
206 * The connection list lock protects the list of referring sockets in a datagram
207 * socket PCB. This lock is also overloaded to protect a global list of
208 * sockets whose buffers contain socket references in the form of SCM_RIGHTS
209 * messages. To avoid recursion, such references are released by a dedicated
212 * The mtxpool lock protects the vnode from being modified while referenced.
213 * Lock ordering rules require that it be acquired before any PCB locks.
215 * The unpcb lock (unp_mtx) protects the most commonly referenced fields in the
216 * unpcb. This includes the unp_conn field, which either links two connected
217 * PCBs together (for connected socket types) or points at the destination
218 * socket (for connectionless socket types). The operations of creating or
219 * destroying a connection therefore involve locking multiple PCBs. To avoid
220 * lock order reversals, in some cases this involves dropping a PCB lock and
221 * using a reference counter to maintain liveness.
223 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
224 * allocated in pru_attach() and freed in pru_detach(). The validity of that
225 * pointer is an invariant, so no lock is required to dereference the so_pcb
226 * pointer if a valid socket reference is held by the caller. In practice,
227 * this is always true during operations performed on a socket. Each unpcb
228 * has a back-pointer to its socket, unp_socket, which will be stable under
229 * the same circumstances.
231 * This pointer may only be safely dereferenced as long as a valid reference
232 * to the unpcb is held. Typically, this reference will be from the socket,
233 * or from another unpcb when the referring unpcb's lock is held (in order
234 * that the reference not be invalidated during use). For example, to follow
235 * unp->unp_conn->unp_socket, you need to hold a lock on unp_conn to guarantee
236 * that detach is not run clearing unp_socket.
238 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
239 * protocols, bind() is a non-atomic operation, and connect() requires
240 * potential sleeping in the protocol, due to potentially waiting on local or
241 * distributed file systems. We try to separate "lookup" operations, which
242 * may sleep, and the IPC operations themselves, which typically can occur
243 * with relative atomicity as locks can be held over the entire operation.
245 * Another tricky issue is simultaneous multi-threaded or multi-process
246 * access to a single UNIX domain socket. These are handled by the flags
247 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
248 * binding, both of which involve dropping UNIX domain socket locks in order
249 * to perform namei() and other file system operations.
251 static struct rwlock unp_link_rwlock;
252 static struct mtx unp_defers_lock;
254 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
257 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
259 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
262 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
263 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
264 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
265 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
266 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
268 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
270 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
271 "unp_defer", NULL, MTX_DEF)
272 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
273 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
275 #define UNP_REF_LIST_LOCK() UNP_DEFERRED_LOCK();
276 #define UNP_REF_LIST_UNLOCK() UNP_DEFERRED_UNLOCK();
278 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
281 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
282 #define UNP_PCB_LOCKPTR(unp) (&(unp)->unp_mtx)
283 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
284 #define UNP_PCB_TRYLOCK(unp) mtx_trylock(&(unp)->unp_mtx)
285 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
286 #define UNP_PCB_OWNED(unp) mtx_owned(&(unp)->unp_mtx)
287 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
288 #define UNP_PCB_UNLOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_NOTOWNED)
290 static int uipc_connect2(struct socket *, struct socket *);
291 static int uipc_ctloutput(struct socket *, struct sockopt *);
292 static int unp_connect(struct socket *, struct sockaddr *,
294 static int unp_connectat(int, struct socket *, struct sockaddr *,
295 struct thread *, bool);
296 static void unp_connect2(struct socket *so, struct socket *so2, int);
297 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
298 static void unp_dispose(struct socket *so);
299 static void unp_shutdown(struct unpcb *);
300 static void unp_drop(struct unpcb *);
301 static void unp_gc(__unused void *, int);
302 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
303 static void unp_discard(struct file *);
304 static void unp_freerights(struct filedescent **, int);
305 static int unp_internalize(struct mbuf **, struct thread *);
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 *, int);
310 static void unp_process_defers(void * __unused, int);
313 unp_pcb_hold(struct unpcb *unp)
317 old = refcount_acquire(&unp->unp_refcount);
318 KASSERT(old > 0, ("%s: unpcb %p has no references", __func__, unp));
321 static __result_use_check bool
322 unp_pcb_rele(struct unpcb *unp)
326 UNP_PCB_LOCK_ASSERT(unp);
328 if ((ret = refcount_release(&unp->unp_refcount))) {
330 UNP_PCB_LOCK_DESTROY(unp);
331 uma_zfree(unp_zone, unp);
337 unp_pcb_rele_notlast(struct unpcb *unp)
341 ret = refcount_release(&unp->unp_refcount);
342 KASSERT(!ret, ("%s: unpcb %p has no references", __func__, unp));
346 unp_pcb_lock_pair(struct unpcb *unp, struct unpcb *unp2)
348 UNP_PCB_UNLOCK_ASSERT(unp);
349 UNP_PCB_UNLOCK_ASSERT(unp2);
353 } else if ((uintptr_t)unp2 > (uintptr_t)unp) {
363 unp_pcb_unlock_pair(struct unpcb *unp, struct unpcb *unp2)
367 UNP_PCB_UNLOCK(unp2);
371 * Try to lock the connected peer of an already locked socket. In some cases
372 * this requires that we unlock the current socket. The pairbusy counter is
373 * used to block concurrent connection attempts while the lock is dropped. The
374 * caller must be careful to revalidate PCB state.
376 static struct unpcb *
377 unp_pcb_lock_peer(struct unpcb *unp)
381 UNP_PCB_LOCK_ASSERT(unp);
382 unp2 = unp->unp_conn;
385 if (__predict_false(unp == unp2))
388 UNP_PCB_UNLOCK_ASSERT(unp2);
390 if (__predict_true(UNP_PCB_TRYLOCK(unp2)))
392 if ((uintptr_t)unp2 > (uintptr_t)unp) {
402 KASSERT(unp->unp_conn == unp2 || unp->unp_conn == NULL,
403 ("%s: socket %p was reconnected", __func__, unp));
404 if (--unp->unp_pairbusy == 0 && (unp->unp_flags & UNP_WAITING) != 0) {
405 unp->unp_flags &= ~UNP_WAITING;
408 if (unp_pcb_rele(unp2)) {
409 /* unp2 is unlocked. */
412 if (unp->unp_conn == NULL) {
413 UNP_PCB_UNLOCK(unp2);
420 * Definitions of protocols supported in the LOCAL domain.
422 static struct domain localdomain;
423 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
424 static struct pr_usrreqs uipc_usrreqs_seqpacket;
425 static struct protosw localsw[] = {
427 .pr_type = SOCK_STREAM,
428 .pr_domain = &localdomain,
429 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS|
431 .pr_ctloutput = &uipc_ctloutput,
432 .pr_usrreqs = &uipc_usrreqs_stream
435 .pr_type = SOCK_DGRAM,
436 .pr_domain = &localdomain,
437 .pr_flags = PR_ATOMIC | PR_ADDR |PR_RIGHTS | PR_CAPATTACH |
439 .pr_ctloutput = &uipc_ctloutput,
440 .pr_usrreqs = &uipc_usrreqs_dgram
443 .pr_type = SOCK_SEQPACKET,
444 .pr_domain = &localdomain,
447 * XXXRW: For now, PR_ADDR because soreceive will bump into them
448 * due to our use of sbappendaddr. A new sbappend variants is needed
449 * that supports both atomic record writes and control data.
451 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|
452 PR_WANTRCVD|PR_RIGHTS|PR_CAPATTACH,
453 .pr_ctloutput = &uipc_ctloutput,
454 .pr_usrreqs = &uipc_usrreqs_seqpacket,
458 static struct domain localdomain = {
459 .dom_family = AF_LOCAL,
461 .dom_externalize = unp_externalize,
462 .dom_dispose = unp_dispose,
463 .dom_protosw = localsw,
464 .dom_protoswNPROTOSW = &localsw[nitems(localsw)]
469 uipc_abort(struct socket *so)
471 struct unpcb *unp, *unp2;
474 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
475 UNP_PCB_UNLOCK_ASSERT(unp);
478 unp2 = unp->unp_conn;
488 uipc_accept(struct socket *so, struct sockaddr **nam)
490 struct unpcb *unp, *unp2;
491 const struct sockaddr *sa;
494 * Pass back name of connected socket, if it was bound and we are
495 * still connected (our peer may have closed already!).
498 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
500 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
502 unp2 = unp_pcb_lock_peer(unp);
503 if (unp2 != NULL && unp2->unp_addr != NULL)
504 sa = (struct sockaddr *)unp2->unp_addr;
507 bcopy(sa, *nam, sa->sa_len);
509 unp_pcb_unlock_pair(unp, unp2);
516 uipc_attach(struct socket *so, int proto, struct thread *td)
518 u_long sendspace, recvspace;
523 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
524 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
525 switch (so->so_type) {
527 sendspace = unpst_sendspace;
528 recvspace = unpst_recvspace;
532 STAILQ_INIT(&so->so_rcv.uxdg_mb);
533 sendspace = unpdg_maxdgram;
534 recvspace = unpdg_recvspace;
538 sendspace = unpsp_sendspace;
539 recvspace = unpsp_recvspace;
543 panic("uipc_attach");
545 error = soreserve(so, sendspace, recvspace);
549 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
552 LIST_INIT(&unp->unp_refs);
553 UNP_PCB_LOCK_INIT(unp);
554 unp->unp_socket = so;
556 refcount_init(&unp->unp_refcount, 1);
558 if ((locked = UNP_LINK_WOWNED()) == false)
561 unp->unp_gencnt = ++unp_gencnt;
562 unp->unp_ino = ++unp_ino;
564 switch (so->so_type) {
566 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
570 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
574 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
578 panic("uipc_attach");
588 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
590 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
600 if (nam->sa_family != AF_UNIX)
601 return (EAFNOSUPPORT);
604 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
606 if (soun->sun_len > sizeof(struct sockaddr_un))
608 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
613 * We don't allow simultaneous bind() calls on a single UNIX domain
614 * socket, so flag in-progress operations, and return an error if an
615 * operation is already in progress.
617 * Historically, we have not allowed a socket to be rebound, so this
618 * also returns an error. Not allowing re-binding simplifies the
619 * implementation and avoids a great many possible failure modes.
622 if (unp->unp_vnode != NULL) {
626 if (unp->unp_flags & UNP_BINDING) {
630 unp->unp_flags |= UNP_BINDING;
633 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
634 bcopy(soun->sun_path, buf, namelen);
638 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
639 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_BINDAT));
640 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
645 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
656 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
662 vattr.va_type = VSOCK;
663 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_pd->pd_cmask);
665 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
669 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
672 VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
673 vn_finished_write(mp);
674 if (error == ERELOOKUP)
679 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
680 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
683 VOP_UNP_BIND(vp, unp);
685 unp->unp_addr = soun;
686 unp->unp_flags &= ~UNP_BINDING;
689 VOP_VPUT_PAIR(nd.ni_dvp, &vp, true);
690 vn_finished_write(mp);
696 unp->unp_flags &= ~UNP_BINDING;
703 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
706 return (uipc_bindat(AT_FDCWD, so, nam, td));
710 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
714 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
715 error = unp_connect(so, nam, td);
720 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
725 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
726 error = unp_connectat(fd, so, nam, td, false);
731 uipc_close(struct socket *so)
733 struct unpcb *unp, *unp2;
734 struct vnode *vp = NULL;
738 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
741 if ((vp = unp->unp_vnode) != NULL) {
742 vplock = mtx_pool_find(mtxpool_sleep, vp);
746 if (vp && unp->unp_vnode == NULL) {
752 unp->unp_vnode = NULL;
754 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
755 unp_disconnect(unp, unp2);
765 uipc_connect2(struct socket *so1, struct socket *so2)
767 struct unpcb *unp, *unp2;
769 if (so1->so_type != so2->so_type)
773 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
775 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
776 unp_pcb_lock_pair(unp, unp2);
777 unp_connect2(so1, so2, PRU_CONNECT2);
778 unp_pcb_unlock_pair(unp, unp2);
784 uipc_detach(struct socket *so)
786 struct unpcb *unp, *unp2;
789 int local_unp_rights;
792 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
798 LIST_REMOVE(unp, unp_link);
799 if (unp->unp_gcflag & UNPGC_DEAD)
800 LIST_REMOVE(unp, unp_dead);
801 unp->unp_gencnt = ++unp_gencnt;
805 UNP_PCB_UNLOCK_ASSERT(unp);
807 if ((vp = unp->unp_vnode) != NULL) {
808 vplock = mtx_pool_find(mtxpool_sleep, vp);
812 if (unp->unp_vnode != vp && unp->unp_vnode != NULL) {
818 if ((vp = unp->unp_vnode) != NULL) {
820 unp->unp_vnode = NULL;
822 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
823 unp_disconnect(unp, unp2);
828 while (!LIST_EMPTY(&unp->unp_refs)) {
829 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
832 UNP_REF_LIST_UNLOCK();
835 UNP_PCB_UNLOCK_ASSERT(ref);
839 UNP_REF_LIST_UNLOCK();
842 local_unp_rights = unp_rights;
843 unp->unp_socket->so_pcb = NULL;
844 unp->unp_socket = NULL;
845 free(unp->unp_addr, M_SONAME);
846 unp->unp_addr = NULL;
847 if (!unp_pcb_rele(unp))
853 if (local_unp_rights)
854 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
856 switch (so->so_type) {
859 * Everything should have been unlinked/freed by unp_dispose().
861 MPASS(STAILQ_EMPTY(&so->so_rcv.uxdg_mb));
866 uipc_disconnect(struct socket *so)
868 struct unpcb *unp, *unp2;
871 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
874 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL)
875 unp_disconnect(unp, unp2);
882 uipc_listen(struct socket *so, int backlog, struct thread *td)
887 MPASS(so->so_type != SOCK_DGRAM);
890 * Synchronize with concurrent connection attempts.
895 if (unp->unp_conn != NULL || (unp->unp_flags & UNP_CONNECTING) != 0)
897 else if (unp->unp_vnode == NULL)
898 error = EDESTADDRREQ;
905 error = solisten_proto_check(so);
907 cru2xt(td, &unp->unp_peercred);
908 solisten_proto(so, backlog);
916 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
918 struct unpcb *unp, *unp2;
919 const struct sockaddr *sa;
922 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
924 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
927 * XXX: It seems that this test always fails even when connection is
928 * established. So, this else clause is added as workaround to
929 * return PF_LOCAL sockaddr.
931 unp2 = unp->unp_conn;
934 if (unp2->unp_addr != NULL)
935 sa = (struct sockaddr *) unp2->unp_addr;
938 bcopy(sa, *nam, sa->sa_len);
939 UNP_PCB_UNLOCK(unp2);
942 bcopy(sa, *nam, sa->sa_len);
949 uipc_rcvd(struct socket *so, int flags)
951 struct unpcb *unp, *unp2;
956 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
957 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
958 ("%s: socktype %d", __func__, so->so_type));
961 * Adjust backpressure on sender and wakeup any waiting to write.
963 * The unp lock is acquired to maintain the validity of the unp_conn
964 * pointer; no lock on unp2 is required as unp2->unp_socket will be
965 * static as long as we don't permit unp2 to disconnect from unp,
966 * which is prevented by the lock on unp. We cache values from
967 * so_rcv to avoid holding the so_rcv lock over the entire
968 * transaction on the remote so_snd.
970 SOCKBUF_LOCK(&so->so_rcv);
971 mbcnt = so->so_rcv.sb_mbcnt;
972 sbcc = sbavail(&so->so_rcv);
973 SOCKBUF_UNLOCK(&so->so_rcv);
975 * There is a benign race condition at this point. If we're planning to
976 * clear SB_STOP, but uipc_send is called on the connected socket at
977 * this instant, it might add data to the sockbuf and set SB_STOP. Then
978 * we would erroneously clear SB_STOP below, even though the sockbuf is
979 * full. The race is benign because the only ill effect is to allow the
980 * sockbuf to exceed its size limit, and the size limits are not
981 * strictly guaranteed anyway.
984 unp2 = unp->unp_conn;
989 so2 = unp2->unp_socket;
990 SOCKBUF_LOCK(&so2->so_snd);
991 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
992 so2->so_snd.sb_flags &= ~SB_STOP;
993 sowwakeup_locked(so2);
999 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
1000 struct mbuf *control, struct thread *td)
1002 struct unpcb *unp, *unp2;
1007 unp = sotounpcb(so);
1008 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
1009 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
1010 ("%s: socktype %d", __func__, so->so_type));
1013 if (flags & PRUS_OOB) {
1017 if (control != NULL && (error = unp_internalize(&control, td)))
1021 if ((so->so_state & SS_ISCONNECTED) == 0) {
1023 if ((error = unp_connect(so, nam, td)) != 0)
1032 if ((unp2 = unp_pcb_lock_peer(unp)) == NULL) {
1033 UNP_PCB_UNLOCK(unp);
1036 } else if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1037 unp_pcb_unlock_pair(unp, unp2);
1041 UNP_PCB_UNLOCK(unp);
1042 if ((so2 = unp2->unp_socket) == NULL) {
1043 UNP_PCB_UNLOCK(unp2);
1047 SOCKBUF_LOCK(&so2->so_rcv);
1048 if (unp2->unp_flags & UNP_WANTCRED_MASK) {
1050 * Credentials are passed only once on SOCK_STREAM and
1051 * SOCK_SEQPACKET (LOCAL_CREDS => WANTCRED_ONESHOT), or
1052 * forever (LOCAL_CREDS_PERSISTENT => WANTCRED_ALWAYS).
1054 control = unp_addsockcred(td, control, unp2->unp_flags);
1055 unp2->unp_flags &= ~UNP_WANTCRED_ONESHOT;
1059 * Send to paired receive port and wake up readers. Don't
1060 * check for space available in the receive buffer if we're
1061 * attaching ancillary data; Unix domain sockets only check
1062 * for space in the sending sockbuf, and that check is
1063 * performed one level up the stack. At that level we cannot
1064 * precisely account for the amount of buffer space used
1065 * (e.g., because control messages are not yet internalized).
1067 switch (so->so_type) {
1069 if (control != NULL) {
1070 sbappendcontrol_locked(&so2->so_rcv, m,
1074 sbappend_locked(&so2->so_rcv, m, flags);
1077 case SOCK_SEQPACKET:
1078 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1079 &sun_noname, m, control))
1084 mbcnt = so2->so_rcv.sb_mbcnt;
1085 sbcc = sbavail(&so2->so_rcv);
1087 sorwakeup_locked(so2);
1089 SOCKBUF_UNLOCK(&so2->so_rcv);
1092 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1093 * it would be possible for uipc_rcvd to be called at this
1094 * point, drain the receiving sockbuf, clear SB_STOP, and then
1095 * we would set SB_STOP below. That could lead to an empty
1096 * sockbuf having SB_STOP set
1098 SOCKBUF_LOCK(&so->so_snd);
1099 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1100 so->so_snd.sb_flags |= SB_STOP;
1101 SOCKBUF_UNLOCK(&so->so_snd);
1102 UNP_PCB_UNLOCK(unp2);
1106 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1108 if (flags & PRUS_EOF) {
1112 UNP_PCB_UNLOCK(unp);
1114 if (control != NULL && error != 0)
1115 unp_scan(control, unp_freerights);
1118 if (control != NULL)
1121 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1122 * for freeing memory.
1124 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1130 * PF_UNIX/SOCK_DGRAM send
1132 * Allocate a record consisting of 3 mbufs in the sequence of
1133 * from -> control -> data and append it to the socket buffer.
1136 uipc_sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1137 struct mbuf *m, struct mbuf *c, int flags, struct thread *td)
1139 struct unpcb *unp, *unp2;
1140 const struct sockaddr *from;
1147 MPASS((uio != NULL && m == NULL) || (m != NULL && uio == NULL));
1152 if (__predict_false(flags & MSG_OOB)) {
1157 if (__predict_false(uio->uio_resid > unpdg_maxdgram)) {
1161 m = m_uiotombuf(uio, M_WAITOK, 0, max_hdr, M_PKTHDR);
1162 if (__predict_false(m == NULL)) {
1166 f = m_get(M_WAITOK, MT_SONAME);
1167 if (c != NULL && (error = unp_internalize(&c, td)))
1170 /* pru_sosend() with mbuf usually is a kernel thread. */
1173 if (__predict_false(c != NULL))
1174 panic("%s: control from a kernel thread", __func__);
1176 if (__predict_false(m->m_pkthdr.len > unpdg_maxdgram)) {
1180 if ((f = m_get(M_NOWAIT, MT_SONAME)) == NULL) {
1184 /* Condition the foreign mbuf to our standards. */
1186 m_tag_delete_chain(m, NULL);
1187 m->m_pkthdr.rcvif = NULL;
1188 m->m_pkthdr.flowid = 0;
1189 m->m_pkthdr.csum_flags = 0;
1190 m->m_pkthdr.fibnum = 0;
1191 m->m_pkthdr.rsstype = 0;
1194 unp = sotounpcb(so);
1198 * XXXGL: would be cool to fully remove so_snd out of the equation
1199 * and avoid this lock, which is not only extraneous, but also being
1200 * released, thus still leaving possibility for a race. We can easily
1201 * handle SBS_CANTSENDMORE/SS_ISCONNECTED complement in unpcb, but it
1202 * is more difficult to invent something to handle so_error.
1204 error = SOCK_IO_SEND_LOCK(so, SBLOCKWAIT(flags));
1207 SOCK_SENDBUF_LOCK(so);
1208 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1209 SOCK_SENDBUF_UNLOCK(so);
1213 if (so->so_error != 0) {
1214 error = so->so_error;
1216 SOCK_SENDBUF_UNLOCK(so);
1219 if (((so->so_state & SS_ISCONNECTED) == 0) && addr == NULL) {
1220 SOCK_SENDBUF_UNLOCK(so);
1221 error = EDESTADDRREQ;
1224 SOCK_SENDBUF_UNLOCK(so);
1227 if ((error = unp_connectat(AT_FDCWD, so, addr, td, true)))
1229 UNP_PCB_LOCK_ASSERT(unp);
1230 unp2 = unp->unp_conn;
1231 UNP_PCB_LOCK_ASSERT(unp2);
1234 unp2 = unp_pcb_lock_peer(unp);
1236 UNP_PCB_UNLOCK(unp);
1242 if (unp2->unp_flags & UNP_WANTCRED_MASK)
1243 c = unp_addsockcred(td, c, unp2->unp_flags);
1244 if (unp->unp_addr != NULL)
1245 from = (struct sockaddr *)unp->unp_addr;
1248 f->m_len = from->sa_len;
1249 MPASS(from->sa_len <= MLEN);
1250 bcopy(from, mtod(f, void *), from->sa_len);
1251 cc = f->m_len + m->m_pkthdr.len;
1253 /* Concatenate: from -> control -> data. */
1257 cc += m_length(c, &clast);
1265 so2 = unp2->unp_socket;
1267 SOCK_RECVBUF_LOCK(so2);
1268 if (cc <= sbspace(sb)) {
1269 STAILQ_INSERT_TAIL(&sb->uxdg_mb, f, m_stailqpkt);
1270 /* XXX: would be nice if m_uiotombuf() returns count. */
1271 for (; f != NULL ; f = f->m_next) {
1272 if (f->m_type != MT_DATA)
1273 sb->sb_ctl += f->m_len;
1274 sb->sb_mbcnt += MSIZE;
1275 if (f->m_flags & M_EXT)
1276 sb->sb_mbcnt += f->m_ext.ext_size;
1280 sorwakeup_locked(so2);
1282 soroverflow_locked(so2);
1283 error = (so->so_state & SS_NBIO) ? EAGAIN : ENOBUFS;
1287 unp_disconnect(unp, unp2);
1289 unp_pcb_unlock_pair(unp, unp2);
1291 td->td_ru.ru_msgsnd++;
1294 SOCK_IO_SEND_UNLOCK(so);
1297 unp_scan(c, unp_freerights);
1310 * PF_UNIX/SOCK_DGRAM receive with MSG_PEEK
1313 uipc_peek_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1314 struct mbuf **controlp, int *flagsp)
1320 SOCK_RECVBUF_UNLOCK(so);
1322 m = STAILQ_FIRST(&so->so_rcv.uxdg_mb);
1323 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1325 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1328 KASSERT(m, ("%s: no data or control after soname", __func__));
1331 * With MSG_PEEK the control isn't executed, just copied.
1333 while (m != NULL && m->m_type == MT_CONTROL) {
1334 if (controlp != NULL) {
1335 *controlp = m_copym(m, 0, m->m_len, M_WAITOK);
1336 controlp = &(*controlp)->m_next;
1340 KASSERT(m == NULL || m->m_type == MT_DATA,
1341 ("%s: not MT_DATA mbuf %p", __func__, m));
1342 while (m != NULL && uio->uio_resid > 0) {
1343 len = uio->uio_resid;
1346 error = uiomove(mtod(m, char *), (int)len, uio);
1348 SOCK_IO_RECV_UNLOCK(so);
1351 if (len == m->m_len)
1354 SOCK_IO_RECV_UNLOCK(so);
1356 if (m != NULL && flagsp != NULL)
1357 *flagsp |= MSG_TRUNC;
1363 * PF_UNIX/SOCK_DGRAM receive
1366 uipc_soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1367 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1369 struct mbuf *m, *m2;
1378 if (controlp != NULL)
1381 flags = flagsp != NULL ? *flagsp : 0;
1382 nonblock = (so->so_state & SS_NBIO) ||
1383 (flags & (MSG_DONTWAIT | MSG_NBIO));
1385 error = SOCK_IO_RECV_LOCK(so, SBLOCKWAIT(flags));
1386 if (__predict_false(error))
1390 * Loop blocking while waiting for a datagram.
1392 SOCK_RECVBUF_LOCK(so);
1393 while ((m = STAILQ_FIRST(&so->so_rcv.uxdg_mb)) == NULL) {
1394 KASSERT(sbavail(&so->so_rcv) == 0,
1395 ("soreceive_dgram: sb_mb NULL but sbavail %u",
1396 sbavail(&so->so_rcv)));
1398 error = so->so_error;
1400 SOCK_RECVBUF_UNLOCK(so);
1401 SOCK_IO_RECV_UNLOCK(so);
1404 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1405 uio->uio_resid == 0) {
1406 SOCK_RECVBUF_UNLOCK(so);
1407 SOCK_IO_RECV_UNLOCK(so);
1411 SOCK_RECVBUF_UNLOCK(so);
1412 SOCK_IO_RECV_UNLOCK(so);
1413 return (EWOULDBLOCK);
1415 error = sbwait(so, SO_RCV);
1417 SOCK_RECVBUF_UNLOCK(so);
1418 SOCK_IO_RECV_UNLOCK(so);
1422 SOCK_RECVBUF_LOCK_ASSERT(so);
1425 uio->uio_td->td_ru.ru_msgrcv++;
1427 if (__predict_false(flags & MSG_PEEK))
1428 return (uipc_peek_dgram(so, psa, uio, controlp, flagsp));
1430 STAILQ_REMOVE_HEAD(&so->so_rcv.uxdg_mb, m_stailqpkt);
1431 for (m2 = m; m2 != NULL; m2 = m2->m_next) {
1432 if (m2->m_type != MT_DATA)
1433 so->so_rcv.sb_ctl -= m2->m_len;
1434 so->so_rcv.sb_acc -= m2->m_len;
1435 so->so_rcv.sb_ccc -= m2->m_len;
1436 so->so_rcv.sb_mbcnt -= MSIZE;
1437 if (m2->m_flags & M_EXT)
1438 so->so_rcv.sb_mbcnt -= m2->m_ext.ext_size;
1440 SOCK_RECVBUF_UNLOCK(so);
1442 KASSERT(m->m_type == MT_SONAME, ("m->m_type == %d", m->m_type));
1444 *psa = sodupsockaddr(mtod(m, struct sockaddr *), M_WAITOK);
1446 KASSERT(m, ("%s: no data or control after soname", __func__));
1449 * Packet to copyout() is now in 'm' and it is disconnected from the
1452 * Process one or more MT_CONTROL mbufs present before any data mbufs
1453 * in the first mbuf chain on the socket buffer. We call into the
1454 * unp_externalize() to perform externalization (or freeing if
1455 * controlp == NULL). In some cases there can be only MT_CONTROL mbufs
1456 * without MT_DATA mbufs.
1458 while (m != NULL && m->m_type == MT_CONTROL) {
1461 /* XXXGL: unp_externalize() is also dom_externalize() KBI and
1462 * it frees whole chain, so we must disconnect the mbuf.
1464 cm = m; m = m->m_next; cm->m_next = NULL;
1465 error = unp_externalize(cm, controlp, flags);
1467 SOCK_IO_RECV_UNLOCK(so);
1468 unp_scan(m, unp_freerights);
1472 if (controlp != NULL) {
1473 while (*controlp != NULL)
1474 controlp = &(*controlp)->m_next;
1477 KASSERT(m == NULL || m->m_type == MT_DATA,
1478 ("%s: not MT_DATA mbuf %p", __func__, m));
1479 while (m != NULL && uio->uio_resid > 0) {
1480 len = uio->uio_resid;
1483 error = uiomove(mtod(m, char *), (int)len, uio);
1485 SOCK_IO_RECV_UNLOCK(so);
1489 if (len == m->m_len)
1496 SOCK_IO_RECV_UNLOCK(so);
1509 uipc_ready_scan(struct socket *so, struct mbuf *m, int count, int *errorp)
1511 struct mbuf *mb, *n;
1515 if (SOLISTENING(so)) {
1522 if (sb->sb_fnrdy != NULL) {
1523 for (mb = sb->sb_mb, n = mb->m_nextpkt; mb != NULL;) {
1525 *errorp = sbready(sb, m, count);
1538 return (mb != NULL);
1542 uipc_ready(struct socket *so, struct mbuf *m, int count)
1544 struct unpcb *unp, *unp2;
1548 unp = sotounpcb(so);
1550 KASSERT(so->so_type == SOCK_STREAM,
1551 ("%s: unexpected socket type for %p", __func__, so));
1554 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
1555 UNP_PCB_UNLOCK(unp);
1556 so2 = unp2->unp_socket;
1557 SOCKBUF_LOCK(&so2->so_rcv);
1558 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1559 sorwakeup_locked(so2);
1561 SOCKBUF_UNLOCK(&so2->so_rcv);
1562 UNP_PCB_UNLOCK(unp2);
1565 UNP_PCB_UNLOCK(unp);
1568 * The receiving socket has been disconnected, but may still be valid.
1569 * In this case, the now-ready mbufs are still present in its socket
1570 * buffer, so perform an exhaustive search before giving up and freeing
1574 LIST_FOREACH(unp, &unp_shead, unp_link) {
1575 if (uipc_ready_scan(unp->unp_socket, m, count, &error))
1581 for (i = 0; i < count; i++)
1589 uipc_sense(struct socket *so, struct stat *sb)
1593 unp = sotounpcb(so);
1594 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1596 sb->st_blksize = so->so_snd.sb_hiwat;
1598 sb->st_ino = unp->unp_ino;
1603 uipc_shutdown(struct socket *so)
1607 unp = sotounpcb(so);
1608 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1613 UNP_PCB_UNLOCK(unp);
1618 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1621 const struct sockaddr *sa;
1623 unp = sotounpcb(so);
1624 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1626 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1628 if (unp->unp_addr != NULL)
1629 sa = (struct sockaddr *) unp->unp_addr;
1632 bcopy(sa, *nam, sa->sa_len);
1633 UNP_PCB_UNLOCK(unp);
1637 static struct pr_usrreqs uipc_usrreqs_dgram = {
1638 .pru_abort = uipc_abort,
1639 .pru_accept = uipc_accept,
1640 .pru_attach = uipc_attach,
1641 .pru_bind = uipc_bind,
1642 .pru_bindat = uipc_bindat,
1643 .pru_connect = uipc_connect,
1644 .pru_connectat = uipc_connectat,
1645 .pru_connect2 = uipc_connect2,
1646 .pru_detach = uipc_detach,
1647 .pru_disconnect = uipc_disconnect,
1648 .pru_peeraddr = uipc_peeraddr,
1649 .pru_sosend = uipc_sosend_dgram,
1650 .pru_sense = uipc_sense,
1651 .pru_shutdown = uipc_shutdown,
1652 .pru_sockaddr = uipc_sockaddr,
1653 .pru_soreceive = uipc_soreceive_dgram,
1654 .pru_close = uipc_close,
1657 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1658 .pru_abort = uipc_abort,
1659 .pru_accept = uipc_accept,
1660 .pru_attach = uipc_attach,
1661 .pru_bind = uipc_bind,
1662 .pru_bindat = uipc_bindat,
1663 .pru_connect = uipc_connect,
1664 .pru_connectat = uipc_connectat,
1665 .pru_connect2 = uipc_connect2,
1666 .pru_detach = uipc_detach,
1667 .pru_disconnect = uipc_disconnect,
1668 .pru_listen = uipc_listen,
1669 .pru_peeraddr = uipc_peeraddr,
1670 .pru_rcvd = uipc_rcvd,
1671 .pru_send = uipc_send,
1672 .pru_sense = uipc_sense,
1673 .pru_shutdown = uipc_shutdown,
1674 .pru_sockaddr = uipc_sockaddr,
1675 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1676 .pru_close = uipc_close,
1679 static struct pr_usrreqs uipc_usrreqs_stream = {
1680 .pru_abort = uipc_abort,
1681 .pru_accept = uipc_accept,
1682 .pru_attach = uipc_attach,
1683 .pru_bind = uipc_bind,
1684 .pru_bindat = uipc_bindat,
1685 .pru_connect = uipc_connect,
1686 .pru_connectat = uipc_connectat,
1687 .pru_connect2 = uipc_connect2,
1688 .pru_detach = uipc_detach,
1689 .pru_disconnect = uipc_disconnect,
1690 .pru_listen = uipc_listen,
1691 .pru_peeraddr = uipc_peeraddr,
1692 .pru_rcvd = uipc_rcvd,
1693 .pru_send = uipc_send,
1694 .pru_ready = uipc_ready,
1695 .pru_sense = uipc_sense,
1696 .pru_shutdown = uipc_shutdown,
1697 .pru_sockaddr = uipc_sockaddr,
1698 .pru_soreceive = soreceive_generic,
1699 .pru_close = uipc_close,
1703 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1709 if (sopt->sopt_level != SOL_LOCAL)
1712 unp = sotounpcb(so);
1713 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1715 switch (sopt->sopt_dir) {
1717 switch (sopt->sopt_name) {
1718 case LOCAL_PEERCRED:
1720 if (unp->unp_flags & UNP_HAVEPC)
1721 xu = unp->unp_peercred;
1723 if (so->so_type == SOCK_STREAM)
1728 UNP_PCB_UNLOCK(unp);
1730 error = sooptcopyout(sopt, &xu, sizeof(xu));
1734 /* Unlocked read. */
1735 optval = unp->unp_flags & UNP_WANTCRED_ONESHOT ? 1 : 0;
1736 error = sooptcopyout(sopt, &optval, sizeof(optval));
1739 case LOCAL_CREDS_PERSISTENT:
1740 /* Unlocked read. */
1741 optval = unp->unp_flags & UNP_WANTCRED_ALWAYS ? 1 : 0;
1742 error = sooptcopyout(sopt, &optval, sizeof(optval));
1745 case LOCAL_CONNWAIT:
1746 /* Unlocked read. */
1747 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1748 error = sooptcopyout(sopt, &optval, sizeof(optval));
1758 switch (sopt->sopt_name) {
1760 case LOCAL_CREDS_PERSISTENT:
1761 case LOCAL_CONNWAIT:
1762 error = sooptcopyin(sopt, &optval, sizeof(optval),
1767 #define OPTSET(bit, exclusive) do { \
1768 UNP_PCB_LOCK(unp); \
1770 if ((unp->unp_flags & (exclusive)) != 0) { \
1771 UNP_PCB_UNLOCK(unp); \
1775 unp->unp_flags |= (bit); \
1777 unp->unp_flags &= ~(bit); \
1778 UNP_PCB_UNLOCK(unp); \
1781 switch (sopt->sopt_name) {
1783 OPTSET(UNP_WANTCRED_ONESHOT, UNP_WANTCRED_ALWAYS);
1786 case LOCAL_CREDS_PERSISTENT:
1787 OPTSET(UNP_WANTCRED_ALWAYS, UNP_WANTCRED_ONESHOT);
1790 case LOCAL_CONNWAIT:
1791 OPTSET(UNP_CONNWAIT, 0);
1800 error = ENOPROTOOPT;
1813 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1816 return (unp_connectat(AT_FDCWD, so, nam, td, false));
1820 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1821 struct thread *td, bool return_locked)
1824 struct sockaddr_un *soun;
1827 struct unpcb *unp, *unp2, *unp3;
1828 struct nameidata nd;
1829 char buf[SOCK_MAXADDRLEN];
1830 struct sockaddr *sa;
1831 cap_rights_t rights;
1835 if (nam->sa_family != AF_UNIX)
1836 return (EAFNOSUPPORT);
1837 if (nam->sa_len > sizeof(struct sockaddr_un))
1839 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1842 soun = (struct sockaddr_un *)nam;
1843 bcopy(soun->sun_path, buf, len);
1847 unp = sotounpcb(so);
1851 * Wait for connection state to stabilize. If a connection
1852 * already exists, give up. For datagram sockets, which permit
1853 * multiple consecutive connect(2) calls, upper layers are
1854 * responsible for disconnecting in advance of a subsequent
1855 * connect(2), but this is not synchronized with PCB connection
1858 * Also make sure that no threads are currently attempting to
1859 * lock the peer socket, to ensure that unp_conn cannot
1860 * transition between two valid sockets while locks are dropped.
1862 if (SOLISTENING(so))
1864 else if (unp->unp_conn != NULL)
1866 else if ((unp->unp_flags & UNP_CONNECTING) != 0) {
1870 UNP_PCB_UNLOCK(unp);
1873 if (unp->unp_pairbusy > 0) {
1874 unp->unp_flags |= UNP_WAITING;
1875 mtx_sleep(unp, UNP_PCB_LOCKPTR(unp), 0, "unpeer", 0);
1880 unp->unp_flags |= UNP_CONNECTING;
1881 UNP_PCB_UNLOCK(unp);
1883 connreq = (so->so_proto->pr_flags & PR_CONNREQUIRED) != 0;
1885 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1888 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1889 UIO_SYSSPACE, buf, fd, cap_rights_init_one(&rights, CAP_CONNECTAT));
1895 ASSERT_VOP_LOCKED(vp, "unp_connect");
1896 NDFREE_NOTHING(&nd);
1900 if (vp->v_type != VSOCK) {
1905 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1909 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1913 unp = sotounpcb(so);
1914 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1916 vplock = mtx_pool_find(mtxpool_sleep, vp);
1918 VOP_UNP_CONNECT(vp, &unp2);
1920 error = ECONNREFUSED;
1923 so2 = unp2->unp_socket;
1924 if (so->so_type != so2->so_type) {
1929 if (SOLISTENING(so2)) {
1930 CURVNET_SET(so2->so_vnet);
1931 so2 = sonewconn(so2, 0);
1936 error = ECONNREFUSED;
1939 unp3 = sotounpcb(so2);
1940 unp_pcb_lock_pair(unp2, unp3);
1941 if (unp2->unp_addr != NULL) {
1942 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1943 unp3->unp_addr = (struct sockaddr_un *) sa;
1947 unp_copy_peercred(td, unp3, unp, unp2);
1949 UNP_PCB_UNLOCK(unp2);
1953 * It is safe to block on the PCB lock here since unp2 is
1954 * nascent and cannot be connected to any other sockets.
1958 mac_socketpeer_set_from_socket(so, so2);
1959 mac_socketpeer_set_from_socket(so2, so);
1962 unp_pcb_lock_pair(unp, unp2);
1964 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1965 sotounpcb(so2) == unp2,
1966 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1967 unp_connect2(so, so2, PRU_CONNECT);
1968 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1969 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1970 unp->unp_flags &= ~UNP_CONNECTING;
1972 unp_pcb_unlock_pair(unp, unp2);
1978 * If we are returning locked (called via uipc_sosend_dgram()),
1979 * we need to be sure that vput() won't sleep. This is
1980 * guaranteed by VOP_UNP_CONNECT() call above and unp2 lock.
1981 * SOCK_STREAM/SEQPACKET can't request return_locked (yet).
1983 MPASS(!(return_locked && connreq));
1987 if (__predict_false(error)) {
1989 KASSERT((unp->unp_flags & UNP_CONNECTING) != 0,
1990 ("%s: unp %p has UNP_CONNECTING clear", __func__, unp));
1991 unp->unp_flags &= ~UNP_CONNECTING;
1992 UNP_PCB_UNLOCK(unp);
1998 * Set socket peer credentials at connection time.
2000 * The client's PCB credentials are copied from its process structure. The
2001 * server's PCB credentials are copied from the socket on which it called
2002 * listen(2). uipc_listen cached that process's credentials at the time.
2005 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
2006 struct unpcb *server_unp, struct unpcb *listen_unp)
2008 cru2xt(td, &client_unp->unp_peercred);
2009 client_unp->unp_flags |= UNP_HAVEPC;
2011 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
2012 sizeof(server_unp->unp_peercred));
2013 server_unp->unp_flags |= UNP_HAVEPC;
2014 client_unp->unp_flags |= (listen_unp->unp_flags & UNP_WANTCRED_MASK);
2018 unp_connect2(struct socket *so, struct socket *so2, int req)
2023 MPASS(so2->so_type == so->so_type);
2024 unp = sotounpcb(so);
2025 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
2026 unp2 = sotounpcb(so2);
2027 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
2029 UNP_PCB_LOCK_ASSERT(unp);
2030 UNP_PCB_LOCK_ASSERT(unp2);
2031 KASSERT(unp->unp_conn == NULL,
2032 ("%s: socket %p is already connected", __func__, unp));
2034 unp->unp_conn = unp2;
2037 switch (so->so_type) {
2039 UNP_REF_LIST_LOCK();
2040 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
2041 UNP_REF_LIST_UNLOCK();
2046 case SOCK_SEQPACKET:
2047 KASSERT(unp2->unp_conn == NULL,
2048 ("%s: socket %p is already connected", __func__, unp2));
2049 unp2->unp_conn = unp;
2050 if (req == PRU_CONNECT &&
2051 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
2059 panic("unp_connect2");
2064 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
2066 struct socket *so, *so2;
2068 struct unpcb *unptmp;
2071 UNP_PCB_LOCK_ASSERT(unp);
2072 UNP_PCB_LOCK_ASSERT(unp2);
2073 KASSERT(unp->unp_conn == unp2,
2074 ("%s: unpcb %p is not connected to %p", __func__, unp, unp2));
2076 unp->unp_conn = NULL;
2077 so = unp->unp_socket;
2078 so2 = unp2->unp_socket;
2079 switch (unp->unp_socket->so_type) {
2081 UNP_REF_LIST_LOCK();
2083 LIST_FOREACH(unptmp, &unp2->unp_refs, unp_reflink) {
2087 KASSERT(unptmp != NULL,
2088 ("%s: %p not found in reflist of %p", __func__, unp, unp2));
2090 LIST_REMOVE(unp, unp_reflink);
2091 UNP_REF_LIST_UNLOCK();
2094 so->so_state &= ~SS_ISCONNECTED;
2100 case SOCK_SEQPACKET:
2102 soisdisconnected(so);
2103 MPASS(unp2->unp_conn == unp);
2104 unp2->unp_conn = NULL;
2106 soisdisconnected(so2);
2111 unp_pcb_rele_notlast(unp);
2112 if (!unp_pcb_rele(unp))
2113 UNP_PCB_UNLOCK(unp);
2115 if (!unp_pcb_rele(unp))
2116 UNP_PCB_UNLOCK(unp);
2117 if (!unp_pcb_rele(unp2))
2118 UNP_PCB_UNLOCK(unp2);
2123 * unp_pcblist() walks the global list of struct unpcb's to generate a
2124 * pointer list, bumping the refcount on each unpcb. It then copies them out
2125 * sequentially, validating the generation number on each to see if it has
2126 * been detached. All of this is necessary because copyout() may sleep on
2130 unp_pcblist(SYSCTL_HANDLER_ARGS)
2132 struct unpcb *unp, **unp_list;
2134 struct xunpgen *xug;
2135 struct unp_head *head;
2140 switch ((intptr_t)arg1) {
2149 case SOCK_SEQPACKET:
2154 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
2158 * The process of preparing the PCB list is too time-consuming and
2159 * resource-intensive to repeat twice on every request.
2161 if (req->oldptr == NULL) {
2163 req->oldidx = 2 * (sizeof *xug)
2164 + (n + n/8) * sizeof(struct xunpcb);
2168 if (req->newptr != NULL)
2172 * OK, now we're committed to doing something.
2174 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK | M_ZERO);
2176 gencnt = unp_gencnt;
2180 xug->xug_len = sizeof *xug;
2182 xug->xug_gen = gencnt;
2183 xug->xug_sogen = so_gencnt;
2184 error = SYSCTL_OUT(req, xug, sizeof *xug);
2190 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
2193 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
2194 unp = LIST_NEXT(unp, unp_link)) {
2196 if (unp->unp_gencnt <= gencnt) {
2197 if (cr_cansee(req->td->td_ucred,
2198 unp->unp_socket->so_cred)) {
2199 UNP_PCB_UNLOCK(unp);
2202 unp_list[i++] = unp;
2205 UNP_PCB_UNLOCK(unp);
2208 n = i; /* In case we lost some during malloc. */
2211 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
2212 for (i = 0; i < n; i++) {
2215 if (unp_pcb_rele(unp))
2218 if (unp->unp_gencnt <= gencnt) {
2219 xu->xu_len = sizeof *xu;
2220 xu->xu_unpp = (uintptr_t)unp;
2222 * XXX - need more locking here to protect against
2223 * connect/disconnect races for SMP.
2225 if (unp->unp_addr != NULL)
2226 bcopy(unp->unp_addr, &xu->xu_addr,
2227 unp->unp_addr->sun_len);
2229 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
2230 if (unp->unp_conn != NULL &&
2231 unp->unp_conn->unp_addr != NULL)
2232 bcopy(unp->unp_conn->unp_addr,
2234 unp->unp_conn->unp_addr->sun_len);
2236 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
2237 xu->unp_vnode = (uintptr_t)unp->unp_vnode;
2238 xu->unp_conn = (uintptr_t)unp->unp_conn;
2239 xu->xu_firstref = (uintptr_t)LIST_FIRST(&unp->unp_refs);
2240 xu->xu_nextref = (uintptr_t)LIST_NEXT(unp, unp_reflink);
2241 xu->unp_gencnt = unp->unp_gencnt;
2242 sotoxsocket(unp->unp_socket, &xu->xu_socket);
2243 UNP_PCB_UNLOCK(unp);
2244 error = SYSCTL_OUT(req, xu, sizeof *xu);
2246 UNP_PCB_UNLOCK(unp);
2252 * Give the user an updated idea of our state. If the
2253 * generation differs from what we told her before, she knows
2254 * that something happened while we were processing this
2255 * request, and it might be necessary to retry.
2257 xug->xug_gen = unp_gencnt;
2258 xug->xug_sogen = so_gencnt;
2259 xug->xug_count = unp_count;
2260 error = SYSCTL_OUT(req, xug, sizeof *xug);
2262 free(unp_list, M_TEMP);
2267 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist,
2268 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2269 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
2270 "List of active local datagram sockets");
2271 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist,
2272 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2273 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
2274 "List of active local stream sockets");
2275 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
2276 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2277 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
2278 "List of active local seqpacket sockets");
2281 unp_shutdown(struct unpcb *unp)
2286 UNP_PCB_LOCK_ASSERT(unp);
2288 unp2 = unp->unp_conn;
2289 if ((unp->unp_socket->so_type == SOCK_STREAM ||
2290 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
2291 so = unp2->unp_socket;
2298 unp_drop(struct unpcb *unp)
2304 * Regardless of whether the socket's peer dropped the connection
2305 * with this socket by aborting or disconnecting, POSIX requires
2306 * that ECONNRESET is returned.
2310 so = unp->unp_socket;
2312 so->so_error = ECONNRESET;
2313 if ((unp2 = unp_pcb_lock_peer(unp)) != NULL) {
2314 /* Last reference dropped in unp_disconnect(). */
2315 unp_pcb_rele_notlast(unp);
2316 unp_disconnect(unp, unp2);
2317 } else if (!unp_pcb_rele(unp)) {
2318 UNP_PCB_UNLOCK(unp);
2323 unp_freerights(struct filedescent **fdep, int fdcount)
2328 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
2330 for (i = 0; i < fdcount; i++) {
2331 fp = fdep[i]->fde_file;
2332 filecaps_free(&fdep[i]->fde_caps);
2335 free(fdep[0], M_FILECAPS);
2339 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
2341 struct thread *td = curthread; /* XXX */
2342 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
2345 struct filedesc *fdesc = td->td_proc->p_fd;
2346 struct filedescent **fdep;
2348 socklen_t clen = control->m_len, datalen;
2352 UNP_LINK_UNLOCK_ASSERT();
2355 if (controlp != NULL) /* controlp == NULL => free control messages */
2357 while (cm != NULL) {
2358 MPASS(clen >= sizeof(*cm) && clen >= cm->cmsg_len);
2360 data = CMSG_DATA(cm);
2361 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
2362 if (cm->cmsg_level == SOL_SOCKET
2363 && cm->cmsg_type == SCM_RIGHTS) {
2364 newfds = datalen / sizeof(*fdep);
2369 /* If we're not outputting the descriptors free them. */
2370 if (error || controlp == NULL) {
2371 unp_freerights(fdep, newfds);
2374 FILEDESC_XLOCK(fdesc);
2377 * Now change each pointer to an fd in the global
2378 * table to an integer that is the index to the local
2379 * fd table entry that we set up to point to the
2380 * global one we are transferring.
2382 newlen = newfds * sizeof(int);
2383 *controlp = sbcreatecontrol(NULL, newlen,
2384 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2387 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2388 if (fdallocn(td, 0, fdp, newfds) != 0) {
2389 FILEDESC_XUNLOCK(fdesc);
2391 unp_freerights(fdep, newfds);
2396 for (i = 0; i < newfds; i++, fdp++) {
2397 _finstall(fdesc, fdep[i]->fde_file, *fdp,
2398 (flags & MSG_CMSG_CLOEXEC) != 0 ? O_CLOEXEC : 0,
2399 &fdep[i]->fde_caps);
2400 unp_externalize_fp(fdep[i]->fde_file);
2404 * The new type indicates that the mbuf data refers to
2405 * kernel resources that may need to be released before
2406 * the mbuf is freed.
2408 m_chtype(*controlp, MT_EXTCONTROL);
2409 FILEDESC_XUNLOCK(fdesc);
2410 free(fdep[0], M_FILECAPS);
2412 /* We can just copy anything else across. */
2413 if (error || controlp == NULL)
2415 *controlp = sbcreatecontrol(NULL, datalen,
2416 cm->cmsg_type, cm->cmsg_level, M_WAITOK);
2418 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
2421 controlp = &(*controlp)->m_next;
2424 if (CMSG_SPACE(datalen) < clen) {
2425 clen -= CMSG_SPACE(datalen);
2426 cm = (struct cmsghdr *)
2427 ((caddr_t)cm + CMSG_SPACE(datalen));
2439 unp_zone_change(void *tag)
2442 uma_zone_set_max(unp_zone, maxsockets);
2447 unp_zdtor(void *mem, int size __unused, void *arg __unused)
2453 KASSERT(LIST_EMPTY(&unp->unp_refs),
2454 ("%s: unpcb %p has lingering refs", __func__, unp));
2455 KASSERT(unp->unp_socket == NULL,
2456 ("%s: unpcb %p has socket backpointer", __func__, unp));
2457 KASSERT(unp->unp_vnode == NULL,
2458 ("%s: unpcb %p has vnode references", __func__, unp));
2459 KASSERT(unp->unp_conn == NULL,
2460 ("%s: unpcb %p is still connected", __func__, unp));
2461 KASSERT(unp->unp_addr == NULL,
2462 ("%s: unpcb %p has leaked addr", __func__, unp));
2467 unp_init(void *arg __unused)
2476 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, dtor,
2477 NULL, NULL, UMA_ALIGN_CACHE, 0);
2478 uma_zone_set_max(unp_zone, maxsockets);
2479 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
2480 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
2481 NULL, EVENTHANDLER_PRI_ANY);
2482 LIST_INIT(&unp_dhead);
2483 LIST_INIT(&unp_shead);
2484 LIST_INIT(&unp_sphead);
2485 SLIST_INIT(&unp_defers);
2486 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
2487 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
2488 UNP_LINK_LOCK_INIT();
2489 UNP_DEFERRED_LOCK_INIT();
2491 SYSINIT(unp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_SECOND, unp_init, NULL);
2494 unp_internalize_cleanup_rights(struct mbuf *control)
2501 for (m = control; m != NULL; m = m->m_next) {
2502 cp = mtod(m, struct cmsghdr *);
2503 if (cp->cmsg_level != SOL_SOCKET ||
2504 cp->cmsg_type != SCM_RIGHTS)
2506 data = CMSG_DATA(cp);
2507 datalen = (caddr_t)cp + cp->cmsg_len - (caddr_t)data;
2508 unp_freerights(data, datalen / sizeof(struct filedesc *));
2513 unp_internalize(struct mbuf **controlp, struct thread *td)
2515 struct mbuf *control, **initial_controlp;
2517 struct filedesc *fdesc;
2520 struct cmsgcred *cmcred;
2521 struct filedescent *fde, **fdep, *fdev;
2524 struct timespec *ts;
2526 socklen_t clen, datalen;
2527 int i, j, error, *fdp, oldfds;
2530 UNP_LINK_UNLOCK_ASSERT();
2535 control = *controlp;
2537 initial_controlp = controlp;
2538 for (clen = control->m_len, cm = mtod(control, struct cmsghdr *),
2539 data = CMSG_DATA(cm);
2541 clen >= sizeof(*cm) && cm->cmsg_level == SOL_SOCKET &&
2542 clen >= cm->cmsg_len && cm->cmsg_len >= sizeof(*cm) &&
2543 (char *)cm + cm->cmsg_len >= (char *)data;
2545 clen -= min(CMSG_SPACE(datalen), clen),
2546 cm = (struct cmsghdr *) ((char *)cm + CMSG_SPACE(datalen)),
2547 data = CMSG_DATA(cm)) {
2548 datalen = (char *)cm + cm->cmsg_len - (char *)data;
2549 switch (cm->cmsg_type) {
2551 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
2552 SCM_CREDS, SOL_SOCKET, M_WAITOK);
2553 cmcred = (struct cmsgcred *)
2554 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2555 cmcred->cmcred_pid = p->p_pid;
2556 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
2557 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
2558 cmcred->cmcred_euid = td->td_ucred->cr_uid;
2559 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
2561 for (i = 0; i < cmcred->cmcred_ngroups; i++)
2562 cmcred->cmcred_groups[i] =
2563 td->td_ucred->cr_groups[i];
2567 oldfds = datalen / sizeof (int);
2570 /* On some machines sizeof pointer is bigger than
2571 * sizeof int, so we need to check if data fits into
2572 * single mbuf. We could allocate several mbufs, and
2573 * unp_externalize() should even properly handle that.
2574 * But it is not worth to complicate the code for an
2575 * insane scenario of passing over 200 file descriptors
2578 newlen = oldfds * sizeof(fdep[0]);
2579 if (CMSG_SPACE(newlen) > MCLBYTES) {
2584 * Check that all the FDs passed in refer to legal
2585 * files. If not, reject the entire operation.
2588 FILEDESC_SLOCK(fdesc);
2589 for (i = 0; i < oldfds; i++, fdp++) {
2590 fp = fget_noref(fdesc, *fdp);
2592 FILEDESC_SUNLOCK(fdesc);
2596 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
2597 FILEDESC_SUNLOCK(fdesc);
2604 * Now replace the integer FDs with pointers to the
2605 * file structure and capability rights.
2607 *controlp = sbcreatecontrol(NULL, newlen,
2608 SCM_RIGHTS, SOL_SOCKET, M_WAITOK);
2610 for (i = 0; i < oldfds; i++, fdp++) {
2611 if (!fhold(fdesc->fd_ofiles[*fdp].fde_file)) {
2613 for (j = 0; j < i; j++, fdp++) {
2614 fdrop(fdesc->fd_ofiles[*fdp].
2617 FILEDESC_SUNLOCK(fdesc);
2623 fdep = (struct filedescent **)
2624 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2625 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2627 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2628 fde = &fdesc->fd_ofiles[*fdp];
2630 fdep[i]->fde_file = fde->fde_file;
2631 filecaps_copy(&fde->fde_caps,
2632 &fdep[i]->fde_caps, true);
2633 unp_internalize_fp(fdep[i]->fde_file);
2635 FILEDESC_SUNLOCK(fdesc);
2639 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2640 SCM_TIMESTAMP, SOL_SOCKET, M_WAITOK);
2641 tv = (struct timeval *)
2642 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2647 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2648 SCM_BINTIME, SOL_SOCKET, M_WAITOK);
2649 bt = (struct bintime *)
2650 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2655 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2656 SCM_REALTIME, SOL_SOCKET, M_WAITOK);
2657 ts = (struct timespec *)
2658 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2663 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2664 SCM_MONOTONIC, SOL_SOCKET, M_WAITOK);
2665 ts = (struct timespec *)
2666 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2675 controlp = &(*controlp)->m_next;
2681 if (error != 0 && initial_controlp != NULL)
2682 unp_internalize_cleanup_rights(*initial_controlp);
2687 static struct mbuf *
2688 unp_addsockcred(struct thread *td, struct mbuf *control, int mode)
2690 struct mbuf *m, *n, *n_prev;
2691 const struct cmsghdr *cm;
2692 int ngroups, i, cmsgtype;
2695 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2696 if (mode & UNP_WANTCRED_ALWAYS) {
2697 ctrlsz = SOCKCRED2SIZE(ngroups);
2698 cmsgtype = SCM_CREDS2;
2700 ctrlsz = SOCKCREDSIZE(ngroups);
2701 cmsgtype = SCM_CREDS;
2704 m = sbcreatecontrol(NULL, ctrlsz, cmsgtype, SOL_SOCKET, M_NOWAIT);
2708 if (mode & UNP_WANTCRED_ALWAYS) {
2709 struct sockcred2 *sc;
2711 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2713 sc->sc_pid = td->td_proc->p_pid;
2714 sc->sc_uid = td->td_ucred->cr_ruid;
2715 sc->sc_euid = td->td_ucred->cr_uid;
2716 sc->sc_gid = td->td_ucred->cr_rgid;
2717 sc->sc_egid = td->td_ucred->cr_gid;
2718 sc->sc_ngroups = ngroups;
2719 for (i = 0; i < sc->sc_ngroups; i++)
2720 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2722 struct sockcred *sc;
2724 sc = (void *)CMSG_DATA(mtod(m, struct cmsghdr *));
2725 sc->sc_uid = td->td_ucred->cr_ruid;
2726 sc->sc_euid = td->td_ucred->cr_uid;
2727 sc->sc_gid = td->td_ucred->cr_rgid;
2728 sc->sc_egid = td->td_ucred->cr_gid;
2729 sc->sc_ngroups = ngroups;
2730 for (i = 0; i < sc->sc_ngroups; i++)
2731 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2735 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2736 * created SCM_CREDS control message (struct sockcred) has another
2739 if (control != NULL && cmsgtype == SCM_CREDS)
2740 for (n = control, n_prev = NULL; n != NULL;) {
2741 cm = mtod(n, struct cmsghdr *);
2742 if (cm->cmsg_level == SOL_SOCKET &&
2743 cm->cmsg_type == SCM_CREDS) {
2745 control = n->m_next;
2747 n_prev->m_next = n->m_next;
2755 /* Prepend it to the head. */
2756 m->m_next = control;
2760 static struct unpcb *
2761 fptounp(struct file *fp)
2765 if (fp->f_type != DTYPE_SOCKET)
2767 if ((so = fp->f_data) == NULL)
2769 if (so->so_proto->pr_domain != &localdomain)
2771 return sotounpcb(so);
2775 unp_discard(struct file *fp)
2777 struct unp_defer *dr;
2779 if (unp_externalize_fp(fp)) {
2780 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2782 UNP_DEFERRED_LOCK();
2783 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2784 UNP_DEFERRED_UNLOCK();
2785 atomic_add_int(&unp_defers_count, 1);
2786 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2788 closef_nothread(fp);
2792 unp_process_defers(void *arg __unused, int pending)
2794 struct unp_defer *dr;
2795 SLIST_HEAD(, unp_defer) drl;
2800 UNP_DEFERRED_LOCK();
2801 if (SLIST_FIRST(&unp_defers) == NULL) {
2802 UNP_DEFERRED_UNLOCK();
2805 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2806 UNP_DEFERRED_UNLOCK();
2808 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2809 SLIST_REMOVE_HEAD(&drl, ud_link);
2810 closef_nothread(dr->ud_fp);
2814 atomic_add_int(&unp_defers_count, -count);
2819 unp_internalize_fp(struct file *fp)
2824 if ((unp = fptounp(fp)) != NULL) {
2826 unp->unp_msgcount++;
2833 unp_externalize_fp(struct file *fp)
2839 if ((unp = fptounp(fp)) != NULL) {
2840 unp->unp_msgcount--;
2850 * unp_defer indicates whether additional work has been defered for a future
2851 * pass through unp_gc(). It is thread local and does not require explicit
2854 static int unp_marked;
2857 unp_remove_dead_ref(struct filedescent **fdep, int fdcount)
2864 * This function can only be called from the gc task.
2866 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2867 ("%s: not on gc callout", __func__));
2868 UNP_LINK_LOCK_ASSERT();
2870 for (i = 0; i < fdcount; i++) {
2871 fp = fdep[i]->fde_file;
2872 if ((unp = fptounp(fp)) == NULL)
2874 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2881 unp_restore_undead_ref(struct filedescent **fdep, int fdcount)
2888 * This function can only be called from the gc task.
2890 KASSERT(taskqueue_member(taskqueue_thread, curthread) != 0,
2891 ("%s: not on gc callout", __func__));
2892 UNP_LINK_LOCK_ASSERT();
2894 for (i = 0; i < fdcount; i++) {
2895 fp = fdep[i]->fde_file;
2896 if ((unp = fptounp(fp)) == NULL)
2898 if ((unp->unp_gcflag & UNPGC_DEAD) == 0)
2906 unp_scan_socket(struct socket *so, void (*op)(struct filedescent **, int))
2909 SOCK_LOCK_ASSERT(so);
2911 if (sotounpcb(so)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2914 SOCK_RECVBUF_LOCK(so);
2915 switch (so->so_type) {
2917 unp_scan(STAILQ_FIRST(&so->so_rcv.uxdg_mb), op);
2920 case SOCK_SEQPACKET:
2921 unp_scan(so->so_rcv.sb_mb, op);
2924 SOCK_RECVBUF_UNLOCK(so);
2928 unp_gc_scan(struct unpcb *unp, void (*op)(struct filedescent **, int))
2930 struct socket *so, *soa;
2932 so = unp->unp_socket;
2934 if (SOLISTENING(so)) {
2936 * Mark all sockets in our accept queue.
2938 TAILQ_FOREACH(soa, &so->sol_comp, so_list)
2939 unp_scan_socket(soa, op);
2942 * Mark all sockets we reference with RIGHTS.
2944 unp_scan_socket(so, op);
2949 static int unp_recycled;
2950 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2951 "Number of unreachable sockets claimed by the garbage collector.");
2953 static int unp_taskcount;
2954 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2955 "Number of times the garbage collector has run.");
2957 SYSCTL_UINT(_net_local, OID_AUTO, sockcount, CTLFLAG_RD, &unp_count, 0,
2958 "Number of active local sockets.");
2961 unp_gc(__unused void *arg, int pending)
2963 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2965 struct unp_head **head;
2966 struct unp_head unp_deadhead; /* List of potentially-dead sockets. */
2967 struct file *f, **unref;
2968 struct unpcb *unp, *unptmp;
2969 int i, total, unp_unreachable;
2971 LIST_INIT(&unp_deadhead);
2975 * First determine which sockets may be in cycles.
2977 unp_unreachable = 0;
2979 for (head = heads; *head != NULL; head++)
2980 LIST_FOREACH(unp, *head, unp_link) {
2981 KASSERT((unp->unp_gcflag & ~UNPGC_IGNORE_RIGHTS) == 0,
2982 ("%s: unp %p has unexpected gc flags 0x%x",
2983 __func__, unp, (unsigned int)unp->unp_gcflag));
2988 * Check for an unreachable socket potentially in a
2989 * cycle. It must be in a queue as indicated by
2990 * msgcount, and this must equal the file reference
2991 * count. Note that when msgcount is 0 the file is
2994 if (f != NULL && unp->unp_msgcount != 0 &&
2995 refcount_load(&f->f_count) == unp->unp_msgcount) {
2996 LIST_INSERT_HEAD(&unp_deadhead, unp, unp_dead);
2997 unp->unp_gcflag |= UNPGC_DEAD;
2998 unp->unp_gcrefs = unp->unp_msgcount;
3004 * Scan all sockets previously marked as potentially being in a cycle
3005 * and remove the references each socket holds on any UNPGC_DEAD
3006 * sockets in its queue. After this step, all remaining references on
3007 * sockets marked UNPGC_DEAD should not be part of any cycle.
3009 LIST_FOREACH(unp, &unp_deadhead, unp_dead)
3010 unp_gc_scan(unp, unp_remove_dead_ref);
3013 * If a socket still has a non-negative refcount, it cannot be in a
3014 * cycle. In this case increment refcount of all children iteratively.
3015 * Stop the scan once we do a complete loop without discovering
3016 * a new reachable socket.
3020 LIST_FOREACH_SAFE(unp, &unp_deadhead, unp_dead, unptmp)
3021 if (unp->unp_gcrefs > 0) {
3022 unp->unp_gcflag &= ~UNPGC_DEAD;
3023 LIST_REMOVE(unp, unp_dead);
3024 KASSERT(unp_unreachable > 0,
3025 ("%s: unp_unreachable underflow.",
3028 unp_gc_scan(unp, unp_restore_undead_ref);
3030 } while (unp_marked);
3034 if (unp_unreachable == 0)
3038 * Allocate space for a local array of dead unpcbs.
3039 * TODO: can this path be simplified by instead using the local
3040 * dead list at unp_deadhead, after taking out references
3041 * on the file object and/or unpcb and dropping the link lock?
3043 unref = malloc(unp_unreachable * sizeof(struct file *),
3047 * Iterate looking for sockets which have been specifically marked
3048 * as unreachable and store them locally.
3052 LIST_FOREACH(unp, &unp_deadhead, unp_dead) {
3053 KASSERT((unp->unp_gcflag & UNPGC_DEAD) != 0,
3054 ("%s: unp %p not marked UNPGC_DEAD", __func__, unp));
3055 unp->unp_gcflag &= ~UNPGC_DEAD;
3057 if (unp->unp_msgcount == 0 || f == NULL ||
3058 refcount_load(&f->f_count) != unp->unp_msgcount ||
3062 KASSERT(total <= unp_unreachable,
3063 ("%s: incorrect unreachable count.", __func__));
3068 * Now flush all sockets, free'ing rights. This will free the
3069 * struct files associated with these sockets but leave each socket
3070 * with one remaining ref.
3072 for (i = 0; i < total; i++) {
3075 so = unref[i]->f_data;
3076 CURVNET_SET(so->so_vnet);
3082 * And finally release the sockets so they can be reclaimed.
3084 for (i = 0; i < total; i++)
3085 fdrop(unref[i], NULL);
3086 unp_recycled += total;
3087 free(unref, M_TEMP);
3091 * Synchronize against unp_gc, which can trip over data as we are freeing it.
3094 unp_dispose(struct socket *so)
3096 struct sockbuf *sb = &so->so_rcv;
3100 MPASS(!SOLISTENING(so));
3102 unp = sotounpcb(so);
3104 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
3108 * Grab our special mbufs before calling sbrelease().
3110 SOCK_RECVBUF_LOCK(so);
3111 switch (so->so_type) {
3113 m = STAILQ_FIRST(&sb->uxdg_mb);
3114 STAILQ_INIT(&sb->uxdg_mb);
3115 /* XXX: our shortened sbrelease() */
3116 (void)chgsbsize(so->so_cred->cr_uidinfo, &sb->sb_hiwat, 0,
3120 case SOCK_SEQPACKET:
3121 m = sbcut_locked(sb, sb->sb_ccc);
3122 KASSERT(sb->sb_ccc == 0 && sb->sb_mb == 0 && sb->sb_mbcnt == 0,
3123 ("%s: ccc %u mb %p mbcnt %u", __func__,
3124 sb->sb_ccc, (void *)sb->sb_mb, sb->sb_mbcnt));
3125 sbrelease_locked(so, SO_RCV);
3128 SOCK_RECVBUF_UNLOCK(so);
3129 if (SOCK_IO_RECV_OWNED(so))
3130 SOCK_IO_RECV_UNLOCK(so);
3133 unp_scan(m, unp_freerights);
3139 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
3144 socklen_t clen, datalen;
3146 while (m0 != NULL) {
3147 for (m = m0; m; m = m->m_next) {
3148 if (m->m_type != MT_CONTROL)
3151 cm = mtod(m, struct cmsghdr *);
3154 while (cm != NULL) {
3155 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
3158 data = CMSG_DATA(cm);
3159 datalen = (caddr_t)cm + cm->cmsg_len
3162 if (cm->cmsg_level == SOL_SOCKET &&
3163 cm->cmsg_type == SCM_RIGHTS) {
3164 (*op)(data, datalen /
3165 sizeof(struct filedescent *));
3168 if (CMSG_SPACE(datalen) < clen) {
3169 clen -= CMSG_SPACE(datalen);
3170 cm = (struct cmsghdr *)
3171 ((caddr_t)cm + CMSG_SPACE(datalen));
3183 * A helper function called by VFS before socket-type vnode reclamation.
3184 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
3188 vfs_unp_reclaim(struct vnode *vp)
3194 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
3195 KASSERT(vp->v_type == VSOCK,
3196 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
3199 vplock = mtx_pool_find(mtxpool_sleep, vp);
3201 VOP_UNP_CONNECT(vp, &unp);
3205 if (unp->unp_vnode == vp) {
3207 unp->unp_vnode = NULL;
3210 UNP_PCB_UNLOCK(unp);
3219 db_print_indent(int indent)
3223 for (i = 0; i < indent; i++)
3228 db_print_unpflags(int unp_flags)
3233 if (unp_flags & UNP_HAVEPC) {
3234 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
3237 if (unp_flags & UNP_WANTCRED_ALWAYS) {
3238 db_printf("%sUNP_WANTCRED_ALWAYS", comma ? ", " : "");
3241 if (unp_flags & UNP_WANTCRED_ONESHOT) {
3242 db_printf("%sUNP_WANTCRED_ONESHOT", comma ? ", " : "");
3245 if (unp_flags & UNP_CONNWAIT) {
3246 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
3249 if (unp_flags & UNP_CONNECTING) {
3250 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
3253 if (unp_flags & UNP_BINDING) {
3254 db_printf("%sUNP_BINDING", comma ? ", " : "");
3260 db_print_xucred(int indent, struct xucred *xu)
3264 db_print_indent(indent);
3265 db_printf("cr_version: %u cr_uid: %u cr_pid: %d cr_ngroups: %d\n",
3266 xu->cr_version, xu->cr_uid, xu->cr_pid, xu->cr_ngroups);
3267 db_print_indent(indent);
3268 db_printf("cr_groups: ");
3270 for (i = 0; i < xu->cr_ngroups; i++) {
3271 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
3278 db_print_unprefs(int indent, struct unp_head *uh)
3284 LIST_FOREACH(unp, uh, unp_reflink) {
3285 if (counter % 4 == 0)
3286 db_print_indent(indent);
3287 db_printf("%p ", unp);
3288 if (counter % 4 == 3)
3292 if (counter != 0 && counter % 4 != 0)
3296 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
3301 db_printf("usage: show unpcb <addr>\n");
3304 unp = (struct unpcb *)addr;
3306 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
3309 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
3312 db_printf("unp_refs:\n");
3313 db_print_unprefs(2, &unp->unp_refs);
3315 /* XXXRW: Would be nice to print the full address, if any. */
3316 db_printf("unp_addr: %p\n", unp->unp_addr);
3318 db_printf("unp_gencnt: %llu\n",
3319 (unsigned long long)unp->unp_gencnt);
3321 db_printf("unp_flags: %x (", unp->unp_flags);
3322 db_print_unpflags(unp->unp_flags);
3325 db_printf("unp_peercred:\n");
3326 db_print_xucred(2, &unp->unp_peercred);
3328 db_printf("unp_refcount: %u\n", unp->unp_refcount);