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/resourcevar.h>
79 #include <sys/rwlock.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/signalvar.h>
85 #include <sys/sysctl.h>
86 #include <sys/systm.h>
87 #include <sys/taskqueue.h>
89 #include <sys/unpcb.h>
90 #include <sys/vnode.h>
98 #include <security/mac/mac_framework.h>
104 * (l) Locked using list lock
105 * (g) Locked using linkage lock
108 static uma_zone_t unp_zone;
109 static unp_gen_t unp_gencnt; /* (l) */
110 static u_int unp_count; /* (l) Count of local sockets. */
111 static ino_t unp_ino; /* Prototype for fake inode numbers. */
112 static int unp_rights; /* (g) File descriptors in flight. */
113 static struct unp_head unp_shead; /* (l) List of stream sockets. */
114 static struct unp_head unp_dhead; /* (l) List of datagram sockets. */
116 static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
119 * Garbage collection of cyclic file descriptor/socket references occurs
120 * asynchronously in a taskqueue context in order to avoid recursion and
121 * reentrance in the UNIX domain socket, file descriptor, and socket layer
122 * code. See unp_gc() for a full description.
124 static struct task unp_gc_task;
127 * Both send and receive buffers are allocated PIPSIZ bytes of buffering for
128 * stream sockets, although the total for sender and receiver is actually
131 * Datagram sockets really use the sendspace as the maximum datagram size,
132 * and don't really want to reserve the sendspace. Their recvspace should be
133 * large enough for at least one max-size datagram plus address.
138 static u_long unpst_sendspace = PIPSIZ;
139 static u_long unpst_recvspace = PIPSIZ;
140 static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
141 static u_long unpdg_recvspace = 4*1024;
143 SYSCTL_NODE(_net, PF_LOCAL, local, CTLFLAG_RW, 0, "Local domain");
144 SYSCTL_NODE(_net_local, SOCK_STREAM, stream, CTLFLAG_RW, 0, "SOCK_STREAM");
145 SYSCTL_NODE(_net_local, SOCK_DGRAM, dgram, CTLFLAG_RW, 0, "SOCK_DGRAM");
147 SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
148 &unpst_sendspace, 0, "Default stream send space.");
149 SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
150 &unpst_recvspace, 0, "Default stream receive space.");
151 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
152 &unpdg_sendspace, 0, "Default datagram send space.");
153 SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
154 &unpdg_recvspace, 0, "Default datagram receive space.");
155 SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0,
156 "File descriptors in flight.");
159 * Locking and synchronization:
161 * Three types of locks exit in the local domain socket implementation: a
162 * global list mutex, a global linkage rwlock, and per-unpcb mutexes. Of the
163 * global locks, the list lock protects the socket count, global generation
164 * number, and stream/datagram global lists. The linkage lock protects the
165 * interconnection of unpcbs, the v_socket and unp_vnode pointers, and can be
166 * held exclusively over the acquisition of multiple unpcb locks to prevent
169 * UNIX domain sockets each have an unpcb hung off of their so_pcb pointer,
170 * allocated in pru_attach() and freed in pru_detach(). The validity of that
171 * pointer is an invariant, so no lock is required to dereference the so_pcb
172 * pointer if a valid socket reference is held by the caller. In practice,
173 * this is always true during operations performed on a socket. Each unpcb
174 * has a back-pointer to its socket, unp_socket, which will be stable under
175 * the same circumstances.
177 * This pointer may only be safely dereferenced as long as a valid reference
178 * to the unpcb is held. Typically, this reference will be from the socket,
179 * or from another unpcb when the referring unpcb's lock is held (in order
180 * that the reference not be invalidated during use). For example, to follow
181 * unp->unp_conn->unp_socket, you need unlock the lock on unp, not unp_conn,
182 * as unp_socket remains valid as long as the reference to unp_conn is valid.
184 * Fields of unpcbss are locked using a per-unpcb lock, unp_mtx. Individual
185 * atomic reads without the lock may be performed "lockless", but more
186 * complex reads and read-modify-writes require the mutex to be held. No
187 * lock order is defined between unpcb locks -- multiple unpcb locks may be
188 * acquired at the same time only when holding the linkage rwlock
189 * exclusively, which prevents deadlocks.
191 * Blocking with UNIX domain sockets is a tricky issue: unlike most network
192 * protocols, bind() is a non-atomic operation, and connect() requires
193 * potential sleeping in the protocol, due to potentially waiting on local or
194 * distributed file systems. We try to separate "lookup" operations, which
195 * may sleep, and the IPC operations themselves, which typically can occur
196 * with relative atomicity as locks can be held over the entire operation.
198 * Another tricky issue is simultaneous multi-threaded or multi-process
199 * access to a single UNIX domain socket. These are handled by the flags
200 * UNP_CONNECTING and UNP_BINDING, which prevent concurrent connecting or
201 * binding, both of which involve dropping UNIX domain socket locks in order
202 * to perform namei() and other file system operations.
204 static struct rwlock unp_link_rwlock;
205 static struct mtx unp_list_lock;
207 #define UNP_LINK_LOCK_INIT() rw_init(&unp_link_rwlock, \
210 #define UNP_LINK_LOCK_ASSERT() rw_assert(&unp_link_rwlock, \
212 #define UNP_LINK_UNLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
215 #define UNP_LINK_RLOCK() rw_rlock(&unp_link_rwlock)
216 #define UNP_LINK_RUNLOCK() rw_runlock(&unp_link_rwlock)
217 #define UNP_LINK_WLOCK() rw_wlock(&unp_link_rwlock)
218 #define UNP_LINK_WUNLOCK() rw_wunlock(&unp_link_rwlock)
219 #define UNP_LINK_WLOCK_ASSERT() rw_assert(&unp_link_rwlock, \
222 #define UNP_LIST_LOCK_INIT() mtx_init(&unp_list_lock, \
223 "unp_list_lock", NULL, MTX_DEF)
224 #define UNP_LIST_LOCK() mtx_lock(&unp_list_lock)
225 #define UNP_LIST_UNLOCK() mtx_unlock(&unp_list_lock)
227 #define UNP_PCB_LOCK_INIT(unp) mtx_init(&(unp)->unp_mtx, \
228 "unp_mtx", "unp_mtx", \
229 MTX_DUPOK|MTX_DEF|MTX_RECURSE)
230 #define UNP_PCB_LOCK_DESTROY(unp) mtx_destroy(&(unp)->unp_mtx)
231 #define UNP_PCB_LOCK(unp) mtx_lock(&(unp)->unp_mtx)
232 #define UNP_PCB_UNLOCK(unp) mtx_unlock(&(unp)->unp_mtx)
233 #define UNP_PCB_LOCK_ASSERT(unp) mtx_assert(&(unp)->unp_mtx, MA_OWNED)
235 static int uipc_connect2(struct socket *, struct socket *);
236 static int uipc_ctloutput(struct socket *, struct sockopt *);
237 static int unp_connect(struct socket *, struct sockaddr *,
239 static int unp_connect2(struct socket *so, struct socket *so2, int);
240 static void unp_disconnect(struct unpcb *unp, struct unpcb *unp2);
241 static void unp_dispose(struct mbuf *);
242 static void unp_shutdown(struct unpcb *);
243 static void unp_drop(struct unpcb *, int);
244 static void unp_gc(__unused void *, int);
245 static void unp_scan(struct mbuf *, void (*)(struct file *));
246 static void unp_discard(struct file *);
247 static void unp_freerights(struct file **, int);
248 static void unp_init(void);
249 static int unp_internalize(struct mbuf **, struct thread *);
250 static void unp_internalize_fp(struct file *);
251 static int unp_externalize(struct mbuf *, struct mbuf **);
252 static void unp_externalize_fp(struct file *);
253 static struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
256 * Definitions of protocols supported in the LOCAL domain.
258 static struct domain localdomain;
259 static struct pr_usrreqs uipc_usrreqs_dgram, uipc_usrreqs_stream;
260 static struct protosw localsw[] = {
262 .pr_type = SOCK_STREAM,
263 .pr_domain = &localdomain,
264 .pr_flags = PR_CONNREQUIRED|PR_WANTRCVD|PR_RIGHTS,
265 .pr_ctloutput = &uipc_ctloutput,
266 .pr_usrreqs = &uipc_usrreqs_stream
269 .pr_type = SOCK_DGRAM,
270 .pr_domain = &localdomain,
271 .pr_flags = PR_ATOMIC|PR_ADDR|PR_RIGHTS,
272 .pr_usrreqs = &uipc_usrreqs_dgram
276 static struct domain localdomain = {
277 .dom_family = AF_LOCAL,
279 .dom_init = unp_init,
280 .dom_externalize = unp_externalize,
281 .dom_dispose = unp_dispose,
282 .dom_protosw = localsw,
283 .dom_protoswNPROTOSW = &localsw[sizeof(localsw)/sizeof(localsw[0])]
288 uipc_abort(struct socket *so)
290 struct unpcb *unp, *unp2;
293 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
297 unp2 = unp->unp_conn;
300 unp_drop(unp2, ECONNABORTED);
301 UNP_PCB_UNLOCK(unp2);
308 uipc_accept(struct socket *so, struct sockaddr **nam)
310 struct unpcb *unp, *unp2;
311 const struct sockaddr *sa;
314 * Pass back name of connected socket, if it was bound and we are
315 * still connected (our peer may have closed already!).
318 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
320 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
322 unp2 = unp->unp_conn;
323 if (unp2 != NULL && unp2->unp_addr != NULL) {
325 sa = (struct sockaddr *) unp2->unp_addr;
326 bcopy(sa, *nam, sa->sa_len);
327 UNP_PCB_UNLOCK(unp2);
330 bcopy(sa, *nam, sa->sa_len);
337 uipc_attach(struct socket *so, int proto, struct thread *td)
339 u_long sendspace, recvspace;
343 KASSERT(so->so_pcb == NULL, ("uipc_attach: so_pcb != NULL"));
344 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
345 switch (so->so_type) {
347 sendspace = unpst_sendspace;
348 recvspace = unpst_recvspace;
352 sendspace = unpdg_sendspace;
353 recvspace = unpdg_recvspace;
357 panic("uipc_attach");
359 error = soreserve(so, sendspace, recvspace);
363 unp = uma_zalloc(unp_zone, M_NOWAIT | M_ZERO);
366 LIST_INIT(&unp->unp_refs);
367 UNP_PCB_LOCK_INIT(unp);
368 unp->unp_socket = so;
370 unp->unp_refcount = 1;
373 unp->unp_gencnt = ++unp_gencnt;
375 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead : &unp_shead,
383 uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
385 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
387 int error, namelen, vfslocked;
395 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
397 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
402 * We don't allow simultaneous bind() calls on a single UNIX domain
403 * socket, so flag in-progress operations, and return an error if an
404 * operation is already in progress.
406 * Historically, we have not allowed a socket to be rebound, so this
407 * also returns an error. Not allowing re-binding simplifies the
408 * implementation and avoids a great many possible failure modes.
411 if (unp->unp_vnode != NULL) {
415 if (unp->unp_flags & UNP_BINDING) {
419 unp->unp_flags |= UNP_BINDING;
422 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
423 bcopy(soun->sun_path, buf, namelen);
428 NDINIT(&nd, CREATE, MPSAFE | NOFOLLOW | LOCKPARENT | SAVENAME,
429 UIO_SYSSPACE, buf, td);
430 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
435 vfslocked = NDHASGIANT(&nd);
436 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
437 NDFREE(&nd, NDF_ONLY_PNBUF);
447 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
450 VFS_UNLOCK_GIANT(vfslocked);
454 vattr.va_type = VSOCK;
455 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
457 error = mac_vnode_check_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
461 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
462 NDFREE(&nd, NDF_ONLY_PNBUF);
465 vn_finished_write(mp);
469 ASSERT_VOP_ELOCKED(vp, "uipc_bind");
470 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
474 vp->v_socket = unp->unp_socket;
476 unp->unp_addr = soun;
477 unp->unp_flags &= ~UNP_BINDING;
481 vn_finished_write(mp);
482 VFS_UNLOCK_GIANT(vfslocked);
487 VFS_UNLOCK_GIANT(vfslocked);
489 unp->unp_flags &= ~UNP_BINDING;
496 uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
500 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
502 error = unp_connect(so, nam, td);
508 uipc_close(struct socket *so)
510 struct unpcb *unp, *unp2;
513 KASSERT(unp != NULL, ("uipc_close: unp == NULL"));
517 unp2 = unp->unp_conn;
520 unp_disconnect(unp, unp2);
521 UNP_PCB_UNLOCK(unp2);
528 uipc_connect2(struct socket *so1, struct socket *so2)
530 struct unpcb *unp, *unp2;
535 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
538 KASSERT(unp2 != NULL, ("uipc_connect2: unp2 == NULL"));
540 error = unp_connect2(so1, so2, PRU_CONNECT2);
541 UNP_PCB_UNLOCK(unp2);
548 uipc_detach(struct socket *so)
550 struct unpcb *unp, *unp2;
551 struct sockaddr_un *saved_unp_addr;
553 int freeunp, local_unp_rights;
556 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
561 LIST_REMOVE(unp, unp_link);
562 unp->unp_gencnt = ++unp_gencnt;
567 * XXXRW: Should assert vp->v_socket == so.
569 if ((vp = unp->unp_vnode) != NULL) {
570 unp->unp_vnode->v_socket = NULL;
571 unp->unp_vnode = NULL;
573 unp2 = unp->unp_conn;
576 unp_disconnect(unp, unp2);
577 UNP_PCB_UNLOCK(unp2);
581 * We hold the linkage lock exclusively, so it's OK to acquire
582 * multiple pcb locks at a time.
584 while (!LIST_EMPTY(&unp->unp_refs)) {
585 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
588 unp_drop(ref, ECONNRESET);
591 local_unp_rights = unp_rights;
593 unp->unp_socket->so_pcb = NULL;
594 saved_unp_addr = unp->unp_addr;
595 unp->unp_addr = NULL;
597 freeunp = (unp->unp_refcount == 0);
598 if (saved_unp_addr != NULL)
599 free(saved_unp_addr, M_SONAME);
601 UNP_PCB_LOCK_DESTROY(unp);
602 uma_zfree(unp_zone, unp);
608 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
610 VFS_UNLOCK_GIANT(vfslocked);
612 if (local_unp_rights)
613 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
617 uipc_disconnect(struct socket *so)
619 struct unpcb *unp, *unp2;
622 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
626 unp2 = unp->unp_conn;
629 unp_disconnect(unp, unp2);
630 UNP_PCB_UNLOCK(unp2);
638 uipc_listen(struct socket *so, int backlog, struct thread *td)
644 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
647 if (unp->unp_vnode == NULL) {
653 error = solisten_proto_check(so);
655 cru2x(td->td_ucred, &unp->unp_peercred);
656 unp->unp_flags |= UNP_HAVEPCCACHED;
657 solisten_proto(so, backlog);
665 uipc_peeraddr(struct socket *so, struct sockaddr **nam)
667 struct unpcb *unp, *unp2;
668 const struct sockaddr *sa;
671 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
673 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
676 * XXX: It seems that this test always fails even when connection is
677 * established. So, this else clause is added as workaround to
678 * return PF_LOCAL sockaddr.
680 unp2 = unp->unp_conn;
683 if (unp2->unp_addr != NULL)
684 sa = (struct sockaddr *) unp2->unp_addr;
687 bcopy(sa, *nam, sa->sa_len);
688 UNP_PCB_UNLOCK(unp2);
691 bcopy(sa, *nam, sa->sa_len);
698 uipc_rcvd(struct socket *so, int flags)
700 struct unpcb *unp, *unp2;
706 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
708 if (so->so_type == SOCK_DGRAM)
709 panic("uipc_rcvd DGRAM?");
711 if (so->so_type != SOCK_STREAM)
712 panic("uipc_rcvd unknown socktype");
715 * Adjust backpressure on sender and wakeup any waiting to write.
717 * The unp lock is acquired to maintain the validity of the unp_conn
718 * pointer; no lock on unp2 is required as unp2->unp_socket will be
719 * static as long as we don't permit unp2 to disconnect from unp,
720 * which is prevented by the lock on unp. We cache values from
721 * so_rcv to avoid holding the so_rcv lock over the entire
722 * transaction on the remote so_snd.
724 SOCKBUF_LOCK(&so->so_rcv);
725 mbcnt = so->so_rcv.sb_mbcnt;
726 sbcc = so->so_rcv.sb_cc;
727 SOCKBUF_UNLOCK(&so->so_rcv);
729 unp2 = unp->unp_conn;
734 so2 = unp2->unp_socket;
735 SOCKBUF_LOCK(&so2->so_snd);
736 so2->so_snd.sb_mbmax += unp->unp_mbcnt - mbcnt;
737 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc - sbcc;
738 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
739 newhiwat, RLIM_INFINITY);
740 sowwakeup_locked(so2);
741 unp->unp_mbcnt = mbcnt;
748 uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
749 struct mbuf *control, struct thread *td)
751 struct unpcb *unp, *unp2;
753 u_int mbcnt_delta, sbcc;
758 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
760 if (flags & PRUS_OOB) {
764 if (control != NULL && (error = unp_internalize(&control, td)))
766 if ((nam != NULL) || (flags & PRUS_EOF))
770 switch (so->so_type) {
773 const struct sockaddr *from;
775 unp2 = unp->unp_conn;
777 UNP_LINK_WLOCK_ASSERT();
782 error = unp_connect(so, nam, td);
785 unp2 = unp->unp_conn;
789 * Because connect() and send() are non-atomic in a sendto()
790 * with a target address, it's possible that the socket will
791 * have disconnected before the send() can run. In that case
792 * return the slightly counter-intuitive but otherwise
793 * correct error that the socket is not connected.
800 if (unp2->unp_flags & UNP_WANTCRED)
801 control = unp_addsockcred(td, control);
803 if (unp->unp_addr != NULL)
804 from = (struct sockaddr *)unp->unp_addr;
807 so2 = unp2->unp_socket;
808 SOCKBUF_LOCK(&so2->so_rcv);
809 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
810 sorwakeup_locked(so2);
814 SOCKBUF_UNLOCK(&so2->so_rcv);
818 UNP_LINK_WLOCK_ASSERT();
820 unp_disconnect(unp, unp2);
821 UNP_PCB_UNLOCK(unp2);
828 if ((so->so_state & SS_ISCONNECTED) == 0) {
830 UNP_LINK_WLOCK_ASSERT();
831 error = unp_connect(so, nam, td);
841 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
847 * Because connect() and send() are non-atomic in a sendto()
848 * with a target address, it's possible that the socket will
849 * have disconnected before the send() can run. In that case
850 * return the slightly counter-intuitive but otherwise
851 * correct error that the socket is not connected.
853 * Locking here must be done carefully: the linkage lock
854 * prevents interconnections between unpcbs from changing, so
855 * we can traverse from unp to unp2 without acquiring unp's
856 * lock. Socket buffer locks follow unpcb locks, so we can
857 * acquire both remote and lock socket buffer locks.
859 unp2 = unp->unp_conn;
864 so2 = unp2->unp_socket;
866 SOCKBUF_LOCK(&so2->so_rcv);
867 if (unp2->unp_flags & UNP_WANTCRED) {
869 * Credentials are passed only once on SOCK_STREAM.
871 unp2->unp_flags &= ~UNP_WANTCRED;
872 control = unp_addsockcred(td, control);
875 * Send to paired receive port, and then reduce send buffer
876 * hiwater marks to maintain backpressure. Wake up readers.
878 if (control != NULL) {
879 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
882 sbappend_locked(&so2->so_rcv, m);
883 mbcnt_delta = so2->so_rcv.sb_mbcnt - unp2->unp_mbcnt;
884 unp2->unp_mbcnt = so2->so_rcv.sb_mbcnt;
885 sbcc = so2->so_rcv.sb_cc;
886 sorwakeup_locked(so2);
888 SOCKBUF_LOCK(&so->so_snd);
889 newhiwat = so->so_snd.sb_hiwat - (sbcc - unp2->unp_cc);
890 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
891 newhiwat, RLIM_INFINITY);
892 so->so_snd.sb_mbmax -= mbcnt_delta;
893 SOCKBUF_UNLOCK(&so->so_snd);
895 UNP_PCB_UNLOCK(unp2);
900 panic("uipc_send unknown socktype");
904 * PRUS_EOF is equivalent to pru_send followed by pru_shutdown.
906 if (flags & PRUS_EOF) {
913 if ((nam != NULL) || (flags & PRUS_EOF))
918 if (control != NULL && error != 0)
919 unp_dispose(control);
930 uipc_sense(struct socket *so, struct stat *sb)
932 struct unpcb *unp, *unp2;
936 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
938 sb->st_blksize = so->so_snd.sb_hiwat;
941 unp2 = unp->unp_conn;
942 if (so->so_type == SOCK_STREAM && unp2 != NULL) {
943 so2 = unp2->unp_socket;
944 sb->st_blksize += so2->so_rcv.sb_cc;
947 if (unp->unp_ino == 0)
948 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
949 sb->st_ino = unp->unp_ino;
956 uipc_shutdown(struct socket *so)
961 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
973 uipc_sockaddr(struct socket *so, struct sockaddr **nam)
976 const struct sockaddr *sa;
979 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
981 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
983 if (unp->unp_addr != NULL)
984 sa = (struct sockaddr *) unp->unp_addr;
987 bcopy(sa, *nam, sa->sa_len);
992 static struct pr_usrreqs uipc_usrreqs_dgram = {
993 .pru_abort = uipc_abort,
994 .pru_accept = uipc_accept,
995 .pru_attach = uipc_attach,
996 .pru_bind = uipc_bind,
997 .pru_connect = uipc_connect,
998 .pru_connect2 = uipc_connect2,
999 .pru_detach = uipc_detach,
1000 .pru_disconnect = uipc_disconnect,
1001 .pru_listen = uipc_listen,
1002 .pru_peeraddr = uipc_peeraddr,
1003 .pru_rcvd = uipc_rcvd,
1004 .pru_send = uipc_send,
1005 .pru_sense = uipc_sense,
1006 .pru_shutdown = uipc_shutdown,
1007 .pru_sockaddr = uipc_sockaddr,
1008 .pru_soreceive = soreceive_dgram,
1009 .pru_close = uipc_close,
1012 static struct pr_usrreqs uipc_usrreqs_stream = {
1013 .pru_abort = uipc_abort,
1014 .pru_accept = uipc_accept,
1015 .pru_attach = uipc_attach,
1016 .pru_bind = uipc_bind,
1017 .pru_connect = uipc_connect,
1018 .pru_connect2 = uipc_connect2,
1019 .pru_detach = uipc_detach,
1020 .pru_disconnect = uipc_disconnect,
1021 .pru_listen = uipc_listen,
1022 .pru_peeraddr = uipc_peeraddr,
1023 .pru_rcvd = uipc_rcvd,
1024 .pru_send = uipc_send,
1025 .pru_sense = uipc_sense,
1026 .pru_shutdown = uipc_shutdown,
1027 .pru_sockaddr = uipc_sockaddr,
1028 .pru_soreceive = soreceive_generic,
1029 .pru_close = uipc_close,
1033 uipc_ctloutput(struct socket *so, struct sockopt *sopt)
1039 if (sopt->sopt_level != 0)
1042 unp = sotounpcb(so);
1043 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
1045 switch (sopt->sopt_dir) {
1047 switch (sopt->sopt_name) {
1048 case LOCAL_PEERCRED:
1050 if (unp->unp_flags & UNP_HAVEPC)
1051 xu = unp->unp_peercred;
1053 if (so->so_type == SOCK_STREAM)
1058 UNP_PCB_UNLOCK(unp);
1060 error = sooptcopyout(sopt, &xu, sizeof(xu));
1064 /* Unlocked read. */
1065 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
1066 error = sooptcopyout(sopt, &optval, sizeof(optval));
1069 case LOCAL_CONNWAIT:
1070 /* Unlocked read. */
1071 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
1072 error = sooptcopyout(sopt, &optval, sizeof(optval));
1082 switch (sopt->sopt_name) {
1084 case LOCAL_CONNWAIT:
1085 error = sooptcopyin(sopt, &optval, sizeof(optval),
1090 #define OPTSET(bit) do { \
1091 UNP_PCB_LOCK(unp); \
1093 unp->unp_flags |= bit; \
1095 unp->unp_flags &= ~bit; \
1096 UNP_PCB_UNLOCK(unp); \
1099 switch (sopt->sopt_name) {
1101 OPTSET(UNP_WANTCRED);
1104 case LOCAL_CONNWAIT:
1105 OPTSET(UNP_CONNWAIT);
1114 error = ENOPROTOOPT;
1127 unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1129 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
1131 struct socket *so2, *so3;
1132 struct unpcb *unp, *unp2, *unp3;
1133 int error, len, vfslocked;
1134 struct nameidata nd;
1135 char buf[SOCK_MAXADDRLEN];
1136 struct sockaddr *sa;
1138 UNP_LINK_WLOCK_ASSERT();
1140 unp = sotounpcb(so);
1141 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1143 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
1146 bcopy(soun->sun_path, buf, len);
1150 if (unp->unp_flags & UNP_CONNECTING) {
1151 UNP_PCB_UNLOCK(unp);
1155 unp->unp_flags |= UNP_CONNECTING;
1156 UNP_PCB_UNLOCK(unp);
1158 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
1159 NDINIT(&nd, LOOKUP, MPSAFE | FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf,
1166 ASSERT_VOP_LOCKED(vp, "unp_connect");
1167 vfslocked = NDHASGIANT(&nd);
1168 NDFREE(&nd, NDF_ONLY_PNBUF);
1172 if (vp->v_type != VSOCK) {
1177 error = mac_vnode_check_open(td->td_ucred, vp, VWRITE | VREAD);
1181 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
1184 VFS_UNLOCK_GIANT(vfslocked);
1186 unp = sotounpcb(so);
1187 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1190 * Lock linkage lock for two reasons: make sure v_socket is stable,
1191 * and to protect simultaneous locking of multiple pcbs.
1196 error = ECONNREFUSED;
1199 if (so->so_type != so2->so_type) {
1203 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
1204 if (so2->so_options & SO_ACCEPTCONN) {
1205 so3 = sonewconn(so2, 0);
1209 error = ECONNREFUSED;
1212 unp = sotounpcb(so);
1213 unp2 = sotounpcb(so2);
1214 unp3 = sotounpcb(so3);
1218 if (unp2->unp_addr != NULL) {
1219 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
1220 unp3->unp_addr = (struct sockaddr_un *) sa;
1225 * The connecter's (client's) credentials are copied from its
1226 * process structure at the time of connect() (which is now).
1228 cru2x(td->td_ucred, &unp3->unp_peercred);
1229 unp3->unp_flags |= UNP_HAVEPC;
1232 * The receiver's (server's) credentials are copied from the
1233 * unp_peercred member of socket on which the former called
1234 * listen(); uipc_listen() cached that process's credentials
1235 * at that time so we can use them now.
1237 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
1238 ("unp_connect: listener without cached peercred"));
1239 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
1240 sizeof(unp->unp_peercred));
1241 unp->unp_flags |= UNP_HAVEPC;
1242 if (unp2->unp_flags & UNP_WANTCRED)
1243 unp3->unp_flags |= UNP_WANTCRED;
1244 UNP_PCB_UNLOCK(unp3);
1245 UNP_PCB_UNLOCK(unp2);
1246 UNP_PCB_UNLOCK(unp);
1248 mac_socketpeer_set_from_socket(so, so3);
1249 mac_socketpeer_set_from_socket(so3, so);
1254 unp = sotounpcb(so);
1255 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
1256 unp2 = sotounpcb(so2);
1257 KASSERT(unp2 != NULL, ("unp_connect: unp2 == NULL"));
1260 error = unp_connect2(so, so2, PRU_CONNECT);
1261 UNP_PCB_UNLOCK(unp2);
1262 UNP_PCB_UNLOCK(unp);
1267 * Giant has been previously acquired. This means filesystem
1268 * isn't MPSAFE. Do it once again.
1274 VFS_UNLOCK_GIANT(vfslocked);
1278 unp->unp_flags &= ~UNP_CONNECTING;
1279 UNP_PCB_UNLOCK(unp);
1284 unp_connect2(struct socket *so, struct socket *so2, int req)
1289 unp = sotounpcb(so);
1290 KASSERT(unp != NULL, ("unp_connect2: unp == NULL"));
1291 unp2 = sotounpcb(so2);
1292 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
1294 UNP_LINK_WLOCK_ASSERT();
1295 UNP_PCB_LOCK_ASSERT(unp);
1296 UNP_PCB_LOCK_ASSERT(unp2);
1298 if (so2->so_type != so->so_type)
1299 return (EPROTOTYPE);
1300 unp->unp_conn = unp2;
1302 switch (so->so_type) {
1304 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
1309 unp2->unp_conn = unp;
1310 if (req == PRU_CONNECT &&
1311 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1319 panic("unp_connect2");
1325 unp_disconnect(struct unpcb *unp, struct unpcb *unp2)
1329 KASSERT(unp2 != NULL, ("unp_disconnect: unp2 == NULL"));
1331 UNP_LINK_WLOCK_ASSERT();
1332 UNP_PCB_LOCK_ASSERT(unp);
1333 UNP_PCB_LOCK_ASSERT(unp2);
1335 unp->unp_conn = NULL;
1336 switch (unp->unp_socket->so_type) {
1338 LIST_REMOVE(unp, unp_reflink);
1339 so = unp->unp_socket;
1341 so->so_state &= ~SS_ISCONNECTED;
1346 soisdisconnected(unp->unp_socket);
1347 unp2->unp_conn = NULL;
1348 soisdisconnected(unp2->unp_socket);
1354 * unp_pcblist() walks the global list of struct unpcb's to generate a
1355 * pointer list, bumping the refcount on each unpcb. It then copies them out
1356 * sequentially, validating the generation number on each to see if it has
1357 * been detached. All of this is necessary because copyout() may sleep on
1361 unp_pcblist(SYSCTL_HANDLER_ARGS)
1365 struct unpcb *unp, **unp_list;
1367 struct xunpgen *xug;
1368 struct unp_head *head;
1371 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1374 * The process of preparing the PCB list is too time-consuming and
1375 * resource-intensive to repeat twice on every request.
1377 if (req->oldptr == NULL) {
1379 req->oldidx = 2 * (sizeof *xug)
1380 + (n + n/8) * sizeof(struct xunpcb);
1384 if (req->newptr != NULL)
1388 * OK, now we're committed to doing something.
1390 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1392 gencnt = unp_gencnt;
1396 xug->xug_len = sizeof *xug;
1398 xug->xug_gen = gencnt;
1399 xug->xug_sogen = so_gencnt;
1400 error = SYSCTL_OUT(req, xug, sizeof *xug);
1406 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1409 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1410 unp = LIST_NEXT(unp, unp_link)) {
1412 if (unp->unp_gencnt <= gencnt) {
1413 if (cr_cansee(req->td->td_ucred,
1414 unp->unp_socket->so_cred)) {
1415 UNP_PCB_UNLOCK(unp);
1418 unp_list[i++] = unp;
1419 unp->unp_refcount++;
1421 UNP_PCB_UNLOCK(unp);
1424 n = i; /* In case we lost some during malloc. */
1427 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1428 for (i = 0; i < n; i++) {
1431 unp->unp_refcount--;
1432 if (unp->unp_refcount != 0 && unp->unp_gencnt <= gencnt) {
1433 xu->xu_len = sizeof *xu;
1436 * XXX - need more locking here to protect against
1437 * connect/disconnect races for SMP.
1439 if (unp->unp_addr != NULL)
1440 bcopy(unp->unp_addr, &xu->xu_addr,
1441 unp->unp_addr->sun_len);
1442 if (unp->unp_conn != NULL &&
1443 unp->unp_conn->unp_addr != NULL)
1444 bcopy(unp->unp_conn->unp_addr,
1446 unp->unp_conn->unp_addr->sun_len);
1447 bcopy(unp, &xu->xu_unp, sizeof *unp);
1448 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1449 UNP_PCB_UNLOCK(unp);
1450 error = SYSCTL_OUT(req, xu, sizeof *xu);
1452 freeunp = (unp->unp_refcount == 0);
1453 UNP_PCB_UNLOCK(unp);
1455 UNP_PCB_LOCK_DESTROY(unp);
1456 uma_zfree(unp_zone, unp);
1463 * Give the user an updated idea of our state. If the
1464 * generation differs from what we told her before, she knows
1465 * that something happened while we were processing this
1466 * request, and it might be necessary to retry.
1468 xug->xug_gen = unp_gencnt;
1469 xug->xug_sogen = so_gencnt;
1470 xug->xug_count = unp_count;
1471 error = SYSCTL_OUT(req, xug, sizeof *xug);
1473 free(unp_list, M_TEMP);
1478 SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1479 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1480 "List of active local datagram sockets");
1481 SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1482 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1483 "List of active local stream sockets");
1486 unp_shutdown(struct unpcb *unp)
1491 UNP_LINK_WLOCK_ASSERT();
1492 UNP_PCB_LOCK_ASSERT(unp);
1494 unp2 = unp->unp_conn;
1495 if (unp->unp_socket->so_type == SOCK_STREAM && unp2 != NULL) {
1496 so = unp2->unp_socket;
1503 unp_drop(struct unpcb *unp, int errno)
1505 struct socket *so = unp->unp_socket;
1508 UNP_LINK_WLOCK_ASSERT();
1509 UNP_PCB_LOCK_ASSERT(unp);
1511 so->so_error = errno;
1512 unp2 = unp->unp_conn;
1516 unp_disconnect(unp, unp2);
1517 UNP_PCB_UNLOCK(unp2);
1521 unp_freerights(struct file **rp, int fdcount)
1526 for (i = 0; i < fdcount; i++) {
1534 unp_externalize(struct mbuf *control, struct mbuf **controlp)
1536 struct thread *td = curthread; /* XXX */
1537 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1543 socklen_t clen = control->m_len, datalen;
1548 UNP_LINK_UNLOCK_ASSERT();
1551 if (controlp != NULL) /* controlp == NULL => free control messages */
1553 while (cm != NULL) {
1554 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1558 data = CMSG_DATA(cm);
1559 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1560 if (cm->cmsg_level == SOL_SOCKET
1561 && cm->cmsg_type == SCM_RIGHTS) {
1562 newfds = datalen / sizeof(struct file *);
1565 /* If we're not outputting the descriptors free them. */
1566 if (error || controlp == NULL) {
1567 unp_freerights(rp, newfds);
1570 FILEDESC_XLOCK(td->td_proc->p_fd);
1571 /* if the new FD's will not fit free them. */
1572 if (!fdavail(td, newfds)) {
1573 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1575 unp_freerights(rp, newfds);
1580 * Now change each pointer to an fd in the global
1581 * table to an integer that is the index to the local
1582 * fd table entry that we set up to point to the
1583 * global one we are transferring.
1585 newlen = newfds * sizeof(int);
1586 *controlp = sbcreatecontrol(NULL, newlen,
1587 SCM_RIGHTS, SOL_SOCKET);
1588 if (*controlp == NULL) {
1589 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1591 unp_freerights(rp, newfds);
1596 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1597 for (i = 0; i < newfds; i++) {
1598 if (fdalloc(td, 0, &f))
1599 panic("unp_externalize fdalloc failed");
1601 td->td_proc->p_fd->fd_ofiles[f] = fp;
1602 unp_externalize_fp(fp);
1605 FILEDESC_XUNLOCK(td->td_proc->p_fd);
1607 /* We can just copy anything else across. */
1608 if (error || controlp == NULL)
1610 *controlp = sbcreatecontrol(NULL, datalen,
1611 cm->cmsg_type, cm->cmsg_level);
1612 if (*controlp == NULL) {
1617 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1620 controlp = &(*controlp)->m_next;
1623 if (CMSG_SPACE(datalen) < clen) {
1624 clen -= CMSG_SPACE(datalen);
1625 cm = (struct cmsghdr *)
1626 ((caddr_t)cm + CMSG_SPACE(datalen));
1638 unp_zone_change(void *tag)
1641 uma_zone_set_max(unp_zone, maxsockets);
1649 if (!IS_DEFAULT_VNET(curvnet))
1652 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1653 NULL, NULL, UMA_ALIGN_PTR, 0);
1654 if (unp_zone == NULL)
1656 uma_zone_set_max(unp_zone, maxsockets);
1657 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1658 NULL, EVENTHANDLER_PRI_ANY);
1659 LIST_INIT(&unp_dhead);
1660 LIST_INIT(&unp_shead);
1661 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1662 UNP_LINK_LOCK_INIT();
1663 UNP_LIST_LOCK_INIT();
1667 unp_internalize(struct mbuf **controlp, struct thread *td)
1669 struct mbuf *control = *controlp;
1670 struct proc *p = td->td_proc;
1671 struct filedesc *fdescp = p->p_fd;
1672 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1673 struct cmsgcred *cmcred;
1679 socklen_t clen = control->m_len, datalen;
1683 UNP_LINK_UNLOCK_ASSERT();
1687 while (cm != NULL) {
1688 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1689 || cm->cmsg_len > clen) {
1693 data = CMSG_DATA(cm);
1694 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1696 switch (cm->cmsg_type) {
1698 * Fill in credential information.
1701 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1702 SCM_CREDS, SOL_SOCKET);
1703 if (*controlp == NULL) {
1707 cmcred = (struct cmsgcred *)
1708 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1709 cmcred->cmcred_pid = p->p_pid;
1710 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1711 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1712 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1713 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1715 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1716 cmcred->cmcred_groups[i] =
1717 td->td_ucred->cr_groups[i];
1721 oldfds = datalen / sizeof (int);
1723 * Check that all the FDs passed in refer to legal
1724 * files. If not, reject the entire operation.
1727 FILEDESC_SLOCK(fdescp);
1728 for (i = 0; i < oldfds; i++) {
1730 if ((unsigned)fd >= fdescp->fd_nfiles ||
1731 fdescp->fd_ofiles[fd] == NULL) {
1732 FILEDESC_SUNLOCK(fdescp);
1736 fp = fdescp->fd_ofiles[fd];
1737 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1738 FILEDESC_SUNLOCK(fdescp);
1746 * Now replace the integer FDs with pointers to the
1747 * associated global file table entry..
1749 newlen = oldfds * sizeof(struct file *);
1750 *controlp = sbcreatecontrol(NULL, newlen,
1751 SCM_RIGHTS, SOL_SOCKET);
1752 if (*controlp == NULL) {
1753 FILEDESC_SUNLOCK(fdescp);
1758 rp = (struct file **)
1759 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1760 for (i = 0; i < oldfds; i++) {
1761 fp = fdescp->fd_ofiles[*fdp++];
1763 unp_internalize_fp(fp);
1765 FILEDESC_SUNLOCK(fdescp);
1769 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1770 SCM_TIMESTAMP, SOL_SOCKET);
1771 if (*controlp == NULL) {
1775 tv = (struct timeval *)
1776 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1785 controlp = &(*controlp)->m_next;
1786 if (CMSG_SPACE(datalen) < clen) {
1787 clen -= CMSG_SPACE(datalen);
1788 cm = (struct cmsghdr *)
1789 ((caddr_t)cm + CMSG_SPACE(datalen));
1801 static struct mbuf *
1802 unp_addsockcred(struct thread *td, struct mbuf *control)
1804 struct mbuf *m, *n, *n_prev;
1805 struct sockcred *sc;
1806 const struct cmsghdr *cm;
1810 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1811 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1815 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1816 sc->sc_uid = td->td_ucred->cr_ruid;
1817 sc->sc_euid = td->td_ucred->cr_uid;
1818 sc->sc_gid = td->td_ucred->cr_rgid;
1819 sc->sc_egid = td->td_ucred->cr_gid;
1820 sc->sc_ngroups = ngroups;
1821 for (i = 0; i < sc->sc_ngroups; i++)
1822 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1825 * Unlink SCM_CREDS control messages (struct cmsgcred), since just
1826 * created SCM_CREDS control message (struct sockcred) has another
1829 if (control != NULL)
1830 for (n = control, n_prev = NULL; n != NULL;) {
1831 cm = mtod(n, struct cmsghdr *);
1832 if (cm->cmsg_level == SOL_SOCKET &&
1833 cm->cmsg_type == SCM_CREDS) {
1835 control = n->m_next;
1837 n_prev->m_next = n->m_next;
1845 /* Prepend it to the head. */
1846 m->m_next = control;
1850 static struct unpcb *
1851 fptounp(struct file *fp)
1855 if (fp->f_type != DTYPE_SOCKET)
1857 if ((so = fp->f_data) == NULL)
1859 if (so->so_proto->pr_domain != &localdomain)
1861 return sotounpcb(so);
1865 unp_discard(struct file *fp)
1868 unp_externalize_fp(fp);
1869 (void) closef(fp, (struct thread *)NULL);
1873 unp_internalize_fp(struct file *fp)
1878 if ((unp = fptounp(fp)) != NULL) {
1880 unp->unp_msgcount++;
1888 unp_externalize_fp(struct file *fp)
1893 if ((unp = fptounp(fp)) != NULL)
1894 unp->unp_msgcount--;
1900 * unp_defer indicates whether additional work has been defered for a future
1901 * pass through unp_gc(). It is thread local and does not require explicit
1904 static int unp_marked;
1905 static int unp_unreachable;
1908 unp_accessable(struct file *fp)
1912 if ((unp = fptounp(fp)) == NULL)
1914 if (unp->unp_gcflag & UNPGC_REF)
1916 unp->unp_gcflag &= ~UNPGC_DEAD;
1917 unp->unp_gcflag |= UNPGC_REF;
1922 unp_gc_process(struct unpcb *unp)
1928 /* Already processed. */
1929 if (unp->unp_gcflag & UNPGC_SCANNED)
1934 * Check for a socket potentially in a cycle. It must be in a
1935 * queue as indicated by msgcount, and this must equal the file
1936 * reference count. Note that when msgcount is 0 the file is NULL.
1938 if ((unp->unp_gcflag & UNPGC_REF) == 0 && fp &&
1939 unp->unp_msgcount != 0 && fp->f_count == unp->unp_msgcount) {
1940 unp->unp_gcflag |= UNPGC_DEAD;
1946 * Mark all sockets we reference with RIGHTS.
1948 so = unp->unp_socket;
1949 SOCKBUF_LOCK(&so->so_rcv);
1950 unp_scan(so->so_rcv.sb_mb, unp_accessable);
1951 SOCKBUF_UNLOCK(&so->so_rcv);
1954 * Mark all sockets in our accept queue.
1957 TAILQ_FOREACH(soa, &so->so_comp, so_list) {
1958 SOCKBUF_LOCK(&soa->so_rcv);
1959 unp_scan(soa->so_rcv.sb_mb, unp_accessable);
1960 SOCKBUF_UNLOCK(&soa->so_rcv);
1963 unp->unp_gcflag |= UNPGC_SCANNED;
1966 static int unp_recycled;
1967 SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0,
1968 "Number of unreachable sockets claimed by the garbage collector.");
1970 static int unp_taskcount;
1971 SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0,
1972 "Number of times the garbage collector has run.");
1975 unp_gc(__unused void *arg, int pending)
1977 struct unp_head *heads[] = { &unp_dhead, &unp_shead, NULL };
1978 struct unp_head **head;
1979 struct file **unref;
1986 * First clear all gc flags from previous runs.
1988 for (head = heads; *head != NULL; head++)
1989 LIST_FOREACH(unp, *head, unp_link)
1990 unp->unp_gcflag = 0;
1993 * Scan marking all reachable sockets with UNPGC_REF. Once a socket
1994 * is reachable all of the sockets it references are reachable.
1995 * Stop the scan once we do a complete loop without discovering
1996 * a new reachable socket.
1999 unp_unreachable = 0;
2001 for (head = heads; *head != NULL; head++)
2002 LIST_FOREACH(unp, *head, unp_link)
2003 unp_gc_process(unp);
2004 } while (unp_marked);
2006 if (unp_unreachable == 0)
2010 * Allocate space for a local list of dead unpcbs.
2012 unref = malloc(unp_unreachable * sizeof(struct file *),
2016 * Iterate looking for sockets which have been specifically marked
2017 * as as unreachable and store them locally.
2020 for (i = 0, head = heads; *head != NULL; head++)
2021 LIST_FOREACH(unp, *head, unp_link)
2022 if (unp->unp_gcflag & UNPGC_DEAD) {
2023 unref[i++] = unp->unp_file;
2024 fhold(unp->unp_file);
2025 KASSERT(unp->unp_file != NULL,
2026 ("unp_gc: Invalid unpcb."));
2027 KASSERT(i <= unp_unreachable,
2028 ("unp_gc: incorrect unreachable count."));
2033 * Now flush all sockets, free'ing rights. This will free the
2034 * struct files associated with these sockets but leave each socket
2035 * with one remaining ref.
2037 for (i = 0; i < unp_unreachable; i++)
2038 sorflush(unref[i]->f_data);
2041 * And finally release the sockets so they can be reclaimed.
2043 for (i = 0; i < unp_unreachable; i++)
2044 fdrop(unref[i], NULL);
2045 unp_recycled += unp_unreachable;
2046 free(unref, M_TEMP);
2050 unp_dispose(struct mbuf *m)
2054 unp_scan(m, unp_discard);
2058 unp_scan(struct mbuf *m0, void (*op)(struct file *))
2065 socklen_t clen, datalen;
2068 while (m0 != NULL) {
2069 for (m = m0; m; m = m->m_next) {
2070 if (m->m_type != MT_CONTROL)
2073 cm = mtod(m, struct cmsghdr *);
2076 while (cm != NULL) {
2077 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
2080 data = CMSG_DATA(cm);
2081 datalen = (caddr_t)cm + cm->cmsg_len
2084 if (cm->cmsg_level == SOL_SOCKET &&
2085 cm->cmsg_type == SCM_RIGHTS) {
2086 qfds = datalen / sizeof (struct file *);
2088 for (i = 0; i < qfds; i++)
2092 if (CMSG_SPACE(datalen) < clen) {
2093 clen -= CMSG_SPACE(datalen);
2094 cm = (struct cmsghdr *)
2095 ((caddr_t)cm + CMSG_SPACE(datalen));
2108 db_print_indent(int indent)
2112 for (i = 0; i < indent; i++)
2117 db_print_unpflags(int unp_flags)
2122 if (unp_flags & UNP_HAVEPC) {
2123 db_printf("%sUNP_HAVEPC", comma ? ", " : "");
2126 if (unp_flags & UNP_HAVEPCCACHED) {
2127 db_printf("%sUNP_HAVEPCCACHED", comma ? ", " : "");
2130 if (unp_flags & UNP_WANTCRED) {
2131 db_printf("%sUNP_WANTCRED", comma ? ", " : "");
2134 if (unp_flags & UNP_CONNWAIT) {
2135 db_printf("%sUNP_CONNWAIT", comma ? ", " : "");
2138 if (unp_flags & UNP_CONNECTING) {
2139 db_printf("%sUNP_CONNECTING", comma ? ", " : "");
2142 if (unp_flags & UNP_BINDING) {
2143 db_printf("%sUNP_BINDING", comma ? ", " : "");
2149 db_print_xucred(int indent, struct xucred *xu)
2153 db_print_indent(indent);
2154 db_printf("cr_version: %u cr_uid: %u cr_ngroups: %d\n",
2155 xu->cr_version, xu->cr_uid, xu->cr_ngroups);
2156 db_print_indent(indent);
2157 db_printf("cr_groups: ");
2159 for (i = 0; i < xu->cr_ngroups; i++) {
2160 db_printf("%s%u", comma ? ", " : "", xu->cr_groups[i]);
2167 db_print_unprefs(int indent, struct unp_head *uh)
2173 LIST_FOREACH(unp, uh, unp_reflink) {
2174 if (counter % 4 == 0)
2175 db_print_indent(indent);
2176 db_printf("%p ", unp);
2177 if (counter % 4 == 3)
2181 if (counter != 0 && counter % 4 != 0)
2185 DB_SHOW_COMMAND(unpcb, db_show_unpcb)
2190 db_printf("usage: show unpcb <addr>\n");
2193 unp = (struct unpcb *)addr;
2195 db_printf("unp_socket: %p unp_vnode: %p\n", unp->unp_socket,
2198 db_printf("unp_ino: %d unp_conn: %p\n", unp->unp_ino,
2201 db_printf("unp_refs:\n");
2202 db_print_unprefs(2, &unp->unp_refs);
2204 /* XXXRW: Would be nice to print the full address, if any. */
2205 db_printf("unp_addr: %p\n", unp->unp_addr);
2207 db_printf("unp_cc: %d unp_mbcnt: %d unp_gencnt: %llu\n",
2208 unp->unp_cc, unp->unp_mbcnt,
2209 (unsigned long long)unp->unp_gencnt);
2211 db_printf("unp_flags: %x (", unp->unp_flags);
2212 db_print_unpflags(unp->unp_flags);
2215 db_printf("unp_peercred:\n");
2216 db_print_xucred(2, &unp->unp_peercred);
2218 db_printf("unp_refcount: %u\n", unp->unp_refcount);