2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1989, 1991, 1993
5 * The Regents of the University of California.
6 * Copyright (c) 2004-2009 Robert N. M. Watson
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/fcntl.h>
69 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
70 #include <sys/eventhandler.h>
72 #include <sys/filedesc.h>
73 #include <sys/kernel.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);
110 * (l) Locked using list lock
111 * (g) Locked using linkage lock
114 static uma_zone_t unp_zone;
115 static unp_gen_t unp_gencnt; /* (l) */
116 static u_int unp_count; /* (l) Count of local sockets. */
117 static ino_t unp_ino; /* Prototype for fake inode numbers. */
118 static int unp_rights; /* (g) File descriptors in flight. */
119 static struct unp_head unp_shead; /* (l) List of stream sockets. */
120 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
121 static struct unp_head unp_sphead; /* (l) List of seqpacket sockets. */
124 SLIST_ENTRY(unp_defer) ud_link;
127 static SLIST_HEAD(, unp_defer) unp_defers;
128 static int unp_defers_count;
130 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
133 * Garbage collection of cyclic file descriptor/socket references occurs
134 * asynchronously in a taskqueue context in order to avoid recursion and
135 * reentrance in the UNIX domain socket, file descriptor, and socket layer
136 * code. See unp_gc() for a full description.
138 static struct timeout_task unp_gc_task;
141 * The close of unix domain sockets attached as SCM_RIGHTS is
142 * postponed to the taskqueue, to avoid arbitrary recursion depth.
143 * The attached sockets might have another sockets attached.
145 static struct task unp_defer_task;
148 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
149 * stream sockets, although the total for sender and receiver is actually
152 * Datagram sockets really use the sendspace as the maximum datagram size,
153 * and don't really want to reserve the sendspace. Their recvspace should be
154 * large enough for at least one max-size datagram plus address.
159 static u_long unpst_sendspace = PIPSIZ;
160 static u_long unpst_recvspace = PIPSIZ;
161 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
162 static u_long unpdg_recvspace = 4*1024;
163 static u_long unpsp_sendspace = PIPSIZ; /* really max datagram size */
164 static u_long unpsp_recvspace = PIPSIZ;
166 static SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
167 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
169 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
170 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
174 &unpst_sendspace, 0, "Default stream send space.");
175 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
176 &unpst_recvspace, 0, "Default stream receive space.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
178 &unpdg_sendspace, 0, "Default datagram send space.");
179 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
180 &unpdg_recvspace, 0, "Default datagram receive space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
182 &unpsp_sendspace, 0, "Default seqpacket send space.");
183 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
184 &unpsp_recvspace, 0, "Default seqpacket receive space.");
185 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
186 "File descriptors in flight.");
187 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
188 &unp_defers_count, 0,
189 "File descriptors deferred to taskqueue for close.");
192 * Locking and synchronization:
194 * Two types of locks exist in the local domain socket implementation: a
195 * a global linkage rwlock and per-unpcb mutexes. The linkage lock protects
196 * the socket count, global generation number, stream/datagram global lists and
197 * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
198 * held exclusively over the acquisition of multiple unpcb locks to prevent
201 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
202 * allocated in pru_attach() and freed in pru_detach(). The validity of that
203 * pointer is an invariant, so no lock is required to dereference the so_pcb
204 * pointer if a valid socket reference is held by the caller. In practice,
205 * this is always true during operations performed on a socket. Each unpcb
206 * has a back-pointer to its socket, unp_socket, which will be stable under
207 * the same circumstances.
209 * This pointer may only be safely dereferenced as long as a valid reference
210 * to the unpcb is held. Typically, this reference will be from the socket,
211 * or from another unpcb when the referring unpcb's lock is held (in order
212 * that the reference not be invalidated during use). For example, to follow
213 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
214 * as unp_socket remains valid as long as the reference to unp_conn is valid.
216 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
217 * atomic reads without the lock may be performed "lockless", but more
218 * complex reads and read-modify-writes require the mutex to be held. No
219 * lock order is defined between unpcb locks -- multiple unpcb locks may be
220 * acquired at the same time only when holding the linkage rwlock
221 * exclusively, which prevents deadlocks.
223 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
224 * protocols, bind() is a non-atomic operation, and connect() requires
225 * potential sleeping in the protocol, due to potentially waiting on local or
226 * distributed file systems. We try to separate "lookup" operations, which
227 * may sleep, and the IPC operations themselves, which typically can occur
228 * with relative atomicity as locks can be held over the entire operation.
230 * Another tricky issue is simultaneous multi-threaded or multi-process
231 * access to a single UNIX domain socket. These are handled by the flags
232 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
233 * binding, both of which involve dropping UNIX domain socket locks in order
234 * to perform namei() and other file system operations.
236 static struct rwlock unp_link_rwlock;
237 static struct mtx unp_defers_lock;
239 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
242 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
244 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
247 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
248 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
249 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
250 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
251 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
253 #define UNP_LINK_WOWNED() rw_wowned(&unp_link_rwlock)
255 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
256 "unp_defer", NULL, MTX_DEF)
257 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
258 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
260 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
261 "unp_mtx", "unp_mtx", \
262 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
263 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
264 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
265 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
266 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
268 static int uipc_connect2(struct socket *, struct socket *);
269 static int uipc_ctloutput(struct socket *, struct sockopt *);
270 static int unp_connect(struct socket *, struct sockaddr *,
272 static int unp_connectat(int, struct socket *, struct sockaddr *,
274 static int unp_connect2(struct socket *so, struct socket *so2, int);
275 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
276 static void unp_dispose(struct socket *so);
277 static void unp_dispose_mbuf(struct mbuf *);
278 static void unp_shutdown(struct unpcb *);
279 static void unp_drop(struct unpcb *);
280 static void unp_gc(__unused void *, int);
281 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
282 static void unp_discard(struct file *);
283 static void unp_freerights(struct filedescent **, int);
284 static void unp_init(void);
285 static int unp_internalize(struct mbuf **, struct thread *);
286 static void unp_internalize_fp(struct file *);
287 static int unp_externalize(struct mbuf *, struct mbuf **, int);
288 static int unp_externalize_fp(struct file *);
289 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
290 static void unp_process_defers(void * __unused, int);
293 * Definitions of protocols supported in the LOCAL domain.
295 static struct domain localdomain;
296 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
297 static struct pr_usrreqs uipc_usrreqs_seqpacket;
298 static struct protosw localsw[] = {
300 .pr_type = SOCK_STREAM,
301 .pr_domain = &localdomain,
302 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
303 .pr_ctloutput = &uipc_ctloutput,
304 .pr_usrreqs = &uipc_usrreqs_stream
307 .pr_type = SOCK_DGRAM,
308 .pr_domain = &localdomain,
309 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
310 .pr_ctloutput = &uipc_ctloutput,
311 .pr_usrreqs = &uipc_usrreqs_dgram
314 .pr_type = SOCK_SEQPACKET,
315 .pr_domain = &localdomain,
318 * XXXRW: For now, PR_ADDR because soreceive will bump into them
319 * due to our use of sbappendaddr. A new sbappend variants is needed
320 * that supports both atomic record writes and control data.
322 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
324 .pr_ctloutput = &uipc_ctloutput,
325 .pr_usrreqs = &uipc_usrreqs_seqpacket,
329 static struct domain localdomain = {
330 .dom_family = AF_LOCAL,
332 .dom_init = unp_init,
333 .dom_externalize = unp_externalize,
334 .dom_dispose = unp_dispose,
335 .dom_protosw = localsw,
336 .dom_protoswNPROTOSW = &localsw[nitems(localsw)]
341 uipc_abort(struct socket *so)
343 struct unpcb *unp, *unp2;
346 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
350 unp2 = unp->unp_conn;
354 UNP_PCB_UNLOCK(unp2);
361 uipc_accept(struct socket *so, struct sockaddr **nam)
363 struct unpcb *unp, *unp2;
364 const struct sockaddr *sa;
367 * Pass back name of connected socket, if it was bound and we are
368 * still connected (our peer may have closed already!).
371 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
373 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
375 unp2 = unp->unp_conn;
376 if (unp2 != NULL && unp2->unp_addr != NULL) {
378 sa = (struct sockaddr *) unp2->unp_addr;
379 bcopy(sa, *nam, sa->sa_len);
380 UNP_PCB_UNLOCK(unp2);
383 bcopy(sa, *nam, sa->sa_len);
390 uipc_attach(struct socket *so, int proto, struct thread *td)
392 u_long sendspace, recvspace;
397 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
398 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
399 switch (so->so_type) {
401 sendspace = unpst_sendspace;
402 recvspace = unpst_recvspace;
406 sendspace = unpdg_sendspace;
407 recvspace = unpdg_recvspace;
411 sendspace = unpsp_sendspace;
412 recvspace = unpsp_recvspace;
416 panic("uipc_attach");
418 error = soreserve(so, sendspace, recvspace);
422 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
425 LIST_INIT(&unp->unp_refs);
426 UNP_PCB_LOCK_INIT(unp);
427 unp->unp_socket = so;
429 unp->unp_refcount = 1;
430 if (so->so_listen != NULL)
431 unp->unp_flags |= UNP_NASCENT;
433 if ((locked = UNP_LINK_WOWNED()) == false)
436 unp->unp_gencnt = ++unp_gencnt;
438 switch (so->so_type) {
440 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
444 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
448 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
452 panic("uipc_attach");
462 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
464 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
474 if (nam->sa_family != AF_UNIX)
475 return (EAFNOSUPPORT);
478 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
480 if (soun->sun_len > sizeof(struct sockaddr_un))
482 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
487 * We don't allow simultaneous bind() calls on a single UNIX domain
488 * socket, so flag in-progress operations, and return an error if an
489 * operation is already in progress.
491 * Historically, we have not allowed a socket to be rebound, so this
492 * also returns an error. Not allowing re-binding simplifies the
493 * implementation and avoids a great many possible failure modes.
496 if (unp->unp_vnode != NULL) {
500 if (unp->unp_flags & UNP_BINDING) {
504 unp->unp_flags |= UNP_BINDING;
507 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
508 bcopy(soun->sun_path, buf, namelen);
512 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
513 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
514 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
519 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
520 NDFREE(&nd, NDF_ONLY_PNBUF);
530 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
536 vattr.va_type = VSOCK;
537 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
539 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
543 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
544 NDFREE(&nd, NDF_ONLY_PNBUF);
547 vn_finished_write(mp);
551 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
552 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
556 VOP_UNP_BIND(vp, unp);
558 unp->unp_addr = soun;
559 unp->unp_flags &= ~UNP_BINDING;
563 vn_finished_write(mp);
569 unp->unp_flags &= ~UNP_BINDING;
576 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
579 return (uipc_bindat(AT_FDCWD, so, nam, td));
583 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
587 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
589 error = unp_connect(so, nam, td);
595 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
600 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
602 error = unp_connectat(fd, so, nam, td);
608 uipc_close(struct socket *so)
610 struct unpcb *unp, *unp2;
611 struct vnode *vp = NULL;
614 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
618 unp2 = unp->unp_conn;
621 unp_disconnect(unp, unp2);
622 UNP_PCB_UNLOCK(unp2);
624 if (SOLISTENING(so) && ((vp = unp->unp_vnode) != NULL)) {
626 unp->unp_vnode = NULL;
635 uipc_connect2(struct socket *so1, struct socket *so2)
637 struct unpcb *unp, *unp2;
642 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
645 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
647 error = unp_connect2(so1, so2, PRU_CONNECT2);
648 UNP_PCB_UNLOCK(unp2);
655 uipc_detach(struct socket *so)
657 struct unpcb *unp, *unp2;
658 struct sockaddr_un *saved_unp_addr;
660 int freeunp, local_unp_rights;
663 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
666 local_unp_rights = 0;
669 LIST_REMOVE(unp, unp_link);
670 unp->unp_gencnt = ++unp_gencnt;
673 if ((unp->unp_flags & UNP_NASCENT) != 0)
676 if ((vp = unp->unp_vnode) != NULL) {
678 unp->unp_vnode = NULL;
680 unp2 = unp->unp_conn;
683 unp_disconnect(unp, unp2);
684 UNP_PCB_UNLOCK(unp2);
688 * We hold the linkage lock exclusively, so it's OK to acquire
689 * multiple pcb locks at a time.
691 while (!LIST_EMPTY(&unp->unp_refs)) {
692 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
698 local_unp_rights = unp_rights;
701 unp->unp_socket->so_pcb = NULL;
702 saved_unp_addr = unp->unp_addr;
703 unp->unp_addr = NULL;
705 freeunp = (unp->unp_refcount == 0);
706 if (saved_unp_addr != NULL)
707 free(saved_unp_addr, M_SONAME);
709 UNP_PCB_LOCK_DESTROY(unp);
710 uma_zfree(unp_zone, unp);
715 if (local_unp_rights)
716 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
720 uipc_disconnect(struct socket *so)
722 struct unpcb *unp, *unp2;
725 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
729 unp2 = unp->unp_conn;
732 unp_disconnect(unp, unp2);
733 UNP_PCB_UNLOCK(unp2);
741 uipc_listen(struct socket *so, int backlog, struct thread *td)
746 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
750 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
753 if (unp->unp_vnode == NULL) {
754 /* Already connected or not bound to an address. */
755 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
761 error = solisten_proto_check(so);
763 cru2x(td->td_ucred, &unp->unp_peercred);
764 solisten_proto(so, backlog);
772 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
774 struct unpcb *unp, *unp2;
775 const struct sockaddr *sa;
778 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
780 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
783 * XXX: It seems that this test always fails even when connection is
784 * established. So, this else clause is added as workaround to
785 * return PF_LOCAL sockaddr.
787 unp2 = unp->unp_conn;
790 if (unp2->unp_addr != NULL)
791 sa = (struct sockaddr *) unp2->unp_addr;
794 bcopy(sa, *nam, sa->sa_len);
795 UNP_PCB_UNLOCK(unp2);
798 bcopy(sa, *nam, sa->sa_len);
805 uipc_rcvd(struct socket *so, int flags)
807 struct unpcb *unp, *unp2;
812 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
813 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
814 ("%s: socktype %d", __func__, so->so_type));
817 * Adjust backpressure on sender and wakeup any waiting to write.
819 * The unp lock is acquired to maintain the validity of the unp_conn
820 * pointer; no lock on unp2 is required as unp2->unp_socket will be
821 * static as long as we don't permit unp2 to disconnect from unp,
822 * which is prevented by the lock on unp. We cache values from
823 * so_rcv to avoid holding the so_rcv lock over the entire
824 * transaction on the remote so_snd.
826 SOCKBUF_LOCK(&so->so_rcv);
827 mbcnt = so->so_rcv.sb_mbcnt;
828 sbcc = sbavail(&so->so_rcv);
829 SOCKBUF_UNLOCK(&so->so_rcv);
831 * There is a benign race condition at this point. If we're planning to
832 * clear SB_STOP, but uipc_send is called on the connected socket at
833 * this instant, it might add data to the sockbuf and set SB_STOP. Then
834 * we would erroneously clear SB_STOP below, even though the sockbuf is
835 * full. The race is benign because the only ill effect is to allow the
836 * sockbuf to exceed its size limit, and the size limits are not
837 * strictly guaranteed anyway.
840 unp2 = unp->unp_conn;
845 so2 = unp2->unp_socket;
846 SOCKBUF_LOCK(&so2->so_snd);
847 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
848 so2->so_snd.sb_flags &= ~SB_STOP;
849 sowwakeup_locked(so2);
855 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
856 struct mbuf *control, struct thread *td)
858 struct unpcb *unp, *unp2;
864 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
865 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
866 so->so_type == SOCK_SEQPACKET,
867 ("%s: socktype %d", __func__, so->so_type));
869 if (flags & PRUS_OOB) {
873 if (control != NULL && (error = unp_internalize(&control, td)))
875 if ((nam != NULL) || (flags & PRUS_EOF))
879 switch (so->so_type) {
882 const struct sockaddr *from;
884 unp2 = unp->unp_conn;
886 UNP_LINK_WLOCK_ASSERT();
891 error = unp_connect(so, nam, td);
894 unp2 = unp->unp_conn;
898 * Because connect() and send() are non-atomic in a sendto()
899 * with a target address, it's possible that the socket will
900 * have disconnected before the send() can run. In that case
901 * return the slightly counter-intuitive but otherwise
902 * correct error that the socket is not connected.
909 if (unp2->unp_flags & UNP_WANTCRED)
910 control = unp_addsockcred(td, control);
912 if (unp->unp_addr != NULL)
913 from = (struct sockaddr *)unp->unp_addr;
916 so2 = unp2->unp_socket;
917 SOCKBUF_LOCK(&so2->so_rcv);
918 if (sbappendaddr_locked(&so2->so_rcv, from, m,
920 sorwakeup_locked(so2);
924 SOCKBUF_UNLOCK(&so2->so_rcv);
928 UNP_LINK_WLOCK_ASSERT();
930 unp_disconnect(unp, unp2);
931 UNP_PCB_UNLOCK(unp2);
939 if ((so->so_state & SS_ISCONNECTED) == 0) {
941 UNP_LINK_WLOCK_ASSERT();
942 error = unp_connect(so, nam, td);
952 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
958 * Because connect() and send() are non-atomic in a sendto()
959 * with a target address, it's possible that the socket will
960 * have disconnected before the send() can run. In that case
961 * return the slightly counter-intuitive but otherwise
962 * correct error that the socket is not connected.
964 * Locking here must be done carefully: the linkage lock
965 * prevents interconnections between unpcbs from changing, so
966 * we can traverse from unp to unp2 without acquiring unp's
967 * lock. Socket buffer locks follow unpcb locks, so we can
968 * acquire both remote and lock socket buffer locks.
970 unp2 = unp->unp_conn;
975 so2 = unp2->unp_socket;
977 SOCKBUF_LOCK(&so2->so_rcv);
978 if (unp2->unp_flags & UNP_WANTCRED) {
980 * Credentials are passed only once on SOCK_STREAM
981 * and SOCK_SEQPACKET.
983 unp2->unp_flags &= ~UNP_WANTCRED;
984 control = unp_addsockcred(td, control);
987 * Send to paired receive port, and then reduce send buffer
988 * hiwater marks to maintain backpressure. Wake up readers.
990 switch (so->so_type) {
992 if (control != NULL) {
993 if (sbappendcontrol_locked(&so2->so_rcv, m,
997 sbappend_locked(&so2->so_rcv, m, flags);
1000 case SOCK_SEQPACKET: {
1001 const struct sockaddr *from;
1005 * Don't check for space available in so2->so_rcv.
1006 * Unix domain sockets only check for space in the
1007 * sending sockbuf, and that check is performed one
1008 * level up the stack.
1010 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1017 mbcnt = so2->so_rcv.sb_mbcnt;
1018 sbcc = sbavail(&so2->so_rcv);
1020 sorwakeup_locked(so2);
1022 SOCKBUF_UNLOCK(&so2->so_rcv);
1025 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1026 * it would be possible for uipc_rcvd to be called at this
1027 * point, drain the receiving sockbuf, clear SB_STOP, and then
1028 * we would set SB_STOP below. That could lead to an empty
1029 * sockbuf having SB_STOP set
1031 SOCKBUF_LOCK(&so->so_snd);
1032 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1033 so->so_snd.sb_flags |= SB_STOP;
1034 SOCKBUF_UNLOCK(&so->so_snd);
1035 UNP_PCB_UNLOCK(unp2);
1041 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1043 if (flags & PRUS_EOF) {
1047 UNP_PCB_UNLOCK(unp);
1050 if ((nam != NULL) || (flags & PRUS_EOF))
1055 if (control != NULL && error != 0)
1056 unp_dispose_mbuf(control);
1059 if (control != NULL)
1062 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1063 * for freeing memory.
1065 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1071 uipc_ready(struct socket *so, struct mbuf *m, int count)
1073 struct unpcb *unp, *unp2;
1077 unp = sotounpcb(so);
1080 if ((unp2 = unp->unp_conn) == NULL) {
1082 for (int i = 0; i < count; i++)
1084 return (ECONNRESET);
1087 so2 = unp2->unp_socket;
1089 SOCKBUF_LOCK(&so2->so_rcv);
1090 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1091 sorwakeup_locked(so2);
1093 SOCKBUF_UNLOCK(&so2->so_rcv);
1095 UNP_PCB_UNLOCK(unp2);
1102 uipc_sense(struct socket *so, struct stat *sb)
1106 unp = sotounpcb(so);
1107 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1109 sb->st_blksize = so->so_snd.sb_hiwat;
1112 if (unp->unp_ino == 0)
1113 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1114 sb->st_ino = unp->unp_ino;
1115 UNP_PCB_UNLOCK(unp);
1120 uipc_shutdown(struct socket *so)
1124 unp = sotounpcb(so);
1125 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1131 UNP_PCB_UNLOCK(unp);
1137 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1140 const struct sockaddr *sa;
1142 unp = sotounpcb(so);
1143 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1145 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1147 if (unp->unp_addr != NULL)
1148 sa = (struct sockaddr *) unp->unp_addr;
1151 bcopy(sa, *nam, sa->sa_len);
1152 UNP_PCB_UNLOCK(unp);
1156 static struct pr_usrreqs uipc_usrreqs_dgram = {
1157 .pru_abort = uipc_abort,
1158 .pru_accept = uipc_accept,
1159 .pru_attach = uipc_attach,
1160 .pru_bind = uipc_bind,
1161 .pru_bindat = uipc_bindat,
1162 .pru_connect = uipc_connect,
1163 .pru_connectat = uipc_connectat,
1164 .pru_connect2 = uipc_connect2,
1165 .pru_detach = uipc_detach,
1166 .pru_disconnect = uipc_disconnect,
1167 .pru_listen = uipc_listen,
1168 .pru_peeraddr = uipc_peeraddr,
1169 .pru_rcvd = uipc_rcvd,
1170 .pru_send = uipc_send,
1171 .pru_sense = uipc_sense,
1172 .pru_shutdown = uipc_shutdown,
1173 .pru_sockaddr = uipc_sockaddr,
1174 .pru_soreceive = soreceive_dgram,
1175 .pru_close = uipc_close,
1178 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1179 .pru_abort = uipc_abort,
1180 .pru_accept = uipc_accept,
1181 .pru_attach = uipc_attach,
1182 .pru_bind = uipc_bind,
1183 .pru_bindat = uipc_bindat,
1184 .pru_connect = uipc_connect,
1185 .pru_connectat = uipc_connectat,
1186 .pru_connect2 = uipc_connect2,
1187 .pru_detach = uipc_detach,
1188 .pru_disconnect = uipc_disconnect,
1189 .pru_listen = uipc_listen,
1190 .pru_peeraddr = uipc_peeraddr,
1191 .pru_rcvd = uipc_rcvd,
1192 .pru_send = uipc_send,
1193 .pru_sense = uipc_sense,
1194 .pru_shutdown = uipc_shutdown,
1195 .pru_sockaddr = uipc_sockaddr,
1196 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1197 .pru_close = uipc_close,
1200 static struct pr_usrreqs uipc_usrreqs_stream = {
1201 .pru_abort = uipc_abort,
1202 .pru_accept = uipc_accept,
1203 .pru_attach = uipc_attach,
1204 .pru_bind = uipc_bind,
1205 .pru_bindat = uipc_bindat,
1206 .pru_connect = uipc_connect,
1207 .pru_connectat = uipc_connectat,
1208 .pru_connect2 = uipc_connect2,
1209 .pru_detach = uipc_detach,
1210 .pru_disconnect = uipc_disconnect,
1211 .pru_listen = uipc_listen,
1212 .pru_peeraddr = uipc_peeraddr,
1213 .pru_rcvd = uipc_rcvd,
1214 .pru_send = uipc_send,
1215 .pru_ready = uipc_ready,
1216 .pru_sense = uipc_sense,
1217 .pru_shutdown = uipc_shutdown,
1218 .pru_sockaddr = uipc_sockaddr,
1219 .pru_soreceive = soreceive_generic,
1220 .pru_close = uipc_close,
1224 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1230 if (sopt->sopt_level != 0)
1233 unp = sotounpcb(so);
1234 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1236 switch (sopt->sopt_dir) {
1238 switch (sopt->sopt_name) {
1239 case LOCAL_PEERCRED:
1241 if (unp->unp_flags & UNP_HAVEPC)
1242 xu = unp->unp_peercred;
1244 if (so->so_type == SOCK_STREAM)
1249 UNP_PCB_UNLOCK(unp);
1251 error = sooptcopyout(sopt, &xu, sizeof(xu));
1255 /* Unlocked read. */
1256 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1257 error = sooptcopyout(sopt, &optval, sizeof(optval));
1260 case LOCAL_CONNWAIT:
1261 /* Unlocked read. */
1262 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1263 error = sooptcopyout(sopt, &optval, sizeof(optval));
1273 switch (sopt->sopt_name) {
1275 case LOCAL_CONNWAIT:
1276 error = sooptcopyin(sopt, &optval, sizeof(optval),
1281 #define OPTSET(bit) do { \
1282 UNP_PCB_LOCK(unp); \
1284 unp->unp_flags |= bit; \
1286 unp->unp_flags &= ~bit; \
1287 UNP_PCB_UNLOCK(unp); \
1290 switch (sopt->sopt_name) {
1292 OPTSET(UNP_WANTCRED);
1295 case LOCAL_CONNWAIT:
1296 OPTSET(UNP_CONNWAIT);
1305 error = ENOPROTOOPT;
1318 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1321 return (unp_connectat(AT_FDCWD, so, nam, td));
1325 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1328 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1331 struct unpcb *unp, *unp2, *unp3;
1332 struct nameidata nd;
1333 char buf[SOCK_MAXADDRLEN];
1334 struct sockaddr *sa;
1335 cap_rights_t rights;
1338 if (nam->sa_family != AF_UNIX)
1339 return (EAFNOSUPPORT);
1341 UNP_LINK_WLOCK_ASSERT();
1343 unp = sotounpcb(so);
1344 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1346 if (nam->sa_len > sizeof(struct sockaddr_un))
1348 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1351 bcopy(soun->sun_path, buf, len);
1355 if (unp->unp_flags & UNP_CONNECTING) {
1356 UNP_PCB_UNLOCK(unp);
1360 unp->unp_flags |= UNP_CONNECTING;
1361 UNP_PCB_UNLOCK(unp);
1363 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1364 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1365 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1371 ASSERT_VOP_LOCKED(vp, "unp_connect");
1372 NDFREE(&nd, NDF_ONLY_PNBUF);
1376 if (vp->v_type != VSOCK) {
1381 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1385 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1389 unp = sotounpcb(so);
1390 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1393 * Lock linkage lock for two reasons: make sure v_socket is stable,
1394 * and to protect simultaneous locking of multiple pcbs.
1397 VOP_UNP_CONNECT(vp, &unp2);
1399 error = ECONNREFUSED;
1402 so2 = unp2->unp_socket;
1403 if (so->so_type != so2->so_type) {
1409 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1410 if (so2->so_options & SO_ACCEPTCONN) {
1411 CURVNET_SET(so2->so_vnet);
1412 so2 = sonewconn(so2, 0);
1417 error = ECONNREFUSED;
1420 unp3 = sotounpcb(so2);
1422 if (unp2->unp_addr != NULL) {
1423 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1424 unp3->unp_addr = (struct sockaddr_un *) sa;
1429 * The connector's (client's) credentials are copied from its
1430 * process structure at the time of connect() (which is now).
1432 cru2x(td->td_ucred, &unp3->unp_peercred);
1433 unp3->unp_flags |= UNP_HAVEPC;
1436 * The receiver's (server's) credentials are copied from the
1437 * unp_peercred member of socket on which the former called
1438 * listen(); uipc_listen() cached that process's credentials
1439 * at that time so we can use them now.
1441 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1442 sizeof(unp->unp_peercred));
1443 unp->unp_flags |= UNP_HAVEPC;
1444 if (unp2->unp_flags & UNP_WANTCRED)
1445 unp3->unp_flags |= UNP_WANTCRED;
1446 UNP_PCB_UNLOCK(unp2);
1449 mac_socketpeer_set_from_socket(so, so2);
1450 mac_socketpeer_set_from_socket(so2, so);
1454 KASSERT(unp2 != NULL && so2 != NULL && unp2->unp_socket == so2 &&
1455 sotounpcb(so2) == unp2,
1456 ("%s: unp2 %p so2 %p", __func__, unp2, so2));
1457 error = unp_connect2(so, so2, PRU_CONNECT);
1459 UNP_PCB_UNLOCK(unp2);
1460 UNP_PCB_UNLOCK(unp);
1469 unp->unp_flags &= ~UNP_CONNECTING;
1470 UNP_PCB_UNLOCK(unp);
1475 unp_connect2(struct socket *so, struct socket *so2, int req)
1480 unp = sotounpcb(so);
1481 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1482 unp2 = sotounpcb(so2);
1483 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1485 UNP_LINK_WLOCK_ASSERT();
1486 UNP_PCB_LOCK_ASSERT(unp);
1487 UNP_PCB_LOCK_ASSERT(unp2);
1489 if (so2->so_type != so->so_type)
1490 return (EPROTOTYPE);
1491 unp2->unp_flags &= ~UNP_NASCENT;
1492 unp->unp_conn = unp2;
1494 switch (so->so_type) {
1496 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1501 case SOCK_SEQPACKET:
1502 unp2->unp_conn = unp;
1503 if (req == PRU_CONNECT &&
1504 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1512 panic("unp_connect2");
1518 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1522 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1524 UNP_LINK_WLOCK_ASSERT();
1525 UNP_PCB_LOCK_ASSERT(unp);
1526 UNP_PCB_LOCK_ASSERT(unp2);
1528 unp->unp_conn = NULL;
1529 switch (unp->unp_socket->so_type) {
1531 LIST_REMOVE(unp, unp_reflink);
1532 so = unp->unp_socket;
1534 so->so_state &= ~SS_ISCONNECTED;
1539 case SOCK_SEQPACKET:
1540 soisdisconnected(unp->unp_socket);
1541 unp2->unp_conn = NULL;
1542 soisdisconnected(unp2->unp_socket);
1548 * unp_pcblist() walks the global list of struct unpcb's to generate a
1549 * pointer list, bumping the refcount on each unpcb. It then copies them out
1550 * sequentially, validating the generation number on each to see if it has
1551 * been detached. All of this is necessary because copyout() may sleep on
1555 unp_pcblist(SYSCTL_HANDLER_ARGS)
1557 struct unpcb *unp, **unp_list;
1559 struct xunpgen *xug;
1560 struct unp_head *head;
1563 int error, freeunp, n;
1565 switch ((intptr_t)arg1) {
1574 case SOCK_SEQPACKET:
1579 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1583 * The process of preparing the PCB list is too time-consuming and
1584 * resource-intensive to repeat twice on every request.
1586 if (req->oldptr == NULL) {
1588 req->oldidx = 2 * (sizeof *xug)
1589 + (n + n/8) * sizeof(struct xunpcb);
1593 if (req->newptr != NULL)
1597 * OK, now we're committed to doing something.
1599 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1601 gencnt = unp_gencnt;
1605 xug->xug_len = sizeof *xug;
1607 xug->xug_gen = gencnt;
1608 xug->xug_sogen = so_gencnt;
1609 error = SYSCTL_OUT(req, xug, sizeof *xug);
1615 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1618 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1619 unp = LIST_NEXT(unp, unp_link)) {
1621 if (unp->unp_gencnt <= gencnt) {
1622 if (cr_cansee(req->td->td_ucred,
1623 unp->unp_socket->so_cred)) {
1624 UNP_PCB_UNLOCK(unp);
1627 unp_list[i++] = unp;
1628 unp->unp_refcount++;
1630 UNP_PCB_UNLOCK(unp);
1633 n = i; /* In case we lost some during malloc. */
1636 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1637 for (i = 0; i < n; i++) {
1640 unp->unp_refcount--;
1641 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1642 xu->xu_len = sizeof *xu;
1645 * XXX - need more locking here to protect against
1646 * connect/disconnect races for SMP.
1648 if (unp->unp_addr != NULL)
1649 bcopy(unp->unp_addr, &xu->xu_addr,
1650 unp->unp_addr->sun_len);
1652 bzero(&xu->xu_addr, sizeof(xu->xu_addr));
1653 if (unp->unp_conn != NULL &&
1654 unp->unp_conn->unp_addr != NULL)
1655 bcopy(unp->unp_conn->unp_addr,
1657 unp->unp_conn->unp_addr->sun_len);
1659 bzero(&xu->xu_caddr, sizeof(xu->xu_caddr));
1660 xu->unp_vnode = unp->unp_vnode;
1661 xu->unp_conn = unp->unp_conn;
1662 xu->xu_firstref = LIST_FIRST(&unp->unp_refs);
1663 xu->xu_nextref = LIST_NEXT(unp, unp_reflink);
1664 xu->unp_gencnt = unp->unp_gencnt;
1665 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1666 UNP_PCB_UNLOCK(unp);
1667 error = SYSCTL_OUT(req, xu, sizeof *xu);
1669 freeunp = (unp->unp_refcount == 0);
1670 UNP_PCB_UNLOCK(unp);
1672 UNP_PCB_LOCK_DESTROY(unp);
1673 uma_zfree(unp_zone, unp);
1680 * Give the user an updated idea of our state. If the
1681 * generation differs from what we told her before, she knows
1682 * that something happened while we were processing this
1683 * request, and it might be necessary to retry.
1685 xug->xug_gen = unp_gencnt;
1686 xug->xug_sogen = so_gencnt;
1687 xug->xug_count = unp_count;
1688 error = SYSCTL_OUT(req, xug, sizeof *xug);
1690 free(unp_list, M_TEMP);
1695 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1696 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1697 "List of active local datagram sockets");
1698 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1699 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1700 "List of active local stream sockets");
1701 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1702 CTLTYPE_OPAQUE | CTLFLAG_RD,
1703 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1704 "List of active local seqpacket sockets");
1707 unp_shutdown(struct unpcb *unp)
1712 UNP_LINK_WLOCK_ASSERT();
1713 UNP_PCB_LOCK_ASSERT(unp);
1715 unp2 = unp->unp_conn;
1716 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1717 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1718 so = unp2->unp_socket;
1725 unp_drop(struct unpcb *unp)
1727 struct socket *so = unp->unp_socket;
1730 UNP_LINK_WLOCK_ASSERT();
1731 UNP_PCB_LOCK_ASSERT(unp);
1734 * Regardless of whether the socket's peer dropped the connection
1735 * with this socket by aborting or disconnecting, POSIX requires
1736 * that ECONNRESET is returned.
1738 so->so_error = ECONNRESET;
1739 unp2 = unp->unp_conn;
1743 unp_disconnect(unp, unp2);
1744 UNP_PCB_UNLOCK(unp2);
1748 unp_freerights(struct filedescent **fdep, int fdcount)
1753 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1755 for (i = 0; i < fdcount; i++) {
1756 fp = fdep[i]->fde_file;
1757 filecaps_free(&fdep[i]->fde_caps);
1760 free(fdep[0], M_FILECAPS);
1764 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1766 struct thread *td = curthread; /* XXX */
1767 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1770 struct filedesc *fdesc = td->td_proc->p_fd;
1771 struct filedescent **fdep;
1773 socklen_t clen = control->m_len, datalen;
1777 UNP_LINK_UNLOCK_ASSERT();
1780 if (controlp != NULL) /* controlp == NULL => free control messages */
1782 while (cm != NULL) {
1783 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1787 data = CMSG_DATA(cm);
1788 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1789 if (cm->cmsg_level == SOL_SOCKET
1790 && cm->cmsg_type == SCM_RIGHTS) {
1791 newfds = datalen / sizeof(*fdep);
1796 /* If we're not outputting the descriptors free them. */
1797 if (error || controlp == NULL) {
1798 unp_freerights(fdep, newfds);
1801 FILEDESC_XLOCK(fdesc);
1804 * Now change each pointer to an fd in the global
1805 * table to an integer that is the index to the local
1806 * fd table entry that we set up to point to the
1807 * global one we are transferring.
1809 newlen = newfds * sizeof(int);
1810 *controlp = sbcreatecontrol(NULL, newlen,
1811 SCM_RIGHTS, SOL_SOCKET);
1812 if (*controlp == NULL) {
1813 FILEDESC_XUNLOCK(fdesc);
1815 unp_freerights(fdep, newfds);
1820 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1821 if (fdallocn(td, 0, fdp, newfds) != 0) {
1822 FILEDESC_XUNLOCK(fdesc);
1824 unp_freerights(fdep, newfds);
1829 for (i = 0; i < newfds; i++, fdp++) {
1830 _finstall(fdesc, fdep[i]->fde_file, *fdp,
1831 (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
1832 &fdep[i]->fde_caps);
1833 unp_externalize_fp(fdep[i]->fde_file);
1835 FILEDESC_XUNLOCK(fdesc);
1836 free(fdep[0], M_FILECAPS);
1838 /* We can just copy anything else across. */
1839 if (error || controlp == NULL)
1841 *controlp = sbcreatecontrol(NULL, datalen,
1842 cm->cmsg_type, cm->cmsg_level);
1843 if (*controlp == NULL) {
1848 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1851 controlp = &(*controlp)->m_next;
1854 if (CMSG_SPACE(datalen) < clen) {
1855 clen -= CMSG_SPACE(datalen);
1856 cm = (struct cmsghdr *)
1857 ((caddr_t)cm + CMSG_SPACE(datalen));
1869 unp_zone_change(void *tag)
1872 uma_zone_set_max(unp_zone, maxsockets);
1880 if (!IS_DEFAULT_VNET(curvnet))
1883 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1884 NULL, NULL, UMA_ALIGN_PTR, 0);
1885 if (unp_zone == NULL)
1887 uma_zone_set_max(unp_zone, maxsockets);
1888 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
1889 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1890 NULL, EVENTHANDLER_PRI_ANY);
1891 LIST_INIT(&unp_dhead);
1892 LIST_INIT(&unp_shead);
1893 LIST_INIT(&unp_sphead);
1894 SLIST_INIT(&unp_defers);
1895 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
1896 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1897 UNP_LINK_LOCK_INIT();
1898 UNP_DEFERRED_LOCK_INIT();
1902 unp_internalize(struct mbuf **controlp, struct thread *td)
1904 struct mbuf *control = *controlp;
1905 struct proc *p = td->td_proc;
1906 struct filedesc *fdesc = p->p_fd;
1908 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1909 struct cmsgcred *cmcred;
1910 struct filedescent *fde, **fdep, *fdev;
1913 struct timespec *ts;
1916 socklen_t clen = control->m_len, datalen;
1920 UNP_LINK_UNLOCK_ASSERT();
1924 while (cm != NULL) {
1925 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1926 || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
1930 data = CMSG_DATA(cm);
1931 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1933 switch (cm->cmsg_type) {
1935 * Fill in credential information.
1938 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1939 SCM_CREDS, SOL_SOCKET);
1940 if (*controlp == NULL) {
1944 cmcred = (struct cmsgcred *)
1945 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1946 cmcred->cmcred_pid = p->p_pid;
1947 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1948 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1949 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1950 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1952 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1953 cmcred->cmcred_groups[i] =
1954 td->td_ucred->cr_groups[i];
1958 oldfds = datalen / sizeof (int);
1962 * Check that all the FDs passed in refer to legal
1963 * files. If not, reject the entire operation.
1966 FILEDESC_SLOCK(fdesc);
1967 for (i = 0; i < oldfds; i++, fdp++) {
1968 fp = fget_locked(fdesc, *fdp);
1970 FILEDESC_SUNLOCK(fdesc);
1974 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1975 FILEDESC_SUNLOCK(fdesc);
1983 * Now replace the integer FDs with pointers to the
1984 * file structure and capability rights.
1986 newlen = oldfds * sizeof(fdep[0]);
1987 *controlp = sbcreatecontrol(NULL, newlen,
1988 SCM_RIGHTS, SOL_SOCKET);
1989 if (*controlp == NULL) {
1990 FILEDESC_SUNLOCK(fdesc);
1995 fdep = (struct filedescent **)
1996 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1997 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
1999 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2000 fde = &fdesc->fd_ofiles[*fdp];
2002 fdep[i]->fde_file = fde->fde_file;
2003 filecaps_copy(&fde->fde_caps,
2004 &fdep[i]->fde_caps, true);
2005 unp_internalize_fp(fdep[i]->fde_file);
2007 FILEDESC_SUNLOCK(fdesc);
2011 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2012 SCM_TIMESTAMP, SOL_SOCKET);
2013 if (*controlp == NULL) {
2017 tv = (struct timeval *)
2018 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2023 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2024 SCM_BINTIME, SOL_SOCKET);
2025 if (*controlp == NULL) {
2029 bt = (struct bintime *)
2030 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2035 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2036 SCM_REALTIME, SOL_SOCKET);
2037 if (*controlp == NULL) {
2041 ts = (struct timespec *)
2042 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2047 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2048 SCM_MONOTONIC, SOL_SOCKET);
2049 if (*controlp == NULL) {
2053 ts = (struct timespec *)
2054 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2063 controlp = &(*controlp)->m_next;
2064 if (CMSG_SPACE(datalen) < clen) {
2065 clen -= CMSG_SPACE(datalen);
2066 cm = (struct cmsghdr *)
2067 ((caddr_t)cm + CMSG_SPACE(datalen));
2079 static struct mbuf *
2080 unp_addsockcred(struct thread *td, struct mbuf *control)
2082 struct mbuf *m, *n, *n_prev;
2083 struct sockcred *sc;
2084 const struct cmsghdr *cm;
2088 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2089 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2093 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2094 sc->sc_uid = td->td_ucred->cr_ruid;
2095 sc->sc_euid = td->td_ucred->cr_uid;
2096 sc->sc_gid = td->td_ucred->cr_rgid;
2097 sc->sc_egid = td->td_ucred->cr_gid;
2098 sc->sc_ngroups = ngroups;
2099 for (i = 0; i < sc->sc_ngroups; i++)
2100 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2103 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2104 * created SCM_CREDS control message (struct sockcred) has another
2107 if (control != NULL)
2108 for (n = control, n_prev = NULL; n != NULL;) {
2109 cm = mtod(n, struct cmsghdr *);
2110 if (cm->cmsg_level == SOL_SOCKET &&
2111 cm->cmsg_type == SCM_CREDS) {
2113 control = n->m_next;
2115 n_prev->m_next = n->m_next;
2123 /* Prepend it to the head. */
2124 m->m_next = control;
2128 static struct unpcb *
2129 fptounp(struct file *fp)
2133 if (fp->f_type != DTYPE_SOCKET)
2135 if ((so = fp->f_data) == NULL)
2137 if (so->so_proto->pr_domain != &localdomain)
2139 return sotounpcb(so);
2143 unp_discard(struct file *fp)
2145 struct unp_defer *dr;
2147 if (unp_externalize_fp(fp)) {
2148 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2150 UNP_DEFERRED_LOCK();
2151 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2152 UNP_DEFERRED_UNLOCK();
2153 atomic_add_int(&unp_defers_count, 1);
2154 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2156 (void) closef(fp, (struct thread *)NULL);
2160 unp_process_defers(void *arg __unused, int pending)
2162 struct unp_defer *dr;
2163 SLIST_HEAD(, unp_defer) drl;
2168 UNP_DEFERRED_LOCK();
2169 if (SLIST_FIRST(&unp_defers) == NULL) {
2170 UNP_DEFERRED_UNLOCK();
2173 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2174 UNP_DEFERRED_UNLOCK();
2176 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2177 SLIST_REMOVE_HEAD(&drl, ud_link);
2178 closef(dr->ud_fp, NULL);
2182 atomic_add_int(&unp_defers_count, -count);
2187 unp_internalize_fp(struct file *fp)
2192 if ((unp = fptounp(fp)) != NULL) {
2194 unp->unp_msgcount++;
2202 unp_externalize_fp(struct file *fp)
2208 if ((unp = fptounp(fp)) != NULL) {
2209 unp->unp_msgcount--;
2219 * unp_defer indicates whether additional work has been defered for a future
2220 * pass through unp_gc(). It is thread local and does not require explicit
2223 static int unp_marked;
2224 static int unp_unreachable;
2227 unp_accessable(struct filedescent **fdep, int fdcount)
2233 for (i = 0; i < fdcount; i++) {
2234 fp = fdep[i]->fde_file;
2235 if ((unp = fptounp(fp)) == NULL)
2237 if (unp->unp_gcflag & UNPGC_REF)
2239 unp->unp_gcflag &= ~UNPGC_DEAD;
2240 unp->unp_gcflag |= UNPGC_REF;
2246 unp_gc_process(struct unpcb *unp)
2248 struct socket *so, *soa;
2251 /* Already processed. */
2252 if (unp->unp_gcflag & UNPGC_SCANNED)
2257 * Check for a socket potentially in a cycle. It must be in a
2258 * queue as indicated by msgcount, and this must equal the file
2259 * reference count. Note that when msgcount is 0 the file is NULL.
2261 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2262 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2263 unp->unp_gcflag |= UNPGC_DEAD;
2268 so = unp->unp_socket;
2270 if (SOLISTENING(so)) {
2272 * Mark all sockets in our accept queue.
2274 TAILQ_FOREACH(soa, &so->sol_comp, so_list) {
2275 if (sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS)
2277 SOCKBUF_LOCK(&soa->so_rcv);
2278 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2279 SOCKBUF_UNLOCK(&soa->so_rcv);
2283 * Mark all sockets we reference with RIGHTS.
2285 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2286 SOCKBUF_LOCK(&so->so_rcv);
2287 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2288 SOCKBUF_UNLOCK(&so->so_rcv);
2292 unp->unp_gcflag |= UNPGC_SCANNED;
2295 static int unp_recycled;
2296 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2297 "Number of unreachable sockets claimed by the garbage collector.");
2299 static int unp_taskcount;
2300 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2301 "Number of times the garbage collector has run.");
2304 unp_gc(__unused void *arg, int pending)
2306 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2308 struct unp_head **head;
2309 struct file *f, **unref;
2316 * First clear all gc flags from previous runs, apart from
2317 * UNPGC_IGNORE_RIGHTS.
2319 for (head = heads; *head != NULL; head++)
2320 LIST_FOREACH(unp, *head, unp_link)
2322 (unp->unp_gcflag & UNPGC_IGNORE_RIGHTS);
2325 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2326 * is reachable all of the sockets it references are reachable.
2327 * Stop the scan once we do a complete loop without discovering
2328 * a new reachable socket.
2331 unp_unreachable = 0;
2333 for (head = heads; *head != NULL; head++)
2334 LIST_FOREACH(unp, *head, unp_link)
2335 unp_gc_process(unp);
2336 } while (unp_marked);
2338 if (unp_unreachable == 0)
2342 * Allocate space for a local list of dead unpcbs.
2344 unref = malloc(unp_unreachable * sizeof(struct file *),
2348 * Iterate looking for sockets which have been specifically marked
2349 * as as unreachable and store them locally.
2352 for (total = 0, head = heads; *head != NULL; head++)
2353 LIST_FOREACH(unp, *head, unp_link)
2354 if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2356 if (unp->unp_msgcount == 0 || f == NULL ||
2357 f->f_count != unp->unp_msgcount)
2361 KASSERT(total <= unp_unreachable,
2362 ("unp_gc: incorrect unreachable count."));
2367 * Now flush all sockets, free'ing rights. This will free the
2368 * struct files associated with these sockets but leave each socket
2369 * with one remaining ref.
2371 for (i = 0; i < total; i++) {
2374 so = unref[i]->f_data;
2375 CURVNET_SET(so->so_vnet);
2381 * And finally release the sockets so they can be reclaimed.
2383 for (i = 0; i < total; i++)
2384 fdrop(unref[i], NULL);
2385 unp_recycled += total;
2386 free(unref, M_TEMP);
2390 unp_dispose_mbuf(struct mbuf *m)
2394 unp_scan(m, unp_freerights);
2398 * Synchronize against unp_gc, which can trip over data as we are freeing it.
2401 unp_dispose(struct socket *so)
2405 unp = sotounpcb(so);
2407 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2409 if (!SOLISTENING(so))
2410 unp_dispose_mbuf(so->so_rcv.sb_mb);
2414 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2419 socklen_t clen, datalen;
2421 while (m0 != NULL) {
2422 for (m = m0; m; m = m->m_next) {
2423 if (m->m_type != MT_CONTROL)
2426 cm = mtod(m, struct cmsghdr *);
2429 while (cm != NULL) {
2430 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2433 data = CMSG_DATA(cm);
2434 datalen = (caddr_t)cm + cm->cmsg_len
2437 if (cm->cmsg_level == SOL_SOCKET &&
2438 cm->cmsg_type == SCM_RIGHTS) {
2439 (*op)(data, datalen /
2440 sizeof(struct filedescent *));
2443 if (CMSG_SPACE(datalen) < clen) {
2444 clen -= CMSG_SPACE(datalen);
2445 cm = (struct cmsghdr *)
2446 ((caddr_t)cm + CMSG_SPACE(datalen));
2458 * A helper function called by VFS before socket-type vnode reclamation.
2459 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2463 vfs_unp_reclaim(struct vnode *vp)
2468 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2469 KASSERT(vp->v_type == VSOCK,
2470 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2474 VOP_UNP_CONNECT(vp, &unp);
2478 if (unp->unp_vnode == vp) {
2480 unp->unp_vnode = NULL;
2483 UNP_PCB_UNLOCK(unp);
2492 db_print_indent(int indent)
2496 for (i = 0; i < indent; i++)
2501 db_print_unpflags(int unp_flags)
2506 if (unp_flags & UNP_HAVEPC) {
2507 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2510 if (unp_flags & UNP_WANTCRED) {
2511 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2514 if (unp_flags & UNP_CONNWAIT) {
2515 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2518 if (unp_flags & UNP_CONNECTING) {
2519 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2522 if (unp_flags & UNP_BINDING) {
2523 db_printf("%sUNP_BINDING", comma ? ", " : "");
2529 db_print_xucred(int indent, struct xucred *xu)
2533 db_print_indent(indent);
2534 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2535 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2536 db_print_indent(indent);
2537 db_printf("cr_groups: ");
2539 for (i = 0; i < xu->cr_ngroups; i++) {
2540 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2547 db_print_unprefs(int indent, struct unp_head *uh)
2553 LIST_FOREACH(unp, uh, unp_reflink) {
2554 if (counter % 4 == 0)
2555 db_print_indent(indent);
2556 db_printf("%p ", unp);
2557 if (counter % 4 == 3)
2561 if (counter != 0 && counter % 4 != 0)
2565 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2570 db_printf("usage: show unpcb <addr>\n");
2573 unp = (struct unpcb *)addr;
2575 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2578 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2581 db_printf("unp_refs:\n");
2582 db_print_unprefs(2, &unp->unp_refs);
2584 /* XXXRW: Would be nice to print the full address, if any. */
2585 db_printf("unp_addr: %p\n", unp->unp_addr);
2587 db_printf("unp_gencnt: %llu\n",
2588 (unsigned long long)unp->unp_gencnt);
2590 db_printf("unp_flags: %x (", unp->unp_flags);
2591 db_print_unpflags(unp->unp_flags);
2594 db_printf("unp_peercred:\n");
2595 db_print_xucred(2, &unp->unp_peercred);
2597 db_printf("unp_refcount: %u\n", unp->unp_refcount);