2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004-2008 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$");
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>
98 #include <security/mac/mac_framework.h>
102 static uma_zone_t unp_zone;
103 static unp_gen_t unp_gencnt;
104 static u_int unp_count; /* Count of local sockets. */
105 static ino_t unp_ino; /* Prototype for fake inode numbers. */
106 static int unp_rights; /* File descriptors in flight. */
107 static struct unp_head unp_shead; /* List of local stream sockets. */
108 static struct unp_head unp_dhead; /* List of local datagram sockets. */
110 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
113 * Garbage collection of cyclic file descriptor/socket references occurs
114 * asynchronously in a taskqueue context in order to avoid recursion and
115 * reentrance in the UNIX domain socket, file descriptor, and socket layer
116 * code. See unp_gc() for a full description.
118 static struct task unp_gc_task;
121 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
122 * stream sockets, although the total for sender and receiver is actually
125 * Datagram sockets really use the sendspace as the maximum datagram size,
126 * and don't really want to reserve the sendspace. Their recvspace should be
127 * large enough for at least one max-size datagram plus address.
132 static u_long unpst_sendspace = PIPSIZ;
133 static u_long unpst_recvspace = PIPSIZ;
134 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
135 static u_long unpdg_recvspace = 4*1024;
137 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
138 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
139 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
141 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
142 &unpst_sendspace, 0, "");
143 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
144 &unpst_recvspace, 0, "");
145 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
146 &unpdg_sendspace, 0, "");
147 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
148 &unpdg_recvspace, 0, "");
149 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
152 * Locking and synchronization:
154 * The global UNIX domain socket rwlock (unp_global_rwlock) protects all
155 * global variables, including the linked lists tracking the set of allocated
156 * UNIX domain sockets. The global rwlock also serves to prevent deadlock
157 * when more than one PCB lock is acquired at a time (i.e., during
158 * connect()). Finally, the global rwlock protects uncounted references from
159 * vnodes to sockets bound to those vnodes: to safely dereference the
160 * v_socket pointer, the global rwlock must be held while a full reference is
163 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
164 * allocated in pru_attach() and freed in pru_detach(). The validity of that
165 * pointer is an invariant, so no lock is required to dereference the so_pcb
166 * pointer if a valid socket reference is held by the caller. In practice,
167 * this is always true during operations performed on a socket. Each unpcb
168 * has a back-pointer to its socket, unp_socket, which will be stable under
169 * the same circumstances.
171 * This pointer may only be safely dereferenced as long as a valid reference
172 * to the unpcb is held. Typically, this reference will be from the socket,
173 * or from another unpcb when the referring unpcb's lock is held (in order
174 * that the reference not be invalidated during use). For example, to follow
175 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
176 * as unp_socket remains valid as long as the reference to unp_conn is valid.
178 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
179 * atomic reads without the lock may be performed "lockless", but more
180 * complex reads and read-modify-writes require the mutex to be held. No
181 * lock order is defined between unpcb locks -- multiple unpcb locks may be
182 * acquired at the same time only when holding the global UNIX domain socket
183 * rwlock exclusively, which prevents deadlocks.
185 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
186 * protocols, bind() is a non-atomic operation, and connect() requires
187 * potential sleeping in the protocol, due to potentially waiting on local or
188 * distributed file systems. We try to separate "lookup" operations, which
189 * may sleep, and the IPC operations themselves, which typically can occur
190 * with relative atomicity as locks can be held over the entire operation.
192 * Another tricky issue is simultaneous multi-threaded or multi-process
193 * access to a single UNIX domain socket. These are handled by the flags
194 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
195 * binding, both of which involve dropping UNIX domain socket locks in order
196 * to perform namei() and other file system operations.
198 static struct rwlock unp_global_rwlock;
200 #define UNP_GLOBAL_LOCK_INIT() rw_init(&unp_global_rwlock, \
203 #define UNP_GLOBAL_LOCK_ASSERT() rw_assert(&unp_global_rwlock, \
205 #define UNP_GLOBAL_UNLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
208 #define UNP_GLOBAL_WLOCK() rw_wlock(&unp_global_rwlock)
209 #define UNP_GLOBAL_WUNLOCK() rw_wunlock(&unp_global_rwlock)
210 #define UNP_GLOBAL_WLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
212 #define UNP_GLOBAL_WOWNED() rw_wowned(&unp_global_rwlock)
214 #define UNP_GLOBAL_RLOCK() rw_rlock(&unp_global_rwlock)
215 #define UNP_GLOBAL_RUNLOCK() rw_runlock(&unp_global_rwlock)
216 #define UNP_GLOBAL_RLOCK_ASSERT() rw_assert(&unp_global_rwlock, \
219 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
220 "unp_mtx", "unp_mtx", \
221 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
222 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
223 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
224 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
225 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
227 static int uipc_connect2(struct socket *, struct socket *);
228 static int uipc_ctloutput(struct socket *, struct sockopt *);
229 static int unp_connect(struct socket *, struct sockaddr *,
231 static int unp_connect2(struct socket *so, struct socket *so2, int);
232 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
233 static void unp_dispose(struct mbuf *);
234 static void unp_shutdown(struct unpcb *);
235 static void unp_drop(struct unpcb *, int);
236 static void unp_gc(__unused void *, int);
237 static void unp_scan(struct mbuf *, void (*)(struct file *));
238 static void unp_mark(struct file *);
239 static void unp_discard(struct file *);
240 static void unp_freerights(struct file **, int);
241 static void unp_init(void);
242 static int unp_internalize(struct mbuf **, struct thread *);
243 static int unp_externalize(struct mbuf *, struct mbuf **);
244 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
247 * Definitions of protocols supported in the LOCAL domain.
249 static struct domain localdomain;
250 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
251 static struct protosw localsw[] = {
253 .pr_type = SOCK_STREAM,
254 .pr_domain = &localdomain,
255 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
256 .pr_ctloutput = &uipc_ctloutput,
257 .pr_usrreqs = &uipc_usrreqs_stream
260 .pr_type = SOCK_DGRAM,
261 .pr_domain = &localdomain,
262 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
263 .pr_usrreqs = &uipc_usrreqs_dgram
267 static struct domain localdomain = {
268 .dom_family = AF_LOCAL,
270 .dom_init = unp_init,
271 .dom_externalize = unp_externalize,
272 .dom_dispose = unp_dispose,
273 .dom_protosw = localsw,
274 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
279 uipc_abort(struct socket *so)
281 struct unpcb *unp, *unp2;
284 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
288 unp2 = unp->unp_conn;
291 unp_drop(unp2, ECONNABORTED);
292 UNP_PCB_UNLOCK(unp2);
295 UNP_GLOBAL_WUNLOCK();
299 uipc_accept(struct socket *so, struct sockaddr **nam)
301 struct unpcb *unp, *unp2;
302 const struct sockaddr *sa;
305 * Pass back name of connected socket, if it was bound and we are
306 * still connected (our peer may have closed already!).
309 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
311 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
313 unp2 = unp->unp_conn;
314 if (unp2 != NULL && unp2->unp_addr != NULL) {
316 sa = (struct sockaddr *) unp2->unp_addr;
317 bcopy(sa, *nam, sa->sa_len);
318 UNP_PCB_UNLOCK(unp2);
321 bcopy(sa, *nam, sa->sa_len);
323 UNP_GLOBAL_RUNLOCK();
328 uipc_attach(struct socket *so, int proto, struct thread *td)
330 u_long sendspace, recvspace;
334 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
335 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
336 switch (so->so_type) {
338 sendspace = unpst_sendspace;
339 recvspace = unpst_recvspace;
343 sendspace = unpdg_sendspace;
344 recvspace = unpdg_recvspace;
348 panic("uipc_attach");
350 error = soreserve(so, sendspace, recvspace);
354 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
357 LIST_INIT(&unp->unp_refs);
358 UNP_PCB_LOCK_INIT(unp);
359 unp->unp_socket = so;
361 unp->unp_refcount = 1;
364 * uipc_attach() may be called indirectly from within the UNIX domain
365 * socket code via sonewconn() in unp_connect(). Since rwlocks can
366 * not be recursed, we do the closest thing.
369 if (!UNP_GLOBAL_WOWNED()) {
373 unp->unp_gencnt = ++unp_gencnt;
375 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
378 UNP_GLOBAL_WUNLOCK();
384 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
386 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
388 int error, namelen, vfslocked;
396 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
398 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
403 * We don't allow simultaneous bind() calls on a single UNIX domain
404 * socket, so flag in-progress operations, and return an error if an
405 * operation is already in progress.
407 * Historically, we have not allowed a socket to be rebound, so this
408 * also returns an error. Not allowing re-binding simplifies the
409 * implementation and avoids a great many possible failure modes.
412 if (unp->unp_vnode != NULL) {
416 if (unp->unp_flags & UNP_BINDING) {
420 unp->unp_flags |= UNP_BINDING;
423 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
424 strlcpy(buf, soun->sun_path, namelen + 1);
428 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
429 UIO_SYSSPACE, buf, td);
430 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
435 vfslocked = NDHASGIANT(&nd);
436 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
437 NDFREE(&nd, NDF_ONLY_PNBUF);
447 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
450 VFS_UNLOCK_GIANT(vfslocked);
454 vattr.va_type = VSOCK;
455 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
457 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
461 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
462 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
464 NDFREE(&nd, NDF_ONLY_PNBUF);
467 vn_finished_write(mp);
471 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
472 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
476 vp->v_socket = unp->unp_socket;
478 unp->unp_addr = soun;
479 unp->unp_flags &= ~UNP_BINDING;
481 UNP_GLOBAL_WUNLOCK();
482 VOP_UNLOCK(vp, 0, td);
483 vn_finished_write(mp);
484 VFS_UNLOCK_GIANT(vfslocked);
489 VFS_UNLOCK_GIANT(vfslocked);
491 unp->unp_flags &= ~UNP_BINDING;
498 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
502 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
504 error = unp_connect(so, nam, td);
505 UNP_GLOBAL_WUNLOCK();
510 uipc_close(struct socket *so)
512 struct unpcb *unp, *unp2;
515 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
519 unp2 = unp->unp_conn;
522 unp_disconnect(unp, unp2);
523 UNP_PCB_UNLOCK(unp2);
526 UNP_GLOBAL_WUNLOCK();
530 uipc_connect2(struct socket *so1, struct socket *so2)
532 struct unpcb *unp, *unp2;
537 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
540 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
542 error = unp_connect2(so1, so2, PRU_CONNECT2);
543 UNP_PCB_UNLOCK(unp2);
545 UNP_GLOBAL_WUNLOCK();
550 uipc_detach(struct socket *so)
552 struct unpcb *unp, *unp2;
553 struct sockaddr_un *saved_unp_addr;
555 int freeunp, local_unp_rights;
558 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
563 LIST_REMOVE(unp, unp_link);
564 unp->unp_gencnt = ++unp_gencnt;
568 * XXXRW: Should assert vp->v_socket == so.
570 if ((vp = unp->unp_vnode) != NULL) {
571 unp->unp_vnode->v_socket = NULL;
572 unp->unp_vnode = NULL;
574 unp2 = unp->unp_conn;
577 unp_disconnect(unp, unp2);
578 UNP_PCB_UNLOCK(unp2);
582 * We hold the global lock exclusively, so it's OK to acquire
583 * multiple pcb locks at a time.
585 while (!LIST_EMPTY(&unp->unp_refs)) {
586 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
589 unp_drop(ref, ECONNRESET);
592 local_unp_rights = unp_rights;
593 UNP_GLOBAL_WUNLOCK();
594 unp->unp_socket->so_pcb = NULL;
595 saved_unp_addr = unp->unp_addr;
596 unp->unp_addr = NULL;
598 freeunp = (unp->unp_refcount == 0);
599 if (saved_unp_addr != NULL)
600 FREE(saved_unp_addr, M_SONAME);
602 UNP_PCB_LOCK_DESTROY(unp);
603 uma_zfree(unp_zone, unp);
609 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
611 VFS_UNLOCK_GIANT(vfslocked);
613 if (local_unp_rights)
614 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
618 uipc_disconnect(struct socket *so)
620 struct unpcb *unp, *unp2;
623 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
627 unp2 = unp->unp_conn;
630 unp_disconnect(unp, unp2);
631 UNP_PCB_UNLOCK(unp2);
634 UNP_GLOBAL_WUNLOCK();
639 uipc_listen(struct socket *so, int backlog, struct thread *td)
645 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
648 if (unp->unp_vnode == NULL) {
654 error = solisten_proto_check(so);
656 cru2x(td->td_ucred, &unp->unp_peercred);
657 unp->unp_flags |= UNP_HAVEPCCACHED;
658 solisten_proto(so, backlog);
666 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
668 struct unpcb *unp, *unp2;
669 const struct sockaddr *sa;
672 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
674 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
677 * XXX: It seems that this test always fails even when connection is
678 * established. So, this else clause is added as workaround to
679 * return PF_LOCAL sockaddr.
681 unp2 = unp->unp_conn;
684 if (unp2->unp_addr != NULL)
685 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
688 bcopy(sa, *nam, sa->sa_len);
689 UNP_PCB_UNLOCK(unp2);
692 bcopy(sa, *nam, sa->sa_len);
699 uipc_rcvd(struct socket *so, int flags)
701 struct unpcb *unp, *unp2;
707 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
709 if (so->so_type == SOCK_DGRAM)
710 panic("uipc_rcvd DGRAM?");
712 if (so->so_type != SOCK_STREAM)
713 panic("uipc_rcvd unknown socktype");
716 * Adjust backpressure on sender and wakeup any waiting to write.
718 * The unp lock is acquired to maintain the validity of the unp_conn
719 * pointer; no lock on unp2 is required as unp2->unp_socket will be
720 * static as long as we don't permit unp2 to disconnect from unp,
721 * which is prevented by the lock on unp. We cache values from
722 * so_rcv to avoid holding the so_rcv lock over the entire
723 * transaction on the remote so_snd.
725 SOCKBUF_LOCK(&so->so_rcv);
726 mbcnt = so->so_rcv.sb_mbcnt;
727 sbcc = so->so_rcv.sb_cc;
728 SOCKBUF_UNLOCK(&so->so_rcv);
730 unp2 = unp->unp_conn;
735 so2 = unp2->unp_socket;
736 SOCKBUF_LOCK(&so2->so_snd);
737 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
738 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
739 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
740 newhiwat, RLIM_INFINITY);
741 sowwakeup_locked(so2);
742 unp->unp_mbcnt = mbcnt;
749 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
750 struct mbuf *control, struct thread *td)
752 struct unpcb *unp, *unp2;
754 u_int mbcnt_delta, sbcc;
759 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
761 if (flags & PRUS_OOB) {
765 if (control != NULL && (error = unp_internalize(&control, td)))
767 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;
790 * Because connect() and send() are non-atomic in a sendto()
791 * with a target address, it's possible that the socket will
792 * have disconnected before the send() can run. In that case
793 * return the slightly counter-intuitive but otherwise
794 * correct error that the socket is not connected.
801 if (unp2->unp_flags & UNP_WANTCRED)
802 control = unp_addsockcred(td, control);
804 if (unp->unp_addr != NULL)
805 from = (struct sockaddr *)unp->unp_addr;
808 so2 = unp2->unp_socket;
809 SOCKBUF_LOCK(&so2->so_rcv);
810 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
811 sorwakeup_locked(so2);
815 SOCKBUF_UNLOCK(&so2->so_rcv);
819 UNP_GLOBAL_WLOCK_ASSERT();
821 unp_disconnect(unp, unp2);
822 UNP_PCB_UNLOCK(unp2);
829 if ((so->so_state & SS_ISCONNECTED) == 0) {
831 UNP_GLOBAL_WLOCK_ASSERT();
832 error = unp_connect(so, nam, td);
842 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
848 * Because connect() and send() are non-atomic in a sendto()
849 * with a target address, it's possible that the socket will
850 * have disconnected before the send() can run. In that case
851 * return the slightly counter-intuitive but otherwise
852 * correct error that the socket is not connected.
854 * Locking here must be done carefully: the global lock
855 * prevents interconnections between unpcbs from changing, so
856 * we can traverse from unp to unp2 without acquiring unp's
857 * lock. Socket buffer locks follow unpcb locks, so we can
858 * acquire both remote and lock socket buffer locks.
860 unp2 = unp->unp_conn;
865 so2 = unp2->unp_socket;
867 SOCKBUF_LOCK(&so2->so_rcv);
868 if (unp2->unp_flags & UNP_WANTCRED) {
870 * Credentials are passed only once on SOCK_STREAM.
872 unp2->unp_flags &= ~UNP_WANTCRED;
873 control = unp_addsockcred(td, control);
876 * Send to paired receive port, and then reduce send buffer
877 * hiwater marks to maintain backpressure. Wake up readers.
879 if (control != NULL) {
880 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
883 sbappend_locked(&so2->so_rcv, m);
884 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
885 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
886 sbcc = so2->so_rcv.sb_cc;
887 sorwakeup_locked(so2);
889 SOCKBUF_LOCK(&so->so_snd);
890 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
891 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
892 newhiwat, RLIM_INFINITY);
893 so->so_snd.sb_mbmax -= mbcnt_delta;
894 SOCKBUF_UNLOCK(&so->so_snd);
896 UNP_PCB_UNLOCK(unp2);
901 panic("uipc_send unknown socktype");
905 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
907 if (flags & PRUS_EOF) {
914 if ((nam != NULL) || (flags & PRUS_EOF))
915 UNP_GLOBAL_WUNLOCK();
917 UNP_GLOBAL_RUNLOCK();
919 if (control != NULL && error != 0)
920 unp_dispose(control);
931 uipc_sense(struct socket *so, struct stat *sb)
933 struct unpcb *unp, *unp2;
937 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
939 sb->st_blksize = so->so_snd.sb_hiwat;
942 unp2 = unp->unp_conn;
943 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
944 so2 = unp2->unp_socket;
945 sb->st_blksize += so2->so_rcv.sb_cc;
948 if (unp->unp_ino == 0)
949 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
950 sb->st_ino = unp->unp_ino;
952 UNP_GLOBAL_RUNLOCK();
957 uipc_shutdown(struct socket *so)
962 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
969 UNP_GLOBAL_WUNLOCK();
974 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
977 const struct sockaddr *sa;
980 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
982 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
984 if (unp->unp_addr != NULL)
985 sa = (struct sockaddr *) unp->unp_addr;
988 bcopy(sa, *nam, sa->sa_len);
993 static struct pr_usrreqs uipc_usrreqs_dgram = {
994 .pru_abort = uipc_abort,
995 .pru_accept = uipc_accept,
996 .pru_attach = uipc_attach,
997 .pru_bind = uipc_bind,
998 .pru_connect = uipc_connect,
999 .pru_connect2 = uipc_connect2,
1000 .pru_detach = uipc_detach,
1001 .pru_disconnect = uipc_disconnect,
1002 .pru_listen = uipc_listen,
1003 .pru_peeraddr = uipc_peeraddr,
1004 .pru_rcvd = uipc_rcvd,
1005 .pru_send = uipc_send,
1006 .pru_sense = uipc_sense,
1007 .pru_shutdown = uipc_shutdown,
1008 .pru_sockaddr = uipc_sockaddr,
1009 .pru_soreceive = soreceive_dgram,
1010 .pru_close = uipc_close,
1013 static struct pr_usrreqs uipc_usrreqs_stream = {
1014 .pru_abort = uipc_abort,
1015 .pru_accept = uipc_accept,
1016 .pru_attach = uipc_attach,
1017 .pru_bind = uipc_bind,
1018 .pru_connect = uipc_connect,
1019 .pru_connect2 = uipc_connect2,
1020 .pru_detach = uipc_detach,
1021 .pru_disconnect = uipc_disconnect,
1022 .pru_listen = uipc_listen,
1023 .pru_peeraddr = uipc_peeraddr,
1024 .pru_rcvd = uipc_rcvd,
1025 .pru_send = uipc_send,
1026 .pru_sense = uipc_sense,
1027 .pru_shutdown = uipc_shutdown,
1028 .pru_sockaddr = uipc_sockaddr,
1029 .pru_soreceive = soreceive_generic,
1030 .pru_close = uipc_close,
1034 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1040 if (sopt->sopt_level != 0)
1043 unp = sotounpcb(so);
1044 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1046 switch (sopt->sopt_dir) {
1048 switch (sopt->sopt_name) {
1049 case LOCAL_PEERCRED:
1051 if (unp->unp_flags & UNP_HAVEPC)
1052 xu = unp->unp_peercred;
1054 if (so->so_type == SOCK_STREAM)
1059 UNP_PCB_UNLOCK(unp);
1061 error = sooptcopyout(sopt, &xu, sizeof(xu));
1065 /* Unlocked read. */
1066 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1067 error = sooptcopyout(sopt, &optval, sizeof(optval));
1070 case LOCAL_CONNWAIT:
1071 /* Unlocked read. */
1072 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1073 error = sooptcopyout(sopt, &optval, sizeof(optval));
1083 switch (sopt->sopt_name) {
1085 case LOCAL_CONNWAIT:
1086 error = sooptcopyin(sopt, &optval, sizeof(optval),
1091 #define OPTSET(bit) do { \
1092 UNP_PCB_LOCK(unp); \
1094 unp->unp_flags |= bit; \
1096 unp->unp_flags &= ~bit; \
1097 UNP_PCB_UNLOCK(unp); \
1100 switch (sopt->sopt_name) {
1102 OPTSET(UNP_WANTCRED);
1105 case LOCAL_CONNWAIT:
1106 OPTSET(UNP_CONNWAIT);
1115 error = ENOPROTOOPT;
1128 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1130 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1132 struct socket *so2, *so3;
1133 struct unpcb *unp, *unp2, *unp3;
1134 int error, len, vfslocked;
1135 struct nameidata nd;
1136 char buf[SOCK_MAXADDRLEN];
1137 struct sockaddr *sa;
1139 UNP_GLOBAL_WLOCK_ASSERT();
1141 unp = sotounpcb(so);
1142 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1144 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1147 strlcpy(buf, soun->sun_path, len + 1);
1150 if (unp->unp_flags & UNP_CONNECTING) {
1151 UNP_PCB_UNLOCK(unp);
1154 UNP_GLOBAL_WUNLOCK();
1155 unp->unp_flags |= UNP_CONNECTING;
1156 UNP_PCB_UNLOCK(unp);
1158 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1159 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1166 ASSERT_VOP_LOCKED(vp, "unp_connect");
1167 vfslocked = NDHASGIANT(&nd);
1168 NDFREE(&nd, NDF_ONLY_PNBUF);
1172 if (vp->v_type != VSOCK) {
1177 error = mac_check_vnode_open(td->td_ucred, vp, VWRITE | VREAD);
1181 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1184 VFS_UNLOCK_GIANT(vfslocked);
1186 unp = sotounpcb(so);
1187 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1190 * Lock global lock for two reasons: make sure v_socket is stable,
1191 * and to protect simultaneous locking of multiple pcbs.
1196 error = ECONNREFUSED;
1199 if (so->so_type != so2->so_type) {
1203 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1204 if (so2->so_options & SO_ACCEPTCONN) {
1206 * We can't drop the global lock here or 'so2' may
1207 * become invalid. As a result, we need to handle
1208 * possibly lock recursion in uipc_attach.
1210 so3 = sonewconn(so2, 0);
1214 error = ECONNREFUSED;
1217 unp = sotounpcb(so);
1218 unp2 = sotounpcb(so2);
1219 unp3 = sotounpcb(so3);
1223 if (unp2->unp_addr != NULL) {
1224 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1225 unp3->unp_addr = (struct sockaddr_un *) sa;
1230 * The connecter's (client's) credentials are copied from its
1231 * process structure at the time of connect() (which is now).
1233 cru2x(td->td_ucred, &unp3->unp_peercred);
1234 unp3->unp_flags |= UNP_HAVEPC;
1237 * The receiver's (server's) credentials are copied from the
1238 * unp_peercred member of socket on which the former called
1239 * listen(); uipc_listen() cached that process's credentials
1240 * at that time so we can use them now.
1242 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1243 ("unp_connect: listener without cached peercred"));
1244 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1245 sizeof(unp->unp_peercred));
1246 unp->unp_flags |= UNP_HAVEPC;
1247 if (unp2->unp_flags & UNP_WANTCRED)
1248 unp3->unp_flags |= UNP_WANTCRED;
1249 UNP_PCB_UNLOCK(unp3);
1250 UNP_PCB_UNLOCK(unp2);
1251 UNP_PCB_UNLOCK(unp);
1254 mac_set_socket_peer_from_socket(so, so3);
1255 mac_set_socket_peer_from_socket(so3, so);
1261 unp = sotounpcb(so);
1262 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1263 unp2 = sotounpcb(so2);
1264 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1267 error = unp_connect2(so, so2, PRU_CONNECT);
1268 UNP_PCB_UNLOCK(unp2);
1269 UNP_PCB_UNLOCK(unp);
1271 UNP_GLOBAL_WUNLOCK();
1274 * Giant has been previously acquired. This means filesystem
1275 * isn't MPSAFE. Do it once again.
1281 VFS_UNLOCK_GIANT(vfslocked);
1285 unp->unp_flags &= ~UNP_CONNECTING;
1286 UNP_PCB_UNLOCK(unp);
1291 unp_connect2(struct socket *so, struct socket *so2, int req)
1296 unp = sotounpcb(so);
1297 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1298 unp2 = sotounpcb(so2);
1299 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1301 UNP_GLOBAL_WLOCK_ASSERT();
1302 UNP_PCB_LOCK_ASSERT(unp);
1303 UNP_PCB_LOCK_ASSERT(unp2);
1305 if (so2->so_type != so->so_type)
1306 return (EPROTOTYPE);
1307 unp->unp_conn = unp2;
1309 switch (so->so_type) {
1311 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1316 unp2->unp_conn = unp;
1317 if (req == PRU_CONNECT &&
1318 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1326 panic("unp_connect2");
1332 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1336 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1338 UNP_GLOBAL_WLOCK_ASSERT();
1339 UNP_PCB_LOCK_ASSERT(unp);
1340 UNP_PCB_LOCK_ASSERT(unp2);
1342 unp->unp_conn = NULL;
1343 switch (unp->unp_socket->so_type) {
1345 LIST_REMOVE(unp, unp_reflink);
1346 so = unp->unp_socket;
1348 so->so_state &= ~SS_ISCONNECTED;
1353 soisdisconnected(unp->unp_socket);
1354 unp2->unp_conn = NULL;
1355 soisdisconnected(unp2->unp_socket);
1361 * unp_pcblist() walks the global list of struct unpcb's to generate a
1362 * pointer list, bumping the refcount on each unpcb. It then copies them out
1363 * sequentially, validating the generation number on each to see if it has
1364 * been detached. All of this is necessary because copyout() may sleep on
1368 unp_pcblist(SYSCTL_HANDLER_ARGS)
1372 struct unpcb *unp, **unp_list;
1374 struct xunpgen *xug;
1375 struct unp_head *head;
1378 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1381 * The process of preparing the PCB list is too time-consuming and
1382 * resource-intensive to repeat twice on every request.
1384 if (req->oldptr == NULL) {
1386 req->oldidx = 2 * (sizeof *xug)
1387 + (n + n/8) * sizeof(struct xunpcb);
1391 if (req->newptr != NULL)
1395 * OK, now we're committed to doing something.
1397 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1399 gencnt = unp_gencnt;
1401 UNP_GLOBAL_RUNLOCK();
1403 xug->xug_len = sizeof *xug;
1405 xug->xug_gen = gencnt;
1406 xug->xug_sogen = so_gencnt;
1407 error = SYSCTL_OUT(req, xug, sizeof *xug);
1413 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1416 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1417 unp = LIST_NEXT(unp, unp_link)) {
1419 if (unp->unp_gencnt <= gencnt) {
1420 if (cr_cansee(req->td->td_ucred,
1421 unp->unp_socket->so_cred)) {
1422 UNP_PCB_UNLOCK(unp);
1425 unp_list[i++] = unp;
1426 unp->unp_refcount++;
1428 UNP_PCB_UNLOCK(unp);
1430 UNP_GLOBAL_RUNLOCK();
1431 n = i; /* In case we lost some during malloc. */
1434 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1435 for (i = 0; i < n; i++) {
1438 unp->unp_refcount--;
1439 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1440 xu->xu_len = sizeof *xu;
1443 * XXX - need more locking here to protect against
1444 * connect/disconnect races for SMP.
1446 if (unp->unp_addr != NULL)
1447 bcopy(unp->unp_addr, &xu->xu_addr,
1448 unp->unp_addr->sun_len);
1449 if (unp->unp_conn != NULL &&
1450 unp->unp_conn->unp_addr != NULL)
1451 bcopy(unp->unp_conn->unp_addr,
1453 unp->unp_conn->unp_addr->sun_len);
1454 bcopy(unp, &xu->xu_unp, sizeof *unp);
1455 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1456 UNP_PCB_UNLOCK(unp);
1457 error = SYSCTL_OUT(req, xu, sizeof *xu);
1459 freeunp = (unp->unp_refcount == 0);
1460 UNP_PCB_UNLOCK(unp);
1462 UNP_PCB_LOCK_DESTROY(unp);
1463 uma_zfree(unp_zone, unp);
1470 * Give the user an updated idea of our state. If the
1471 * generation differs from what we told her before, she knows
1472 * that something happened while we were processing this
1473 * request, and it might be necessary to retry.
1475 xug->xug_gen = unp_gencnt;
1476 xug->xug_sogen = so_gencnt;
1477 xug->xug_count = unp_count;
1478 error = SYSCTL_OUT(req, xug, sizeof *xug);
1480 free(unp_list, M_TEMP);
1485 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1486 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1487 "List of active local datagram sockets");
1488 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1489 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1490 "List of active local stream sockets");
1493 unp_shutdown(struct unpcb *unp)
1498 UNP_GLOBAL_WLOCK_ASSERT();
1499 UNP_PCB_LOCK_ASSERT(unp);
1501 unp2 = unp->unp_conn;
1502 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1503 so = unp2->unp_socket;
1510 unp_drop(struct unpcb *unp, int errno)
1512 struct socket *so = unp->unp_socket;
1515 UNP_GLOBAL_WLOCK_ASSERT();
1516 UNP_PCB_LOCK_ASSERT(unp);
1518 so->so_error = errno;
1519 unp2 = unp->unp_conn;
1523 unp_disconnect(unp, unp2);
1524 UNP_PCB_UNLOCK(unp2);
1528 unp_freerights(struct file **rp, int fdcount)
1533 for (i = 0; i < fdcount; i++) {
1541 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1543 struct thread *td = curthread; /* XXX */
1544 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1550 socklen_t clen = control->m_len, datalen;
1555 UNP_GLOBAL_UNLOCK_ASSERT();
1558 if (controlp != NULL) /* controlp == NULL => free control messages */
1560 while (cm != NULL) {
1561 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1565 data = CMSG_DATA(cm);
1566 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1567 if (cm->cmsg_level == SOL_SOCKET
1568 && cm->cmsg_type == SCM_RIGHTS) {
1569 newfds = datalen / sizeof(struct file *);
1572 /* If we're not outputting the descriptors free them. */
1573 if (error || controlp == NULL) {
1574 unp_freerights(rp, newfds);
1577 FILEDESC_XLOCK(td->td_proc->p_fd);
1578 /* if the new FD's will not fit free them. */
1579 if (!fdavail(td, newfds)) {
1580 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1582 unp_freerights(rp, newfds);
1587 * Now change each pointer to an fd in the global
1588 * table to an integer that is the index to the local
1589 * fd table entry that we set up to point to the
1590 * global one we are transferring.
1592 newlen = newfds * sizeof(int);
1593 *controlp = sbcreatecontrol(NULL, newlen,
1594 SCM_RIGHTS, SOL_SOCKET);
1595 if (*controlp == NULL) {
1596 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1598 unp_freerights(rp, newfds);
1603 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1604 for (i = 0; i < newfds; i++) {
1605 if (fdalloc(td, 0, &f))
1606 panic("unp_externalize fdalloc failed");
1608 td->td_proc->p_fd->fd_ofiles[f] = fp;
1614 UNP_GLOBAL_WUNLOCK();
1617 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1619 /* We can just copy anything else across. */
1620 if (error || controlp == NULL)
1622 *controlp = sbcreatecontrol(NULL, datalen,
1623 cm->cmsg_type, cm->cmsg_level);
1624 if (*controlp == NULL) {
1629 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1632 controlp = &(*controlp)->m_next;
1635 if (CMSG_SPACE(datalen) < clen) {
1636 clen -= CMSG_SPACE(datalen);
1637 cm = (struct cmsghdr *)
1638 ((caddr_t)cm + CMSG_SPACE(datalen));
1650 unp_zone_change(void *tag)
1653 uma_zone_set_max(unp_zone, maxsockets);
1660 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1661 NULL, NULL, UMA_ALIGN_PTR, 0);
1662 if (unp_zone == NULL)
1664 uma_zone_set_max(unp_zone, maxsockets);
1665 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1666 NULL, EVENTHANDLER_PRI_ANY);
1667 LIST_INIT(&unp_dhead);
1668 LIST_INIT(&unp_shead);
1669 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1670 UNP_GLOBAL_LOCK_INIT();
1674 unp_internalize(struct mbuf **controlp, struct thread *td)
1676 struct mbuf *control = *controlp;
1677 struct proc *p = td->td_proc;
1678 struct filedesc *fdescp = p->p_fd;
1679 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1680 struct cmsgcred *cmcred;
1686 socklen_t clen = control->m_len, datalen;
1690 UNP_GLOBAL_UNLOCK_ASSERT();
1694 while (cm != NULL) {
1695 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1696 || cm->cmsg_len > clen) {
1700 data = CMSG_DATA(cm);
1701 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1703 switch (cm->cmsg_type) {
1705 * Fill in credential information.
1708 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1709 SCM_CREDS, SOL_SOCKET);
1710 if (*controlp == NULL) {
1714 cmcred = (struct cmsgcred *)
1715 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1716 cmcred->cmcred_pid = p->p_pid;
1717 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1718 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1719 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1720 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1722 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1723 cmcred->cmcred_groups[i] =
1724 td->td_ucred->cr_groups[i];
1728 oldfds = datalen / sizeof (int);
1730 * Check that all the FDs passed in refer to legal
1731 * files. If not, reject the entire operation.
1734 FILEDESC_SLOCK(fdescp);
1735 for (i = 0; i < oldfds; i++) {
1737 if ((unsigned)fd >= fdescp->fd_nfiles ||
1738 fdescp->fd_ofiles[fd] == NULL) {
1739 FILEDESC_SUNLOCK(fdescp);
1743 fp = fdescp->fd_ofiles[fd];
1744 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1745 FILEDESC_SUNLOCK(fdescp);
1753 * Now replace the integer FDs with pointers to the
1754 * associated global file table entry..
1756 newlen = oldfds * sizeof(struct file *);
1757 *controlp = sbcreatecontrol(NULL, newlen,
1758 SCM_RIGHTS, SOL_SOCKET);
1759 if (*controlp == NULL) {
1760 FILEDESC_SUNLOCK(fdescp);
1765 rp = (struct file **)
1766 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1767 for (i = 0; i < oldfds; i++) {
1768 fp = fdescp->fd_ofiles[*fdp++];
1776 UNP_GLOBAL_WUNLOCK();
1778 FILEDESC_SUNLOCK(fdescp);
1782 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1783 SCM_TIMESTAMP, SOL_SOCKET);
1784 if (*controlp == NULL) {
1788 tv = (struct timeval *)
1789 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1798 controlp = &(*controlp)->m_next;
1799 if (CMSG_SPACE(datalen) < clen) {
1800 clen -= CMSG_SPACE(datalen);
1801 cm = (struct cmsghdr *)
1802 ((caddr_t)cm + CMSG_SPACE(datalen));
1814 static struct mbuf *
1815 unp_addsockcred(struct thread *td, struct mbuf *control)
1817 struct mbuf *m, *n, *n_prev;
1818 struct sockcred *sc;
1819 const struct cmsghdr *cm;
1823 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1824 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1828 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1829 sc->sc_uid = td->td_ucred->cr_ruid;
1830 sc->sc_euid = td->td_ucred->cr_uid;
1831 sc->sc_gid = td->td_ucred->cr_rgid;
1832 sc->sc_egid = td->td_ucred->cr_gid;
1833 sc->sc_ngroups = ngroups;
1834 for (i = 0; i < sc->sc_ngroups; i++)
1835 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1838 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1839 * created SCM_CREDS control message (struct sockcred) has another
1842 if (control != NULL)
1843 for (n = control, n_prev = NULL; n != NULL;) {
1844 cm = mtod(n, struct cmsghdr *);
1845 if (cm->cmsg_level == SOL_SOCKET &&
1846 cm->cmsg_type == SCM_CREDS) {
1848 control = n->m_next;
1850 n_prev->m_next = n->m_next;
1858 /* Prepend it to the head. */
1859 m->m_next = control;
1864 * unp_defer indicates whether additional work has been defered for a future
1865 * pass through unp_gc(). It is thread local and does not require explicit
1868 static int unp_defer;
1870 static int unp_taskcount;
1871 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1873 static int unp_recycled;
1874 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1877 unp_gc(__unused void *arg, int pending)
1879 struct file *fp, *nextfp;
1882 struct file **extra_ref, **fpp;
1885 int nfiles_slack = 20;
1891 * Before going through all this, set all FDs to be NOT deferred and
1892 * NOT externally accessible.
1894 sx_slock(&filelist_lock);
1895 LIST_FOREACH(fp, &filehead, f_list)
1896 fp->f_gcflag &= ~(FMARK|FDEFER);
1898 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1899 LIST_FOREACH(fp, &filehead, f_list) {
1902 * If the file is not open, skip it -- could be a
1903 * file in the process of being opened, or in the
1904 * process of being closed. If the file is
1905 * "closing", it may have been marked for deferred
1906 * consideration. Clear the flag now if so.
1908 if (fp->f_count == 0) {
1909 if (fp->f_gcflag & FDEFER)
1911 fp->f_gcflag &= ~(FMARK|FDEFER);
1917 * If we already marked it as 'defer' in a
1918 * previous pass, then try to process it this
1919 * time and un-mark it.
1921 if (fp->f_gcflag & FDEFER) {
1922 fp->f_gcflag &= ~FDEFER;
1926 * If it's not deferred, then check if it's
1927 * already marked.. if so skip it
1929 if (fp->f_gcflag & FMARK) {
1935 * If all references are from messages in
1936 * transit, then skip it. it's not externally
1939 if (fp->f_count == fp->f_msgcount) {
1945 * If it got this far then it must be
1946 * externally accessible.
1948 fp->f_gcflag |= FMARK;
1952 * Either it was deferred, or it is externally
1953 * accessible and not already marked so. Now check
1954 * if it is possibly one of OUR sockets.
1956 if (fp->f_type != DTYPE_SOCKET ||
1957 (so = fp->f_data) == NULL) {
1962 if (so->so_proto->pr_domain != &localdomain ||
1963 (so->so_proto->pr_flags & PR_RIGHTS) == 0) {
1969 * Tell any other threads that do a subsequent
1970 * fdrop() that we are scanning the message
1973 fp->f_gcflag |= FWAIT;
1977 * So, Ok, it's one of our sockets and it IS
1978 * externally accessible (or was deferred). Now we
1979 * look to see if we hold any file descriptors in its
1980 * message buffers. Follow those links and mark them
1981 * as accessible too.
1983 SOCKBUF_LOCK(&so->so_rcv);
1984 unp_scan(so->so_rcv.sb_mb, unp_mark);
1985 SOCKBUF_UNLOCK(&so->so_rcv);
1988 * If socket is in listening state, then sockets
1989 * in its accept queue are accessible, and so
1990 * are any descriptors in those sockets' receive
1994 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
1995 SOCKBUF_LOCK(&soa->so_rcv);
1996 unp_scan(soa->so_rcv.sb_mb, unp_mark);
1997 SOCKBUF_UNLOCK(&soa->so_rcv);
2002 * Wake up any threads waiting in fdrop().
2005 fp->f_gcflag &= ~FWAIT;
2006 wakeup(&fp->f_gcflag);
2009 } while (unp_defer);
2010 sx_sunlock(&filelist_lock);
2013 * XXXRW: The following comments need updating for a post-SMPng and
2014 * deferred unp_gc() world, but are still generally accurate.
2016 * We grab an extra reference to each of the file table entries that
2017 * are not otherwise accessible and then free the rights that are
2018 * stored in messages on them.
2020 * The bug in the orginal code is a little tricky, so I'll describe
2021 * what's wrong with it here.
2023 * It is incorrect to simply unp_discard each entry for f_msgcount
2024 * times -- consider the case of sockets A and B that contain
2025 * references to each other. On a last close of some other socket,
2026 * we trigger a gc since the number of outstanding rights (unp_rights)
2027 * is non-zero. If during the sweep phase the gc code unp_discards,
2028 * we end up doing a (full) closef on the descriptor. A closef on A
2029 * results in the following chain. Closef calls soo_close, which
2030 * calls soclose. Soclose calls first (through the switch
2031 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
2032 * returns because the previous instance had set unp_gcing, and we
2033 * return all the way back to soclose, which marks the socket with
2034 * SS_NOFDREF, and then calls sofree. Sofree calls sorflush to free
2035 * up the rights that are queued in messages on the socket A, i.e.,
2036 * the reference on B. The sorflush calls via the dom_dispose switch
2037 * unp_dispose, which unp_scans with unp_discard. This second
2038 * instance of unp_discard just calls closef on B.
2040 * Well, a similar chain occurs on B, resulting in a sorflush on B,
2041 * which results in another closef on A. Unfortunately, A is already
2042 * being closed, and the descriptor has already been marked with
2043 * SS_NOFDREF, and soclose panics at this point.
2045 * Here, we first take an extra reference to each inaccessible
2046 * descriptor. Then, we call sorflush ourself, since we know it is a
2047 * Unix domain socket anyhow. After we destroy all the rights
2048 * carried in messages, we do a last closef to get rid of our extra
2049 * reference. This is the last close, and the unp_detach etc will
2050 * shut down the socket.
2052 * 91/09/19, bsy@cs.cmu.edu
2055 nfiles_snap = openfiles + nfiles_slack; /* some slack */
2056 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
2058 sx_slock(&filelist_lock);
2059 if (nfiles_snap < openfiles) {
2060 sx_sunlock(&filelist_lock);
2061 free(extra_ref, M_TEMP);
2065 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
2066 fp != NULL; fp = nextfp) {
2067 nextfp = LIST_NEXT(fp, f_list);
2071 * If it's not open, skip it
2073 if (fp->f_count == 0) {
2079 * If all refs are from msgs, and it's not marked accessible
2080 * then it must be referenced from some unreachable cycle of
2081 * (shut-down) FDs, so include it in our list of FDs to
2084 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
2091 sx_sunlock(&filelist_lock);
2094 * For each FD on our hit list, do the following two things:
2096 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2097 struct file *tfp = *fpp;
2099 if (tfp->f_type == DTYPE_SOCKET &&
2100 tfp->f_data != NULL) {
2102 sorflush(tfp->f_data);
2107 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
2108 closef(*fpp, (struct thread *) NULL);
2111 free(extra_ref, M_TEMP);
2115 unp_dispose(struct mbuf *m)
2119 unp_scan(m, unp_discard);
2123 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2130 socklen_t clen, datalen;
2133 while (m0 != NULL) {
2134 for (m = m0; m; m = m->m_next) {
2135 if (m->m_type != MT_CONTROL)
2138 cm = mtod(m, struct cmsghdr *);
2141 while (cm != NULL) {
2142 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2145 data = CMSG_DATA(cm);
2146 datalen = (caddr_t)cm + cm->cmsg_len
2149 if (cm->cmsg_level == SOL_SOCKET &&
2150 cm->cmsg_type == SCM_RIGHTS) {
2151 qfds = datalen / sizeof (struct file *);
2153 for (i = 0; i < qfds; i++)
2157 if (CMSG_SPACE(datalen) < clen) {
2158 clen -= CMSG_SPACE(datalen);
2159 cm = (struct cmsghdr *)
2160 ((caddr_t)cm + CMSG_SPACE(datalen));
2172 unp_mark(struct file *fp)
2175 /* XXXRW: Should probably assert file list lock here. */
2177 if (fp->f_gcflag & FMARK)
2180 fp->f_gcflag |= (FMARK|FDEFER);
2184 unp_discard(struct file *fp)
2192 UNP_GLOBAL_WUNLOCK();
2193 (void) closef(fp, (struct thread *)NULL);
2198 db_print_indent(int indent)
2202 for (i = 0; i < indent; i++)
2207 db_print_unpflags(int unp_flags)
2212 if (unp_flags & UNP_HAVEPC) {
2213 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2216 if (unp_flags & UNP_HAVEPCCACHED) {
2217 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2220 if (unp_flags & UNP_WANTCRED) {
2221 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2224 if (unp_flags & UNP_CONNWAIT) {
2225 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2228 if (unp_flags & UNP_CONNECTING) {
2229 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2232 if (unp_flags & UNP_BINDING) {
2233 db_printf("%sUNP_BINDING", comma ? ", " : "");
2239 db_print_xucred(int indent, struct xucred *xu)
2243 db_print_indent(indent);
2244 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2245 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2246 db_print_indent(indent);
2247 db_printf("cr_groups: ");
2249 for (i = 0; i < xu->cr_ngroups; i++) {
2250 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2257 db_print_unprefs(int indent, struct unp_head *uh)
2263 LIST_FOREACH(unp, uh, unp_reflink) {
2264 if (counter % 4 == 0)
2265 db_print_indent(indent);
2266 db_printf("%p ", unp);
2267 if (counter % 4 == 3)
2271 if (counter != 0 && counter % 4 != 0)
2275 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2280 db_printf("usage: show unpcb <addr>\n");
2283 unp = (struct unpcb *)addr;
2285 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2288 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2291 db_printf("unp_refs:\n");
2292 db_print_unprefs(2, &unp->unp_refs);
2294 /* XXXRW: Would be nice to print the full address, if any. */
2295 db_printf("unp_addr: %p\n", unp->unp_addr);
2297 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2298 unp->unp_cc, unp->unp_mbcnt,
2299 (unsigned long long)unp->unp_gencnt);
2301 db_printf("unp_flags: %x (", unp->unp_flags);
2302 db_print_unpflags(unp->unp_flags);
2305 db_printf("unp_peercred:\n");
2306 db_print_xucred(2, &unp->unp_peercred);
2308 db_printf("unp_refcount: %u\n", unp->unp_refcount);