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/capability.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_shutdown(struct unpcb *);
282 static void unp_drop(struct unpcb *, int);
283 static void unp_gc(__unused void *, int);
284 static void unp_scan(struct mbuf *, void (*)(struct filedescent **, int));
285 static void unp_discard(struct file *);
286 static void unp_freerights(struct filedescent **, int);
287 static void unp_init(void);
288 static int unp_internalize(struct mbuf **, struct thread *);
289 static void unp_internalize_fp(struct file *);
290 static int unp_externalize(struct mbuf *, struct mbuf **, int);
291 static int unp_externalize_fp(struct file *);
292 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
293 static void unp_process_defers(void * __unused, int);
296 * Definitions of protocols supported in the LOCAL domain.
298 static struct domain localdomain;
299 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
300 static struct pr_usrreqs uipc_usrreqs_seqpacket;
301 static struct protosw localsw[] = {
303 .pr_type = SOCK_STREAM,
304 .pr_domain = &localdomain,
305 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
306 .pr_ctloutput = &uipc_ctloutput,
307 .pr_usrreqs = &uipc_usrreqs_stream
310 .pr_type = SOCK_DGRAM,
311 .pr_domain = &localdomain,
312 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
313 .pr_ctloutput = &uipc_ctloutput,
314 .pr_usrreqs = &uipc_usrreqs_dgram
317 .pr_type = SOCK_SEQPACKET,
318 .pr_domain = &localdomain,
321 * XXXRW: For now, PR_ADDR because soreceive will bump into them
322 * due to our use of sbappendaddr. A new sbappend variants is needed
323 * that supports both atomic record writes and control data.
325 .pr_flags = PR_ADDR|PR_ATOMIC|PR_CONNREQUIRED|PR_WANTRCVD|
327 .pr_ctloutput = &uipc_ctloutput,
328 .pr_usrreqs = &uipc_usrreqs_seqpacket,
332 static struct domain localdomain = {
333 .dom_family = AF_LOCAL,
335 .dom_init = unp_init,
336 .dom_externalize = unp_externalize,
337 .dom_dispose = unp_dispose,
338 .dom_protosw = localsw,
339 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
344 uipc_abort(struct socket *so)
346 struct unpcb *unp, *unp2;
349 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
353 unp2 = unp->unp_conn;
356 unp_drop(unp2, ECONNABORTED);
357 UNP_PCB_UNLOCK(unp2);
364 uipc_accept(struct socket *so, struct sockaddr **nam)
366 struct unpcb *unp, *unp2;
367 const struct sockaddr *sa;
370 * Pass back name of connected socket, if it was bound and we are
371 * still connected (our peer may have closed already!).
374 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
376 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
378 unp2 = unp->unp_conn;
379 if (unp2 != NULL && unp2->unp_addr != NULL) {
381 sa = (struct sockaddr *) unp2->unp_addr;
382 bcopy(sa, *nam, sa->sa_len);
383 UNP_PCB_UNLOCK(unp2);
386 bcopy(sa, *nam, sa->sa_len);
393 uipc_attach(struct socket *so, int proto, struct thread *td)
395 u_long sendspace, recvspace;
399 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
400 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
401 switch (so->so_type) {
403 sendspace = unpst_sendspace;
404 recvspace = unpst_recvspace;
408 sendspace = unpdg_sendspace;
409 recvspace = unpdg_recvspace;
413 sendspace = unpsp_sendspace;
414 recvspace = unpsp_recvspace;
418 panic("uipc_attach");
420 error = soreserve(so, sendspace, recvspace);
424 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
427 LIST_INIT(&unp->unp_refs);
428 UNP_PCB_LOCK_INIT(unp);
429 unp->unp_socket = so;
431 unp->unp_refcount = 1;
434 unp->unp_gencnt = ++unp_gencnt;
436 switch (so->so_type) {
438 LIST_INSERT_HEAD(&unp_shead, unp, unp_link);
442 LIST_INSERT_HEAD(&unp_dhead, unp, unp_link);
446 LIST_INSERT_HEAD(&unp_sphead, unp, unp_link);
450 panic("uipc_attach");
458 uipc_bindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
460 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
470 if (nam->sa_family != AF_UNIX)
471 return (EAFNOSUPPORT);
474 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
476 if (soun->sun_len > sizeof(struct sockaddr_un))
478 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
483 * We don't allow simultaneous bind() calls on a single UNIX domain
484 * socket, so flag in-progress operations, and return an error if an
485 * operation is already in progress.
487 * Historically, we have not allowed a socket to be rebound, so this
488 * also returns an error. Not allowing re-binding simplifies the
489 * implementation and avoids a great many possible failure modes.
492 if (unp->unp_vnode != NULL) {
496 if (unp->unp_flags & UNP_BINDING) {
500 unp->unp_flags |= UNP_BINDING;
503 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
504 bcopy(soun->sun_path, buf, namelen);
508 NDINIT_ATRIGHTS(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME,
509 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_BINDAT), td);
510 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
515 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
516 NDFREE(&nd, NDF_ONLY_PNBUF);
526 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
532 vattr.va_type = VSOCK;
533 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
535 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
539 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
540 NDFREE(&nd, NDF_ONLY_PNBUF);
543 vn_finished_write(mp);
547 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
548 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
552 VOP_UNP_BIND(vp, unp->unp_socket);
554 unp->unp_addr = soun;
555 unp->unp_flags &= ~UNP_BINDING;
559 vn_finished_write(mp);
565 unp->unp_flags &= ~UNP_BINDING;
572 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
575 return (uipc_bindat(AT_FDCWD, so, nam, td));
579 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
583 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
585 error = unp_connect(so, nam, td);
591 uipc_connectat(int fd, struct socket *so, struct sockaddr *nam,
596 KASSERT(td == curthread, ("uipc_connectat: td != curthread"));
598 error = unp_connectat(fd, so, nam, td);
604 uipc_close(struct socket *so)
606 struct unpcb *unp, *unp2;
609 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
613 unp2 = unp->unp_conn;
616 unp_disconnect(unp, unp2);
617 UNP_PCB_UNLOCK(unp2);
624 uipc_connect2(struct socket *so1, struct socket *so2)
626 struct unpcb *unp, *unp2;
631 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
634 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
636 error = unp_connect2(so1, so2, PRU_CONNECT2);
637 UNP_PCB_UNLOCK(unp2);
644 uipc_detach(struct socket *so)
646 struct unpcb *unp, *unp2;
647 struct sockaddr_un *saved_unp_addr;
649 int freeunp, local_unp_rights;
652 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
657 LIST_REMOVE(unp, unp_link);
658 unp->unp_gencnt = ++unp_gencnt;
663 * XXXRW: Should assert vp->v_socket == so.
665 if ((vp = unp->unp_vnode) != NULL) {
667 unp->unp_vnode = NULL;
669 unp2 = unp->unp_conn;
672 unp_disconnect(unp, unp2);
673 UNP_PCB_UNLOCK(unp2);
677 * We hold the linkage lock exclusively, so it's OK to acquire
678 * multiple pcb locks at a time.
680 while (!LIST_EMPTY(&unp->unp_refs)) {
681 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
684 unp_drop(ref, ECONNRESET);
687 local_unp_rights = unp_rights;
689 unp->unp_socket->so_pcb = NULL;
690 saved_unp_addr = unp->unp_addr;
691 unp->unp_addr = NULL;
693 freeunp = (unp->unp_refcount == 0);
694 if (saved_unp_addr != NULL)
695 free(saved_unp_addr, M_SONAME);
697 UNP_PCB_LOCK_DESTROY(unp);
698 uma_zfree(unp_zone, unp);
703 if (local_unp_rights)
704 taskqueue_enqueue_timeout(taskqueue_thread, &unp_gc_task, -1);
708 uipc_disconnect(struct socket *so)
710 struct unpcb *unp, *unp2;
713 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
717 unp2 = unp->unp_conn;
720 unp_disconnect(unp, unp2);
721 UNP_PCB_UNLOCK(unp2);
729 uipc_listen(struct socket *so, int backlog, struct thread *td)
735 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
738 if (unp->unp_vnode == NULL) {
744 error = solisten_proto_check(so);
746 cru2x(td->td_ucred, &unp->unp_peercred);
747 unp->unp_flags |= UNP_HAVEPCCACHED;
748 solisten_proto(so, backlog);
756 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
758 struct unpcb *unp, *unp2;
759 const struct sockaddr *sa;
762 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
764 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
767 * XXX: It seems that this test always fails even when connection is
768 * established. So, this else clause is added as workaround to
769 * return PF_LOCAL sockaddr.
771 unp2 = unp->unp_conn;
774 if (unp2->unp_addr != NULL)
775 sa = (struct sockaddr *) unp2->unp_addr;
778 bcopy(sa, *nam, sa->sa_len);
779 UNP_PCB_UNLOCK(unp2);
782 bcopy(sa, *nam, sa->sa_len);
789 uipc_rcvd(struct socket *so, int flags)
791 struct unpcb *unp, *unp2;
796 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
798 if (so->so_type != SOCK_STREAM && so->so_type != SOCK_SEQPACKET)
799 panic("uipc_rcvd socktype %d", so->so_type);
802 * Adjust backpressure on sender and wakeup any waiting to write.
804 * The unp lock is acquired to maintain the validity of the unp_conn
805 * pointer; no lock on unp2 is required as unp2->unp_socket will be
806 * static as long as we don't permit unp2 to disconnect from unp,
807 * which is prevented by the lock on unp. We cache values from
808 * so_rcv to avoid holding the so_rcv lock over the entire
809 * transaction on the remote so_snd.
811 SOCKBUF_LOCK(&so->so_rcv);
812 mbcnt = so->so_rcv.sb_mbcnt;
813 sbcc = so->so_rcv.sb_cc;
814 SOCKBUF_UNLOCK(&so->so_rcv);
816 * There is a benign race condition at this point. If we're planning to
817 * clear SB_STOP, but uipc_send is called on the connected socket at
818 * this instant, it might add data to the sockbuf and set SB_STOP. Then
819 * we would erroneously clear SB_STOP below, even though the sockbuf is
820 * full. The race is benign because the only ill effect is to allow the
821 * sockbuf to exceed its size limit, and the size limits are not
822 * strictly guaranteed anyway.
825 unp2 = unp->unp_conn;
830 so2 = unp2->unp_socket;
831 SOCKBUF_LOCK(&so2->so_snd);
832 if (sbcc < so2->so_snd.sb_hiwat && mbcnt < so2->so_snd.sb_mbmax)
833 so2->so_snd.sb_flags &= ~SB_STOP;
834 sowwakeup_locked(so2);
840 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
841 struct mbuf *control, struct thread *td)
843 struct unpcb *unp, *unp2;
849 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
851 if (flags & PRUS_OOB) {
855 if (control != NULL && (error = unp_internalize(&control, td)))
857 if ((nam != NULL) || (flags & PRUS_EOF))
861 switch (so->so_type) {
864 const struct sockaddr *from;
866 unp2 = unp->unp_conn;
868 UNP_LINK_WLOCK_ASSERT();
873 error = unp_connect(so, nam, td);
876 unp2 = unp->unp_conn;
880 * Because connect() and send() are non-atomic in a sendto()
881 * with a target address, it's possible that the socket will
882 * have disconnected before the send() can run. In that case
883 * return the slightly counter-intuitive but otherwise
884 * correct error that the socket is not connected.
891 if (unp2->unp_flags & UNP_WANTCRED)
892 control = unp_addsockcred(td, control);
894 if (unp->unp_addr != NULL)
895 from = (struct sockaddr *)unp->unp_addr;
898 so2 = unp2->unp_socket;
899 SOCKBUF_LOCK(&so2->so_rcv);
900 if (sbappendaddr_locked(&so2->so_rcv, from, m,
902 sorwakeup_locked(so2);
906 SOCKBUF_UNLOCK(&so2->so_rcv);
910 UNP_LINK_WLOCK_ASSERT();
912 unp_disconnect(unp, unp2);
913 UNP_PCB_UNLOCK(unp2);
921 if ((so->so_state & SS_ISCONNECTED) == 0) {
923 UNP_LINK_WLOCK_ASSERT();
924 error = unp_connect(so, nam, td);
934 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
940 * Because connect() and send() are non-atomic in a sendto()
941 * with a target address, it's possible that the socket will
942 * have disconnected before the send() can run. In that case
943 * return the slightly counter-intuitive but otherwise
944 * correct error that the socket is not connected.
946 * Locking here must be done carefully: the linkage lock
947 * prevents interconnections between unpcbs from changing, so
948 * we can traverse from unp to unp2 without acquiring unp's
949 * lock. Socket buffer locks follow unpcb locks, so we can
950 * acquire both remote and lock socket buffer locks.
952 unp2 = unp->unp_conn;
957 so2 = unp2->unp_socket;
959 SOCKBUF_LOCK(&so2->so_rcv);
960 if (unp2->unp_flags & UNP_WANTCRED) {
962 * Credentials are passed only once on SOCK_STREAM
963 * and SOCK_SEQPACKET.
965 unp2->unp_flags &= ~UNP_WANTCRED;
966 control = unp_addsockcred(td, control);
969 * Send to paired receive port, and then reduce send buffer
970 * hiwater marks to maintain backpressure. Wake up readers.
972 switch (so->so_type) {
974 if (control != NULL) {
975 if (sbappendcontrol_locked(&so2->so_rcv, m,
979 sbappend_locked(&so2->so_rcv, m);
982 case SOCK_SEQPACKET: {
983 const struct sockaddr *from;
987 * Don't check for space available in so2->so_rcv.
988 * Unix domain sockets only check for space in the
989 * sending sockbuf, and that check is performed one
990 * level up the stack.
992 if (sbappendaddr_nospacecheck_locked(&so2->so_rcv,
999 mbcnt = so2->so_rcv.sb_mbcnt;
1000 sbcc = so2->so_rcv.sb_cc;
1001 sorwakeup_locked(so2);
1004 * The PCB lock on unp2 protects the SB_STOP flag. Without it,
1005 * it would be possible for uipc_rcvd to be called at this
1006 * point, drain the receiving sockbuf, clear SB_STOP, and then
1007 * we would set SB_STOP below. That could lead to an empty
1008 * sockbuf having SB_STOP set
1010 SOCKBUF_LOCK(&so->so_snd);
1011 if (sbcc >= so->so_snd.sb_hiwat || mbcnt >= so->so_snd.sb_mbmax)
1012 so->so_snd.sb_flags |= SB_STOP;
1013 SOCKBUF_UNLOCK(&so->so_snd);
1014 UNP_PCB_UNLOCK(unp2);
1019 panic("uipc_send unknown socktype");
1023 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
1025 if (flags & PRUS_EOF) {
1029 UNP_PCB_UNLOCK(unp);
1032 if ((nam != NULL) || (flags & PRUS_EOF))
1037 if (control != NULL && error != 0)
1038 unp_dispose(control);
1041 if (control != NULL)
1049 uipc_sense(struct socket *so, struct stat *sb)
1053 unp = sotounpcb(so);
1054 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
1056 sb->st_blksize = so->so_snd.sb_hiwat;
1059 if (unp->unp_ino == 0)
1060 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
1061 sb->st_ino = unp->unp_ino;
1062 UNP_PCB_UNLOCK(unp);
1067 uipc_shutdown(struct socket *so)
1071 unp = sotounpcb(so);
1072 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1078 UNP_PCB_UNLOCK(unp);
1084 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1087 const struct sockaddr *sa;
1089 unp = sotounpcb(so);
1090 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1092 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1094 if (unp->unp_addr != NULL)
1095 sa = (struct sockaddr *) unp->unp_addr;
1098 bcopy(sa, *nam, sa->sa_len);
1099 UNP_PCB_UNLOCK(unp);
1103 static struct pr_usrreqs uipc_usrreqs_dgram = {
1104 .pru_abort = uipc_abort,
1105 .pru_accept = uipc_accept,
1106 .pru_attach = uipc_attach,
1107 .pru_bind = uipc_bind,
1108 .pru_bindat = uipc_bindat,
1109 .pru_connect = uipc_connect,
1110 .pru_connectat = uipc_connectat,
1111 .pru_connect2 = uipc_connect2,
1112 .pru_detach = uipc_detach,
1113 .pru_disconnect = uipc_disconnect,
1114 .pru_listen = uipc_listen,
1115 .pru_peeraddr = uipc_peeraddr,
1116 .pru_rcvd = uipc_rcvd,
1117 .pru_send = uipc_send,
1118 .pru_sense = uipc_sense,
1119 .pru_shutdown = uipc_shutdown,
1120 .pru_sockaddr = uipc_sockaddr,
1121 .pru_soreceive = soreceive_dgram,
1122 .pru_close = uipc_close,
1125 static struct pr_usrreqs uipc_usrreqs_seqpacket = {
1126 .pru_abort = uipc_abort,
1127 .pru_accept = uipc_accept,
1128 .pru_attach = uipc_attach,
1129 .pru_bind = uipc_bind,
1130 .pru_bindat = uipc_bindat,
1131 .pru_connect = uipc_connect,
1132 .pru_connectat = uipc_connectat,
1133 .pru_connect2 = uipc_connect2,
1134 .pru_detach = uipc_detach,
1135 .pru_disconnect = uipc_disconnect,
1136 .pru_listen = uipc_listen,
1137 .pru_peeraddr = uipc_peeraddr,
1138 .pru_rcvd = uipc_rcvd,
1139 .pru_send = uipc_send,
1140 .pru_sense = uipc_sense,
1141 .pru_shutdown = uipc_shutdown,
1142 .pru_sockaddr = uipc_sockaddr,
1143 .pru_soreceive = soreceive_generic, /* XXX: or...? */
1144 .pru_close = uipc_close,
1147 static struct pr_usrreqs uipc_usrreqs_stream = {
1148 .pru_abort = uipc_abort,
1149 .pru_accept = uipc_accept,
1150 .pru_attach = uipc_attach,
1151 .pru_bind = uipc_bind,
1152 .pru_bindat = uipc_bindat,
1153 .pru_connect = uipc_connect,
1154 .pru_connectat = uipc_connectat,
1155 .pru_connect2 = uipc_connect2,
1156 .pru_detach = uipc_detach,
1157 .pru_disconnect = uipc_disconnect,
1158 .pru_listen = uipc_listen,
1159 .pru_peeraddr = uipc_peeraddr,
1160 .pru_rcvd = uipc_rcvd,
1161 .pru_send = uipc_send,
1162 .pru_sense = uipc_sense,
1163 .pru_shutdown = uipc_shutdown,
1164 .pru_sockaddr = uipc_sockaddr,
1165 .pru_soreceive = soreceive_generic,
1166 .pru_close = uipc_close,
1170 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1176 if (sopt->sopt_level != 0)
1179 unp = sotounpcb(so);
1180 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1182 switch (sopt->sopt_dir) {
1184 switch (sopt->sopt_name) {
1185 case LOCAL_PEERCRED:
1187 if (unp->unp_flags & UNP_HAVEPC)
1188 xu = unp->unp_peercred;
1190 if (so->so_type == SOCK_STREAM)
1195 UNP_PCB_UNLOCK(unp);
1197 error = sooptcopyout(sopt, &xu, sizeof(xu));
1201 /* Unlocked read. */
1202 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1203 error = sooptcopyout(sopt, &optval, sizeof(optval));
1206 case LOCAL_CONNWAIT:
1207 /* Unlocked read. */
1208 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1209 error = sooptcopyout(sopt, &optval, sizeof(optval));
1219 switch (sopt->sopt_name) {
1221 case LOCAL_CONNWAIT:
1222 error = sooptcopyin(sopt, &optval, sizeof(optval),
1227 #define OPTSET(bit) do { \
1228 UNP_PCB_LOCK(unp); \
1230 unp->unp_flags |= bit; \
1232 unp->unp_flags &= ~bit; \
1233 UNP_PCB_UNLOCK(unp); \
1236 switch (sopt->sopt_name) {
1238 OPTSET(UNP_WANTCRED);
1241 case LOCAL_CONNWAIT:
1242 OPTSET(UNP_CONNWAIT);
1251 error = ENOPROTOOPT;
1264 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1267 return (unp_connectat(AT_FDCWD, so, nam, td));
1271 unp_connectat(int fd, struct socket *so, struct sockaddr *nam,
1274 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1276 struct socket *so2, *so3;
1277 struct unpcb *unp, *unp2, *unp3;
1278 struct nameidata nd;
1279 char buf[SOCK_MAXADDRLEN];
1280 struct sockaddr *sa;
1281 cap_rights_t rights;
1284 if (nam->sa_family != AF_UNIX)
1285 return (EAFNOSUPPORT);
1287 UNP_LINK_WLOCK_ASSERT();
1289 unp = sotounpcb(so);
1290 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1292 if (nam->sa_len > sizeof(struct sockaddr_un))
1294 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1297 bcopy(soun->sun_path, buf, len);
1301 if (unp->unp_flags & UNP_CONNECTING) {
1302 UNP_PCB_UNLOCK(unp);
1306 unp->unp_flags |= UNP_CONNECTING;
1307 UNP_PCB_UNLOCK(unp);
1309 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1310 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
1311 UIO_SYSSPACE, buf, fd, cap_rights_init(&rights, CAP_CONNECTAT), td);
1317 ASSERT_VOP_LOCKED(vp, "unp_connect");
1318 NDFREE(&nd, NDF_ONLY_PNBUF);
1322 if (vp->v_type != VSOCK) {
1327 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1331 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1335 unp = sotounpcb(so);
1336 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1339 * Lock linkage lock for two reasons: make sure v_socket is stable,
1340 * and to protect simultaneous locking of multiple pcbs.
1343 VOP_UNP_CONNECT(vp, &so2);
1345 error = ECONNREFUSED;
1348 if (so->so_type != so2->so_type) {
1352 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1353 if (so2->so_options & SO_ACCEPTCONN) {
1354 CURVNET_SET(so2->so_vnet);
1355 so3 = sonewconn(so2, 0);
1360 error = ECONNREFUSED;
1363 unp = sotounpcb(so);
1364 unp2 = sotounpcb(so2);
1365 unp3 = sotounpcb(so3);
1369 if (unp2->unp_addr != NULL) {
1370 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1371 unp3->unp_addr = (struct sockaddr_un *) sa;
1376 * The connector's (client's) credentials are copied from its
1377 * process structure at the time of connect() (which is now).
1379 cru2x(td->td_ucred, &unp3->unp_peercred);
1380 unp3->unp_flags |= UNP_HAVEPC;
1383 * The receiver's (server's) credentials are copied from the
1384 * unp_peercred member of socket on which the former called
1385 * listen(); uipc_listen() cached that process's credentials
1386 * at that time so we can use them now.
1388 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1389 ("unp_connect: listener without cached peercred"));
1390 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1391 sizeof(unp->unp_peercred));
1392 unp->unp_flags |= UNP_HAVEPC;
1393 if (unp2->unp_flags & UNP_WANTCRED)
1394 unp3->unp_flags |= UNP_WANTCRED;
1395 UNP_PCB_UNLOCK(unp3);
1396 UNP_PCB_UNLOCK(unp2);
1397 UNP_PCB_UNLOCK(unp);
1399 mac_socketpeer_set_from_socket(so, so3);
1400 mac_socketpeer_set_from_socket(so3, so);
1405 unp = sotounpcb(so);
1406 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1407 unp2 = sotounpcb(so2);
1408 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1411 error = unp_connect2(so, so2, PRU_CONNECT);
1412 UNP_PCB_UNLOCK(unp2);
1413 UNP_PCB_UNLOCK(unp);
1422 unp->unp_flags &= ~UNP_CONNECTING;
1423 UNP_PCB_UNLOCK(unp);
1428 unp_connect2(struct socket *so, struct socket *so2, int req)
1433 unp = sotounpcb(so);
1434 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1435 unp2 = sotounpcb(so2);
1436 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1438 UNP_LINK_WLOCK_ASSERT();
1439 UNP_PCB_LOCK_ASSERT(unp);
1440 UNP_PCB_LOCK_ASSERT(unp2);
1442 if (so2->so_type != so->so_type)
1443 return (EPROTOTYPE);
1444 unp->unp_conn = unp2;
1446 switch (so->so_type) {
1448 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1453 case SOCK_SEQPACKET:
1454 unp2->unp_conn = unp;
1455 if (req == PRU_CONNECT &&
1456 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1464 panic("unp_connect2");
1470 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1474 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1476 UNP_LINK_WLOCK_ASSERT();
1477 UNP_PCB_LOCK_ASSERT(unp);
1478 UNP_PCB_LOCK_ASSERT(unp2);
1480 unp->unp_conn = NULL;
1481 switch (unp->unp_socket->so_type) {
1483 LIST_REMOVE(unp, unp_reflink);
1484 so = unp->unp_socket;
1486 so->so_state &= ~SS_ISCONNECTED;
1491 case SOCK_SEQPACKET:
1492 soisdisconnected(unp->unp_socket);
1493 unp2->unp_conn = NULL;
1494 soisdisconnected(unp2->unp_socket);
1500 * unp_pcblist() walks the global list of struct unpcb's to generate a
1501 * pointer list, bumping the refcount on each unpcb. It then copies them out
1502 * sequentially, validating the generation number on each to see if it has
1503 * been detached. All of this is necessary because copyout() may sleep on
1507 unp_pcblist(SYSCTL_HANDLER_ARGS)
1511 struct unpcb *unp, **unp_list;
1513 struct xunpgen *xug;
1514 struct unp_head *head;
1517 switch ((intptr_t)arg1) {
1526 case SOCK_SEQPACKET:
1531 panic("unp_pcblist: arg1 %d", (int)(intptr_t)arg1);
1535 * The process of preparing the PCB list is too time-consuming and
1536 * resource-intensive to repeat twice on every request.
1538 if (req->oldptr == NULL) {
1540 req->oldidx = 2 * (sizeof *xug)
1541 + (n + n/8) * sizeof(struct xunpcb);
1545 if (req->newptr != NULL)
1549 * OK, now we're committed to doing something.
1551 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1553 gencnt = unp_gencnt;
1557 xug->xug_len = sizeof *xug;
1559 xug->xug_gen = gencnt;
1560 xug->xug_sogen = so_gencnt;
1561 error = SYSCTL_OUT(req, xug, sizeof *xug);
1567 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1570 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1571 unp = LIST_NEXT(unp, unp_link)) {
1573 if (unp->unp_gencnt <= gencnt) {
1574 if (cr_cansee(req->td->td_ucred,
1575 unp->unp_socket->so_cred)) {
1576 UNP_PCB_UNLOCK(unp);
1579 unp_list[i++] = unp;
1580 unp->unp_refcount++;
1582 UNP_PCB_UNLOCK(unp);
1585 n = i; /* In case we lost some during malloc. */
1588 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1589 for (i = 0; i < n; i++) {
1592 unp->unp_refcount--;
1593 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1594 xu->xu_len = sizeof *xu;
1597 * XXX - need more locking here to protect against
1598 * connect/disconnect races for SMP.
1600 if (unp->unp_addr != NULL)
1601 bcopy(unp->unp_addr, &xu->xu_addr,
1602 unp->unp_addr->sun_len);
1603 if (unp->unp_conn != NULL &&
1604 unp->unp_conn->unp_addr != NULL)
1605 bcopy(unp->unp_conn->unp_addr,
1607 unp->unp_conn->unp_addr->sun_len);
1608 bcopy(unp, &xu->xu_unp, sizeof *unp);
1609 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1610 UNP_PCB_UNLOCK(unp);
1611 error = SYSCTL_OUT(req, xu, sizeof *xu);
1613 freeunp = (unp->unp_refcount == 0);
1614 UNP_PCB_UNLOCK(unp);
1616 UNP_PCB_LOCK_DESTROY(unp);
1617 uma_zfree(unp_zone, unp);
1624 * Give the user an updated idea of our state. If the
1625 * generation differs from what we told her before, she knows
1626 * that something happened while we were processing this
1627 * request, and it might be necessary to retry.
1629 xug->xug_gen = unp_gencnt;
1630 xug->xug_sogen = so_gencnt;
1631 xug->xug_count = unp_count;
1632 error = SYSCTL_OUT(req, xug, sizeof *xug);
1634 free(unp_list, M_TEMP);
1639 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1640 (void *)(intptr_t)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1641 "List of active local datagram sockets");
1642 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
1643 (void *)(intptr_t)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1644 "List of active local stream sockets");
1645 SYSCTL_PROC(_net_local_seqpacket, OID_AUTO, pcblist,
1646 CTLTYPE_OPAQUE | CTLFLAG_RD,
1647 (void *)(intptr_t)SOCK_SEQPACKET, 0, unp_pcblist, "S,xunpcb",
1648 "List of active local seqpacket sockets");
1651 unp_shutdown(struct unpcb *unp)
1656 UNP_LINK_WLOCK_ASSERT();
1657 UNP_PCB_LOCK_ASSERT(unp);
1659 unp2 = unp->unp_conn;
1660 if ((unp->unp_socket->so_type == SOCK_STREAM ||
1661 (unp->unp_socket->so_type == SOCK_SEQPACKET)) && unp2 != NULL) {
1662 so = unp2->unp_socket;
1669 unp_drop(struct unpcb *unp, int errno)
1671 struct socket *so = unp->unp_socket;
1674 UNP_LINK_WLOCK_ASSERT();
1675 UNP_PCB_LOCK_ASSERT(unp);
1677 so->so_error = errno;
1678 unp2 = unp->unp_conn;
1682 unp_disconnect(unp, unp2);
1683 UNP_PCB_UNLOCK(unp2);
1687 unp_freerights(struct filedescent **fdep, int fdcount)
1692 KASSERT(fdcount > 0, ("%s: fdcount %d", __func__, fdcount));
1694 for (i = 0; i < fdcount; i++) {
1695 fp = fdep[i]->fde_file;
1696 filecaps_free(&fdep[i]->fde_caps);
1699 free(fdep[0], M_FILECAPS);
1703 unp_externalize(struct mbuf *control, struct mbuf **controlp, int flags)
1705 struct thread *td = curthread; /* XXX */
1706 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1709 struct filedesc *fdesc = td->td_proc->p_fd;
1710 struct filedescent *fde, **fdep;
1712 socklen_t clen = control->m_len, datalen;
1716 UNP_LINK_UNLOCK_ASSERT();
1719 if (controlp != NULL) /* controlp == NULL => free control messages */
1721 while (cm != NULL) {
1722 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1726 data = CMSG_DATA(cm);
1727 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1728 if (cm->cmsg_level == SOL_SOCKET
1729 && cm->cmsg_type == SCM_RIGHTS) {
1730 newfds = datalen / sizeof(*fdep);
1735 /* If we're not outputting the descriptors free them. */
1736 if (error || controlp == NULL) {
1737 unp_freerights(fdep, newfds);
1740 FILEDESC_XLOCK(fdesc);
1743 * Now change each pointer to an fd in the global
1744 * table to an integer that is the index to the local
1745 * fd table entry that we set up to point to the
1746 * global one we are transferring.
1748 newlen = newfds * sizeof(int);
1749 *controlp = sbcreatecontrol(NULL, newlen,
1750 SCM_RIGHTS, SOL_SOCKET);
1751 if (*controlp == NULL) {
1752 FILEDESC_XUNLOCK(fdesc);
1754 unp_freerights(fdep, newfds);
1759 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1760 if (fdallocn(td, 0, fdp, newfds) != 0) {
1761 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1763 unp_freerights(fdep, newfds);
1768 for (i = 0; i < newfds; i++, fdp++) {
1769 fde = &fdesc->fd_ofiles[*fdp];
1770 fde->fde_file = fdep[i]->fde_file;
1771 filecaps_move(&fdep[i]->fde_caps,
1773 if ((flags & MSG_CMSG_CLOEXEC) != 0)
1774 fde->fde_flags |= UF_EXCLOSE;
1775 unp_externalize_fp(fde->fde_file);
1777 FILEDESC_XUNLOCK(fdesc);
1778 free(fdep[0], M_FILECAPS);
1780 /* We can just copy anything else across. */
1781 if (error || controlp == NULL)
1783 *controlp = sbcreatecontrol(NULL, datalen,
1784 cm->cmsg_type, cm->cmsg_level);
1785 if (*controlp == NULL) {
1790 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1793 controlp = &(*controlp)->m_next;
1796 if (CMSG_SPACE(datalen) < clen) {
1797 clen -= CMSG_SPACE(datalen);
1798 cm = (struct cmsghdr *)
1799 ((caddr_t)cm + CMSG_SPACE(datalen));
1811 unp_zone_change(void *tag)
1814 uma_zone_set_max(unp_zone, maxsockets);
1822 if (!IS_DEFAULT_VNET(curvnet))
1825 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1826 NULL, NULL, UMA_ALIGN_PTR, 0);
1827 if (unp_zone == NULL)
1829 uma_zone_set_max(unp_zone, maxsockets);
1830 uma_zone_set_warning(unp_zone, "kern.ipc.maxsockets limit reached");
1831 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1832 NULL, EVENTHANDLER_PRI_ANY);
1833 LIST_INIT(&unp_dhead);
1834 LIST_INIT(&unp_shead);
1835 LIST_INIT(&unp_sphead);
1836 SLIST_INIT(&unp_defers);
1837 TIMEOUT_TASK_INIT(taskqueue_thread, &unp_gc_task, 0, unp_gc, NULL);
1838 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1839 UNP_LINK_LOCK_INIT();
1840 UNP_LIST_LOCK_INIT();
1841 UNP_DEFERRED_LOCK_INIT();
1845 unp_internalize(struct mbuf **controlp, struct thread *td)
1847 struct mbuf *control = *controlp;
1848 struct proc *p = td->td_proc;
1849 struct filedesc *fdesc = p->p_fd;
1851 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1852 struct cmsgcred *cmcred;
1853 struct filedescent *fde, **fdep, *fdev;
1858 socklen_t clen = control->m_len, datalen;
1862 UNP_LINK_UNLOCK_ASSERT();
1866 while (cm != NULL) {
1867 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1868 || cm->cmsg_len > clen || cm->cmsg_len < sizeof(*cm)) {
1872 data = CMSG_DATA(cm);
1873 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1875 switch (cm->cmsg_type) {
1877 * Fill in credential information.
1880 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1881 SCM_CREDS, SOL_SOCKET);
1882 if (*controlp == NULL) {
1886 cmcred = (struct cmsgcred *)
1887 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1888 cmcred->cmcred_pid = p->p_pid;
1889 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1890 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1891 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1892 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1894 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1895 cmcred->cmcred_groups[i] =
1896 td->td_ucred->cr_groups[i];
1900 oldfds = datalen / sizeof (int);
1904 * Check that all the FDs passed in refer to legal
1905 * files. If not, reject the entire operation.
1908 FILEDESC_SLOCK(fdesc);
1909 for (i = 0; i < oldfds; i++, fdp++) {
1910 fp = fget_locked(fdesc, *fdp);
1912 FILEDESC_SUNLOCK(fdesc);
1916 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1917 FILEDESC_SUNLOCK(fdesc);
1925 * Now replace the integer FDs with pointers to the
1926 * file structure and capability rights.
1928 newlen = oldfds * sizeof(fdep[0]);
1929 *controlp = sbcreatecontrol(NULL, newlen,
1930 SCM_RIGHTS, SOL_SOCKET);
1931 if (*controlp == NULL) {
1932 FILEDESC_SUNLOCK(fdesc);
1937 fdep = (struct filedescent **)
1938 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1939 fdev = malloc(sizeof(*fdev) * oldfds, M_FILECAPS,
1941 for (i = 0; i < oldfds; i++, fdev++, fdp++) {
1942 fde = &fdesc->fd_ofiles[*fdp];
1944 fdep[i]->fde_file = fde->fde_file;
1945 filecaps_copy(&fde->fde_caps,
1946 &fdep[i]->fde_caps);
1947 unp_internalize_fp(fdep[i]->fde_file);
1949 FILEDESC_SUNLOCK(fdesc);
1953 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1954 SCM_TIMESTAMP, SOL_SOCKET);
1955 if (*controlp == NULL) {
1959 tv = (struct timeval *)
1960 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1965 *controlp = sbcreatecontrol(NULL, sizeof(*bt),
1966 SCM_BINTIME, SOL_SOCKET);
1967 if (*controlp == NULL) {
1971 bt = (struct bintime *)
1972 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1981 controlp = &(*controlp)->m_next;
1982 if (CMSG_SPACE(datalen) < clen) {
1983 clen -= CMSG_SPACE(datalen);
1984 cm = (struct cmsghdr *)
1985 ((caddr_t)cm + CMSG_SPACE(datalen));
1997 static struct mbuf *
1998 unp_addsockcred(struct thread *td, struct mbuf *control)
2000 struct mbuf *m, *n, *n_prev;
2001 struct sockcred *sc;
2002 const struct cmsghdr *cm;
2006 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
2007 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
2011 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
2012 sc->sc_uid = td->td_ucred->cr_ruid;
2013 sc->sc_euid = td->td_ucred->cr_uid;
2014 sc->sc_gid = td->td_ucred->cr_rgid;
2015 sc->sc_egid = td->td_ucred->cr_gid;
2016 sc->sc_ngroups = ngroups;
2017 for (i = 0; i < sc->sc_ngroups; i++)
2018 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
2021 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
2022 * created SCM_CREDS control message (struct sockcred) has another
2025 if (control != NULL)
2026 for (n = control, n_prev = NULL; n != NULL;) {
2027 cm = mtod(n, struct cmsghdr *);
2028 if (cm->cmsg_level == SOL_SOCKET &&
2029 cm->cmsg_type == SCM_CREDS) {
2031 control = n->m_next;
2033 n_prev->m_next = n->m_next;
2041 /* Prepend it to the head. */
2042 m->m_next = control;
2046 static struct unpcb *
2047 fptounp(struct file *fp)
2051 if (fp->f_type != DTYPE_SOCKET)
2053 if ((so = fp->f_data) == NULL)
2055 if (so->so_proto->pr_domain != &localdomain)
2057 return sotounpcb(so);
2061 unp_discard(struct file *fp)
2063 struct unp_defer *dr;
2065 if (unp_externalize_fp(fp)) {
2066 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
2068 UNP_DEFERRED_LOCK();
2069 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
2070 UNP_DEFERRED_UNLOCK();
2071 atomic_add_int(&unp_defers_count, 1);
2072 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
2074 (void) closef(fp, (struct thread *)NULL);
2078 unp_process_defers(void *arg __unused, int pending)
2080 struct unp_defer *dr;
2081 SLIST_HEAD(, unp_defer) drl;
2086 UNP_DEFERRED_LOCK();
2087 if (SLIST_FIRST(&unp_defers) == NULL) {
2088 UNP_DEFERRED_UNLOCK();
2091 SLIST_SWAP(&unp_defers, &drl, unp_defer);
2092 UNP_DEFERRED_UNLOCK();
2094 while ((dr = SLIST_FIRST(&drl)) != NULL) {
2095 SLIST_REMOVE_HEAD(&drl, ud_link);
2096 closef(dr->ud_fp, NULL);
2100 atomic_add_int(&unp_defers_count, -count);
2105 unp_internalize_fp(struct file *fp)
2110 if ((unp = fptounp(fp)) != NULL) {
2112 unp->unp_msgcount++;
2120 unp_externalize_fp(struct file *fp)
2126 if ((unp = fptounp(fp)) != NULL) {
2127 unp->unp_msgcount--;
2137 * unp_defer indicates whether additional work has been defered for a future
2138 * pass through unp_gc(). It is thread local and does not require explicit
2141 static int unp_marked;
2142 static int unp_unreachable;
2145 unp_accessable(struct filedescent **fdep, int fdcount)
2151 for (i = 0; i < fdcount; i++) {
2152 fp = fdep[i]->fde_file;
2153 if ((unp = fptounp(fp)) == NULL)
2155 if (unp->unp_gcflag & UNPGC_REF)
2157 unp->unp_gcflag &= ~UNPGC_DEAD;
2158 unp->unp_gcflag |= UNPGC_REF;
2164 unp_gc_process(struct unpcb *unp)
2170 /* Already processed. */
2171 if (unp->unp_gcflag & UNPGC_SCANNED)
2176 * Check for a socket potentially in a cycle. It must be in a
2177 * queue as indicated by msgcount, and this must equal the file
2178 * reference count. Note that when msgcount is 0 the file is NULL.
2180 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2181 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2182 unp->unp_gcflag |= UNPGC_DEAD;
2188 * Mark all sockets we reference with RIGHTS.
2190 so = unp->unp_socket;
2191 SOCKBUF_LOCK(&so->so_rcv);
2192 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2193 SOCKBUF_UNLOCK(&so->so_rcv);
2196 * Mark all sockets in our accept queue.
2199 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2200 SOCKBUF_LOCK(&soa->so_rcv);
2201 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2202 SOCKBUF_UNLOCK(&soa->so_rcv);
2205 unp->unp_gcflag |= UNPGC_SCANNED;
2208 static int unp_recycled;
2209 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2210 "Number of unreachable sockets claimed by the garbage collector.");
2212 static int unp_taskcount;
2213 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2214 "Number of times the garbage collector has run.");
2217 unp_gc(__unused void *arg, int pending)
2219 struct unp_head *heads[] = { &unp_dhead, &unp_shead, &unp_sphead,
2221 struct unp_head **head;
2222 struct file *f, **unref;
2229 * First clear all gc flags from previous runs.
2231 for (head = heads; *head != NULL; head++)
2232 LIST_FOREACH(unp, *head, unp_link)
2233 unp->unp_gcflag = 0;
2236 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2237 * is reachable all of the sockets it references are reachable.
2238 * Stop the scan once we do a complete loop without discovering
2239 * a new reachable socket.
2242 unp_unreachable = 0;
2244 for (head = heads; *head != NULL; head++)
2245 LIST_FOREACH(unp, *head, unp_link)
2246 unp_gc_process(unp);
2247 } while (unp_marked);
2249 if (unp_unreachable == 0)
2253 * Allocate space for a local list of dead unpcbs.
2255 unref = malloc(unp_unreachable * sizeof(struct file *),
2259 * Iterate looking for sockets which have been specifically marked
2260 * as as unreachable and store them locally.
2264 for (total = 0, head = heads; *head != NULL; head++)
2265 LIST_FOREACH(unp, *head, unp_link)
2266 if ((unp->unp_gcflag & UNPGC_DEAD) != 0) {
2268 if (unp->unp_msgcount == 0 || f == NULL ||
2269 f->f_count != unp->unp_msgcount)
2273 KASSERT(total <= unp_unreachable,
2274 ("unp_gc: incorrect unreachable count."));
2280 * Now flush all sockets, free'ing rights. This will free the
2281 * struct files associated with these sockets but leave each socket
2282 * with one remaining ref.
2284 for (i = 0; i < total; i++) {
2287 so = unref[i]->f_data;
2288 CURVNET_SET(so->so_vnet);
2294 * And finally release the sockets so they can be reclaimed.
2296 for (i = 0; i < total; i++)
2297 fdrop(unref[i], NULL);
2298 unp_recycled += total;
2299 free(unref, M_TEMP);
2303 unp_dispose(struct mbuf *m)
2307 unp_scan(m, unp_freerights);
2311 unp_scan(struct mbuf *m0, void (*op)(struct filedescent **, int))
2316 socklen_t clen, datalen;
2318 while (m0 != NULL) {
2319 for (m = m0; m; m = m->m_next) {
2320 if (m->m_type != MT_CONTROL)
2323 cm = mtod(m, struct cmsghdr *);
2326 while (cm != NULL) {
2327 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2330 data = CMSG_DATA(cm);
2331 datalen = (caddr_t)cm + cm->cmsg_len
2334 if (cm->cmsg_level == SOL_SOCKET &&
2335 cm->cmsg_type == SCM_RIGHTS) {
2336 (*op)(data, datalen /
2337 sizeof(struct filedescent *));
2340 if (CMSG_SPACE(datalen) < clen) {
2341 clen -= CMSG_SPACE(datalen);
2342 cm = (struct cmsghdr *)
2343 ((caddr_t)cm + CMSG_SPACE(datalen));
2355 * A helper function called by VFS before socket-type vnode reclamation.
2356 * For an active vnode it clears unp_vnode pointer and decrements unp_vnode
2360 vfs_unp_reclaim(struct vnode *vp)
2366 ASSERT_VOP_ELOCKED(vp, "vfs_unp_reclaim");
2367 KASSERT(vp->v_type == VSOCK,
2368 ("vfs_unp_reclaim: vp->v_type != VSOCK"));
2372 VOP_UNP_CONNECT(vp, &so);
2375 unp = sotounpcb(so);
2379 if (unp->unp_vnode == vp) {
2381 unp->unp_vnode = NULL;
2384 UNP_PCB_UNLOCK(unp);
2393 db_print_indent(int indent)
2397 for (i = 0; i < indent; i++)
2402 db_print_unpflags(int unp_flags)
2407 if (unp_flags & UNP_HAVEPC) {
2408 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2411 if (unp_flags & UNP_HAVEPCCACHED) {
2412 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2415 if (unp_flags & UNP_WANTCRED) {
2416 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2419 if (unp_flags & UNP_CONNWAIT) {
2420 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2423 if (unp_flags & UNP_CONNECTING) {
2424 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2427 if (unp_flags & UNP_BINDING) {
2428 db_printf("%sUNP_BINDING", comma ? ", " : "");
2434 db_print_xucred(int indent, struct xucred *xu)
2438 db_print_indent(indent);
2439 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2440 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2441 db_print_indent(indent);
2442 db_printf("cr_groups: ");
2444 for (i = 0; i < xu->cr_ngroups; i++) {
2445 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2452 db_print_unprefs(int indent, struct unp_head *uh)
2458 LIST_FOREACH(unp, uh, unp_reflink) {
2459 if (counter % 4 == 0)
2460 db_print_indent(indent);
2461 db_printf("%p ", unp);
2462 if (counter % 4 == 3)
2466 if (counter != 0 && counter % 4 != 0)
2470 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2475 db_printf("usage: show unpcb <addr>\n");
2478 unp = (struct unpcb *)addr;
2480 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2483 db_printf("unp_ino: %ju unp_conn: %p\n", (uintmax_t)unp->unp_ino,
2486 db_printf("unp_refs:\n");
2487 db_print_unprefs(2, &unp->unp_refs);
2489 /* XXXRW: Would be nice to print the full address, if any. */
2490 db_printf("unp_addr: %p\n", unp->unp_addr);
2492 db_printf("unp_gencnt: %llu\n",
2493 (unsigned long long)unp->unp_gencnt);
2495 db_printf("unp_flags: %x (", unp->unp_flags);
2496 db_print_unpflags(unp->unp_flags);
2499 db_printf("unp_peercred:\n");
2500 db_print_xucred(2, &unp->unp_peercred);
2502 db_printf("unp_refcount: %u\n", unp->unp_refcount);