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 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
427 * We don't allow simultaneous bind() calls on a single UNIX domain
428 * socket, so flag in-progress operations, and return an error if an
429 * operation is already in progress.
431 * Historically, we have not allowed a socket to be rebound, so this
432 * also returns an error. Not allowing re-binding simplifies the
433 * implementation and avoids a great many possible failure modes.
436 if (unp->unp_vnode != NULL) {
440 if (unp->unp_flags & UNP_BINDING) {
444 unp->unp_flags |= UNP_BINDING;
447 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
448 bcopy(soun->sun_path, buf, namelen);
453 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
454 UIO_SYSSPACE, buf, td);
455 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
460 vfslocked = NDHASGIANT(&nd);
461 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
462 NDFREE(&nd, NDF_ONLY_PNBUF);
472 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
475 VFS_UNLOCK_GIANT(vfslocked);
479 vattr.va_type = VSOCK;
480 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
482 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
486 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
487 NDFREE(&nd, NDF_ONLY_PNBUF);
490 vn_finished_write(mp);
494 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
495 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
499 vp->v_socket = unp->unp_socket;
501 unp->unp_addr = soun;
502 unp->unp_flags &= ~UNP_BINDING;
506 vn_finished_write(mp);
507 VFS_UNLOCK_GIANT(vfslocked);
512 VFS_UNLOCK_GIANT(vfslocked);
514 unp->unp_flags &= ~UNP_BINDING;
521 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
525 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
527 error = unp_connect(so, nam, td);
533 uipc_close(struct socket *so)
535 struct unpcb *unp, *unp2;
538 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
542 unp2 = unp->unp_conn;
545 unp_disconnect(unp, unp2);
546 UNP_PCB_UNLOCK(unp2);
553 uipc_connect2(struct socket *so1, struct socket *so2)
555 struct unpcb *unp, *unp2;
560 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
563 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
565 error = unp_connect2(so1, so2, PRU_CONNECT2);
566 UNP_PCB_UNLOCK(unp2);
573 uipc_detach(struct socket *so)
575 struct unpcb *unp, *unp2;
576 struct sockaddr_un *saved_unp_addr;
578 int freeunp, local_unp_rights;
581 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
586 LIST_REMOVE(unp, unp_link);
587 unp->unp_gencnt = ++unp_gencnt;
592 * XXXRW: Should assert vp->v_socket == so.
594 if ((vp = unp->unp_vnode) != NULL) {
595 unp->unp_vnode->v_socket = NULL;
596 unp->unp_vnode = NULL;
598 unp2 = unp->unp_conn;
601 unp_disconnect(unp, unp2);
602 UNP_PCB_UNLOCK(unp2);
606 * We hold the linkage lock exclusively, so it's OK to acquire
607 * multiple pcb locks at a time.
609 while (!LIST_EMPTY(&unp->unp_refs)) {
610 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
613 unp_drop(ref, ECONNRESET);
616 local_unp_rights = unp_rights;
618 unp->unp_socket->so_pcb = NULL;
619 saved_unp_addr = unp->unp_addr;
620 unp->unp_addr = NULL;
622 freeunp = (unp->unp_refcount == 0);
623 if (saved_unp_addr != NULL)
624 free(saved_unp_addr, M_SONAME);
626 UNP_PCB_LOCK_DESTROY(unp);
627 uma_zfree(unp_zone, unp);
633 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
635 VFS_UNLOCK_GIANT(vfslocked);
637 if (local_unp_rights)
638 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
642 uipc_disconnect(struct socket *so)
644 struct unpcb *unp, *unp2;
647 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
651 unp2 = unp->unp_conn;
654 unp_disconnect(unp, unp2);
655 UNP_PCB_UNLOCK(unp2);
663 uipc_listen(struct socket *so, int backlog, struct thread *td)
669 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
672 if (unp->unp_vnode == NULL) {
678 error = solisten_proto_check(so);
680 cru2x(td->td_ucred, &unp->unp_peercred);
681 unp->unp_flags |= UNP_HAVEPCCACHED;
682 solisten_proto(so, backlog);
690 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
692 struct unpcb *unp, *unp2;
693 const struct sockaddr *sa;
696 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
698 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
701 * XXX: It seems that this test always fails even when connection is
702 * established. So, this else clause is added as workaround to
703 * return PF_LOCAL sockaddr.
705 unp2 = unp->unp_conn;
708 if (unp2->unp_addr != NULL)
709 sa = (struct sockaddr *) unp2->unp_addr;
712 bcopy(sa, *nam, sa->sa_len);
713 UNP_PCB_UNLOCK(unp2);
716 bcopy(sa, *nam, sa->sa_len);
723 uipc_rcvd(struct socket *so, int flags)
725 struct unpcb *unp, *unp2;
731 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
733 if (so->so_type == SOCK_DGRAM)
734 panic("uipc_rcvd DGRAM?");
736 if (so->so_type != SOCK_STREAM)
737 panic("uipc_rcvd unknown socktype");
740 * Adjust backpressure on sender and wakeup any waiting to write.
742 * The unp lock is acquired to maintain the validity of the unp_conn
743 * pointer; no lock on unp2 is required as unp2->unp_socket will be
744 * static as long as we don't permit unp2 to disconnect from unp,
745 * which is prevented by the lock on unp. We cache values from
746 * so_rcv to avoid holding the so_rcv lock over the entire
747 * transaction on the remote so_snd.
749 SOCKBUF_LOCK(&so->so_rcv);
750 mbcnt = so->so_rcv.sb_mbcnt;
751 sbcc = so->so_rcv.sb_cc;
752 SOCKBUF_UNLOCK(&so->so_rcv);
754 unp2 = unp->unp_conn;
759 so2 = unp2->unp_socket;
760 SOCKBUF_LOCK(&so2->so_snd);
761 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
762 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
763 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
764 newhiwat, RLIM_INFINITY);
765 sowwakeup_locked(so2);
766 unp->unp_mbcnt = mbcnt;
773 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
774 struct mbuf *control, struct thread *td)
776 struct unpcb *unp, *unp2;
778 u_int mbcnt_delta, sbcc;
783 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
785 if (flags & PRUS_OOB) {
789 if (control != NULL && (error = unp_internalize(&control, td)))
791 if ((nam != NULL) || (flags & PRUS_EOF))
795 switch (so->so_type) {
798 const struct sockaddr *from;
800 unp2 = unp->unp_conn;
802 UNP_LINK_WLOCK_ASSERT();
807 error = unp_connect(so, nam, td);
810 unp2 = unp->unp_conn;
814 * Because connect() and send() are non-atomic in a sendto()
815 * with a target address, it's possible that the socket will
816 * have disconnected before the send() can run. In that case
817 * return the slightly counter-intuitive but otherwise
818 * correct error that the socket is not connected.
825 if (unp2->unp_flags & UNP_WANTCRED)
826 control = unp_addsockcred(td, control);
828 if (unp->unp_addr != NULL)
829 from = (struct sockaddr *)unp->unp_addr;
832 so2 = unp2->unp_socket;
833 SOCKBUF_LOCK(&so2->so_rcv);
834 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
835 sorwakeup_locked(so2);
839 SOCKBUF_UNLOCK(&so2->so_rcv);
843 UNP_LINK_WLOCK_ASSERT();
845 unp_disconnect(unp, unp2);
846 UNP_PCB_UNLOCK(unp2);
853 if ((so->so_state & SS_ISCONNECTED) == 0) {
855 UNP_LINK_WLOCK_ASSERT();
856 error = unp_connect(so, nam, td);
866 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
872 * Because connect() and send() are non-atomic in a sendto()
873 * with a target address, it's possible that the socket will
874 * have disconnected before the send() can run. In that case
875 * return the slightly counter-intuitive but otherwise
876 * correct error that the socket is not connected.
878 * Locking here must be done carefully: the linkage lock
879 * prevents interconnections between unpcbs from changing, so
880 * we can traverse from unp to unp2 without acquiring unp's
881 * lock. Socket buffer locks follow unpcb locks, so we can
882 * acquire both remote and lock socket buffer locks.
884 unp2 = unp->unp_conn;
889 so2 = unp2->unp_socket;
891 SOCKBUF_LOCK(&so2->so_rcv);
892 if (unp2->unp_flags & UNP_WANTCRED) {
894 * Credentials are passed only once on SOCK_STREAM.
896 unp2->unp_flags &= ~UNP_WANTCRED;
897 control = unp_addsockcred(td, control);
900 * Send to paired receive port, and then reduce send buffer
901 * hiwater marks to maintain backpressure. Wake up readers.
903 if (control != NULL) {
904 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
907 sbappend_locked(&so2->so_rcv, m);
908 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
909 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
910 sbcc = so2->so_rcv.sb_cc;
911 sorwakeup_locked(so2);
913 SOCKBUF_LOCK(&so->so_snd);
914 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
915 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
916 newhiwat, RLIM_INFINITY);
917 so->so_snd.sb_mbmax -= mbcnt_delta;
918 SOCKBUF_UNLOCK(&so->so_snd);
920 UNP_PCB_UNLOCK(unp2);
925 panic("uipc_send unknown socktype");
929 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
931 if (flags & PRUS_EOF) {
938 if ((nam != NULL) || (flags & PRUS_EOF))
943 if (control != NULL && error != 0)
944 unp_dispose(control);
955 uipc_sense(struct socket *so, struct stat *sb)
957 struct unpcb *unp, *unp2;
961 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
963 sb->st_blksize = so->so_snd.sb_hiwat;
966 unp2 = unp->unp_conn;
967 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
968 so2 = unp2->unp_socket;
969 sb->st_blksize += so2->so_rcv.sb_cc;
972 if (unp->unp_ino == 0)
973 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
974 sb->st_ino = unp->unp_ino;
981 uipc_shutdown(struct socket *so)
986 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
998 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
1001 const struct sockaddr *sa;
1003 unp = sotounpcb(so);
1004 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
1006 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1008 if (unp->unp_addr != NULL)
1009 sa = (struct sockaddr *) unp->unp_addr;
1012 bcopy(sa, *nam, sa->sa_len);
1013 UNP_PCB_UNLOCK(unp);
1017 static struct pr_usrreqs uipc_usrreqs_dgram = {
1018 .pru_abort = uipc_abort,
1019 .pru_accept = uipc_accept,
1020 .pru_attach = uipc_attach,
1021 .pru_bind = uipc_bind,
1022 .pru_connect = uipc_connect,
1023 .pru_connect2 = uipc_connect2,
1024 .pru_detach = uipc_detach,
1025 .pru_disconnect = uipc_disconnect,
1026 .pru_listen = uipc_listen,
1027 .pru_peeraddr = uipc_peeraddr,
1028 .pru_rcvd = uipc_rcvd,
1029 .pru_send = uipc_send,
1030 .pru_sense = uipc_sense,
1031 .pru_shutdown = uipc_shutdown,
1032 .pru_sockaddr = uipc_sockaddr,
1033 .pru_soreceive = soreceive_dgram,
1034 .pru_close = uipc_close,
1037 static struct pr_usrreqs uipc_usrreqs_stream = {
1038 .pru_abort = uipc_abort,
1039 .pru_accept = uipc_accept,
1040 .pru_attach = uipc_attach,
1041 .pru_bind = uipc_bind,
1042 .pru_connect = uipc_connect,
1043 .pru_connect2 = uipc_connect2,
1044 .pru_detach = uipc_detach,
1045 .pru_disconnect = uipc_disconnect,
1046 .pru_listen = uipc_listen,
1047 .pru_peeraddr = uipc_peeraddr,
1048 .pru_rcvd = uipc_rcvd,
1049 .pru_send = uipc_send,
1050 .pru_sense = uipc_sense,
1051 .pru_shutdown = uipc_shutdown,
1052 .pru_sockaddr = uipc_sockaddr,
1053 .pru_soreceive = soreceive_generic,
1054 .pru_close = uipc_close,
1058 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1064 if (sopt->sopt_level != 0)
1067 unp = sotounpcb(so);
1068 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1070 switch (sopt->sopt_dir) {
1072 switch (sopt->sopt_name) {
1073 case LOCAL_PEERCRED:
1075 if (unp->unp_flags & UNP_HAVEPC)
1076 xu = unp->unp_peercred;
1078 if (so->so_type == SOCK_STREAM)
1083 UNP_PCB_UNLOCK(unp);
1085 error = sooptcopyout(sopt, &xu, sizeof(xu));
1089 /* Unlocked read. */
1090 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1091 error = sooptcopyout(sopt, &optval, sizeof(optval));
1094 case LOCAL_CONNWAIT:
1095 /* Unlocked read. */
1096 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1097 error = sooptcopyout(sopt, &optval, sizeof(optval));
1107 switch (sopt->sopt_name) {
1109 case LOCAL_CONNWAIT:
1110 error = sooptcopyin(sopt, &optval, sizeof(optval),
1115 #define OPTSET(bit) do { \
1116 UNP_PCB_LOCK(unp); \
1118 unp->unp_flags |= bit; \
1120 unp->unp_flags &= ~bit; \
1121 UNP_PCB_UNLOCK(unp); \
1124 switch (sopt->sopt_name) {
1126 OPTSET(UNP_WANTCRED);
1129 case LOCAL_CONNWAIT:
1130 OPTSET(UNP_CONNWAIT);
1139 error = ENOPROTOOPT;
1152 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1154 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1156 struct socket *so2, *so3;
1157 struct unpcb *unp, *unp2, *unp3;
1158 int error, len, vfslocked;
1159 struct nameidata nd;
1160 char buf[SOCK_MAXADDRLEN];
1161 struct sockaddr *sa;
1163 UNP_LINK_WLOCK_ASSERT();
1165 unp = sotounpcb(so);
1166 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1168 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1171 bcopy(soun->sun_path, buf, len);
1175 if (unp->unp_flags & UNP_CONNECTING) {
1176 UNP_PCB_UNLOCK(unp);
1180 unp->unp_flags |= UNP_CONNECTING;
1181 UNP_PCB_UNLOCK(unp);
1183 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1184 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1191 ASSERT_VOP_LOCKED(vp, "unp_connect");
1192 vfslocked = NDHASGIANT(&nd);
1193 NDFREE(&nd, NDF_ONLY_PNBUF);
1197 if (vp->v_type != VSOCK) {
1202 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1206 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1209 VFS_UNLOCK_GIANT(vfslocked);
1211 unp = sotounpcb(so);
1212 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1215 * Lock linkage lock for two reasons: make sure v_socket is stable,
1216 * and to protect simultaneous locking of multiple pcbs.
1221 error = ECONNREFUSED;
1224 if (so->so_type != so2->so_type) {
1228 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1229 if (so2->so_options & SO_ACCEPTCONN) {
1230 so3 = sonewconn(so2, 0);
1234 error = ECONNREFUSED;
1237 unp = sotounpcb(so);
1238 unp2 = sotounpcb(so2);
1239 unp3 = sotounpcb(so3);
1243 if (unp2->unp_addr != NULL) {
1244 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1245 unp3->unp_addr = (struct sockaddr_un *) sa;
1250 * The connecter's (client's) credentials are copied from its
1251 * process structure at the time of connect() (which is now).
1253 cru2x(td->td_ucred, &unp3->unp_peercred);
1254 unp3->unp_flags |= UNP_HAVEPC;
1257 * The receiver's (server's) credentials are copied from the
1258 * unp_peercred member of socket on which the former called
1259 * listen(); uipc_listen() cached that process's credentials
1260 * at that time so we can use them now.
1262 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1263 ("unp_connect: listener without cached peercred"));
1264 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1265 sizeof(unp->unp_peercred));
1266 unp->unp_flags |= UNP_HAVEPC;
1267 if (unp2->unp_flags & UNP_WANTCRED)
1268 unp3->unp_flags |= UNP_WANTCRED;
1269 UNP_PCB_UNLOCK(unp3);
1270 UNP_PCB_UNLOCK(unp2);
1271 UNP_PCB_UNLOCK(unp);
1273 mac_socketpeer_set_from_socket(so, so3);
1274 mac_socketpeer_set_from_socket(so3, so);
1279 unp = sotounpcb(so);
1280 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1281 unp2 = sotounpcb(so2);
1282 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1285 error = unp_connect2(so, so2, PRU_CONNECT);
1286 UNP_PCB_UNLOCK(unp2);
1287 UNP_PCB_UNLOCK(unp);
1292 * Giant has been previously acquired. This means filesystem
1293 * isn't MPSAFE. Do it once again.
1299 VFS_UNLOCK_GIANT(vfslocked);
1303 unp->unp_flags &= ~UNP_CONNECTING;
1304 UNP_PCB_UNLOCK(unp);
1309 unp_connect2(struct socket *so, struct socket *so2, int req)
1314 unp = sotounpcb(so);
1315 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1316 unp2 = sotounpcb(so2);
1317 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1319 UNP_LINK_WLOCK_ASSERT();
1320 UNP_PCB_LOCK_ASSERT(unp);
1321 UNP_PCB_LOCK_ASSERT(unp2);
1323 if (so2->so_type != so->so_type)
1324 return (EPROTOTYPE);
1325 unp->unp_conn = unp2;
1327 switch (so->so_type) {
1329 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1334 unp2->unp_conn = unp;
1335 if (req == PRU_CONNECT &&
1336 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1344 panic("unp_connect2");
1350 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1354 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1356 UNP_LINK_WLOCK_ASSERT();
1357 UNP_PCB_LOCK_ASSERT(unp);
1358 UNP_PCB_LOCK_ASSERT(unp2);
1360 unp->unp_conn = NULL;
1361 switch (unp->unp_socket->so_type) {
1363 LIST_REMOVE(unp, unp_reflink);
1364 so = unp->unp_socket;
1366 so->so_state &= ~SS_ISCONNECTED;
1371 soisdisconnected(unp->unp_socket);
1372 unp2->unp_conn = NULL;
1373 soisdisconnected(unp2->unp_socket);
1379 * unp_pcblist() walks the global list of struct unpcb's to generate a
1380 * pointer list, bumping the refcount on each unpcb. It then copies them out
1381 * sequentially, validating the generation number on each to see if it has
1382 * been detached. All of this is necessary because copyout() may sleep on
1386 unp_pcblist(SYSCTL_HANDLER_ARGS)
1390 struct unpcb *unp, **unp_list;
1392 struct xunpgen *xug;
1393 struct unp_head *head;
1396 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1399 * The process of preparing the PCB list is too time-consuming and
1400 * resource-intensive to repeat twice on every request.
1402 if (req->oldptr == NULL) {
1404 req->oldidx = 2 * (sizeof *xug)
1405 + (n + n/8) * sizeof(struct xunpcb);
1409 if (req->newptr != NULL)
1413 * OK, now we're committed to doing something.
1415 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1417 gencnt = unp_gencnt;
1421 xug->xug_len = sizeof *xug;
1423 xug->xug_gen = gencnt;
1424 xug->xug_sogen = so_gencnt;
1425 error = SYSCTL_OUT(req, xug, sizeof *xug);
1431 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1434 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1435 unp = LIST_NEXT(unp, unp_link)) {
1437 if (unp->unp_gencnt <= gencnt) {
1438 if (cr_cansee(req->td->td_ucred,
1439 unp->unp_socket->so_cred)) {
1440 UNP_PCB_UNLOCK(unp);
1443 unp_list[i++] = unp;
1444 unp->unp_refcount++;
1446 UNP_PCB_UNLOCK(unp);
1449 n = i; /* In case we lost some during malloc. */
1452 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1453 for (i = 0; i < n; i++) {
1456 unp->unp_refcount--;
1457 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1458 xu->xu_len = sizeof *xu;
1461 * XXX - need more locking here to protect against
1462 * connect/disconnect races for SMP.
1464 if (unp->unp_addr != NULL)
1465 bcopy(unp->unp_addr, &xu->xu_addr,
1466 unp->unp_addr->sun_len);
1467 if (unp->unp_conn != NULL &&
1468 unp->unp_conn->unp_addr != NULL)
1469 bcopy(unp->unp_conn->unp_addr,
1471 unp->unp_conn->unp_addr->sun_len);
1472 bcopy(unp, &xu->xu_unp, sizeof *unp);
1473 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1474 UNP_PCB_UNLOCK(unp);
1475 error = SYSCTL_OUT(req, xu, sizeof *xu);
1477 freeunp = (unp->unp_refcount == 0);
1478 UNP_PCB_UNLOCK(unp);
1480 UNP_PCB_LOCK_DESTROY(unp);
1481 uma_zfree(unp_zone, unp);
1488 * Give the user an updated idea of our state. If the
1489 * generation differs from what we told her before, she knows
1490 * that something happened while we were processing this
1491 * request, and it might be necessary to retry.
1493 xug->xug_gen = unp_gencnt;
1494 xug->xug_sogen = so_gencnt;
1495 xug->xug_count = unp_count;
1496 error = SYSCTL_OUT(req, xug, sizeof *xug);
1498 free(unp_list, M_TEMP);
1503 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1504 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1505 "List of active local datagram sockets");
1506 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1507 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1508 "List of active local stream sockets");
1511 unp_shutdown(struct unpcb *unp)
1516 UNP_LINK_WLOCK_ASSERT();
1517 UNP_PCB_LOCK_ASSERT(unp);
1519 unp2 = unp->unp_conn;
1520 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1521 so = unp2->unp_socket;
1528 unp_drop(struct unpcb *unp, int errno)
1530 struct socket *so = unp->unp_socket;
1533 UNP_LINK_WLOCK_ASSERT();
1534 UNP_PCB_LOCK_ASSERT(unp);
1536 so->so_error = errno;
1537 unp2 = unp->unp_conn;
1541 unp_disconnect(unp, unp2);
1542 UNP_PCB_UNLOCK(unp2);
1546 unp_freerights(struct file **rp, int fdcount)
1551 for (i = 0; i < fdcount; i++) {
1559 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1561 struct thread *td = curthread; /* XXX */
1562 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1568 socklen_t clen = control->m_len, datalen;
1573 UNP_LINK_UNLOCK_ASSERT();
1576 if (controlp != NULL) /* controlp == NULL => free control messages */
1578 while (cm != NULL) {
1579 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1583 data = CMSG_DATA(cm);
1584 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1585 if (cm->cmsg_level == SOL_SOCKET
1586 && cm->cmsg_type == SCM_RIGHTS) {
1587 newfds = datalen / sizeof(struct file *);
1590 /* If we're not outputting the descriptors free them. */
1591 if (error || controlp == NULL) {
1592 unp_freerights(rp, newfds);
1595 FILEDESC_XLOCK(td->td_proc->p_fd);
1596 /* if the new FD's will not fit free them. */
1597 if (!fdavail(td, newfds)) {
1598 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1600 unp_freerights(rp, newfds);
1605 * Now change each pointer to an fd in the global
1606 * table to an integer that is the index to the local
1607 * fd table entry that we set up to point to the
1608 * global one we are transferring.
1610 newlen = newfds * sizeof(int);
1611 *controlp = sbcreatecontrol(NULL, newlen,
1612 SCM_RIGHTS, SOL_SOCKET);
1613 if (*controlp == NULL) {
1614 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1616 unp_freerights(rp, newfds);
1621 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1622 for (i = 0; i < newfds; i++) {
1623 if (fdalloc(td, 0, &f))
1624 panic("unp_externalize fdalloc failed");
1626 td->td_proc->p_fd->fd_ofiles[f] = fp;
1627 unp_externalize_fp(fp);
1630 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1632 /* We can just copy anything else across. */
1633 if (error || controlp == NULL)
1635 *controlp = sbcreatecontrol(NULL, datalen,
1636 cm->cmsg_type, cm->cmsg_level);
1637 if (*controlp == NULL) {
1642 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1645 controlp = &(*controlp)->m_next;
1648 if (CMSG_SPACE(datalen) < clen) {
1649 clen -= CMSG_SPACE(datalen);
1650 cm = (struct cmsghdr *)
1651 ((caddr_t)cm + CMSG_SPACE(datalen));
1663 unp_zone_change(void *tag)
1666 uma_zone_set_max(unp_zone, maxsockets);
1674 if (!IS_DEFAULT_VNET(curvnet))
1677 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1678 NULL, NULL, UMA_ALIGN_PTR, 0);
1679 if (unp_zone == NULL)
1681 uma_zone_set_max(unp_zone, maxsockets);
1682 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1683 NULL, EVENTHANDLER_PRI_ANY);
1684 LIST_INIT(&unp_dhead);
1685 LIST_INIT(&unp_shead);
1686 SLIST_INIT(&unp_defers);
1687 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1688 TASK_INIT(&unp_defer_task, 0, unp_process_defers, NULL);
1689 UNP_LINK_LOCK_INIT();
1690 UNP_LIST_LOCK_INIT();
1691 UNP_DEFERRED_LOCK_INIT();
1695 unp_internalize(struct mbuf **controlp, struct thread *td)
1697 struct mbuf *control = *controlp;
1698 struct proc *p = td->td_proc;
1699 struct filedesc *fdescp = p->p_fd;
1700 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1701 struct cmsgcred *cmcred;
1707 socklen_t clen = control->m_len, datalen;
1711 UNP_LINK_UNLOCK_ASSERT();
1715 while (cm != NULL) {
1716 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1717 || cm->cmsg_len > clen) {
1721 data = CMSG_DATA(cm);
1722 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1724 switch (cm->cmsg_type) {
1726 * Fill in credential information.
1729 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1730 SCM_CREDS, SOL_SOCKET);
1731 if (*controlp == NULL) {
1735 cmcred = (struct cmsgcred *)
1736 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1737 cmcred->cmcred_pid = p->p_pid;
1738 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1739 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1740 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1741 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1743 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1744 cmcred->cmcred_groups[i] =
1745 td->td_ucred->cr_groups[i];
1749 oldfds = datalen / sizeof (int);
1751 * Check that all the FDs passed in refer to legal
1752 * files. If not, reject the entire operation.
1755 FILEDESC_SLOCK(fdescp);
1756 for (i = 0; i < oldfds; i++) {
1758 if ((unsigned)fd >= fdescp->fd_nfiles ||
1759 fdescp->fd_ofiles[fd] == NULL) {
1760 FILEDESC_SUNLOCK(fdescp);
1764 fp = fdescp->fd_ofiles[fd];
1765 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1766 FILEDESC_SUNLOCK(fdescp);
1774 * Now replace the integer FDs with pointers to the
1775 * associated global file table entry..
1777 newlen = oldfds * sizeof(struct file *);
1778 *controlp = sbcreatecontrol(NULL, newlen,
1779 SCM_RIGHTS, SOL_SOCKET);
1780 if (*controlp == NULL) {
1781 FILEDESC_SUNLOCK(fdescp);
1786 rp = (struct file **)
1787 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1788 for (i = 0; i < oldfds; i++) {
1789 fp = fdescp->fd_ofiles[*fdp++];
1791 unp_internalize_fp(fp);
1793 FILEDESC_SUNLOCK(fdescp);
1797 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1798 SCM_TIMESTAMP, SOL_SOCKET);
1799 if (*controlp == NULL) {
1803 tv = (struct timeval *)
1804 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1813 controlp = &(*controlp)->m_next;
1814 if (CMSG_SPACE(datalen) < clen) {
1815 clen -= CMSG_SPACE(datalen);
1816 cm = (struct cmsghdr *)
1817 ((caddr_t)cm + CMSG_SPACE(datalen));
1829 static struct mbuf *
1830 unp_addsockcred(struct thread *td, struct mbuf *control)
1832 struct mbuf *m, *n, *n_prev;
1833 struct sockcred *sc;
1834 const struct cmsghdr *cm;
1838 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1839 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1843 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1844 sc->sc_uid = td->td_ucred->cr_ruid;
1845 sc->sc_euid = td->td_ucred->cr_uid;
1846 sc->sc_gid = td->td_ucred->cr_rgid;
1847 sc->sc_egid = td->td_ucred->cr_gid;
1848 sc->sc_ngroups = ngroups;
1849 for (i = 0; i < sc->sc_ngroups; i++)
1850 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1853 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1854 * created SCM_CREDS control message (struct sockcred) has another
1857 if (control != NULL)
1858 for (n = control, n_prev = NULL; n != NULL;) {
1859 cm = mtod(n, struct cmsghdr *);
1860 if (cm->cmsg_level == SOL_SOCKET &&
1861 cm->cmsg_type == SCM_CREDS) {
1863 control = n->m_next;
1865 n_prev->m_next = n->m_next;
1873 /* Prepend it to the head. */
1874 m->m_next = control;
1878 static struct unpcb *
1879 fptounp(struct file *fp)
1883 if (fp->f_type != DTYPE_SOCKET)
1885 if ((so = fp->f_data) == NULL)
1887 if (so->so_proto->pr_domain != &localdomain)
1889 return sotounpcb(so);
1893 unp_discard(struct file *fp)
1895 struct unp_defer *dr;
1897 if (unp_externalize_fp(fp)) {
1898 dr = malloc(sizeof(*dr), M_TEMP, M_WAITOK);
1900 UNP_DEFERRED_LOCK();
1901 SLIST_INSERT_HEAD(&unp_defers, dr, ud_link);
1902 UNP_DEFERRED_UNLOCK();
1903 atomic_add_int(&unp_defers_count, 1);
1904 taskqueue_enqueue(taskqueue_thread, &unp_defer_task);
1906 (void) closef(fp, (struct thread *)NULL);
1910 unp_process_defers(void *arg __unused, int pending)
1912 struct unp_defer *dr;
1913 SLIST_HEAD(, unp_defer) drl;
1918 UNP_DEFERRED_LOCK();
1919 if (SLIST_FIRST(&unp_defers) == NULL) {
1920 UNP_DEFERRED_UNLOCK();
1923 SLIST_SWAP(&unp_defers, &drl, unp_defer);
1924 UNP_DEFERRED_UNLOCK();
1926 while ((dr = SLIST_FIRST(&drl)) != NULL) {
1927 SLIST_REMOVE_HEAD(&drl, ud_link);
1928 closef(dr->ud_fp, NULL);
1932 atomic_add_int(&unp_defers_count, -count);
1937 unp_internalize_fp(struct file *fp)
1942 if ((unp = fptounp(fp)) != NULL) {
1944 unp->unp_msgcount++;
1952 unp_externalize_fp(struct file *fp)
1958 if ((unp = fptounp(fp)) != NULL) {
1959 unp->unp_msgcount--;
1969 * unp_defer indicates whether additional work has been defered for a future
1970 * pass through unp_gc(). It is thread local and does not require explicit
1973 static int unp_marked;
1974 static int unp_unreachable;
1977 unp_accessable(struct file *fp)
1981 if ((unp = fptounp(fp)) == NULL)
1983 if (unp->unp_gcflag & UNPGC_REF)
1985 unp->unp_gcflag &= ~UNPGC_DEAD;
1986 unp->unp_gcflag |= UNPGC_REF;
1991 unp_gc_process(struct unpcb *unp)
1997 /* Already processed. */
1998 if (unp->unp_gcflag & UNPGC_SCANNED)
2003 * Check for a socket potentially in a cycle. It must be in a
2004 * queue as indicated by msgcount, and this must equal the file
2005 * reference count. Note that when msgcount is 0 the file is NULL.
2007 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
2008 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
2009 unp->unp_gcflag |= UNPGC_DEAD;
2015 * Mark all sockets we reference with RIGHTS.
2017 so = unp->unp_socket;
2018 SOCKBUF_LOCK(&so->so_rcv);
2019 unp_scan(so->so_rcv.sb_mb, unp_accessable);
2020 SOCKBUF_UNLOCK(&so->so_rcv);
2023 * Mark all sockets in our accept queue.
2026 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
2027 SOCKBUF_LOCK(&soa->so_rcv);
2028 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
2029 SOCKBUF_UNLOCK(&soa->so_rcv);
2032 unp->unp_gcflag |= UNPGC_SCANNED;
2035 static int unp_recycled;
2036 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
2037 "Number of unreachable sockets claimed by the garbage collector.");
2039 static int unp_taskcount;
2040 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
2041 "Number of times the garbage collector has run.");
2044 unp_gc(__unused void *arg, int pending)
2046 struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
2047 struct unp_head **head;
2048 struct file **unref;
2055 * First clear all gc flags from previous runs.
2057 for (head = heads; *head != NULL; head++)
2058 LIST_FOREACH(unp, *head, unp_link)
2059 unp->unp_gcflag = 0;
2062 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
2063 * is reachable all of the sockets it references are reachable.
2064 * Stop the scan once we do a complete loop without discovering
2065 * a new reachable socket.
2068 unp_unreachable = 0;
2070 for (head = heads; *head != NULL; head++)
2071 LIST_FOREACH(unp, *head, unp_link)
2072 unp_gc_process(unp);
2073 } while (unp_marked);
2075 if (unp_unreachable == 0)
2079 * Allocate space for a local list of dead unpcbs.
2081 unref = malloc(unp_unreachable * sizeof(struct file *),
2085 * Iterate looking for sockets which have been specifically marked
2086 * as as unreachable and store them locally.
2089 for (i = 0, head = heads; *head != NULL; head++)
2090 LIST_FOREACH(unp, *head, unp_link)
2091 if (unp->unp_gcflag & UNPGC_DEAD) {
2092 unref[i++] = unp->unp_file;
2093 fhold(unp->unp_file);
2094 KASSERT(unp->unp_file != NULL,
2095 ("unp_gc: Invalid unpcb."));
2096 KASSERT(i <= unp_unreachable,
2097 ("unp_gc: incorrect unreachable count."));
2102 * Now flush all sockets, free'ing rights. This will free the
2103 * struct files associated with these sockets but leave each socket
2104 * with one remaining ref.
2106 for (i = 0; i < unp_unreachable; i++)
2107 sorflush(unref[i]->f_data);
2110 * And finally release the sockets so they can be reclaimed.
2112 for (i = 0; i < unp_unreachable; i++)
2113 fdrop(unref[i], NULL);
2114 unp_recycled += unp_unreachable;
2115 free(unref, M_TEMP);
2119 unp_dispose(struct mbuf *m)
2123 unp_scan(m, unp_discard);
2127 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2134 socklen_t clen, datalen;
2137 while (m0 != NULL) {
2138 for (m = m0; m; m = m->m_next) {
2139 if (m->m_type != MT_CONTROL)
2142 cm = mtod(m, struct cmsghdr *);
2145 while (cm != NULL) {
2146 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2149 data = CMSG_DATA(cm);
2150 datalen = (caddr_t)cm + cm->cmsg_len
2153 if (cm->cmsg_level == SOL_SOCKET &&
2154 cm->cmsg_type == SCM_RIGHTS) {
2155 qfds = datalen / sizeof (struct file *);
2157 for (i = 0; i < qfds; i++)
2161 if (CMSG_SPACE(datalen) < clen) {
2162 clen -= CMSG_SPACE(datalen);
2163 cm = (struct cmsghdr *)
2164 ((caddr_t)cm + CMSG_SPACE(datalen));
2177 db_print_indent(int indent)
2181 for (i = 0; i < indent; i++)
2186 db_print_unpflags(int unp_flags)
2191 if (unp_flags & UNP_HAVEPC) {
2192 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2195 if (unp_flags & UNP_HAVEPCCACHED) {
2196 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2199 if (unp_flags & UNP_WANTCRED) {
2200 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2203 if (unp_flags & UNP_CONNWAIT) {
2204 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2207 if (unp_flags & UNP_CONNECTING) {
2208 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2211 if (unp_flags & UNP_BINDING) {
2212 db_printf("%sUNP_BINDING", comma ? ", " : "");
2218 db_print_xucred(int indent, struct xucred *xu)
2222 db_print_indent(indent);
2223 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2224 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2225 db_print_indent(indent);
2226 db_printf("cr_groups: ");
2228 for (i = 0; i < xu->cr_ngroups; i++) {
2229 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2236 db_print_unprefs(int indent, struct unp_head *uh)
2242 LIST_FOREACH(unp, uh, unp_reflink) {
2243 if (counter % 4 == 0)
2244 db_print_indent(indent);
2245 db_printf("%p ", unp);
2246 if (counter % 4 == 3)
2250 if (counter != 0 && counter % 4 != 0)
2254 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2259 db_printf("usage: show unpcb <addr>\n");
2262 unp = (struct unpcb *)addr;
2264 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2267 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2270 db_printf("unp_refs:\n");
2271 db_print_unprefs(2, &unp->unp_refs);
2273 /* XXXRW: Would be nice to print the full address, if any. */
2274 db_printf("unp_addr: %p\n", unp->unp_addr);
2276 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2277 unp->unp_cc, unp->unp_mbcnt,
2278 (unsigned long long)unp->unp_gencnt);
2280 db_printf("unp_flags: %x (", unp->unp_flags);
2281 db_print_unpflags(unp->unp_flags);
2284 db_printf("unp_peercred:\n");
2285 db_print_xucred(2, &unp->unp_peercred);
2287 db_printf("unp_refcount: %u\n", unp->unp_refcount);