2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004-2009 Robert N. M. Watson
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
35 * UNIX Domain (Local) Sockets
37 * This is an implementation of UNIX (local) domain sockets. Each socket has
38 * an associated struct unpcb (UNIX protocol control block). Stream sockets
39 * may be connected to 0 or 1 other socket. Datagram sockets may be
40 * connected to 0, 1, or many other sockets. Sockets may be created and
41 * connected in pairs (socketpair(2)), or bound/connected to using the file
42 * system name space. For most purposes, only the receive socket buffer is
43 * used, as sending on one socket delivers directly to the receive socket
44 * buffer of a second socket.
46 * The implementation is substantially complicated by the fact that
47 * "ancillary data", such as file descriptors or credentials, may be passed
48 * across UNIX domain sockets. The potential for passing UNIX domain sockets
49 * over other UNIX domain sockets requires the implementation of a simple
50 * garbage collector to find and tear down cycles of disconnected sockets.
54 * rethink name space problems
55 * need a proper out-of-band
58 #include <sys/cdefs.h>
59 __FBSDID("$FreeBSD$");
63 #include <sys/param.h>
64 #include <sys/domain.h>
65 #include <sys/fcntl.h>
66 #include <sys/malloc.h> /* XXX must be before <sys/file.h> */
67 #include <sys/eventhandler.h>
69 #include <sys/filedesc.h>
70 #include <sys/kernel.h>
73 #include <sys/mount.h>
74 #include <sys/mutex.h>
75 #include <sys/namei.h>
77 #include <sys/protosw.h>
78 #include <sys/queue.h>
79 #include <sys/resourcevar.h>
80 #include <sys/rwlock.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/signalvar.h>
86 #include <sys/sysctl.h>
87 #include <sys/systm.h>
88 #include <sys/taskqueue.h>
90 #include <sys/unpcb.h>
91 #include <sys/vnode.h>
99 #include <security/mac/mac_framework.h>
105 * (l) Locked using list lock
106 * (g) Locked using linkage lock
109 static uma_zone_t unp_zone;
110 static unp_gen_t unp_gencnt; /* (l) */
111 static u_int unp_count; /* (l) Count of local sockets. */
112 static ino_t unp_ino; /* Prototype for fake inode numbers. */
113 static int unp_rights; /* (g) File descriptors in flight. */
114 static struct unp_head unp_shead; /* (l) List of stream sockets. */
115 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
118 SLIST_ENTRY(unp_defer) ud_link;
121 static SLIST_HEAD(, unp_defer) unp_defers;
122 static int unp_defers_count;
124 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
127 * Garbage collection of cyclic file descriptor/socket references occurs
128 * asynchronously in a taskqueue context in order to avoid recursion and
129 * reentrance in the UNIX domain socket, file descriptor, and socket layer
130 * code. See unp_gc() for a full description.
132 static struct task unp_gc_task;
135 * The close of unix domain sockets attached as SCM_RIGHTS is
136 * postponed to the taskqueue, to avoid arbitrary recursion depth.
137 * The attached sockets might have another sockets attached.
139 static struct task unp_defer_task;
142 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
143 * stream sockets, although the total for sender and receiver is actually
146 * Datagram sockets really use the sendspace as the maximum datagram size,
147 * and don't really want to reserve the sendspace. Their recvspace should be
148 * large enough for at least one max-size datagram plus address.
153 static u_long unpst_sendspace = PIPSIZ;
154 static u_long unpst_recvspace = PIPSIZ;
155 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
156 static u_long unpdg_recvspace = 4*1024;
158 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
159 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
160 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
162 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
163 &unpst_sendspace, 0, "Default stream send space.");
164 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
165 &unpst_recvspace, 0, "Default stream receive space.");
166 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
167 &unpdg_sendspace, 0, "Default datagram send space.");
168 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
169 &unpdg_recvspace, 0, "Default datagram receive space.");
170 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
171 "File descriptors in flight.");
172 SYSCTL_INT(_net_local, OID_AUTO, deferred, CTLFLAG_RD,
173 &unp_defers_count, 0,
174 "File descriptors deferred to taskqueue for close.");
177 * Locking and synchronization:
179 * Three types of locks exit in the local domain socket implementation: a
180 * global list mutex, a global linkage rwlock, and per-unpcb mutexes. Of the
181 * global locks, the list lock protects the socket count, global generation
182 * number, and stream/datagram global lists. The linkage lock protects the
183 * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
184 * held exclusively over the acquisition of multiple unpcb locks to prevent
187 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
188 * allocated in pru_attach() and freed in pru_detach(). The validity of that
189 * pointer is an invariant, so no lock is required to dereference the so_pcb
190 * pointer if a valid socket reference is held by the caller. In practice,
191 * this is always true during operations performed on a socket. Each unpcb
192 * has a back-pointer to its socket, unp_socket, which will be stable under
193 * the same circumstances.
195 * This pointer may only be safely dereferenced as long as a valid reference
196 * to the unpcb is held. Typically, this reference will be from the socket,
197 * or from another unpcb when the referring unpcb's lock is held (in order
198 * that the reference not be invalidated during use). For example, to follow
199 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
200 * as unp_socket remains valid as long as the reference to unp_conn is valid.
202 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
203 * atomic reads without the lock may be performed "lockless", but more
204 * complex reads and read-modify-writes require the mutex to be held. No
205 * lock order is defined between unpcb locks -- multiple unpcb locks may be
206 * acquired at the same time only when holding the linkage rwlock
207 * exclusively, which prevents deadlocks.
209 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
210 * protocols, bind() is a non-atomic operation, and connect() requires
211 * potential sleeping in the protocol, due to potentially waiting on local or
212 * distributed file systems. We try to separate "lookup" operations, which
213 * may sleep, and the IPC operations themselves, which typically can occur
214 * with relative atomicity as locks can be held over the entire operation.
216 * Another tricky issue is simultaneous multi-threaded or multi-process
217 * access to a single UNIX domain socket. These are handled by the flags
218 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
219 * binding, both of which involve dropping UNIX domain socket locks in order
220 * to perform namei() and other file system operations.
222 static struct rwlock unp_link_rwlock;
223 static struct mtx unp_list_lock;
224 static struct mtx unp_defers_lock;
226 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
229 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
231 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
234 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
235 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
236 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
237 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
238 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
241 #define UNP_LIST_LOCK_INIT() mtx_init(&unp_list_lock, \
242 "unp_list_lock", NULL, MTX_DEF)
243 #define UNP_LIST_LOCK() mtx_lock(&unp_list_lock)
244 #define UNP_LIST_UNLOCK() mtx_unlock(&unp_list_lock)
246 #define UNP_DEFERRED_LOCK_INIT() mtx_init(&unp_defers_lock, \
247 "unp_defer", NULL, MTX_DEF)
248 #define UNP_DEFERRED_LOCK() mtx_lock(&unp_defers_lock)
249 #define UNP_DEFERRED_UNLOCK() mtx_unlock(&unp_defers_lock)
251 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
252 "unp_mtx", "unp_mtx", \
253 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
254 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
255 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
256 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
257 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
259 static int uipc_connect2(struct socket *, struct socket *);
260 static int uipc_ctloutput(struct socket *, struct sockopt *);
261 static int unp_connect(struct socket *, struct sockaddr *,
263 static int unp_connect2(struct socket *so, struct socket *so2, int);
264 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
265 static void unp_dispose(struct mbuf *);
266 static void unp_shutdown(struct unpcb *);
267 static void unp_drop(struct unpcb *, int);
268 static void unp_gc(__unused void *, int);
269 static void unp_scan(struct mbuf *, void (*)(struct file *));
270 static void unp_discard(struct file *);
271 static void unp_freerights(struct file **, int);
272 static void unp_init(void);
273 static int unp_internalize(struct mbuf **, struct thread *);
274 static void unp_internalize_fp(struct file *);
275 static int unp_externalize(struct mbuf *, struct mbuf **);
276 static int unp_externalize_fp(struct file *);
277 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
278 static void unp_process_defers(void * __unused, int);
281 * Definitions of protocols supported in the LOCAL domain.
283 static struct domain localdomain;
284 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
285 static struct protosw localsw[] = {
287 .pr_type = SOCK_STREAM,
288 .pr_domain = &localdomain,
289 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
290 .pr_ctloutput = &uipc_ctloutput,
291 .pr_usrreqs = &uipc_usrreqs_stream
294 .pr_type = SOCK_DGRAM,
295 .pr_domain = &localdomain,
296 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
297 .pr_usrreqs = &uipc_usrreqs_dgram
301 static struct domain localdomain = {
302 .dom_family = AF_LOCAL,
304 .dom_init = unp_init,
305 .dom_externalize = unp_externalize,
306 .dom_dispose = unp_dispose,
307 .dom_protosw = localsw,
308 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
313 uipc_abort(struct socket *so)
315 struct unpcb *unp, *unp2;
318 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
322 unp2 = unp->unp_conn;
325 unp_drop(unp2, ECONNABORTED);
326 UNP_PCB_UNLOCK(unp2);
333 uipc_accept(struct socket *so, struct sockaddr **nam)
335 struct unpcb *unp, *unp2;
336 const struct sockaddr *sa;
339 * Pass back name of connected socket, if it was bound and we are
340 * still connected (our peer may have closed already!).
343 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
345 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
347 unp2 = unp->unp_conn;
348 if (unp2 != NULL && unp2->unp_addr != NULL) {
350 sa = (struct sockaddr *) unp2->unp_addr;
351 bcopy(sa, *nam, sa->sa_len);
352 UNP_PCB_UNLOCK(unp2);
355 bcopy(sa, *nam, sa->sa_len);
362 uipc_attach(struct socket *so, int proto, struct thread *td)
364 u_long sendspace, recvspace;
368 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
369 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
370 switch (so->so_type) {
372 sendspace = unpst_sendspace;
373 recvspace = unpst_recvspace;
377 sendspace = unpdg_sendspace;
378 recvspace = unpdg_recvspace;
382 panic("uipc_attach");
384 error = soreserve(so, sendspace, recvspace);
388 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
391 LIST_INIT(&unp->unp_refs);
392 UNP_PCB_LOCK_INIT(unp);
393 unp->unp_socket = so;
395 unp->unp_refcount = 1;
398 unp->unp_gencnt = ++unp_gencnt;
400 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
408 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
410 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
412 int error, namelen, vfslocked;
420 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
422 if (soun->sun_len > sizeof(struct sockaddr_un))
424 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
429 * We don't allow simultaneous bind() calls on a single UNIX domain
430 * socket, so flag in-progress operations, and return an error if an
431 * operation is already in progress.
433 * Historically, we have not allowed a socket to be rebound, so this
434 * also returns an error. Not allowing re-binding simplifies the
435 * implementation and avoids a great many possible failure modes.
438 if (unp->unp_vnode != NULL) {
442 if (unp->unp_flags & UNP_BINDING) {
446 unp->unp_flags |= UNP_BINDING;
449 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
450 bcopy(soun->sun_path, buf, namelen);
455 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
456 UIO_SYSSPACE, buf, td);
457 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
462 vfslocked = NDHASGIANT(&nd);
463 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
464 NDFREE(&nd, NDF_ONLY_PNBUF);
474 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
477 VFS_UNLOCK_GIANT(vfslocked);
481 vattr.va_type = VSOCK;
482 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
484 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
488 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
489 NDFREE(&nd, NDF_ONLY_PNBUF);
492 vn_finished_write(mp);
496 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
497 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
501 vp->v_socket = unp->unp_socket;
503 unp->unp_addr = soun;
504 unp->unp_flags &= ~UNP_BINDING;
508 vn_finished_write(mp);
509 VFS_UNLOCK_GIANT(vfslocked);
514 VFS_UNLOCK_GIANT(vfslocked);
516 unp->unp_flags &= ~UNP_BINDING;
523 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
527 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
529 error = unp_connect(so, nam, td);
535 uipc_close(struct socket *so)
537 struct unpcb *unp, *unp2;
540 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
544 unp2 = unp->unp_conn;
547 unp_disconnect(unp, unp2);
548 UNP_PCB_UNLOCK(unp2);
555 uipc_connect2(struct socket *so1, struct socket *so2)
557 struct unpcb *unp, *unp2;
562 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
565 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
567 error = unp_connect2(so1, so2, PRU_CONNECT2);
568 UNP_PCB_UNLOCK(unp2);
575 uipc_detach(struct socket *so)
577 struct unpcb *unp, *unp2;
578 struct sockaddr_un *saved_unp_addr;
580 int freeunp, local_unp_rights;
583 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
588 LIST_REMOVE(unp, unp_link);
589 unp->unp_gencnt = ++unp_gencnt;
594 * XXXRW: Should assert vp->v_socket == so.
596 if ((vp = unp->unp_vnode) != NULL) {
597 unp->unp_vnode->v_socket = NULL;
598 unp->unp_vnode = NULL;
600 unp2 = unp->unp_conn;
603 unp_disconnect(unp, unp2);
604 UNP_PCB_UNLOCK(unp2);
608 * We hold the linkage lock exclusively, so it's OK to acquire
609 * multiple pcb locks at a time.
611 while (!LIST_EMPTY(&unp->unp_refs)) {
612 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
615 unp_drop(ref, ECONNRESET);
618 local_unp_rights = unp_rights;
620 unp->unp_socket->so_pcb = NULL;
621 saved_unp_addr = unp->unp_addr;
622 unp->unp_addr = NULL;
624 freeunp = (unp->unp_refcount == 0);
625 if (saved_unp_addr != NULL)
626 free(saved_unp_addr, M_SONAME);
628 UNP_PCB_LOCK_DESTROY(unp);
629 uma_zfree(unp_zone, unp);
635 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
637 VFS_UNLOCK_GIANT(vfslocked);
639 if (local_unp_rights)
640 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
644 uipc_disconnect(struct socket *so)
646 struct unpcb *unp, *unp2;
649 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
653 unp2 = unp->unp_conn;
656 unp_disconnect(unp, unp2);
657 UNP_PCB_UNLOCK(unp2);
665 uipc_listen(struct socket *so, int backlog, struct thread *td)
671 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
674 if (unp->unp_vnode == NULL) {
680 error = solisten_proto_check(so);
682 cru2x(td->td_ucred, &unp->unp_peercred);
683 unp->unp_flags |= UNP_HAVEPCCACHED;
684 solisten_proto(so, backlog);
692 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
694 struct unpcb *unp, *unp2;
695 const struct sockaddr *sa;
698 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
700 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
703 * XXX: It seems that this test always fails even when connection is
704 * established. So, this else clause is added as workaround to
705 * return PF_LOCAL sockaddr.
707 unp2 = unp->unp_conn;
710 if (unp2->unp_addr != NULL)
711 sa = (struct sockaddr *) unp2->unp_addr;
714 bcopy(sa, *nam, sa->sa_len);
715 UNP_PCB_UNLOCK(unp2);
718 bcopy(sa, *nam, sa->sa_len);
725 uipc_rcvd(struct socket *so, int flags)
727 struct unpcb *unp, *unp2;
733 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
735 if (so->so_type == SOCK_DGRAM)
736 panic("uipc_rcvd DGRAM?");
738 if (so->so_type != SOCK_STREAM)
739 panic("uipc_rcvd unknown socktype");
742 * Adjust backpressure on sender and wakeup any waiting to write.
744 * The unp lock is acquired to maintain the validity of the unp_conn
745 * pointer; no lock on unp2 is required as unp2->unp_socket will be
746 * static as long as we don't permit unp2 to disconnect from unp,
747 * which is prevented by the lock on unp. We cache values from
748 * so_rcv to avoid holding the so_rcv lock over the entire
749 * transaction on the remote so_snd.
751 SOCKBUF_LOCK(&so->so_rcv);
752 mbcnt = so->so_rcv.sb_mbcnt;
753 sbcc = so->so_rcv.sb_cc;
754 SOCKBUF_UNLOCK(&so->so_rcv);
756 unp2 = unp->unp_conn;
761 so2 = unp2->unp_socket;
762 SOCKBUF_LOCK(&so2->so_snd);
763 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
764 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
765 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
766 newhiwat, RLIM_INFINITY);
767 sowwakeup_locked(so2);
768 unp->unp_mbcnt = mbcnt;
775 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
776 struct mbuf *control, struct thread *td)
778 struct unpcb *unp, *unp2;
780 u_int mbcnt_delta, sbcc;
785 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
787 if (flags & PRUS_OOB) {
791 if (control != NULL && (error = unp_internalize(&control, td)))
793 if ((nam != NULL) || (flags & PRUS_EOF))
797 switch (so->so_type) {
800 const struct sockaddr *from;
802 unp2 = unp->unp_conn;
804 UNP_LINK_WLOCK_ASSERT();
809 error = unp_connect(so, nam, td);
812 unp2 = unp->unp_conn;
816 * Because connect() and send() are non-atomic in a sendto()
817 * with a target address, it's possible that the socket will
818 * have disconnected before the send() can run. In that case
819 * return the slightly counter-intuitive but otherwise
820 * correct error that the socket is not connected.
827 if (unp2->unp_flags & UNP_WANTCRED)
828 control = unp_addsockcred(td, control);
830 if (unp->unp_addr != NULL)
831 from = (struct sockaddr *)unp->unp_addr;
834 so2 = unp2->unp_socket;
835 SOCKBUF_LOCK(&so2->so_rcv);
836 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
837 sorwakeup_locked(so2);
841 SOCKBUF_UNLOCK(&so2->so_rcv);
845 UNP_LINK_WLOCK_ASSERT();
847 unp_disconnect(unp, unp2);
848 UNP_PCB_UNLOCK(unp2);
855 if ((so->so_state & SS_ISCONNECTED) == 0) {
857 UNP_LINK_WLOCK_ASSERT();
858 error = unp_connect(so, nam, td);
868 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
874 * Because connect() and send() are non-atomic in a sendto()
875 * with a target address, it's possible that the socket will
876 * have disconnected before the send() can run. In that case
877 * return the slightly counter-intuitive but otherwise
878 * correct error that the socket is not connected.
880 * Locking here must be done carefully: the linkage lock
881 * prevents interconnections between unpcbs from changing, so
882 * we can traverse from unp to unp2 without acquiring unp's
883 * lock. Socket buffer locks follow unpcb locks, so we can
884 * acquire both remote and lock socket buffer locks.
886 unp2 = unp->unp_conn;
891 so2 = unp2->unp_socket;
893 SOCKBUF_LOCK(&so2->so_rcv);
894 if (unp2->unp_flags & UNP_WANTCRED) {
896 * Credentials are passed only once on SOCK_STREAM.
898 unp2->unp_flags &= ~UNP_WANTCRED;
899 control = unp_addsockcred(td, control);
902 * Send to paired receive port, and then reduce send buffer
903 * hiwater marks to maintain backpressure. Wake up readers.
905 if (control != NULL) {
906 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
909 sbappend_locked(&so2->so_rcv, m);
910 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
911 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
912 sbcc = so2->so_rcv.sb_cc;
913 sorwakeup_locked(so2);
915 SOCKBUF_LOCK(&so->so_snd);
916 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
917 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
918 newhiwat, RLIM_INFINITY);
919 so->so_snd.sb_mbmax -= mbcnt_delta;
920 SOCKBUF_UNLOCK(&so->so_snd);
922 UNP_PCB_UNLOCK(unp2);
927 panic("uipc_send unknown socktype");
931 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
933 if (flags & PRUS_EOF) {
940 if ((nam != NULL) || (flags & PRUS_EOF))
945 if (control != NULL && error != 0)
946 unp_dispose(control);
957 uipc_sense(struct socket *so, struct stat *sb)
959 struct unpcb *unp, *unp2;
963 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
965 sb->st_blksize = so->so_snd.sb_hiwat;
968 unp2 = unp->unp_conn;
969 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
970 so2 = unp2->unp_socket;
971 sb->st_blksize += so2->so_rcv.sb_cc;
974 if (unp->unp_ino == 0)
975 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
976 sb->st_ino = unp->unp_ino;
983 uipc_shutdown(struct socket *so)
988 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
1000 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1003 const struct sockaddr *sa;
1005 unp = sotounpcb(so);
1006 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1008 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1010 if (unp->unp_addr != NULL)
1011 sa = (struct sockaddr *) unp->unp_addr;
1014 bcopy(sa, *nam, sa->sa_len);
1015 UNP_PCB_UNLOCK(unp);
1019 static struct pr_usrreqs uipc_usrreqs_dgram = {
1020 .pru_abort = uipc_abort,
1021 .pru_accept = uipc_accept,
1022 .pru_attach = uipc_attach,
1023 .pru_bind = uipc_bind,
1024 .pru_connect = uipc_connect,
1025 .pru_connect2 = uipc_connect2,
1026 .pru_detach = uipc_detach,
1027 .pru_disconnect = uipc_disconnect,
1028 .pru_listen = uipc_listen,
1029 .pru_peeraddr = uipc_peeraddr,
1030 .pru_rcvd = uipc_rcvd,
1031 .pru_send = uipc_send,
1032 .pru_sense = uipc_sense,
1033 .pru_shutdown = uipc_shutdown,
1034 .pru_sockaddr = uipc_sockaddr,
1035 .pru_soreceive = soreceive_dgram,
1036 .pru_close = uipc_close,
1039 static struct pr_usrreqs uipc_usrreqs_stream = {
1040 .pru_abort = uipc_abort,
1041 .pru_accept = uipc_accept,
1042 .pru_attach = uipc_attach,
1043 .pru_bind = uipc_bind,
1044 .pru_connect = uipc_connect,
1045 .pru_connect2 = uipc_connect2,
1046 .pru_detach = uipc_detach,
1047 .pru_disconnect = uipc_disconnect,
1048 .pru_listen = uipc_listen,
1049 .pru_peeraddr = uipc_peeraddr,
1050 .pru_rcvd = uipc_rcvd,
1051 .pru_send = uipc_send,
1052 .pru_sense = uipc_sense,
1053 .pru_shutdown = uipc_shutdown,
1054 .pru_sockaddr = uipc_sockaddr,
1055 .pru_soreceive = soreceive_generic,
1056 .pru_close = uipc_close,
1060 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1066 if (sopt->sopt_level != 0)
1069 unp = sotounpcb(so);
1070 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1072 switch (sopt->sopt_dir) {
1074 switch (sopt->sopt_name) {
1075 case LOCAL_PEERCRED:
1077 if (unp->unp_flags & UNP_HAVEPC)
1078 xu = unp->unp_peercred;
1080 if (so->so_type == SOCK_STREAM)
1085 UNP_PCB_UNLOCK(unp);
1087 error = sooptcopyout(sopt, &xu, sizeof(xu));
1091 /* Unlocked read. */
1092 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1093 error = sooptcopyout(sopt, &optval, sizeof(optval));
1096 case LOCAL_CONNWAIT:
1097 /* Unlocked read. */
1098 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1099 error = sooptcopyout(sopt, &optval, sizeof(optval));
1109 switch (sopt->sopt_name) {
1111 case LOCAL_CONNWAIT:
1112 error = sooptcopyin(sopt, &optval, sizeof(optval),
1117 #define OPTSET(bit) do { \
1118 UNP_PCB_LOCK(unp); \
1120 unp->unp_flags |= bit; \
1122 unp->unp_flags &= ~bit; \
1123 UNP_PCB_UNLOCK(unp); \
1126 switch (sopt->sopt_name) {
1128 OPTSET(UNP_WANTCRED);
1131 case LOCAL_CONNWAIT:
1132 OPTSET(UNP_CONNWAIT);
1141 error = ENOPROTOOPT;
1154 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1156 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1158 struct socket *so2, *so3;
1159 struct unpcb *unp, *unp2, *unp3;
1160 int error, len, vfslocked;
1161 struct nameidata nd;
1162 char buf[SOCK_MAXADDRLEN];
1163 struct sockaddr *sa;
1165 UNP_LINK_WLOCK_ASSERT();
1167 unp = sotounpcb(so);
1168 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1170 if (nam->sa_len > sizeof(struct sockaddr_un))
1172 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1175 bcopy(soun->sun_path, buf, len);
1179 if (unp->unp_flags & UNP_CONNECTING) {
1180 UNP_PCB_UNLOCK(unp);
1184 unp->unp_flags |= UNP_CONNECTING;
1185 UNP_PCB_UNLOCK(unp);
1187 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1188 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1195 ASSERT_VOP_LOCKED(vp, "unp_connect");
1196 vfslocked = NDHASGIANT(&nd);
1197 NDFREE(&nd, NDF_ONLY_PNBUF);
1201 if (vp->v_type != VSOCK) {
1206 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1210 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1213 VFS_UNLOCK_GIANT(vfslocked);
1215 unp = sotounpcb(so);
1216 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1219 * Lock linkage lock for two reasons: make sure v_socket is stable,
1220 * and to protect simultaneous locking of multiple pcbs.
1225 error = ECONNREFUSED;
1228 if (so->so_type != so2->so_type) {
1232 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1233 if (so2->so_options & SO_ACCEPTCONN) {
1234 so3 = sonewconn(so2, 0);
1238 error = ECONNREFUSED;
1241 unp = sotounpcb(so);
1242 unp2 = sotounpcb(so2);
1243 unp3 = sotounpcb(so3);
1247 if (unp2->unp_addr != NULL) {
1248 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1249 unp3->unp_addr = (struct sockaddr_un *) sa;
1254 * The connecter's (client's) credentials are copied from its
1255 * process structure at the time of connect() (which is now).
1257 cru2x(td->td_ucred, &unp3->unp_peercred);
1258 unp3->unp_flags |= UNP_HAVEPC;
1261 * The receiver's (server's) credentials are copied from the
1262 * unp_peercred member of socket on which the former called
1263 * listen(); uipc_listen() cached that process's credentials
1264 * at that time so we can use them now.
1266 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1267 ("unp_connect: listener without cached peercred"));
1268 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1269 sizeof(unp->unp_peercred));
1270 unp->unp_flags |= UNP_HAVEPC;
1271 if (unp2->unp_flags & UNP_WANTCRED)
1272 unp3->unp_flags |= UNP_WANTCRED;
1273 UNP_PCB_UNLOCK(unp3);
1274 UNP_PCB_UNLOCK(unp2);
1275 UNP_PCB_UNLOCK(unp);
1277 mac_socketpeer_set_from_socket(so, so3);
1278 mac_socketpeer_set_from_socket(so3, so);
1283 unp = sotounpcb(so);
1284 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1285 unp2 = sotounpcb(so2);
1286 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1289 error = unp_connect2(so, so2, PRU_CONNECT);
1290 UNP_PCB_UNLOCK(unp2);
1291 UNP_PCB_UNLOCK(unp);
1296 * Giant has been previously acquired. This means filesystem
1297 * isn't MPSAFE. Do it once again.
1303 VFS_UNLOCK_GIANT(vfslocked);
1307 unp->unp_flags &= ~UNP_CONNECTING;
1308 UNP_PCB_UNLOCK(unp);
1313 unp_connect2(struct socket *so, struct socket *so2, int req)
1318 unp = sotounpcb(so);
1319 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1320 unp2 = sotounpcb(so2);
1321 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1323 UNP_LINK_WLOCK_ASSERT();
1324 UNP_PCB_LOCK_ASSERT(unp);
1325 UNP_PCB_LOCK_ASSERT(unp2);
1327 if (so2->so_type != so->so_type)
1328 return (EPROTOTYPE);
1329 unp->unp_conn = unp2;
1331 switch (so->so_type) {
1333 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1338 unp2->unp_conn = unp;
1339 if (req == PRU_CONNECT &&
1340 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1348 panic("unp_connect2");
1354 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1358 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1360 UNP_LINK_WLOCK_ASSERT();
1361 UNP_PCB_LOCK_ASSERT(unp);
1362 UNP_PCB_LOCK_ASSERT(unp2);
1364 unp->unp_conn = NULL;
1365 switch (unp->unp_socket->so_type) {
1367 LIST_REMOVE(unp, unp_reflink);
1368 so = unp->unp_socket;
1370 so->so_state &= ~SS_ISCONNECTED;
1375 soisdisconnected(unp->unp_socket);
1376 unp2->unp_conn = NULL;
1377 soisdisconnected(unp2->unp_socket);
1383 * unp_pcblist() walks the global list of struct unpcb's to generate a
1384 * pointer list, bumping the refcount on each unpcb. It then copies them out
1385 * sequentially, validating the generation number on each to see if it has
1386 * been detached. All of this is necessary because copyout() may sleep on
1390 unp_pcblist(SYSCTL_HANDLER_ARGS)
1394 struct unpcb *unp, **unp_list;
1396 struct xunpgen *xug;
1397 struct unp_head *head;
1400 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1403 * The process of preparing the PCB list is too time-consuming and
1404 * resource-intensive to repeat twice on every request.
1406 if (req->oldptr == NULL) {
1408 req->oldidx = 2 * (sizeof *xug)
1409 + (n + n/8) * sizeof(struct xunpcb);
1413 if (req->newptr != NULL)
1417 * OK, now we're committed to doing something.
1419 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1421 gencnt = unp_gencnt;
1425 xug->xug_len = sizeof *xug;
1427 xug->xug_gen = gencnt;
1428 xug->xug_sogen = so_gencnt;
1429 error = SYSCTL_OUT(req, xug, sizeof *xug);
1435 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1438 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1439 unp = LIST_NEXT(unp, unp_link)) {
1441 if (unp->unp_gencnt <= gencnt) {
1442 if (cr_cansee(req->td->td_ucred,
1443 unp->unp_socket->so_cred)) {
1444 UNP_PCB_UNLOCK(unp);
1447 unp_list[i++] = unp;
1448 unp->unp_refcount++;
1450 UNP_PCB_UNLOCK(unp);
1453 n = i; /* In case we lost some during malloc. */
1456 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1457 for (i = 0; i < n; i++) {
1460 unp->unp_refcount--;
1461 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1462 xu->xu_len = sizeof *xu;
1465 * XXX - need more locking here to protect against
1466 * connect/disconnect races for SMP.
1468 if (unp->unp_addr != NULL)
1469 bcopy(unp->unp_addr, &xu->xu_addr,
1470 unp->unp_addr->sun_len);
1471 if (unp->unp_conn != NULL &&
1472 unp->unp_conn->unp_addr != NULL)
1473 bcopy(unp->unp_conn->unp_addr,
1475 unp->unp_conn->unp_addr->sun_len);
1476 bcopy(unp, &xu->xu_unp, sizeof *unp);
1477 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1478 UNP_PCB_UNLOCK(unp);
1479 error = SYSCTL_OUT(req, xu, sizeof *xu);
1481 freeunp = (unp->unp_refcount == 0);
1482 UNP_PCB_UNLOCK(unp);
1484 UNP_PCB_LOCK_DESTROY(unp);
1485 uma_zfree(unp_zone, unp);
1492 * Give the user an updated idea of our state. If the
1493 * generation differs from what we told her before, she knows
1494 * that something happened while we were processing this
1495 * request, and it might be necessary to retry.
1497 xug->xug_gen = unp_gencnt;
1498 xug->xug_sogen = so_gencnt;
1499 xug->xug_count = unp_count;
1500 error = SYSCTL_OUT(req, xug, sizeof *xug);
1502 free(unp_list, M_TEMP);
1507 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1508 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1509 "List of active local datagram sockets");
1510 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1511 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1512 "List of active local stream sockets");
1515 unp_shutdown(struct unpcb *unp)
1520 UNP_LINK_WLOCK_ASSERT();
1521 UNP_PCB_LOCK_ASSERT(unp);
1523 unp2 = unp->unp_conn;
1524 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1525 so = unp2->unp_socket;
1532 unp_drop(struct unpcb *unp, int errno)
1534 struct socket *so = unp->unp_socket;
1537 UNP_LINK_WLOCK_ASSERT();
1538 UNP_PCB_LOCK_ASSERT(unp);
1540 so->so_error = errno;
1541 unp2 = unp->unp_conn;
1545 unp_disconnect(unp, unp2);
1546 UNP_PCB_UNLOCK(unp2);
1550 unp_freerights(struct file **rp, int fdcount)
1555 for (i = 0; i < fdcount; i++) {
1563 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1565 struct thread *td = curthread; /* XXX */
1566 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1572 socklen_t clen = control->m_len, datalen;
1577 UNP_LINK_UNLOCK_ASSERT();
1580 if (controlp != NULL) /* controlp == NULL => free control messages */
1582 while (cm != NULL) {
1583 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1587 data = CMSG_DATA(cm);
1588 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1589 if (cm->cmsg_level == SOL_SOCKET
1590 && cm->cmsg_type == SCM_RIGHTS) {
1591 newfds = datalen / sizeof(struct file *);
1594 /* If we're not outputting the descriptors free them. */
1595 if (error || controlp == NULL) {
1596 unp_freerights(rp, newfds);
1599 FILEDESC_XLOCK(td->td_proc->p_fd);
1600 /* if the new FD's will not fit free them. */
1601 if (!fdavail(td, newfds)) {
1602 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1604 unp_freerights(rp, newfds);
1609 * Now change each pointer to an fd in the global
1610 * table to an integer that is the index to the local
1611 * fd table entry that we set up to point to the
1612 * global one we are transferring.
1614 newlen = newfds * sizeof(int);
1615 *controlp = sbcreatecontrol(NULL, newlen,
1616 SCM_RIGHTS, SOL_SOCKET);
1617 if (*controlp == NULL) {
1618 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1620 unp_freerights(rp, newfds);
1625 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1626 for (i = 0; i < newfds; i++) {
1627 if (fdalloc(td, 0, &f))
1628 panic("unp_externalize fdalloc failed");
1630 td->td_proc->p_fd->fd_ofiles[f] = fp;
1631 unp_externalize_fp(fp);
1634 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1636 /* We can just copy anything else across. */
1637 if (error || controlp == NULL)
1639 *controlp = sbcreatecontrol(NULL, datalen,
1640 cm->cmsg_type, cm->cmsg_level);
1641 if (*controlp == NULL) {
1646 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1649 controlp = &(*controlp)->m_next;
1652 if (CMSG_SPACE(datalen) < clen) {
1653 clen -= CMSG_SPACE(datalen);
1654 cm = (struct cmsghdr *)
1655 ((caddr_t)cm + CMSG_SPACE(datalen));
1667 unp_zone_change(void *tag)
1670 uma_zone_set_max(unp_zone, maxsockets);
1678 if (!IS_DEFAULT_VNET(curvnet))
1681 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1682 NULL, NULL, UMA_ALIGN_PTR, 0);
1683 if (unp_zone == NULL)
1685 uma_zone_set_max(unp_zone, maxsockets);
1686 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1687 NULL, EVENTHANDLER_PRI_ANY);
1688 LIST_INIT(&unp_dhead);
1689 LIST_INIT(&unp_shead);
1690 SLIST_INIT(&unp_defers);
1691 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1692 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1693 UNP_LINK_LOCK_INIT();
1694 UNP_LIST_LOCK_INIT();
1695 UNP_DEFERRED_LOCK_INIT();
1699 unp_internalize(struct mbuf **controlp, struct thread *td)
1701 struct mbuf *control = *controlp;
1702 struct proc *p = td->td_proc;
1703 struct filedesc *fdescp = p->p_fd;
1704 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1705 struct cmsgcred *cmcred;
1711 socklen_t clen = control->m_len, datalen;
1715 UNP_LINK_UNLOCK_ASSERT();
1719 while (cm != NULL) {
1720 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1721 || cm->cmsg_len > clen) {
1725 data = CMSG_DATA(cm);
1726 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1728 switch (cm->cmsg_type) {
1730 * Fill in credential information.
1733 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1734 SCM_CREDS, SOL_SOCKET);
1735 if (*controlp == NULL) {
1739 cmcred = (struct cmsgcred *)
1740 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1741 cmcred->cmcred_pid = p->p_pid;
1742 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1743 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1744 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1745 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1747 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1748 cmcred->cmcred_groups[i] =
1749 td->td_ucred->cr_groups[i];
1753 oldfds = datalen / sizeof (int);
1755 * Check that all the FDs passed in refer to legal
1756 * files. If not, reject the entire operation.
1759 FILEDESC_SLOCK(fdescp);
1760 for (i = 0; i < oldfds; i++) {
1762 if ((unsigned)fd >= fdescp->fd_nfiles ||
1763 fdescp->fd_ofiles[fd] == NULL) {
1764 FILEDESC_SUNLOCK(fdescp);
1768 fp = fdescp->fd_ofiles[fd];
1769 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1770 FILEDESC_SUNLOCK(fdescp);
1778 * Now replace the integer FDs with pointers to the
1779 * associated global file table entry..
1781 newlen = oldfds * sizeof(struct file *);
1782 *controlp = sbcreatecontrol(NULL, newlen,
1783 SCM_RIGHTS, SOL_SOCKET);
1784 if (*controlp == NULL) {
1785 FILEDESC_SUNLOCK(fdescp);
1790 rp = (struct file **)
1791 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1792 for (i = 0; i < oldfds; i++) {
1793 fp = fdescp->fd_ofiles[*fdp++];
1795 unp_internalize_fp(fp);
1797 FILEDESC_SUNLOCK(fdescp);
1801 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1802 SCM_TIMESTAMP, SOL_SOCKET);
1803 if (*controlp == NULL) {
1807 tv = (struct timeval *)
1808 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1817 controlp = &(*controlp)->m_next;
1818 if (CMSG_SPACE(datalen) < clen) {
1819 clen -= CMSG_SPACE(datalen);
1820 cm = (struct cmsghdr *)
1821 ((caddr_t)cm + CMSG_SPACE(datalen));
1833 static struct mbuf *
1834 unp_addsockcred(struct thread *td, struct mbuf *control)
1836 struct mbuf *m, *n, *n_prev;
1837 struct sockcred *sc;
1838 const struct cmsghdr *cm;
1842 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1843 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1847 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1848 sc->sc_uid = td->td_ucred->cr_ruid;
1849 sc->sc_euid = td->td_ucred->cr_uid;
1850 sc->sc_gid = td->td_ucred->cr_rgid;
1851 sc->sc_egid = td->td_ucred->cr_gid;
1852 sc->sc_ngroups = ngroups;
1853 for (i = 0; i < sc->sc_ngroups; i++)
1854 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1857 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1858 * created SCM_CREDS control message (struct sockcred) has another
1861 if (control != NULL)
1862 for (n = control, n_prev = NULL; n != NULL;) {
1863 cm = mtod(n, struct cmsghdr *);
1864 if (cm->cmsg_level == SOL_SOCKET &&
1865 cm->cmsg_type == SCM_CREDS) {
1867 control = n->m_next;
1869 n_prev->m_next = n->m_next;
1877 /* Prepend it to the head. */
1878 m->m_next = control;
1882 static struct unpcb *
1883 fptounp(struct file *fp)
1887 if (fp->f_type != DTYPE_SOCKET)
1889 if ((so = fp->f_data) == NULL)
1891 if (so->so_proto->pr_domain != &localdomain)
1893 return sotounpcb(so);
1897 unp_discard(struct file *fp)
1899 struct unp_defer *dr;
1901 if (unp_externalize_fp(fp)) {
1902 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
1904 UNP_DEFERRED_LOCK();
1905 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
1906 UNP_DEFERRED_UNLOCK();
1907 atomic_add_int(&unp_defers_count, 1);
1908 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
1910 (void) closef(fp, (struct thread *)NULL);
1914 unp_process_defers(void *arg __unused, int pending)
1916 struct unp_defer *dr;
1917 SLIST_HEAD(, unp_defer) drl;
1922 UNP_DEFERRED_LOCK();
1923 if (SLIST_FIRST(&unp_defers) == NULL) {
1924 UNP_DEFERRED_UNLOCK();
1927 SLIST_SWAP(&unp_defers, &drl, unp_defer);
1928 UNP_DEFERRED_UNLOCK();
1930 while ((dr = SLIST_FIRST(&drl)) != NULL) {
1931 SLIST_REMOVE_HEAD(&drl, ud_link);
1932 closef(dr->ud_fp, NULL);
1936 atomic_add_int(&unp_defers_count, -count);
1941 unp_internalize_fp(struct file *fp)
1946 if ((unp = fptounp(fp)) != NULL) {
1948 unp->unp_msgcount++;
1956 unp_externalize_fp(struct file *fp)
1962 if ((unp = fptounp(fp)) != NULL) {
1963 unp->unp_msgcount--;
1973 * unp_defer indicates whether additional work has been defered for a future
1974 * pass through unp_gc(). It is thread local and does not require explicit
1977 static int unp_marked;
1978 static int unp_unreachable;
1981 unp_accessable(struct file *fp)
1985 if ((unp = fptounp(fp)) == NULL)
1987 if (unp->unp_gcflag & UNPGC_REF)
1989 unp->unp_gcflag &= ~UNPGC_DEAD;
1990 unp->unp_gcflag |= UNPGC_REF;
1995 unp_gc_process(struct unpcb *unp)
2001 /* Already processed. */
2002 if (unp->unp_gcflag & UNPGC_SCANNED)
2007 * Check for a socket potentially in a cycle. It must be in a
2008 * queue as indicated by msgcount, and this must equal the file
2009 * reference count. Note that when msgcount is 0 the file is NULL.
2011 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2012 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2013 unp->unp_gcflag |= UNPGC_DEAD;
2019 * Mark all sockets we reference with RIGHTS.
2021 so = unp->unp_socket;
2022 SOCKBUF_LOCK(&so->so_rcv);
2023 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2024 SOCKBUF_UNLOCK(&so->so_rcv);
2027 * Mark all sockets in our accept queue.
2030 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2031 SOCKBUF_LOCK(&soa->so_rcv);
2032 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2033 SOCKBUF_UNLOCK(&soa->so_rcv);
2036 unp->unp_gcflag |= UNPGC_SCANNED;
2039 static int unp_recycled;
2040 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2041 "Number of unreachable sockets claimed by the garbage collector.");
2043 static int unp_taskcount;
2044 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2045 "Number of times the garbage collector has run.");
2048 unp_gc(__unused void *arg, int pending)
2050 struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
2051 struct unp_head **head;
2052 struct file **unref;
2059 * First clear all gc flags from previous runs.
2061 for (head = heads; *head != NULL; head++)
2062 LIST_FOREACH(unp, *head, unp_link)
2063 unp->unp_gcflag = 0;
2066 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2067 * is reachable all of the sockets it references are reachable.
2068 * Stop the scan once we do a complete loop without discovering
2069 * a new reachable socket.
2072 unp_unreachable = 0;
2074 for (head = heads; *head != NULL; head++)
2075 LIST_FOREACH(unp, *head, unp_link)
2076 unp_gc_process(unp);
2077 } while (unp_marked);
2079 if (unp_unreachable == 0)
2083 * Allocate space for a local list of dead unpcbs.
2085 unref = malloc(unp_unreachable * sizeof(struct file *),
2089 * Iterate looking for sockets which have been specifically marked
2090 * as as unreachable and store them locally.
2093 for (i = 0, head = heads; *head != NULL; head++)
2094 LIST_FOREACH(unp, *head, unp_link)
2095 if (unp->unp_gcflag & UNPGC_DEAD) {
2096 unref[i++] = unp->unp_file;
2097 fhold(unp->unp_file);
2098 KASSERT(unp->unp_file != NULL,
2099 ("unp_gc: Invalid unpcb."));
2100 KASSERT(i <= unp_unreachable,
2101 ("unp_gc: incorrect unreachable count."));
2106 * Now flush all sockets, free'ing rights. This will free the
2107 * struct files associated with these sockets but leave each socket
2108 * with one remaining ref.
2110 for (i = 0; i < unp_unreachable; i++)
2111 sorflush(unref[i]->f_data);
2114 * And finally release the sockets so they can be reclaimed.
2116 for (i = 0; i < unp_unreachable; i++)
2117 fdrop(unref[i], NULL);
2118 unp_recycled += unp_unreachable;
2119 free(unref, M_TEMP);
2123 unp_dispose(struct mbuf *m)
2127 unp_scan(m, unp_discard);
2131 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2138 socklen_t clen, datalen;
2141 while (m0 != NULL) {
2142 for (m = m0; m; m = m->m_next) {
2143 if (m->m_type != MT_CONTROL)
2146 cm = mtod(m, struct cmsghdr *);
2149 while (cm != NULL) {
2150 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2153 data = CMSG_DATA(cm);
2154 datalen = (caddr_t)cm + cm->cmsg_len
2157 if (cm->cmsg_level == SOL_SOCKET &&
2158 cm->cmsg_type == SCM_RIGHTS) {
2159 qfds = datalen / sizeof (struct file *);
2161 for (i = 0; i < qfds; i++)
2165 if (CMSG_SPACE(datalen) < clen) {
2166 clen -= CMSG_SPACE(datalen);
2167 cm = (struct cmsghdr *)
2168 ((caddr_t)cm + CMSG_SPACE(datalen));
2181 db_print_indent(int indent)
2185 for (i = 0; i < indent; i++)
2190 db_print_unpflags(int unp_flags)
2195 if (unp_flags & UNP_HAVEPC) {
2196 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2199 if (unp_flags & UNP_HAVEPCCACHED) {
2200 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2203 if (unp_flags & UNP_WANTCRED) {
2204 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2207 if (unp_flags & UNP_CONNWAIT) {
2208 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2211 if (unp_flags & UNP_CONNECTING) {
2212 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2215 if (unp_flags & UNP_BINDING) {
2216 db_printf("%sUNP_BINDING", comma ? ", " : "");
2222 db_print_xucred(int indent, struct xucred *xu)
2226 db_print_indent(indent);
2227 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2228 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2229 db_print_indent(indent);
2230 db_printf("cr_groups: ");
2232 for (i = 0; i < xu->cr_ngroups; i++) {
2233 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2240 db_print_unprefs(int indent, struct unp_head *uh)
2246 LIST_FOREACH(unp, uh, unp_reflink) {
2247 if (counter % 4 == 0)
2248 db_print_indent(indent);
2249 db_printf("%p ", unp);
2250 if (counter % 4 == 3)
2254 if (counter != 0 && counter % 4 != 0)
2258 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2263 db_printf("usage: show unpcb <addr>\n");
2266 unp = (struct unpcb *)addr;
2268 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2271 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2274 db_printf("unp_refs:\n");
2275 db_print_unprefs(2, &unp->unp_refs);
2277 /* XXXRW: Would be nice to print the full address, if any. */
2278 db_printf("unp_addr: %p\n", unp->unp_addr);
2280 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2281 unp->unp_cc, unp->unp_mbcnt,
2282 (unsigned long long)unp->unp_gencnt);
2284 db_printf("unp_flags: %x (", unp->unp_flags);
2285 db_print_unpflags(unp->unp_flags);
2288 db_printf("unp_peercred:\n");
2289 db_print_xucred(2, &unp->unp_peercred);
2291 db_printf("unp_refcount: %u\n", unp->unp_refcount);