2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004-2007 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
59 #include <sys/cdefs.h>
60 __FBSDID("$FreeBSD$");
64 #include <sys/param.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>
72 #include <sys/kernel.h>
75 #include <sys/mount.h>
76 #include <sys/mutex.h>
77 #include <sys/namei.h>
79 #include <sys/protosw.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>
94 #include <security/mac/mac_framework.h>
98 static uma_zone_t unp_zone;
99 static unp_gen_t unp_gencnt;
100 static u_int unp_count; /* Count of local sockets. */
101 static ino_t unp_ino; /* Prototype for fake inode numbers. */
102 static int unp_rights; /* File descriptors in flight. */
103 static struct unp_head unp_shead; /* List of local stream sockets. */
104 static struct unp_head unp_dhead; /* List of local datagram sockets. */
106 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
109 * Garbage collection of cyclic file descriptor/socket references occurs
110 * asynchronously in a taskqueue context in order to avoid recursion and
111 * reentrance in the UNIX domain socket, file descriptor, and socket layer
112 * code. See unp_gc() for a full description.
114 static struct task unp_gc_task;
117 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
118 * stream sockets, although the total for sender and receiver is actually
121 * Datagram sockets really use the sendspace as the maximum datagram size,
122 * and don't really want to reserve the sendspace. Their recvspace should be
123 * large enough for at least one max-size datagram plus address.
128 static u_long unpst_sendspace = PIPSIZ;
129 static u_long unpst_recvspace = PIPSIZ;
130 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
131 static u_long unpdg_recvspace = 4*1024;
133 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
134 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
135 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
137 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
138 &unpst_sendspace, 0, "");
139 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
140 &unpst_recvspace, 0, "");
141 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
142 &unpdg_sendspace, 0, "");
143 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
144 &unpdg_recvspace, 0, "");
145 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
148 * Locking and synchronization:
150 * The global UNIX domain socket rwlock (unp_global_rwlock) protects all
151 * global variables, including the linked lists tracking the set of allocated
152 * UNIX domain sockets. The global rwlock also serves to prevent deadlock
153 * when more than one PCB lock is acquired at a time (i.e., during
154 * connect()). Finally, the global rwlock protects uncounted references from
155 * vnodes to sockets bound to those vnodes: to safely dereference the
156 * v_socket pointer, the global rwlock must be held while a full reference is
159 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
160 * allocated in pru_attach() and freed in pru_detach(). The validity of that
161 * pointer is an invariant, so no lock is required to dereference the so_pcb
162 * pointer if a valid socket reference is held by the caller. In practice,
163 * this is always true during operations performed on a socket. Each unpcb
164 * has a back-pointer to its socket, unp_socket, which will be stable under
165 * the same circumstances.
167 * This pointer may only be safely dereferenced as long as a valid reference
168 * to the unpcb is held. Typically, this reference will be from the socket,
169 * or from another unpcb when the referring unpcb's lock is held (in order
170 * that the reference not be invalidated during use). For example, to follow
171 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
172 * as unp_socket remains valid as long as the reference to unp_conn is valid.
174 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
175 * atomic reads without the lock may be performed "lockless", but more
176 * complex reads and read-modify-writes require the mutex to be held. No
177 * lock order is defined between unpcb locks -- multiple unpcb locks may be
178 * acquired at the same time only when holding the global UNIX domain socket
179 * rwlock exclusively, which prevents deadlocks.
181 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
182 * protocols, bind() is a non-atomic operation, and connect() requires
183 * potential sleeping in the protocol, due to potentially waiting on local or
184 * distributed file systems. We try to separate "lookup" operations, which
185 * may sleep, and the IPC operations themselves, which typically can occur
186 * with relative atomicity as locks can be held over the entire operation.
188 * Another tricky issue is simultaneous multi-threaded or multi-process
189 * access to a single UNIX domain socket. These are handled by the flags
190 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
191 * binding, both of which involve dropping UNIX domain socket locks in order
192 * to perform namei() and other file system operations.
194 static struct rwlock unp_global_rwlock;
196 #define UNP_GLOBAL_LOCK_INIT() rw_init(&unp_global_rwlock, \
199 #define UNP_GLOBAL_LOCK_ASSERT() rw_assert(&unp_global_rwlock, \
201 #define UNP_GLOBAL_UNLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
204 #define UNP_GLOBAL_WLOCK() rw_wlock(&unp_global_rwlock)
205 #define UNP_GLOBAL_WUNLOCK() rw_wunlock(&unp_global_rwlock)
206 #define UNP_GLOBAL_WLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
208 #define UNP_GLOBAL_WOWNED() rw_wowned(&unp_global_rwlock)
210 #define UNP_GLOBAL_RLOCK() rw_rlock(&unp_global_rwlock)
211 #define UNP_GLOBAL_RUNLOCK() rw_runlock(&unp_global_rwlock)
212 #define UNP_GLOBAL_RLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
215 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
216 "unp_mtx", "unp_mtx", \
217 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
218 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
219 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
220 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
221 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
223 static int unp_connect(struct socket *, struct sockaddr *,
225 static int unp_connect2(struct socket *so, struct socket *so2, int);
226 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
227 static void unp_shutdown(struct unpcb *);
228 static void unp_drop(struct unpcb *, int);
229 static void unp_gc(__unused void *, int);
230 static void unp_scan(struct mbuf *, void (*)(struct file *));
231 static void unp_mark(struct file *);
232 static void unp_discard(struct file *);
233 static void unp_freerights(struct file **, int);
234 static int unp_internalize(struct mbuf **, struct thread *);
235 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
238 * Definitions of protocols supported in the LOCAL domain.
240 static struct domain localdomain;
241 static struct protosw localsw[] = {
243 .pr_type = SOCK_STREAM,
244 .pr_domain = &localdomain,
245 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
246 .pr_ctloutput = &uipc_ctloutput,
247 .pr_usrreqs = &uipc_usrreqs
250 .pr_type = SOCK_DGRAM,
251 .pr_domain = &localdomain,
252 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
253 .pr_usrreqs = &uipc_usrreqs
257 static struct domain localdomain = {
258 .dom_family = AF_LOCAL,
260 .dom_init = unp_init,
261 .dom_externalize = unp_externalize,
262 .dom_dispose = unp_dispose,
263 .dom_protosw = localsw,
264 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
269 uipc_abort(struct socket *so)
271 struct unpcb *unp, *unp2;
274 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
278 unp2 = unp->unp_conn;
281 unp_drop(unp2, ECONNABORTED);
282 UNP_PCB_UNLOCK(unp2);
285 UNP_GLOBAL_WUNLOCK();
289 uipc_accept(struct socket *so, struct sockaddr **nam)
291 struct unpcb *unp, *unp2;
292 const struct sockaddr *sa;
295 * Pass back name of connected socket, if it was bound and we are
296 * still connected (our peer may have closed already!).
299 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
301 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
303 unp2 = unp->unp_conn;
304 if (unp2 != NULL && unp2->unp_addr != NULL) {
306 sa = (struct sockaddr *) unp2->unp_addr;
307 bcopy(sa, *nam, sa->sa_len);
308 UNP_PCB_UNLOCK(unp2);
311 bcopy(sa, *nam, sa->sa_len);
313 UNP_GLOBAL_RUNLOCK();
318 uipc_attach(struct socket *so, int proto, struct thread *td)
320 u_long sendspace, recvspace;
324 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
325 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
326 switch (so->so_type) {
328 sendspace = unpst_sendspace;
329 recvspace = unpst_recvspace;
333 sendspace = unpdg_sendspace;
334 recvspace = unpdg_recvspace;
338 panic("uipc_attach");
340 error = soreserve(so, sendspace, recvspace);
344 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
347 LIST_INIT(&unp->unp_refs);
348 UNP_PCB_LOCK_INIT(unp);
349 unp->unp_socket = so;
351 unp->unp_refcount = 1;
355 * uipc_attach() may be called indirectly from within the UNIX domain
356 * socket code via sonewconn() in unp_connect(). Since rwlocks can
357 * not be recursed, we do the closest thing.
359 if (!UNP_GLOBAL_WOWNED()) {
363 unp->unp_gencnt = ++unp_gencnt;
365 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
368 UNP_GLOBAL_WUNLOCK();
374 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
376 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
386 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
388 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
393 * We don't allow simultaneous bind() calls on a single UNIX domain
394 * socket, so flag in-progress operations, and return an error if an
395 * operation is already in progress.
397 * Historically, we have not allowed a socket to be rebound, so this
398 * also returns an error. Not allowing re-binding certainly
399 * simplifies the implementation and avoids a great many possible
403 if (unp->unp_vnode != NULL) {
407 if (unp->unp_flags & UNP_BINDING) {
411 unp->unp_flags |= UNP_BINDING;
414 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
415 strlcpy(buf, soun->sun_path, namelen + 1);
419 mtx_assert(&Giant, MA_OWNED);
420 NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
422 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
427 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
428 NDFREE(&nd, NDF_ONLY_PNBUF);
438 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
444 vattr.va_type = VSOCK;
445 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
447 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
451 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
452 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
454 NDFREE(&nd, NDF_ONLY_PNBUF);
457 vn_finished_write(mp);
461 ASSERT_VOP_LOCKED(vp, "uipc_bind");
462 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
466 vp->v_socket = unp->unp_socket;
468 unp->unp_addr = soun;
469 unp->unp_flags &= ~UNP_BINDING;
471 UNP_GLOBAL_WUNLOCK();
472 VOP_UNLOCK(vp, 0, td);
473 vn_finished_write(mp);
480 unp->unp_flags &= ~UNP_BINDING;
488 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
492 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
494 error = unp_connect(so, nam, td);
495 UNP_GLOBAL_WUNLOCK();
500 uipc_close(struct socket *so)
502 struct unpcb *unp, *unp2;
505 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
509 unp2 = unp->unp_conn;
512 unp_disconnect(unp, unp2);
513 UNP_PCB_UNLOCK(unp2);
516 UNP_GLOBAL_WUNLOCK();
520 uipc_connect2(struct socket *so1, struct socket *so2)
522 struct unpcb *unp, *unp2;
527 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
530 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
532 error = unp_connect2(so1, so2, PRU_CONNECT2);
533 UNP_PCB_UNLOCK(unp2);
535 UNP_GLOBAL_WUNLOCK();
539 /* control is EOPNOTSUPP */
542 uipc_detach(struct socket *so)
544 struct unpcb *unp, *unp2;
545 struct sockaddr_un *saved_unp_addr;
547 int freeunp, local_unp_rights;
550 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
555 LIST_REMOVE(unp, unp_link);
556 unp->unp_gencnt = ++unp_gencnt;
560 * XXXRW: Should assert vp->v_socket == so.
562 if ((vp = unp->unp_vnode) != NULL) {
563 unp->unp_vnode->v_socket = NULL;
564 unp->unp_vnode = NULL;
566 unp2 = unp->unp_conn;
569 unp_disconnect(unp, unp2);
570 UNP_PCB_UNLOCK(unp2);
574 * We hold the global lock, so it's OK to acquire multiple pcb locks
577 while (!LIST_EMPTY(&unp->unp_refs)) {
578 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
581 unp_drop(ref, ECONNRESET);
584 UNP_GLOBAL_WUNLOCK();
585 unp->unp_socket->so_pcb = NULL;
586 local_unp_rights = unp_rights;
587 saved_unp_addr = unp->unp_addr;
588 unp->unp_addr = NULL;
590 freeunp = (unp->unp_refcount == 0);
591 if (saved_unp_addr != NULL)
592 FREE(saved_unp_addr, M_SONAME);
594 UNP_PCB_LOCK_DESTROY(unp);
595 uma_zfree(unp_zone, unp);
601 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
603 VFS_UNLOCK_GIANT(vfslocked);
605 if (local_unp_rights)
606 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
610 uipc_disconnect(struct socket *so)
612 struct unpcb *unp, *unp2;
615 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
619 unp2 = unp->unp_conn;
622 unp_disconnect(unp, unp2);
623 UNP_PCB_UNLOCK(unp2);
626 UNP_GLOBAL_WUNLOCK();
631 uipc_listen(struct socket *so, int backlog, struct thread *td)
637 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
640 if (unp->unp_vnode == NULL) {
646 error = solisten_proto_check(so);
648 cru2x(td->td_ucred, &unp->unp_peercred);
649 unp->unp_flags |= UNP_HAVEPCCACHED;
650 solisten_proto(so, backlog);
658 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
660 struct unpcb *unp, *unp2;
661 const struct sockaddr *sa;
664 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
666 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
669 * XXX: It seems that this test always fails even when connection is
670 * established. So, this else clause is added as workaround to
671 * return PF_LOCAL sockaddr.
673 unp2 = unp->unp_conn;
676 if (unp2->unp_addr != NULL)
677 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
680 bcopy(sa, *nam, sa->sa_len);
681 UNP_PCB_UNLOCK(unp2);
684 bcopy(sa, *nam, sa->sa_len);
691 uipc_rcvd(struct socket *so, int flags)
693 struct unpcb *unp, *unp2;
699 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
701 if (so->so_type == SOCK_DGRAM)
702 panic("uipc_rcvd DGRAM?");
704 if (so->so_type != SOCK_STREAM)
705 panic("uipc_rcvd unknown socktype");
708 * Adjust backpressure on sender and wakeup any waiting to write.
710 * The consistency requirements here are a bit complex: we must
711 * acquire the lock for our own unpcb in order to prevent it from
712 * disconnecting while in use, changing the unp_conn peer. We do not
713 * need unp2's lock, since the unp2->unp_socket pointer will remain
714 * static as long as the unp2 pcb is valid, which it will be until we
715 * release unp's lock to allow a disconnect. We do need socket
716 * mutexes for both socket endpoints since we manipulate fields in
717 * both; we hold both locks at once since we access both
720 SOCKBUF_LOCK(&so->so_rcv);
721 mbcnt = so->so_rcv.sb_mbcnt;
722 sbcc = so->so_rcv.sb_cc;
723 SOCKBUF_UNLOCK(&so->so_rcv);
725 unp2 = unp->unp_conn;
730 so2 = unp2->unp_socket;
731 SOCKBUF_LOCK(&so2->so_snd);
732 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
733 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
734 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
735 newhiwat, RLIM_INFINITY);
736 sowwakeup_locked(so2);
737 unp->unp_mbcnt = mbcnt;
743 /* pru_rcvoob is EOPNOTSUPP */
746 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
747 struct mbuf *control, struct thread *td)
749 struct unpcb *unp, *unp2;
756 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
758 if (flags & PRUS_OOB) {
763 if (control != NULL && (error = unp_internalize(&control, td)))
766 if ((nam != NULL) || (flags & PRUS_EOF))
771 switch (so->so_type) {
774 const struct sockaddr *from;
776 unp2 = unp->unp_conn;
778 UNP_GLOBAL_WLOCK_ASSERT();
783 error = unp_connect(so, nam, td);
786 unp2 = unp->unp_conn;
794 * Because connect() and send() are non-atomic in a sendto()
795 * with a target address, it's possible that the socket will
796 * have disconnected before the send() can run. In that case
797 * return the slightly counter-intuitive but otherwise
798 * correct error that the socket is not connected.
805 if (unp2->unp_flags & UNP_WANTCRED)
806 control = unp_addsockcred(td, control);
808 if (unp->unp_addr != NULL)
809 from = (struct sockaddr *)unp->unp_addr;
812 so2 = unp2->unp_socket;
813 SOCKBUF_LOCK(&so2->so_rcv);
814 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
815 sorwakeup_locked(so2);
819 SOCKBUF_UNLOCK(&so2->so_rcv);
823 UNP_GLOBAL_WLOCK_ASSERT();
825 unp_disconnect(unp, unp2);
826 UNP_PCB_UNLOCK(unp2);
834 * Connect if not connected yet.
836 * Note: A better implementation would complain if not equal
837 * to the peer's address.
839 if ((so->so_state & SS_ISCONNECTED) == 0) {
841 UNP_GLOBAL_WLOCK_ASSERT();
842 error = unp_connect(so, nam, td);
852 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
857 * Because connect() and send() are non-atomic in a sendto()
858 * with a target address, it's possible that the socket will
859 * have disconnected before the send() can run. In that case
860 * return the slightly counter-intuitive but otherwise
861 * correct error that the socket is not connected.
863 * Lock order here has to be handled carefully: we hold the
864 * global lock, so acquiring two unpcb locks is OK. We must
865 * acquire both before acquiring any socket mutexes. We must
866 * also acquire the local socket send mutex before the remote
867 * socket receive mutex. The only tricky thing is making
868 * sure to acquire the unp2 lock before the local socket send
869 * lock, or we will experience deadlocks.
871 unp2 = unp->unp_conn;
876 so2 = unp2->unp_socket;
878 SOCKBUF_LOCK(&so2->so_rcv);
879 if (unp2->unp_flags & UNP_WANTCRED) {
881 * Credentials are passed only once on SOCK_STREAM.
883 unp2->unp_flags &= ~UNP_WANTCRED;
884 control = unp_addsockcred(td, control);
887 * Send to paired receive port, and then reduce send buffer
888 * hiwater marks to maintain backpressure. Wake up readers.
890 if (control != NULL) {
891 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
894 sbappend_locked(&so2->so_rcv, m);
895 mbcnt = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
896 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
897 sbcc = so2->so_rcv.sb_cc;
898 sorwakeup_locked(so2);
900 SOCKBUF_LOCK(&so->so_snd);
901 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
902 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
903 newhiwat, RLIM_INFINITY);
904 so->so_snd.sb_mbmax -= mbcnt;
905 SOCKBUF_UNLOCK(&so->so_snd);
907 UNP_PCB_UNLOCK(unp2);
912 panic("uipc_send unknown socktype");
916 * SEND_EOF is equivalent to a SEND followed by a SHUTDOWN.
918 if (flags & PRUS_EOF) {
925 if ((nam != NULL) || (flags & PRUS_EOF))
926 UNP_GLOBAL_WUNLOCK();
928 UNP_GLOBAL_RUNLOCK();
930 if (control != NULL && error != 0)
931 unp_dispose(control);
942 uipc_sense(struct socket *so, struct stat *sb)
944 struct unpcb *unp, *unp2;
948 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
950 sb->st_blksize = so->so_snd.sb_hiwat;
953 unp2 = unp->unp_conn;
954 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
955 so2 = unp2->unp_socket;
956 sb->st_blksize += so2->so_rcv.sb_cc;
959 if (unp->unp_ino == 0)
960 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
961 sb->st_ino = unp->unp_ino;
963 UNP_GLOBAL_RUNLOCK();
968 uipc_shutdown(struct socket *so)
973 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
980 UNP_GLOBAL_WUNLOCK();
985 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
988 const struct sockaddr *sa;
991 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
993 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
995 if (unp->unp_addr != NULL)
996 sa = (struct sockaddr *) unp->unp_addr;
999 bcopy(sa, *nam, sa->sa_len);
1000 UNP_PCB_UNLOCK(unp);
1004 struct pr_usrreqs uipc_usrreqs = {
1005 .pru_abort = uipc_abort,
1006 .pru_accept = uipc_accept,
1007 .pru_attach = uipc_attach,
1008 .pru_bind = uipc_bind,
1009 .pru_connect = uipc_connect,
1010 .pru_connect2 = uipc_connect2,
1011 .pru_detach = uipc_detach,
1012 .pru_disconnect = uipc_disconnect,
1013 .pru_listen = uipc_listen,
1014 .pru_peeraddr = uipc_peeraddr,
1015 .pru_rcvd = uipc_rcvd,
1016 .pru_send = uipc_send,
1017 .pru_sense = uipc_sense,
1018 .pru_shutdown = uipc_shutdown,
1019 .pru_sockaddr = uipc_sockaddr,
1020 .pru_close = uipc_close,
1024 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1030 if (sopt->sopt_level != 0)
1033 unp = sotounpcb(so);
1034 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1036 switch (sopt->sopt_dir) {
1038 switch (sopt->sopt_name) {
1039 case LOCAL_PEERCRED:
1041 if (unp->unp_flags & UNP_HAVEPC)
1042 xu = unp->unp_peercred;
1044 if (so->so_type == SOCK_STREAM)
1049 UNP_PCB_UNLOCK(unp);
1051 error = sooptcopyout(sopt, &xu, sizeof(xu));
1056 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1057 error = sooptcopyout(sopt, &optval, sizeof(optval));
1060 case LOCAL_CONNWAIT:
1062 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1063 error = sooptcopyout(sopt, &optval, sizeof(optval));
1073 switch (sopt->sopt_name) {
1075 case LOCAL_CONNWAIT:
1076 error = sooptcopyin(sopt, &optval, sizeof(optval),
1081 #define OPTSET(bit) do { \
1082 UNP_PCB_LOCK(unp); \
1084 unp->unp_flags |= bit; \
1086 unp->unp_flags &= ~bit; \
1087 UNP_PCB_UNLOCK(unp); \
1090 switch (sopt->sopt_name) {
1092 OPTSET(UNP_WANTCRED);
1095 case LOCAL_CONNWAIT:
1096 OPTSET(UNP_CONNWAIT);
1105 error = ENOPROTOOPT;
1118 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1120 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1122 struct socket *so2, *so3;
1123 struct unpcb *unp, *unp2, *unp3;
1125 struct nameidata nd;
1126 char buf[SOCK_MAXADDRLEN];
1127 struct sockaddr *sa;
1129 UNP_GLOBAL_WLOCK_ASSERT();
1130 UNP_GLOBAL_WUNLOCK();
1132 unp = sotounpcb(so);
1133 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1135 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1138 strlcpy(buf, soun->sun_path, len + 1);
1141 if (unp->unp_flags & UNP_CONNECTING) {
1142 UNP_PCB_UNLOCK(unp);
1145 unp->unp_flags |= UNP_CONNECTING;
1146 UNP_PCB_UNLOCK(unp);
1148 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1150 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
1156 ASSERT_VOP_LOCKED(vp, "unp_connect");
1157 NDFREE(&nd, NDF_ONLY_PNBUF);
1161 if (vp->v_type != VSOCK) {
1166 error = mac_check_vnode_open(td->td_ucred, vp, VWRITE | VREAD);
1170 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1175 unp = sotounpcb(so);
1176 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1179 * Lock global lock for two reasons: make sure v_socket is stable,
1180 * and to protect simultaneous locking of multiple pcbs.
1185 error = ECONNREFUSED;
1188 if (so->so_type != so2->so_type) {
1192 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1193 if (so2->so_options & SO_ACCEPTCONN) {
1195 * We can't drop the global lock here or 'so2' may
1196 * become invalid, meaning that we will later recurse
1197 * back into the UNIX domain socket code while
1198 * holding the global lock.
1200 so3 = sonewconn(so2, 0);
1204 error = ECONNREFUSED;
1207 unp = sotounpcb(so);
1208 unp2 = sotounpcb(so2);
1209 unp3 = sotounpcb(so3);
1213 if (unp2->unp_addr != NULL) {
1214 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1215 unp3->unp_addr = (struct sockaddr_un *) sa;
1219 * unp_peercred management:
1221 * The connecter's (client's) credentials are copied from its
1222 * process structure at the time of connect() (which is now).
1224 cru2x(td->td_ucred, &unp3->unp_peercred);
1225 unp3->unp_flags |= UNP_HAVEPC;
1227 * The receiver's (server's) credentials are copied from the
1228 * unp_peercred member of socket on which the former called
1229 * listen(); uipc_listen() cached that process's credentials
1230 * at that time so we can use them now.
1232 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1233 ("unp_connect: listener without cached peercred"));
1234 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1235 sizeof(unp->unp_peercred));
1236 unp->unp_flags |= UNP_HAVEPC;
1237 if (unp2->unp_flags & UNP_WANTCRED)
1238 unp3->unp_flags |= UNP_WANTCRED;
1239 UNP_PCB_UNLOCK(unp3);
1240 UNP_PCB_UNLOCK(unp2);
1241 UNP_PCB_UNLOCK(unp);
1244 mac_set_socket_peer_from_socket(so, so3);
1245 mac_set_socket_peer_from_socket(so3, so);
1251 unp = sotounpcb(so);
1252 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1253 unp2 = sotounpcb(so2);
1254 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1257 error = unp_connect2(so, so2, PRU_CONNECT);
1258 UNP_PCB_UNLOCK(unp2);
1259 UNP_PCB_UNLOCK(unp);
1261 UNP_GLOBAL_WUNLOCK();
1264 mtx_assert(&Giant, MA_OWNED);
1271 unp->unp_flags &= ~UNP_CONNECTING;
1272 UNP_PCB_UNLOCK(unp);
1277 unp_connect2(struct socket *so, struct socket *so2, int req)
1282 unp = sotounpcb(so);
1283 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1284 unp2 = sotounpcb(so2);
1285 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1287 UNP_GLOBAL_WLOCK_ASSERT();
1288 UNP_PCB_LOCK_ASSERT(unp);
1289 UNP_PCB_LOCK_ASSERT(unp2);
1291 if (so2->so_type != so->so_type)
1292 return (EPROTOTYPE);
1293 unp->unp_conn = unp2;
1295 switch (so->so_type) {
1297 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1302 unp2->unp_conn = unp;
1303 if (req == PRU_CONNECT &&
1304 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1312 panic("unp_connect2");
1318 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1322 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1324 UNP_GLOBAL_WLOCK_ASSERT();
1325 UNP_PCB_LOCK_ASSERT(unp);
1326 UNP_PCB_LOCK_ASSERT(unp2);
1328 unp->unp_conn = NULL;
1329 switch (unp->unp_socket->so_type) {
1331 LIST_REMOVE(unp, unp_reflink);
1332 so = unp->unp_socket;
1334 so->so_state &= ~SS_ISCONNECTED;
1339 soisdisconnected(unp->unp_socket);
1340 unp2->unp_conn = NULL;
1341 soisdisconnected(unp2->unp_socket);
1347 * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed by
1348 * the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers are
1349 * safe to reference. It first scans the list of struct unpcb's to generate
1350 * a pointer list, then it rescans its list one entry at a time to
1351 * externalize and copyout. It checks the generation number to see if a
1352 * struct unpcb has been reused, and will skip it if so.
1355 unp_pcblist(SYSCTL_HANDLER_ARGS)
1359 struct unpcb *unp, **unp_list;
1361 struct xunpgen *xug;
1362 struct unp_head *head;
1365 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1368 * The process of preparing the PCB list is too time-consuming and
1369 * resource-intensive to repeat twice on every request.
1371 if (req->oldptr == NULL) {
1373 req->oldidx = 2 * (sizeof *xug)
1374 + (n + n/8) * sizeof(struct xunpcb);
1378 if (req->newptr != NULL)
1382 * OK, now we're committed to doing something.
1384 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1386 gencnt = unp_gencnt;
1388 UNP_GLOBAL_RUNLOCK();
1390 xug->xug_len = sizeof *xug;
1392 xug->xug_gen = gencnt;
1393 xug->xug_sogen = so_gencnt;
1394 error = SYSCTL_OUT(req, xug, sizeof *xug);
1400 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1403 * XXXRW: Note, this code relies very explicitly in pcb's being type
1407 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1408 unp = LIST_NEXT(unp, unp_link)) {
1410 if (unp->unp_gencnt <= gencnt) {
1411 if (cr_cansee(req->td->td_ucred,
1412 unp->unp_socket->so_cred)) {
1413 UNP_PCB_UNLOCK(unp);
1416 unp_list[i++] = unp;
1417 unp->unp_refcount++;
1419 UNP_PCB_UNLOCK(unp);
1421 UNP_GLOBAL_RUNLOCK();
1422 n = i; /* In case we lost some during malloc. */
1425 * XXXRW: The logic below asumes that it is OK to lock a mutex in
1426 * an unpcb that may have been freed.
1429 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1430 for (i = 0; i < n; i++) {
1433 unp->unp_refcount--;
1434 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1435 xu->xu_len = sizeof *xu;
1438 * XXX - need more locking here to protect against
1439 * connect/disconnect races for SMP.
1441 if (unp->unp_addr != NULL)
1442 bcopy(unp->unp_addr, &xu->xu_addr,
1443 unp->unp_addr->sun_len);
1444 if (unp->unp_conn != NULL &&
1445 unp->unp_conn->unp_addr != NULL)
1446 bcopy(unp->unp_conn->unp_addr,
1448 unp->unp_conn->unp_addr->sun_len);
1449 bcopy(unp, &xu->xu_unp, sizeof *unp);
1450 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1451 UNP_PCB_UNLOCK(unp);
1452 error = SYSCTL_OUT(req, xu, sizeof *xu);
1454 freeunp = (unp->unp_refcount == 0);
1455 UNP_PCB_UNLOCK(unp);
1457 UNP_PCB_LOCK_DESTROY(unp);
1458 uma_zfree(unp_zone, unp);
1465 * Give the user an updated idea of our state. If the
1466 * generation differs from what we told her before, she knows
1467 * that something happened while we were processing this
1468 * request, and it might be necessary to retry.
1470 xug->xug_gen = unp_gencnt;
1471 xug->xug_sogen = so_gencnt;
1472 xug->xug_count = unp_count;
1473 error = SYSCTL_OUT(req, xug, sizeof *xug);
1475 free(unp_list, M_TEMP);
1480 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1481 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1482 "List of active local datagram sockets");
1483 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1484 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1485 "List of active local stream sockets");
1488 unp_shutdown(struct unpcb *unp)
1493 UNP_GLOBAL_WLOCK_ASSERT();
1494 UNP_PCB_LOCK_ASSERT(unp);
1496 unp2 = unp->unp_conn;
1497 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1498 so = unp2->unp_socket;
1505 unp_drop(struct unpcb *unp, int errno)
1507 struct socket *so = unp->unp_socket;
1510 UNP_GLOBAL_WLOCK_ASSERT();
1511 UNP_PCB_LOCK_ASSERT(unp);
1513 so->so_error = errno;
1514 unp2 = unp->unp_conn;
1519 unp_disconnect(unp, unp2);
1520 UNP_PCB_UNLOCK(unp2);
1524 unp_freerights(struct file **rp, int fdcount)
1529 for (i = 0; i < fdcount; i++) {
1531 * Zero the pointer before calling unp_discard since it may
1532 * end up in unp_gc()..
1534 * XXXRW: This is less true than it used to be.
1543 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1545 struct thread *td = curthread; /* XXX */
1546 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1552 socklen_t clen = control->m_len, datalen;
1557 UNP_GLOBAL_UNLOCK_ASSERT();
1560 if (controlp != NULL) /* controlp == NULL => free control messages */
1563 while (cm != NULL) {
1564 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1569 data = CMSG_DATA(cm);
1570 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1572 if (cm->cmsg_level == SOL_SOCKET
1573 && cm->cmsg_type == SCM_RIGHTS) {
1574 newfds = datalen / sizeof(struct file *);
1577 /* If we're not outputting the descriptors free them. */
1578 if (error || controlp == NULL) {
1579 unp_freerights(rp, newfds);
1582 FILEDESC_XLOCK(td->td_proc->p_fd);
1583 /* if the new FD's will not fit free them. */
1584 if (!fdavail(td, newfds)) {
1585 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1587 unp_freerights(rp, newfds);
1591 * Now change each pointer to an fd in the global
1592 * table to an integer that is the index to the local
1593 * fd table entry that we set up to point to the
1594 * global one we are transferring.
1596 newlen = newfds * sizeof(int);
1597 *controlp = sbcreatecontrol(NULL, newlen,
1598 SCM_RIGHTS, SOL_SOCKET);
1599 if (*controlp == NULL) {
1600 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1602 unp_freerights(rp, newfds);
1607 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1608 for (i = 0; i < newfds; i++) {
1609 if (fdalloc(td, 0, &f))
1610 panic("unp_externalize fdalloc failed");
1612 td->td_proc->p_fd->fd_ofiles[f] = fp;
1619 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1621 /* We can just copy anything else across. */
1622 if (error || controlp == NULL)
1624 *controlp = sbcreatecontrol(NULL, datalen,
1625 cm->cmsg_type, cm->cmsg_level);
1626 if (*controlp == NULL) {
1631 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1635 controlp = &(*controlp)->m_next;
1638 if (CMSG_SPACE(datalen) < clen) {
1639 clen -= CMSG_SPACE(datalen);
1640 cm = (struct cmsghdr *)
1641 ((caddr_t)cm + CMSG_SPACE(datalen));
1654 unp_zone_change(void *tag)
1657 uma_zone_set_max(unp_zone, maxsockets);
1664 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1665 NULL, NULL, UMA_ALIGN_PTR, 0);
1666 if (unp_zone == NULL)
1668 uma_zone_set_max(unp_zone, maxsockets);
1669 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1670 NULL, EVENTHANDLER_PRI_ANY);
1671 LIST_INIT(&unp_dhead);
1672 LIST_INIT(&unp_shead);
1673 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1674 UNP_GLOBAL_LOCK_INIT();
1678 unp_internalize(struct mbuf **controlp, struct thread *td)
1680 struct mbuf *control = *controlp;
1681 struct proc *p = td->td_proc;
1682 struct filedesc *fdescp = p->p_fd;
1683 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1684 struct cmsgcred *cmcred;
1690 socklen_t clen = control->m_len, datalen;
1694 UNP_GLOBAL_UNLOCK_ASSERT();
1699 while (cm != NULL) {
1700 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1701 || cm->cmsg_len > clen) {
1706 data = CMSG_DATA(cm);
1707 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1709 switch (cm->cmsg_type) {
1711 * Fill in credential information.
1714 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1715 SCM_CREDS, SOL_SOCKET);
1716 if (*controlp == NULL) {
1721 cmcred = (struct cmsgcred *)
1722 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1723 cmcred->cmcred_pid = p->p_pid;
1724 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1725 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1726 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1727 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1729 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1730 cmcred->cmcred_groups[i] =
1731 td->td_ucred->cr_groups[i];
1735 oldfds = datalen / sizeof (int);
1737 * Check that all the FDs passed in refer to legal
1738 * files. If not, reject the entire operation.
1741 FILEDESC_SLOCK(fdescp);
1742 for (i = 0; i < oldfds; i++) {
1744 if ((unsigned)fd >= fdescp->fd_nfiles ||
1745 fdescp->fd_ofiles[fd] == NULL) {
1746 FILEDESC_SUNLOCK(fdescp);
1750 fp = fdescp->fd_ofiles[fd];
1751 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1752 FILEDESC_SUNLOCK(fdescp);
1760 * Now replace the integer FDs with pointers to
1761 * the associated global file table entry..
1763 newlen = oldfds * sizeof(struct file *);
1764 *controlp = sbcreatecontrol(NULL, newlen,
1765 SCM_RIGHTS, SOL_SOCKET);
1766 if (*controlp == NULL) {
1767 FILEDESC_SUNLOCK(fdescp);
1773 rp = (struct file **)
1774 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1775 for (i = 0; i < oldfds; i++) {
1776 fp = fdescp->fd_ofiles[*fdp++];
1784 FILEDESC_SUNLOCK(fdescp);
1788 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1789 SCM_TIMESTAMP, SOL_SOCKET);
1790 if (*controlp == NULL) {
1794 tv = (struct timeval *)
1795 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1804 controlp = &(*controlp)->m_next;
1806 if (CMSG_SPACE(datalen) < clen) {
1807 clen -= CMSG_SPACE(datalen);
1808 cm = (struct cmsghdr *)
1809 ((caddr_t)cm + CMSG_SPACE(datalen));
1822 static struct mbuf *
1823 unp_addsockcred(struct thread *td, struct mbuf *control)
1825 struct mbuf *m, *n, *n_prev;
1826 struct sockcred *sc;
1827 const struct cmsghdr *cm;
1831 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1833 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1837 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1838 sc->sc_uid = td->td_ucred->cr_ruid;
1839 sc->sc_euid = td->td_ucred->cr_uid;
1840 sc->sc_gid = td->td_ucred->cr_rgid;
1841 sc->sc_egid = td->td_ucred->cr_gid;
1842 sc->sc_ngroups = ngroups;
1843 for (i = 0; i < sc->sc_ngroups; i++)
1844 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1847 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1848 * created SCM_CREDS control message (struct sockcred) has another
1851 if (control != NULL)
1852 for (n = control, n_prev = NULL; n != NULL;) {
1853 cm = mtod(n, struct cmsghdr *);
1854 if (cm->cmsg_level == SOL_SOCKET &&
1855 cm->cmsg_type == SCM_CREDS) {
1857 control = n->m_next;
1859 n_prev->m_next = n->m_next;
1867 /* Prepend it to the head. */
1868 m->m_next = control;
1874 * unp_defer indicates whether additional work has been defered for a future
1875 * pass through unp_gc(). It is thread local and does not require explicit
1878 static int unp_defer;
1880 static int unp_taskcount;
1881 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1883 static int unp_recycled;
1884 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1887 unp_gc(__unused void *arg, int pending)
1889 struct file *fp, *nextfp;
1891 struct file **extra_ref, **fpp;
1894 int nfiles_slack = 20;
1899 * Before going through all this, set all FDs to be NOT deferred and
1900 * NOT externally accessible.
1902 sx_slock(&filelist_lock);
1903 LIST_FOREACH(fp, &filehead, f_list)
1904 fp->f_gcflag &= ~(FMARK|FDEFER);
1906 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1907 LIST_FOREACH(fp, &filehead, f_list) {
1910 * If the file is not open, skip it -- could be a
1911 * file in the process of being opened, or in the
1912 * process of being closed. If the file is
1913 * "closing", it may have been marked for deferred
1914 * consideration. Clear the flag now if so.
1916 if (fp->f_count == 0) {
1917 if (fp->f_gcflag & FDEFER)
1919 fp->f_gcflag &= ~(FMARK|FDEFER);
1924 * If we already marked it as 'defer' in a
1925 * previous pass, then try to process it this
1926 * time and un-mark it.
1928 if (fp->f_gcflag & FDEFER) {
1929 fp->f_gcflag &= ~FDEFER;
1933 * If it's not deferred, then check if it's
1934 * already marked.. if so skip it
1936 if (fp->f_gcflag & FMARK) {
1941 * If all references are from messages in
1942 * transit, then skip it. it's not externally
1945 if (fp->f_count == fp->f_msgcount) {
1950 * If it got this far then it must be
1951 * externally accessible.
1953 fp->f_gcflag |= FMARK;
1956 * Either it was deferred, or it is externally
1957 * accessible and not already marked so. Now check
1958 * if it is possibly one of OUR sockets.
1960 if (fp->f_type != DTYPE_SOCKET ||
1961 (so = fp->f_data) == NULL) {
1965 if (so->so_proto->pr_domain != &localdomain ||
1966 (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
1972 * Tell any other threads that do a subsequent
1973 * fdrop() that we are scanning the message
1976 fp->f_gcflag |= FWAIT;
1980 * So, Ok, it's one of our sockets and it IS
1981 * externally accessible (or was deferred). Now we
1982 * look to see if we hold any file descriptors in its
1983 * message buffers. Follow those links and mark them
1984 * as accessible too.
1986 SOCKBUF_LOCK(&so->so_rcv);
1987 unp_scan(so->so_rcv.sb_mb, unp_mark);
1988 SOCKBUF_UNLOCK(&so->so_rcv);
1991 * Wake up any threads waiting in fdrop().
1994 fp->f_gcflag &= ~FWAIT;
1995 wakeup(&fp->f_gcflag);
1998 } while (unp_defer);
1999 sx_sunlock(&filelist_lock);
2001 * XXXRW: The following comments need updating for a post-SMPng and
2002 * deferred unp_gc() world, but are still generally accurate.
2004 * We grab an extra reference to each of the file table entries that
2005 * are not otherwise accessible and then free the rights that are
2006 * stored in messages on them.
2008 * The bug in the orginal code is a little tricky, so I'll describe
2009 * what's wrong with it here.
2011 * It is incorrect to simply unp_discard each entry for f_msgcount
2012 * times -- consider the case of sockets A and B that contain
2013 * references to each other. On a last close of some other socket,
2014 * we trigger a gc since the number of outstanding rights (unp_rights)
2015 * is non-zero. If during the sweep phase the gc code unp_discards,
2016 * we end up doing a (full) closef on the descriptor. A closef on A
2017 * results in the following chain. Closef calls soo_close, which
2018 * calls soclose. Soclose calls first (through the switch
2019 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
2020 * returns because the previous instance had set unp_gcing, and we
2021 * return all the way back to soclose, which marks the socket with
2022 * SS_NOFDREF, and then calls sofree. Sofree calls sorflush to free
2023 * up the rights that are queued in messages on the socket A, i.e.,
2024 * the reference on B. The sorflush calls via the dom_dispose switch
2025 * unp_dispose, which unp_scans with unp_discard. This second
2026 * instance of unp_discard just calls closef on B.
2028 * Well, a similar chain occurs on B, resulting in a sorflush on B,
2029 * which results in another closef on A. Unfortunately, A is already
2030 * being closed, and the descriptor has already been marked with
2031 * SS_NOFDREF, and soclose panics at this point.
2033 * Here, we first take an extra reference to each inaccessible
2034 * descriptor. Then, we call sorflush ourself, since we know it is a
2035 * Unix domain socket anyhow. After we destroy all the rights
2036 * carried in messages, we do a last closef to get rid of our extra
2037 * reference. This is the last close, and the unp_detach etc will
2038 * shut down the socket.
2040 * 91/09/19, bsy@cs.cmu.edu
2043 nfiles_snap = openfiles + nfiles_slack; /* some slack */
2044 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
2046 sx_slock(&filelist_lock);
2047 if (nfiles_snap < openfiles) {
2048 sx_sunlock(&filelist_lock);
2049 free(extra_ref, M_TEMP);
2053 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
2054 fp != NULL; fp = nextfp) {
2055 nextfp = LIST_NEXT(fp, f_list);
2058 * If it's not open, skip it
2060 if (fp->f_count == 0) {
2065 * If all refs are from msgs, and it's not marked accessible
2066 * then it must be referenced from some unreachable cycle of
2067 * (shut-down) FDs, so include it in our list of FDs to
2070 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
2077 sx_sunlock(&filelist_lock);
2079 * For each FD on our hit list, do the following two things:
2081 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2082 struct file *tfp = *fpp;
2084 if (tfp->f_type == DTYPE_SOCKET &&
2085 tfp->f_data != NULL) {
2087 sorflush(tfp->f_data);
2092 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2093 closef(*fpp, (struct thread *) NULL);
2096 free(extra_ref, M_TEMP);
2100 unp_dispose(struct mbuf *m)
2104 unp_scan(m, unp_discard);
2108 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2115 socklen_t clen, datalen;
2118 while (m0 != NULL) {
2119 for (m = m0; m; m = m->m_next) {
2120 if (m->m_type != MT_CONTROL)
2123 cm = mtod(m, struct cmsghdr *);
2126 while (cm != NULL) {
2127 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2130 data = CMSG_DATA(cm);
2131 datalen = (caddr_t)cm + cm->cmsg_len
2134 if (cm->cmsg_level == SOL_SOCKET &&
2135 cm->cmsg_type == SCM_RIGHTS) {
2136 qfds = datalen / sizeof (struct file *);
2138 for (i = 0; i < qfds; i++)
2142 if (CMSG_SPACE(datalen) < clen) {
2143 clen -= CMSG_SPACE(datalen);
2144 cm = (struct cmsghdr *)
2145 ((caddr_t)cm + CMSG_SPACE(datalen));
2157 unp_mark(struct file *fp)
2160 /* XXXRW: Should probably assert file list lock here. */
2162 if (fp->f_gcflag & FMARK)
2165 fp->f_gcflag |= (FMARK|FDEFER);
2169 unp_discard(struct file *fp)
2177 UNP_GLOBAL_WUNLOCK();
2178 (void) closef(fp, (struct thread *)NULL);