2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004-2009 Robert N. M. Watson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
35 * UNIX Domain (Local) Sockets
37 * This is an implementation of UNIX (local) domain sockets. Each socket has
38 * an associated struct unpcb (UNIX protocol control block). Stream sockets
39 * may be connected to 0 or 1 other socket. Datagram sockets may be
40 * connected to 0, 1, or many other sockets. Sockets may be created and
41 * connected in pairs (socketpair(2)), or bound/connected to using the file
42 * system name space. For most purposes, only the receive socket buffer is
43 * used, as sending on one socket delivers directly to the receive socket
44 * buffer of a second socket.
46 * The implementation is substantially complicated by the fact that
47 * "ancillary data", such as file descriptors or credentials, may be passed
48 * across UNIX domain sockets. The potential for passing UNIX domain sockets
49 * over other UNIX domain sockets requires the implementation of a simple
50 * garbage collector to find and tear down cycles of disconnected sockets.
54 * rethink name space problems
55 * need a proper out-of-band
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
63 #include <sys/param.h>
64 #include <sys/capsicum.h>
65 #include <sys/domain.h>
66 #include <sys/fcntl.h>
67 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
68 #include <sys/eventhandler.h>
70 #include <sys/filedesc.h>
71 #include <sys/kernel.h>
74 #include <sys/mount.h>
75 #include <sys/mutex.h>
76 #include <sys/namei.h>
78 #include <sys/protosw.h>
79 #include <sys/queue.h>
80 #include <sys/resourcevar.h>
81 #include <sys/rwlock.h>
82 #include <sys/socket.h>
83 #include <sys/socketvar.h>
84 #include <sys/signalvar.h>
87 #include <sys/sysctl.h>
88 #include <sys/systm.h>
89 #include <sys/taskqueue.h>
91 #include <sys/unpcb.h>
92 #include <sys/vnode.h>
100 #include <security/mac/mac_framework.h>
104 MALLOC_DECLARE(M_FILECAPS);
108 * (l) Locked using list lock
109 * (g) Locked using linkage lock
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_sendspace = 2*1024; /* really max datagram size */
160 static u_long unpdg_recvspace = 4*1024;
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, 0, "Local domain");
165 static SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0,
167 static SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
168 static SYSCTL_NODE(_net_local, SOCK_SEQPACKET, seqpacket, CTLFLAG_RW, 0,
171 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
172 &unpst_sendspace, 0, "Default stream send space.");
173 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
174 &unpst_recvspace, 0, "Default stream receive space.");
175 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
176 &unpdg_sendspace, 0, "Default datagram send space.");
177 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
178 &unpdg_recvspace, 0, "Default datagram receive space.");
179 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, maxseqpacket, CTLFLAG_RW,
180 &unpsp_sendspace, 0, "Default seqpacket send space.");
181 SYSCTL_ULONG(_net_local_seqpacket, OID_AUTO, recvspace, CTLFLAG_RW,
182 &unpsp_recvspace, 0, "Default seqpacket receive space.");
183 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
184 "File descriptors in flight.");
185 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
186 &unp_defers_count, 0,
187 "File descriptors deferred to taskqueue for close.");
190 * Locking and synchronization:
192 * Three types of locks exit in the local domain socket implementation: a
193 * global list mutex, a global linkage rwlock, and per-unpcb mutexes. Of the
194 * global locks, the list lock protects the socket count, global generation
195 * number, and stream/datagram global lists. The linkage lock protects the
196 * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
197 * held exclusively over the acquisition of multiple unpcb locks to prevent
200 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
201 * allocated in pru_attach() and freed in pru_detach(). The validity of that
202 * pointer is an invariant, so no lock is required to dereference the so_pcb
203 * pointer if a valid socket reference is held by the caller. In practice,
204 * this is always true during operations performed on a socket. Each unpcb
205 * has a back-pointer to its socket, unp_socket, which will be stable under
206 * the same circumstances.
208 * This pointer may only be safely dereferenced as long as a valid reference
209 * to the unpcb is held. Typically, this reference will be from the socket,
210 * or from another unpcb when the referring unpcb's lock is held (in order
211 * that the reference not be invalidated during use). For example, to follow
212 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
213 * as unp_socket remains valid as long as the reference to unp_conn is valid.
215 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
216 * atomic reads without the lock may be performed "lockless", but more
217 * complex reads and read-modify-writes require the mutex to be held. No
218 * lock order is defined between unpcb locks -- multiple unpcb locks may be
219 * acquired at the same time only when holding the linkage rwlock
220 * exclusively, which prevents deadlocks.
222 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
223 * protocols, bind() is a non-atomic operation, and connect() requires
224 * potential sleeping in the protocol, due to potentially waiting on local or
225 * distributed file systems. We try to separate "lookup" operations, which
226 * may sleep, and the IPC operations themselves, which typically can occur
227 * with relative atomicity as locks can be held over the entire operation.
229 * Another tricky issue is simultaneous multi-threaded or multi-process
230 * access to a single UNIX domain socket. These are handled by the flags
231 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
232 * binding, both of which involve dropping UNIX domain socket locks in order
233 * to perform namei() and other file system operations.
235 static struct rwlock unp_link_rwlock;
236 static struct mtx unp_list_lock;
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, \
254 #define UNP_LIST_LOCK_INIT() mtx_init(&unp_list_lock, \
255 "unp_list_lock", NULL, MTX_DEF)
256 #define UNP_LIST_LOCK() mtx_lock(&unp_list_lock)
257 #define UNP_LIST_UNLOCK() mtx_unlock(&unp_list_lock)
259 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
260 "unp_defer", NULL, MTX_DEF)
261 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
262 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
264 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
265 "unp_mtx", "unp_mtx", \
266 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
267 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
268 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
269 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
270 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
272 static int uipc_connect2(struct socket *, struct socket *);
273 static int uipc_ctloutput(struct socket *, struct sockopt *);
274 static int unp_connect(struct socket *, struct sockaddr *,
276 static int unp_connectat(int, struct socket *, struct sockaddr *,
278 static int unp_connect2(struct socket *so, struct socket *so2, int);
279 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
280 static void unp_dispose(struct mbuf *);
281 static void unp_dispose_so(struct socket *so);
282 static void unp_shutdown(struct unpcb *);
283 static void unp_drop(struct unpcb *);
284 static void unp_gc(__unused void *, int);
285 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
286 static void unp_discard(struct file *);
287 static void unp_freerights(struct filedescent **, int);
288 static void unp_init(void);
289 static int unp_internalize(struct mbuf **, struct thread *);
290 static void unp_internalize_fp(struct file *);
291 static int unp_externalize(struct mbuf *, struct mbuf **, int);
292 static int unp_externalize_fp(struct file *);
293 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
294 static void unp_process_defers(void * __unused, int);
297 * Definitions of protocols supported in the LOCAL domain.
299 static struct domain localdomain;
300 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
301 static struct pr_usrreqs uipc_usrreqs_seqpacket;
302 static struct protosw localsw[] = {
304 .pr_type = SOCK_STREAM,
305 .pr_domain = &localdomain,
306 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
307 .pr_ctloutput = &uipc_ctloutput,
308 .pr_usrreqs = &uipc_usrreqs_stream
311 .pr_type = SOCK_DGRAM,
312 .pr_domain = &localdomain,
313 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
314 .pr_ctloutput = &uipc_ctloutput,
315 .pr_usrreqs = &uipc_usrreqs_dgram
318 .pr_type = SOCK_SEQPACKET,
319 .pr_domain = &localdomain,
322 * XXXRW: For now, PR_ADDR because soreceive will bump into them
323 * due to our use of sbappendaddr. A new sbappend variants is needed
324 * that supports both atomic record writes and control data.
326 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
328 .pr_ctloutput = &uipc_ctloutput,
329 .pr_usrreqs = &uipc_usrreqs_seqpacket,
333 static struct domain localdomain = {
334 .dom_family = AF_LOCAL,
336 .dom_init = unp_init,
337 .dom_externalize = unp_externalize,
338 .dom_dispose = unp_dispose_so,
339 .dom_protosw = localsw,
340 .dom_protoswNPROTOSW = &localsw[nitems(localsw)]
345 uipc_abort(struct socket *so)
347 struct unpcb *unp, *unp2;
350 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
354 unp2 = unp->unp_conn;
358 UNP_PCB_UNLOCK(unp2);
365 uipc_accept(struct socket *so, struct sockaddr **nam)
367 struct unpcb *unp, *unp2;
368 const struct sockaddr *sa;
371 * Pass back name of connected socket, if it was bound and we are
372 * still connected (our peer may have closed already!).
375 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
377 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
379 unp2 = unp->unp_conn;
380 if (unp2 != NULL && unp2->unp_addr != NULL) {
382 sa = (struct sockaddr *) unp2->unp_addr;
383 bcopy(sa, *nam, sa->sa_len);
384 UNP_PCB_UNLOCK(unp2);
387 bcopy(sa, *nam, sa->sa_len);
394 uipc_attach(struct socket *so, int proto, struct thread *td)
396 u_long sendspace, recvspace;
400 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
401 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
402 switch (so->so_type) {
404 sendspace = unpst_sendspace;
405 recvspace = unpst_recvspace;
409 sendspace = unpdg_sendspace;
410 recvspace = unpdg_recvspace;
414 sendspace = unpsp_sendspace;
415 recvspace = unpsp_recvspace;
419 panic("uipc_attach");
421 error = soreserve(so, sendspace, recvspace);
425 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
428 LIST_INIT(&unp->unp_refs);
429 UNP_PCB_LOCK_INIT(unp);
430 unp->unp_socket = so;
432 unp->unp_refcount = 1;
433 if (so->so_head != NULL)
434 unp->unp_flags |= UNP_NASCENT;
437 unp->unp_gencnt = ++unp_gencnt;
439 switch (so->so_type) {
441 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
445 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
449 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
453 panic("uipc_attach");
461 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
463 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
473 if (nam->sa_family != AF_UNIX)
474 return (EAFNOSUPPORT);
477 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
479 if (soun->sun_len > sizeof(struct sockaddr_un))
481 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
486 * We don't allow simultaneous bind() calls on a single UNIX domain
487 * socket, so flag in-progress operations, and return an error if an
488 * operation is already in progress.
490 * Historically, we have not allowed a socket to be rebound, so this
491 * also returns an error. Not allowing re-binding simplifies the
492 * implementation and avoids a great many possible failure modes.
495 if (unp->unp_vnode != NULL) {
499 if (unp->unp_flags & UNP_BINDING) {
503 unp->unp_flags |= UNP_BINDING;
506 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
507 bcopy(soun->sun_path, buf, namelen);
511 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME | NOCACHE,
512 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
513 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
518 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
519 NDFREE(&nd, NDF_ONLY_PNBUF);
529 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
535 vattr.va_type = VSOCK;
536 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
538 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
542 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
543 NDFREE(&nd, NDF_ONLY_PNBUF);
546 vn_finished_write(mp);
550 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
551 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
555 VOP_UNP_BIND(vp, unp->unp_socket);
557 unp->unp_addr = soun;
558 unp->unp_flags &= ~UNP_BINDING;
562 vn_finished_write(mp);
568 unp->unp_flags &= ~UNP_BINDING;
575 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
578 return (uipc_bindat(AT_FDCWD, so, nam, td));
582 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
586 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
588 error = unp_connect(so, nam, td);
594 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
599 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
601 error = unp_connectat(fd, so, nam, td);
607 uipc_close(struct socket *so)
609 struct unpcb *unp, *unp2;
612 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
616 unp2 = unp->unp_conn;
619 unp_disconnect(unp, unp2);
620 UNP_PCB_UNLOCK(unp2);
627 uipc_connect2(struct socket *so1, struct socket *so2)
629 struct unpcb *unp, *unp2;
634 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
637 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
639 error = unp_connect2(so1, so2, PRU_CONNECT2);
640 UNP_PCB_UNLOCK(unp2);
647 uipc_detach(struct socket *so)
649 struct unpcb *unp, *unp2;
650 struct sockaddr_un *saved_unp_addr;
652 int freeunp, local_unp_rights;
655 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
658 local_unp_rights = 0;
661 LIST_REMOVE(unp, unp_link);
662 unp->unp_gencnt = ++unp_gencnt;
666 if ((unp->unp_flags & UNP_NASCENT) != 0) {
674 * XXXRW: Should assert vp->v_socket == so.
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)
747 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
750 if (unp->unp_vnode == NULL) {
751 /* Already connected or not bound to an address. */
752 error = unp->unp_conn != NULL ? EINVAL : EDESTADDRREQ;
758 error = solisten_proto_check(so);
760 cru2x(td->td_ucred, &unp->unp_peercred);
761 unp->unp_flags |= UNP_HAVEPCCACHED;
762 solisten_proto(so, backlog);
770 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
772 struct unpcb *unp, *unp2;
773 const struct sockaddr *sa;
776 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
778 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
781 * XXX: It seems that this test always fails even when connection is
782 * established. So, this else clause is added as workaround to
783 * return PF_LOCAL sockaddr.
785 unp2 = unp->unp_conn;
788 if (unp2->unp_addr != NULL)
789 sa = (struct sockaddr *) unp2->unp_addr;
792 bcopy(sa, *nam, sa->sa_len);
793 UNP_PCB_UNLOCK(unp2);
796 bcopy(sa, *nam, sa->sa_len);
803 uipc_rcvd(struct socket *so, int flags)
805 struct unpcb *unp, *unp2;
810 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
811 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_SEQPACKET,
812 ("%s: socktype %d", __func__, so->so_type));
815 * Adjust backpressure on sender and wakeup any waiting to write.
817 * The unp lock is acquired to maintain the validity of the unp_conn
818 * pointer; no lock on unp2 is required as unp2->unp_socket will be
819 * static as long as we don't permit unp2 to disconnect from unp,
820 * which is prevented by the lock on unp. We cache values from
821 * so_rcv to avoid holding the so_rcv lock over the entire
822 * transaction on the remote so_snd.
824 SOCKBUF_LOCK(&so->so_rcv);
825 mbcnt = so->so_rcv.sb_mbcnt;
826 sbcc = sbavail(&so->so_rcv);
827 SOCKBUF_UNLOCK(&so->so_rcv);
829 * There is a benign race condition at this point. If we're planning to
830 * clear SB_STOP, but uipc_send is called on the connected socket at
831 * this instant, it might add data to the sockbuf and set SB_STOP. Then
832 * we would erroneously clear SB_STOP below, even though the sockbuf is
833 * full. The race is benign because the only ill effect is to allow the
834 * sockbuf to exceed its size limit, and the size limits are not
835 * strictly guaranteed anyway.
838 unp2 = unp->unp_conn;
843 so2 = unp2->unp_socket;
844 SOCKBUF_LOCK(&so2->so_snd);
845 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
846 so2->so_snd.sb_flags &= ~SB_STOP;
847 sowwakeup_locked(so2);
853 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
854 struct mbuf *control, struct thread *td)
856 struct unpcb *unp, *unp2;
862 KASSERT(unp != NULL, ("%s: unp == NULL", __func__));
863 KASSERT(so->so_type == SOCK_STREAM || so->so_type == SOCK_DGRAM ||
864 so->so_type == SOCK_SEQPACKET,
865 ("%s: socktype %d", __func__, so->so_type));
867 if (flags & PRUS_OOB) {
871 if (control != NULL && (error = unp_internalize(&control, td)))
873 if ((nam != NULL) || (flags & PRUS_EOF))
877 switch (so->so_type) {
880 const struct sockaddr *from;
882 unp2 = unp->unp_conn;
884 UNP_LINK_WLOCK_ASSERT();
889 error = unp_connect(so, nam, td);
892 unp2 = unp->unp_conn;
896 * Because connect() and send() are non-atomic in a sendto()
897 * with a target address, it's possible that the socket will
898 * have disconnected before the send() can run. In that case
899 * return the slightly counter-intuitive but otherwise
900 * correct error that the socket is not connected.
907 if (unp2->unp_flags & UNP_WANTCRED)
908 control = unp_addsockcred(td, control);
910 if (unp->unp_addr != NULL)
911 from = (struct sockaddr *)unp->unp_addr;
914 so2 = unp2->unp_socket;
915 SOCKBUF_LOCK(&so2->so_rcv);
916 if (sbappendaddr_locked(&so2->so_rcv, from, m,
918 sorwakeup_locked(so2);
922 SOCKBUF_UNLOCK(&so2->so_rcv);
926 UNP_LINK_WLOCK_ASSERT();
928 unp_disconnect(unp, unp2);
929 UNP_PCB_UNLOCK(unp2);
937 if ((so->so_state & SS_ISCONNECTED) == 0) {
939 UNP_LINK_WLOCK_ASSERT();
940 error = unp_connect(so, nam, td);
950 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
956 * Because connect() and send() are non-atomic in a sendto()
957 * with a target address, it's possible that the socket will
958 * have disconnected before the send() can run. In that case
959 * return the slightly counter-intuitive but otherwise
960 * correct error that the socket is not connected.
962 * Locking here must be done carefully: the linkage lock
963 * prevents interconnections between unpcbs from changing, so
964 * we can traverse from unp to unp2 without acquiring unp's
965 * lock. Socket buffer locks follow unpcb locks, so we can
966 * acquire both remote and lock socket buffer locks.
968 unp2 = unp->unp_conn;
973 so2 = unp2->unp_socket;
975 SOCKBUF_LOCK(&so2->so_rcv);
976 if (unp2->unp_flags & UNP_WANTCRED) {
978 * Credentials are passed only once on SOCK_STREAM
979 * and SOCK_SEQPACKET.
981 unp2->unp_flags &= ~UNP_WANTCRED;
982 control = unp_addsockcred(td, control);
986 * Send to paired receive port and wake up readers. Don't
987 * check for space available in the receive buffer if we're
988 * attaching ancillary data; Unix domain sockets only check
989 * for space in the sending sockbuf, and that check is
990 * performed one level up the stack. At that level we cannot
991 * precisely account for the amount of buffer space used
992 * (e.g., because control messages are not yet internalized).
994 switch (so->so_type) {
996 if (control != NULL) {
997 sbappendcontrol_locked(&so2->so_rcv, m,
1001 sbappend_locked(&so2->so_rcv, m, flags);
1004 case SOCK_SEQPACKET: {
1005 const struct sockaddr *from;
1008 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
1015 mbcnt = so2->so_rcv.sb_mbcnt;
1016 sbcc = sbavail(&so2->so_rcv);
1018 sorwakeup_locked(so2);
1020 SOCKBUF_UNLOCK(&so2->so_rcv);
1023 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1024 * it would be possible for uipc_rcvd to be called at this
1025 * point, drain the receiving sockbuf, clear SB_STOP, and then
1026 * we would set SB_STOP below. That could lead to an empty
1027 * sockbuf having SB_STOP set
1029 SOCKBUF_LOCK(&so->so_snd);
1030 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1031 so->so_snd.sb_flags |= SB_STOP;
1032 SOCKBUF_UNLOCK(&so->so_snd);
1033 UNP_PCB_UNLOCK(unp2);
1039 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1041 if (flags & PRUS_EOF) {
1045 UNP_PCB_UNLOCK(unp);
1048 if ((nam != NULL) || (flags & PRUS_EOF))
1053 if (control != NULL && error != 0)
1054 unp_dispose(control);
1057 if (control != NULL)
1060 * In case of PRUS_NOTREADY, uipc_ready() is responsible
1061 * for freeing memory.
1063 if (m != NULL && (flags & PRUS_NOTREADY) == 0)
1069 uipc_ready(struct socket *so, struct mbuf *m, int count)
1071 struct unpcb *unp, *unp2;
1075 unp = sotounpcb(so);
1078 if ((unp2 = unp->unp_conn) == NULL) {
1080 for (int i = 0; i < count; i++)
1082 return (ECONNRESET);
1085 so2 = unp2->unp_socket;
1087 SOCKBUF_LOCK(&so2->so_rcv);
1088 if ((error = sbready(&so2->so_rcv, m, count)) == 0)
1089 sorwakeup_locked(so2);
1091 SOCKBUF_UNLOCK(&so2->so_rcv);
1093 UNP_PCB_UNLOCK(unp2);
1100 uipc_sense(struct socket *so, struct stat *sb)
1104 unp = sotounpcb(so);
1105 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1107 sb->st_blksize = so->so_snd.sb_hiwat;
1110 if (unp->unp_ino == 0)
1111 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1112 sb->st_ino = unp->unp_ino;
1113 UNP_PCB_UNLOCK(unp);
1118 uipc_shutdown(struct socket *so)
1122 unp = sotounpcb(so);
1123 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1129 UNP_PCB_UNLOCK(unp);
1135 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1138 const struct sockaddr *sa;
1140 unp = sotounpcb(so);
1141 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1143 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1145 if (unp->unp_addr != NULL)
1146 sa = (struct sockaddr *) unp->unp_addr;
1149 bcopy(sa, *nam, sa->sa_len);
1150 UNP_PCB_UNLOCK(unp);
1154 static struct pr_usrreqs uipc_usrreqs_dgram = {
1155 .pru_abort = uipc_abort,
1156 .pru_accept = uipc_accept,
1157 .pru_attach = uipc_attach,
1158 .pru_bind = uipc_bind,
1159 .pru_bindat = uipc_bindat,
1160 .pru_connect = uipc_connect,
1161 .pru_connectat = uipc_connectat,
1162 .pru_connect2 = uipc_connect2,
1163 .pru_detach = uipc_detach,
1164 .pru_disconnect = uipc_disconnect,
1165 .pru_listen = uipc_listen,
1166 .pru_peeraddr = uipc_peeraddr,
1167 .pru_rcvd = uipc_rcvd,
1168 .pru_send = uipc_send,
1169 .pru_sense = uipc_sense,
1170 .pru_shutdown = uipc_shutdown,
1171 .pru_sockaddr = uipc_sockaddr,
1172 .pru_soreceive = soreceive_dgram,
1173 .pru_close = uipc_close,
1176 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1177 .pru_abort = uipc_abort,
1178 .pru_accept = uipc_accept,
1179 .pru_attach = uipc_attach,
1180 .pru_bind = uipc_bind,
1181 .pru_bindat = uipc_bindat,
1182 .pru_connect = uipc_connect,
1183 .pru_connectat = uipc_connectat,
1184 .pru_connect2 = uipc_connect2,
1185 .pru_detach = uipc_detach,
1186 .pru_disconnect = uipc_disconnect,
1187 .pru_listen = uipc_listen,
1188 .pru_peeraddr = uipc_peeraddr,
1189 .pru_rcvd = uipc_rcvd,
1190 .pru_send = uipc_send,
1191 .pru_sense = uipc_sense,
1192 .pru_shutdown = uipc_shutdown,
1193 .pru_sockaddr = uipc_sockaddr,
1194 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1195 .pru_close = uipc_close,
1198 static struct pr_usrreqs uipc_usrreqs_stream = {
1199 .pru_abort = uipc_abort,
1200 .pru_accept = uipc_accept,
1201 .pru_attach = uipc_attach,
1202 .pru_bind = uipc_bind,
1203 .pru_bindat = uipc_bindat,
1204 .pru_connect = uipc_connect,
1205 .pru_connectat = uipc_connectat,
1206 .pru_connect2 = uipc_connect2,
1207 .pru_detach = uipc_detach,
1208 .pru_disconnect = uipc_disconnect,
1209 .pru_listen = uipc_listen,
1210 .pru_peeraddr = uipc_peeraddr,
1211 .pru_rcvd = uipc_rcvd,
1212 .pru_send = uipc_send,
1213 .pru_ready = uipc_ready,
1214 .pru_sense = uipc_sense,
1215 .pru_shutdown = uipc_shutdown,
1216 .pru_sockaddr = uipc_sockaddr,
1217 .pru_soreceive = soreceive_generic,
1218 .pru_close = uipc_close,
1222 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1228 if (sopt->sopt_level != 0)
1231 unp = sotounpcb(so);
1232 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1234 switch (sopt->sopt_dir) {
1236 switch (sopt->sopt_name) {
1237 case LOCAL_PEERCRED:
1239 if (unp->unp_flags & UNP_HAVEPC)
1240 xu = unp->unp_peercred;
1242 if (so->so_type == SOCK_STREAM)
1247 UNP_PCB_UNLOCK(unp);
1249 error = sooptcopyout(sopt, &xu, sizeof(xu));
1253 /* Unlocked read. */
1254 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1255 error = sooptcopyout(sopt, &optval, sizeof(optval));
1258 case LOCAL_CONNWAIT:
1259 /* Unlocked read. */
1260 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1261 error = sooptcopyout(sopt, &optval, sizeof(optval));
1271 switch (sopt->sopt_name) {
1273 case LOCAL_CONNWAIT:
1274 error = sooptcopyin(sopt, &optval, sizeof(optval),
1279 #define OPTSET(bit) do { \
1280 UNP_PCB_LOCK(unp); \
1282 unp->unp_flags |= bit; \
1284 unp->unp_flags &= ~bit; \
1285 UNP_PCB_UNLOCK(unp); \
1288 switch (sopt->sopt_name) {
1290 OPTSET(UNP_WANTCRED);
1293 case LOCAL_CONNWAIT:
1294 OPTSET(UNP_CONNWAIT);
1303 error = ENOPROTOOPT;
1316 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1319 return (unp_connectat(AT_FDCWD, so, nam, td));
1323 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1326 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1328 struct socket *so2, *so3;
1329 struct unpcb *unp, *unp2, *unp3;
1330 struct nameidata nd;
1331 char buf[SOCK_MAXADDRLEN];
1332 struct sockaddr *sa;
1333 cap_rights_t rights;
1336 if (nam->sa_family != AF_UNIX)
1337 return (EAFNOSUPPORT);
1339 UNP_LINK_WLOCK_ASSERT();
1341 unp = sotounpcb(so);
1342 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1344 if (nam->sa_len > sizeof(struct sockaddr_un))
1346 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1349 bcopy(soun->sun_path, buf, len);
1353 if (unp->unp_flags & UNP_CONNECTING) {
1354 UNP_PCB_UNLOCK(unp);
1358 unp->unp_flags |= UNP_CONNECTING;
1359 UNP_PCB_UNLOCK(unp);
1361 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1362 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1363 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1369 ASSERT_VOP_LOCKED(vp, "unp_connect");
1370 NDFREE(&nd, NDF_ONLY_PNBUF);
1374 if (vp->v_type != VSOCK) {
1379 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1383 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1387 unp = sotounpcb(so);
1388 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1391 * Lock linkage lock for two reasons: make sure v_socket is stable,
1392 * and to protect simultaneous locking of multiple pcbs.
1395 VOP_UNP_CONNECT(vp, &so2);
1397 error = ECONNREFUSED;
1400 if (so->so_type != so2->so_type) {
1404 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1405 if (so2->so_options & SO_ACCEPTCONN) {
1406 CURVNET_SET(so2->so_vnet);
1407 so3 = sonewconn(so2, 0);
1412 error = ECONNREFUSED;
1415 unp = sotounpcb(so);
1416 unp2 = sotounpcb(so2);
1417 unp3 = sotounpcb(so3);
1421 if (unp2->unp_addr != NULL) {
1422 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1423 unp3->unp_addr = (struct sockaddr_un *) sa;
1427 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1428 ("unp_connect: listener without cached peercred"));
1429 unp_copy_peercred(td, unp3, unp, unp2);
1431 UNP_PCB_UNLOCK(unp3);
1432 UNP_PCB_UNLOCK(unp2);
1433 UNP_PCB_UNLOCK(unp);
1435 mac_socketpeer_set_from_socket(so, so3);
1436 mac_socketpeer_set_from_socket(so3, so);
1441 unp = sotounpcb(so);
1442 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1443 unp2 = sotounpcb(so2);
1444 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1447 error = unp_connect2(so, so2, PRU_CONNECT);
1448 UNP_PCB_UNLOCK(unp2);
1449 UNP_PCB_UNLOCK(unp);
1458 unp->unp_flags &= ~UNP_CONNECTING;
1459 UNP_PCB_UNLOCK(unp);
1464 * Set socket peer credentials at connection time.
1466 * The client's PCB credentials are copied from its process structure. The
1467 * server's PCB credentials are copied from the socket on which it called
1468 * listen(2). uipc_listen cached that process's credentials at the time.
1471 unp_copy_peercred(struct thread *td, struct unpcb *client_unp,
1472 struct unpcb *server_unp, struct unpcb *listen_unp)
1474 cru2x(td->td_ucred, &client_unp->unp_peercred);
1475 client_unp->unp_flags |= UNP_HAVEPC;
1477 memcpy(&server_unp->unp_peercred, &listen_unp->unp_peercred,
1478 sizeof(server_unp->unp_peercred));
1479 server_unp->unp_flags |= UNP_HAVEPC;
1480 if (listen_unp->unp_flags & UNP_WANTCRED)
1481 client_unp->unp_flags |= UNP_WANTCRED;
1485 unp_connect2(struct socket *so, struct socket *so2, int req)
1490 unp = sotounpcb(so);
1491 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1492 unp2 = sotounpcb(so2);
1493 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1495 UNP_LINK_WLOCK_ASSERT();
1496 UNP_PCB_LOCK_ASSERT(unp);
1497 UNP_PCB_LOCK_ASSERT(unp2);
1499 if (so2->so_type != so->so_type)
1500 return (EPROTOTYPE);
1501 unp2->unp_flags &= ~UNP_NASCENT;
1502 unp->unp_conn = unp2;
1504 switch (so->so_type) {
1506 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1511 case SOCK_SEQPACKET:
1512 unp2->unp_conn = unp;
1513 if (req == PRU_CONNECT &&
1514 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1522 panic("unp_connect2");
1528 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1532 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1534 UNP_LINK_WLOCK_ASSERT();
1535 UNP_PCB_LOCK_ASSERT(unp);
1536 UNP_PCB_LOCK_ASSERT(unp2);
1538 unp->unp_conn = NULL;
1539 switch (unp->unp_socket->so_type) {
1541 LIST_REMOVE(unp, unp_reflink);
1542 so = unp->unp_socket;
1544 so->so_state &= ~SS_ISCONNECTED;
1549 case SOCK_SEQPACKET:
1550 soisdisconnected(unp->unp_socket);
1551 unp2->unp_conn = NULL;
1552 soisdisconnected(unp2->unp_socket);
1558 * unp_pcblist() walks the global list of struct unpcb's to generate a
1559 * pointer list, bumping the refcount on each unpcb. It then copies them out
1560 * sequentially, validating the generation number on each to see if it has
1561 * been detached. All of this is necessary because copyout() may sleep on
1565 unp_pcblist(SYSCTL_HANDLER_ARGS)
1569 struct unpcb *unp, **unp_list;
1571 struct xunpgen *xug;
1572 struct unp_head *head;
1575 switch ((intptr_t)arg1) {
1584 case SOCK_SEQPACKET:
1589 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1593 * The process of preparing the PCB list is too time-consuming and
1594 * resource-intensive to repeat twice on every request.
1596 if (req->oldptr == NULL) {
1598 req->oldidx = 2 * (sizeof *xug)
1599 + (n + n/8) * sizeof(struct xunpcb);
1603 if (req->newptr != NULL)
1607 * OK, now we're committed to doing something.
1609 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1611 gencnt = unp_gencnt;
1615 xug->xug_len = sizeof *xug;
1617 xug->xug_gen = gencnt;
1618 xug->xug_sogen = so_gencnt;
1619 error = SYSCTL_OUT(req, xug, sizeof *xug);
1625 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1628 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1629 unp = LIST_NEXT(unp, unp_link)) {
1631 if (unp->unp_gencnt <= gencnt) {
1632 if (cr_cansee(req->td->td_ucred,
1633 unp->unp_socket->so_cred)) {
1634 UNP_PCB_UNLOCK(unp);
1637 unp_list[i++] = unp;
1638 unp->unp_refcount++;
1640 UNP_PCB_UNLOCK(unp);
1643 n = i; /* In case we lost some during malloc. */
1646 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1647 for (i = 0; i < n; i++) {
1650 unp->unp_refcount--;
1651 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1652 xu->xu_len = sizeof *xu;
1655 * XXX - need more locking here to protect against
1656 * connect/disconnect races for SMP.
1658 if (unp->unp_addr != NULL)
1659 bcopy(unp->unp_addr, &xu->xu_addr,
1660 unp->unp_addr->sun_len);
1661 if (unp->unp_conn != NULL &&
1662 unp->unp_conn->unp_addr != NULL)
1663 bcopy(unp->unp_conn->unp_addr,
1665 unp->unp_conn->unp_addr->sun_len);
1666 bcopy(unp, &xu->xu_unp, sizeof *unp);
1667 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1668 UNP_PCB_UNLOCK(unp);
1669 error = SYSCTL_OUT(req, xu, sizeof *xu);
1671 freeunp = (unp->unp_refcount == 0);
1672 UNP_PCB_UNLOCK(unp);
1674 UNP_PCB_LOCK_DESTROY(unp);
1675 uma_zfree(unp_zone, unp);
1682 * Give the user an updated idea of our state. If the
1683 * generation differs from what we told her before, she knows
1684 * that something happened while we were processing this
1685 * request, and it might be necessary to retry.
1687 xug->xug_gen = unp_gencnt;
1688 xug->xug_sogen = so_gencnt;
1689 xug->xug_count = unp_count;
1690 error = SYSCTL_OUT(req, xug, sizeof *xug);
1692 free(unp_list, M_TEMP);
1697 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1698 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1699 "List of active local datagram sockets");
1700 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1701 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1702 "List of active local stream sockets");
1703 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1704 CTLTYPE_OPAQUE | CTLFLAG_RD,
1705 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1706 "List of active local seqpacket sockets");
1709 unp_shutdown(struct unpcb *unp)
1714 UNP_LINK_WLOCK_ASSERT();
1715 UNP_PCB_LOCK_ASSERT(unp);
1717 unp2 = unp->unp_conn;
1718 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1719 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1720 so = unp2->unp_socket;
1727 unp_drop(struct unpcb *unp)
1729 struct socket *so = unp->unp_socket;
1732 UNP_LINK_WLOCK_ASSERT();
1733 UNP_PCB_LOCK_ASSERT(unp);
1736 * Regardless of whether the socket's peer dropped the connection
1737 * with this socket by aborting or disconnecting, POSIX requires
1738 * that ECONNRESET is returned.
1740 so->so_error = ECONNRESET;
1741 unp2 = unp->unp_conn;
1745 unp_disconnect(unp, unp2);
1746 UNP_PCB_UNLOCK(unp2);
1750 unp_freerights(struct filedescent **fdep, int fdcount)
1755 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1757 for (i = 0; i < fdcount; i++) {
1758 fp = fdep[i]->fde_file;
1759 filecaps_free(&fdep[i]->fde_caps);
1762 free(fdep[0], M_FILECAPS);
1766 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1768 struct thread *td = curthread; /* XXX */
1769 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1772 struct filedesc *fdesc = td->td_proc->p_fd;
1773 struct filedescent **fdep;
1775 socklen_t clen = control->m_len, datalen;
1779 UNP_LINK_UNLOCK_ASSERT();
1782 if (controlp != NULL) /* controlp == NULL => free control messages */
1784 while (cm != NULL) {
1785 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1789 data = CMSG_DATA(cm);
1790 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1791 if (cm->cmsg_level == SOL_SOCKET
1792 && cm->cmsg_type == SCM_RIGHTS) {
1793 newfds = datalen / sizeof(*fdep);
1798 /* If we're not outputting the descriptors free them. */
1799 if (error || controlp == NULL) {
1800 unp_freerights(fdep, newfds);
1803 FILEDESC_XLOCK(fdesc);
1806 * Now change each pointer to an fd in the global
1807 * table to an integer that is the index to the local
1808 * fd table entry that we set up to point to the
1809 * global one we are transferring.
1811 newlen = newfds * sizeof(int);
1812 *controlp = sbcreatecontrol(NULL, newlen,
1813 SCM_RIGHTS, SOL_SOCKET);
1814 if (*controlp == NULL) {
1815 FILEDESC_XUNLOCK(fdesc);
1817 unp_freerights(fdep, newfds);
1822 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1823 if (fdallocn(td, 0, fdp, newfds) != 0) {
1824 FILEDESC_XUNLOCK(fdesc);
1826 unp_freerights(fdep, newfds);
1831 for (i = 0; i < newfds; i++, fdp++) {
1832 _finstall(fdesc, fdep[i]->fde_file, *fdp,
1833 (flags & MSG_CMSG_CLOEXEC) != 0 ? UF_EXCLOSE : 0,
1834 &fdep[i]->fde_caps);
1835 unp_externalize_fp(fdep[i]->fde_file);
1839 * The new type indicates that the mbuf data refers to
1840 * kernel resources that may need to be released before
1841 * the mbuf is freed.
1843 m_chtype(*controlp, MT_EXTCONTROL);
1844 FILEDESC_XUNLOCK(fdesc);
1845 free(fdep[0], M_FILECAPS);
1847 /* We can just copy anything else across. */
1848 if (error || controlp == NULL)
1850 *controlp = sbcreatecontrol(NULL, datalen,
1851 cm->cmsg_type, cm->cmsg_level);
1852 if (*controlp == NULL) {
1857 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1860 controlp = &(*controlp)->m_next;
1863 if (CMSG_SPACE(datalen) < clen) {
1864 clen -= CMSG_SPACE(datalen);
1865 cm = (struct cmsghdr *)
1866 ((caddr_t)cm + CMSG_SPACE(datalen));
1878 unp_zone_change(void *tag)
1881 uma_zone_set_max(unp_zone, maxsockets);
1889 if (!IS_DEFAULT_VNET(curvnet))
1892 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1893 NULL, NULL, UMA_ALIGN_PTR, 0);
1894 if (unp_zone == NULL)
1896 uma_zone_set_max(unp_zone, maxsockets);
1897 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
1898 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1899 NULL, EVENTHANDLER_PRI_ANY);
1900 LIST_INIT(&unp_dhead);
1901 LIST_INIT(&unp_shead);
1902 LIST_INIT(&unp_sphead);
1903 SLIST_INIT(&unp_defers);
1904 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
1905 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1906 UNP_LINK_LOCK_INIT();
1907 UNP_LIST_LOCK_INIT();
1908 UNP_DEFERRED_LOCK_INIT();
1912 unp_internalize(struct mbuf **controlp, struct thread *td)
1914 struct mbuf *control = *controlp;
1915 struct proc *p = td->td_proc;
1916 struct filedesc *fdesc = p->p_fd;
1918 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1919 struct cmsgcred *cmcred;
1920 struct filedescent *fde, **fdep, *fdev;
1923 struct timespec *ts;
1926 socklen_t clen = control->m_len, datalen;
1930 UNP_LINK_UNLOCK_ASSERT();
1934 while (cm != NULL) {
1935 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1936 || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
1940 data = CMSG_DATA(cm);
1941 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1943 switch (cm->cmsg_type) {
1945 * Fill in credential information.
1948 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1949 SCM_CREDS, SOL_SOCKET);
1950 if (*controlp == NULL) {
1954 cmcred = (struct cmsgcred *)
1955 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1956 cmcred->cmcred_pid = p->p_pid;
1957 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1958 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1959 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1960 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1962 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1963 cmcred->cmcred_groups[i] =
1964 td->td_ucred->cr_groups[i];
1968 oldfds = datalen / sizeof (int);
1972 * Check that all the FDs passed in refer to legal
1973 * files. If not, reject the entire operation.
1976 FILEDESC_SLOCK(fdesc);
1977 for (i = 0; i < oldfds; i++, fdp++) {
1978 fp = fget_locked(fdesc, *fdp);
1980 FILEDESC_SUNLOCK(fdesc);
1984 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1985 FILEDESC_SUNLOCK(fdesc);
1993 * Now replace the integer FDs with pointers to the
1994 * file structure and capability rights.
1996 newlen = oldfds * sizeof(fdep[0]);
1997 *controlp = sbcreatecontrol(NULL, newlen,
1998 SCM_RIGHTS, SOL_SOCKET);
1999 if (*controlp == NULL) {
2000 FILEDESC_SUNLOCK(fdesc);
2005 fdep = (struct filedescent **)
2006 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2007 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
2009 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
2010 fde = &fdesc->fd_ofiles[*fdp];
2012 fdep[i]->fde_file = fde->fde_file;
2013 filecaps_copy(&fde->fde_caps,
2014 &fdep[i]->fde_caps, true);
2015 unp_internalize_fp(fdep[i]->fde_file);
2017 FILEDESC_SUNLOCK(fdesc);
2021 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
2022 SCM_TIMESTAMP, SOL_SOCKET);
2023 if (*controlp == NULL) {
2027 tv = (struct timeval *)
2028 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2033 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
2034 SCM_BINTIME, SOL_SOCKET);
2035 if (*controlp == NULL) {
2039 bt = (struct bintime *)
2040 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2045 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2046 SCM_REALTIME, SOL_SOCKET);
2047 if (*controlp == NULL) {
2051 ts = (struct timespec *)
2052 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2057 *controlp = sbcreatecontrol(NULL, sizeof(*ts),
2058 SCM_MONOTONIC, SOL_SOCKET);
2059 if (*controlp == NULL) {
2063 ts = (struct timespec *)
2064 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
2073 controlp = &(*controlp)->m_next;
2074 if (CMSG_SPACE(datalen) < clen) {
2075 clen -= CMSG_SPACE(datalen);
2076 cm = (struct cmsghdr *)
2077 ((caddr_t)cm + CMSG_SPACE(datalen));
2089 static struct mbuf *
2090 unp_addsockcred(struct thread *td, struct mbuf *control)
2092 struct mbuf *m, *n, *n_prev;
2093 struct sockcred *sc;
2094 const struct cmsghdr *cm;
2098 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2099 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2103 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2104 sc->sc_uid = td->td_ucred->cr_ruid;
2105 sc->sc_euid = td->td_ucred->cr_uid;
2106 sc->sc_gid = td->td_ucred->cr_rgid;
2107 sc->sc_egid = td->td_ucred->cr_gid;
2108 sc->sc_ngroups = ngroups;
2109 for (i = 0; i < sc->sc_ngroups; i++)
2110 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2113 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2114 * created SCM_CREDS control message (struct sockcred) has another
2117 if (control != NULL)
2118 for (n = control, n_prev = NULL; n != NULL;) {
2119 cm = mtod(n, struct cmsghdr *);
2120 if (cm->cmsg_level == SOL_SOCKET &&
2121 cm->cmsg_type == SCM_CREDS) {
2123 control = n->m_next;
2125 n_prev->m_next = n->m_next;
2133 /* Prepend it to the head. */
2134 m->m_next = control;
2138 static struct unpcb *
2139 fptounp(struct file *fp)
2143 if (fp->f_type != DTYPE_SOCKET)
2145 if ((so = fp->f_data) == NULL)
2147 if (so->so_proto->pr_domain != &localdomain)
2149 return sotounpcb(so);
2153 unp_discard(struct file *fp)
2155 struct unp_defer *dr;
2157 if (unp_externalize_fp(fp)) {
2158 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2160 UNP_DEFERRED_LOCK();
2161 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2162 UNP_DEFERRED_UNLOCK();
2163 atomic_add_int(&unp_defers_count, 1);
2164 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2166 (void) closef(fp, (struct thread *)NULL);
2170 unp_process_defers(void *arg __unused, int pending)
2172 struct unp_defer *dr;
2173 SLIST_HEAD(, unp_defer) drl;
2178 UNP_DEFERRED_LOCK();
2179 if (SLIST_FIRST(&unp_defers) == NULL) {
2180 UNP_DEFERRED_UNLOCK();
2183 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2184 UNP_DEFERRED_UNLOCK();
2186 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2187 SLIST_REMOVE_HEAD(&drl, ud_link);
2188 closef(dr->ud_fp, NULL);
2192 atomic_add_int(&unp_defers_count, -count);
2197 unp_internalize_fp(struct file *fp)
2202 if ((unp = fptounp(fp)) != NULL) {
2204 unp->unp_msgcount++;
2212 unp_externalize_fp(struct file *fp)
2218 if ((unp = fptounp(fp)) != NULL) {
2219 unp->unp_msgcount--;
2229 * unp_defer indicates whether additional work has been defered for a future
2230 * pass through unp_gc(). It is thread local and does not require explicit
2233 static int unp_marked;
2234 static int unp_unreachable;
2237 unp_accessable(struct filedescent **fdep, int fdcount)
2243 for (i = 0; i < fdcount; i++) {
2244 fp = fdep[i]->fde_file;
2245 if ((unp = fptounp(fp)) == NULL)
2247 if (unp->unp_gcflag & UNPGC_REF)
2249 unp->unp_gcflag &= ~UNPGC_DEAD;
2250 unp->unp_gcflag |= UNPGC_REF;
2256 unp_gc_process(struct unpcb *unp)
2262 /* Already processed. */
2263 if (unp->unp_gcflag & UNPGC_SCANNED)
2268 * Check for a socket potentially in a cycle. It must be in a
2269 * queue as indicated by msgcount, and this must equal the file
2270 * reference count. Note that when msgcount is 0 the file is NULL.
2272 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2273 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2274 unp->unp_gcflag |= UNPGC_DEAD;
2280 * Mark all sockets we reference with RIGHTS.
2282 so = unp->unp_socket;
2283 if ((unp->unp_gcflag & UNPGC_IGNORE_RIGHTS) == 0) {
2284 SOCKBUF_LOCK(&so->so_rcv);
2285 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2286 SOCKBUF_UNLOCK(&so->so_rcv);
2290 * Mark all sockets in our accept queue.
2293 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2294 if ((sotounpcb(soa)->unp_gcflag & UNPGC_IGNORE_RIGHTS) != 0)
2296 SOCKBUF_LOCK(&soa->so_rcv);
2297 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2298 SOCKBUF_UNLOCK(&soa->so_rcv);
2301 unp->unp_gcflag |= UNPGC_SCANNED;
2304 static int unp_recycled;
2305 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2306 "Number of unreachable sockets claimed by the garbage collector.");
2308 static int unp_taskcount;
2309 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2310 "Number of times the garbage collector has run.");
2313 unp_gc(__unused void *arg, int pending)
2315 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2317 struct unp_head **head;
2318 struct file *f, **unref;
2325 * First clear all gc flags from previous runs, apart from
2326 * UNPGC_IGNORE_RIGHTS.
2328 for (head = heads; *head != NULL; head++)
2329 LIST_FOREACH(unp, *head, unp_link)
2331 (unp->unp_gcflag & UNPGC_IGNORE_RIGHTS);
2334 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2335 * is reachable all of the sockets it references are reachable.
2336 * Stop the scan once we do a complete loop without discovering
2337 * a new reachable socket.
2340 unp_unreachable = 0;
2342 for (head = heads; *head != NULL; head++)
2343 LIST_FOREACH(unp, *head, unp_link)
2344 unp_gc_process(unp);
2345 } while (unp_marked);
2347 if (unp_unreachable == 0)
2351 * Allocate space for a local list of dead unpcbs.
2353 unref = malloc(unp_unreachable * sizeof(struct file *),
2357 * Iterate looking for sockets which have been specifically marked
2358 * as as unreachable and store them locally.
2362 for (total = 0, head = heads; *head != NULL; head++)
2363 LIST_FOREACH(unp, *head, unp_link)
2364 if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2366 if (unp->unp_msgcount == 0 || f == NULL ||
2367 f->f_count != unp->unp_msgcount)
2371 KASSERT(total <= unp_unreachable,
2372 ("unp_gc: incorrect unreachable count."));
2378 * Now flush all sockets, free'ing rights. This will free the
2379 * struct files associated with these sockets but leave each socket
2380 * with one remaining ref.
2382 for (i = 0; i < total; i++) {
2385 so = unref[i]->f_data;
2386 CURVNET_SET(so->so_vnet);
2392 * And finally release the sockets so they can be reclaimed.
2394 for (i = 0; i < total; i++)
2395 fdrop(unref[i], NULL);
2396 unp_recycled += total;
2397 free(unref, M_TEMP);
2401 unp_dispose(struct mbuf *m)
2405 unp_scan(m, unp_freerights);
2409 * Synchronize against unp_gc, which can trip over data as we are freeing it.
2412 unp_dispose_so(struct socket *so)
2416 unp = sotounpcb(so);
2418 unp->unp_gcflag |= UNPGC_IGNORE_RIGHTS;
2420 unp_dispose(so->so_rcv.sb_mb);
2424 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2429 socklen_t clen, datalen;
2431 while (m0 != NULL) {
2432 for (m = m0; m; m = m->m_next) {
2433 if (m->m_type != MT_CONTROL)
2436 cm = mtod(m, struct cmsghdr *);
2439 while (cm != NULL) {
2440 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2443 data = CMSG_DATA(cm);
2444 datalen = (caddr_t)cm + cm->cmsg_len
2447 if (cm->cmsg_level == SOL_SOCKET &&
2448 cm->cmsg_type == SCM_RIGHTS) {
2449 (*op)(data, datalen /
2450 sizeof(struct filedescent *));
2453 if (CMSG_SPACE(datalen) < clen) {
2454 clen -= CMSG_SPACE(datalen);
2455 cm = (struct cmsghdr *)
2456 ((caddr_t)cm + CMSG_SPACE(datalen));
2468 * A helper function called by VFS before socket-type vnode reclamation.
2469 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2473 vfs_unp_reclaim(struct vnode *vp)
2479 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2480 KASSERT(vp->v_type == VSOCK,
2481 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2485 VOP_UNP_CONNECT(vp, &so);
2488 unp = sotounpcb(so);
2492 if (unp->unp_vnode == vp) {
2494 unp->unp_vnode = NULL;
2497 UNP_PCB_UNLOCK(unp);
2506 db_print_indent(int indent)
2510 for (i = 0; i < indent; i++)
2515 db_print_unpflags(int unp_flags)
2520 if (unp_flags & UNP_HAVEPC) {
2521 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2524 if (unp_flags & UNP_HAVEPCCACHED) {
2525 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2528 if (unp_flags & UNP_WANTCRED) {
2529 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2532 if (unp_flags & UNP_CONNWAIT) {
2533 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2536 if (unp_flags & UNP_CONNECTING) {
2537 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2540 if (unp_flags & UNP_BINDING) {
2541 db_printf("%sUNP_BINDING", comma ? ", " : "");
2547 db_print_xucred(int indent, struct xucred *xu)
2551 db_print_indent(indent);
2552 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2553 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2554 db_print_indent(indent);
2555 db_printf("cr_groups: ");
2557 for (i = 0; i < xu->cr_ngroups; i++) {
2558 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2565 db_print_unprefs(int indent, struct unp_head *uh)
2571 LIST_FOREACH(unp, uh, unp_reflink) {
2572 if (counter % 4 == 0)
2573 db_print_indent(indent);
2574 db_printf("%p ", unp);
2575 if (counter % 4 == 3)
2579 if (counter != 0 && counter % 4 != 0)
2583 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2588 db_printf("usage: show unpcb <addr>\n");
2591 unp = (struct unpcb *)addr;
2593 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2596 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2599 db_printf("unp_refs:\n");
2600 db_print_unprefs(2, &unp->unp_refs);
2602 /* XXXRW: Would be nice to print the full address, if any. */
2603 db_printf("unp_addr: %p\n", unp->unp_addr);
2605 db_printf("unp_gencnt: %llu\n",
2606 (unsigned long long)unp->unp_gencnt);
2608 db_printf("unp_flags: %x (", unp->unp_flags);
2609 db_print_unpflags(unp->unp_flags);
2612 db_printf("unp_peercred:\n");
2613 db_print_xucred(2, &unp->unp_peercred);
2615 db_printf("unp_refcount: %u\n", unp->unp_refcount);